a059449efcf31b4ae823d3be27759e5c5e49580f
[ffmpeg.git] / libavcodec / h264.c
1 /*
2  * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
3  * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  */
20  
21 /**
22  * @file h264.c
23  * H.264 / AVC / MPEG4 part10 codec.
24  * @author Michael Niedermayer <michaelni@gmx.at>
25  */
26
27 #include "common.h"
28 #include "dsputil.h"
29 #include "avcodec.h"
30 #include "mpegvideo.h"
31 #include "h264data.h"
32 #include "golomb.h"
33
34 #include "cabac.h"
35
36 #undef NDEBUG
37 #include <assert.h>
38
39 #define interlaced_dct interlaced_dct_is_a_bad_name
40 #define mb_intra mb_intra_isnt_initalized_see_mb_type
41
42 #define LUMA_DC_BLOCK_INDEX   25
43 #define CHROMA_DC_BLOCK_INDEX 26
44
45 #define CHROMA_DC_COEFF_TOKEN_VLC_BITS 8
46 #define COEFF_TOKEN_VLC_BITS           8
47 #define TOTAL_ZEROS_VLC_BITS           9
48 #define CHROMA_DC_TOTAL_ZEROS_VLC_BITS 3
49 #define RUN_VLC_BITS                   3
50 #define RUN7_VLC_BITS                  6
51
52 #define MAX_SPS_COUNT 32
53 #define MAX_PPS_COUNT 256
54
55 #define MAX_MMCO_COUNT 66
56
57 /**
58  * Sequence parameter set
59  */
60 typedef struct SPS{
61     
62     int profile_idc;
63     int level_idc;
64     int log2_max_frame_num;            ///< log2_max_frame_num_minus4 + 4
65     int poc_type;                      ///< pic_order_cnt_type
66     int log2_max_poc_lsb;              ///< log2_max_pic_order_cnt_lsb_minus4
67     int delta_pic_order_always_zero_flag;
68     int offset_for_non_ref_pic;
69     int offset_for_top_to_bottom_field;
70     int poc_cycle_length;              ///< num_ref_frames_in_pic_order_cnt_cycle
71     int ref_frame_count;               ///< num_ref_frames
72     int gaps_in_frame_num_allowed_flag;
73     int mb_width;                      ///< frame_width_in_mbs_minus1 + 1
74     int mb_height;                     ///< frame_height_in_mbs_minus1 + 1
75     int frame_mbs_only_flag;
76     int mb_aff;                        ///<mb_adaptive_frame_field_flag
77     int direct_8x8_inference_flag;
78     int crop;                   ///< frame_cropping_flag
79     int crop_left;              ///< frame_cropping_rect_left_offset
80     int crop_right;             ///< frame_cropping_rect_right_offset
81     int crop_top;               ///< frame_cropping_rect_top_offset
82     int crop_bottom;            ///< frame_cropping_rect_bottom_offset
83     int vui_parameters_present_flag;
84     AVRational sar;
85     int timing_info_present_flag;
86     uint32_t num_units_in_tick;
87     uint32_t time_scale;
88     int fixed_frame_rate_flag;
89     short offset_for_ref_frame[256]; //FIXME dyn aloc?
90 }SPS;
91
92 /**
93  * Picture parameter set
94  */
95 typedef struct PPS{
96     int sps_id;
97     int cabac;                  ///< entropy_coding_mode_flag
98     int pic_order_present;      ///< pic_order_present_flag
99     int slice_group_count;      ///< num_slice_groups_minus1 + 1
100     int mb_slice_group_map_type;
101     int ref_count[2];           ///< num_ref_idx_l0/1_active_minus1 + 1
102     int weighted_pred;          ///< weighted_pred_flag
103     int weighted_bipred_idc;
104     int init_qp;                ///< pic_init_qp_minus26 + 26
105     int init_qs;                ///< pic_init_qs_minus26 + 26
106     int chroma_qp_index_offset;
107     int deblocking_filter_parameters_present; ///< deblocking_filter_parameters_present_flag
108     int constrained_intra_pred; ///< constrained_intra_pred_flag
109     int redundant_pic_cnt_present; ///< redundant_pic_cnt_present_flag
110 }PPS;
111
112 /**
113  * Memory management control operation opcode.
114  */
115 typedef enum MMCOOpcode{
116     MMCO_END=0,
117     MMCO_SHORT2UNUSED,
118     MMCO_LONG2UNUSED,
119     MMCO_SHORT2LONG,
120     MMCO_SET_MAX_LONG,
121     MMCO_RESET, 
122     MMCO_LONG,
123 } MMCOOpcode;
124
125 /**
126  * Memory management control operation.
127  */
128 typedef struct MMCO{
129     MMCOOpcode opcode;
130     int short_frame_num;
131     int long_index;
132 } MMCO;
133
134 /**
135  * H264Context
136  */
137 typedef struct H264Context{
138     MpegEncContext s;
139     int nal_ref_idc;    
140     int nal_unit_type;
141 #define NAL_SLICE               1
142 #define NAL_DPA                 2
143 #define NAL_DPB                 3
144 #define NAL_DPC                 4
145 #define NAL_IDR_SLICE           5
146 #define NAL_SEI                 6
147 #define NAL_SPS                 7
148 #define NAL_PPS                 8
149 #define NAL_PICTURE_DELIMITER   9
150 #define NAL_FILTER_DATA         10
151     uint8_t *rbsp_buffer;
152     int rbsp_buffer_size;
153
154     /**
155       * Used to parse AVC variant of h264
156       */
157     int is_avc; ///< this flag is != 0 if codec is avc1
158     int got_avcC; ///< flag used to parse avcC data only once
159     int nal_length_size; ///< Number of bytes used for nal length (1, 2 or 4)
160
161     int chroma_qp; //QPc
162
163     int prev_mb_skiped; //FIXME remove (IMHO not used)
164
165     //prediction stuff
166     int chroma_pred_mode;
167     int intra16x16_pred_mode;
168     
169     int8_t intra4x4_pred_mode_cache[5*8];
170     int8_t (*intra4x4_pred_mode)[8];
171     void (*pred4x4  [9+3])(uint8_t *src, uint8_t *topright, int stride);//FIXME move to dsp?
172     void (*pred8x8  [4+3])(uint8_t *src, int stride);
173     void (*pred16x16[4+3])(uint8_t *src, int stride);
174     unsigned int topleft_samples_available;
175     unsigned int top_samples_available;
176     unsigned int topright_samples_available;
177     unsigned int left_samples_available;
178     uint8_t (*top_border)[16+2*8];
179     uint8_t left_border[17+2*9];
180
181     /**
182      * non zero coeff count cache.
183      * is 64 if not available.
184      */
185     uint8_t non_zero_count_cache[6*8] __align8;
186     uint8_t (*non_zero_count)[16];
187
188     /**
189      * Motion vector cache.
190      */
191     int16_t mv_cache[2][5*8][2] __align8;
192     int8_t ref_cache[2][5*8] __align8;
193 #define LIST_NOT_USED -1 //FIXME rename?
194 #define PART_NOT_AVAILABLE -2
195     
196     /**
197      * is 1 if the specific list MV&references are set to 0,0,-2.
198      */
199     int mv_cache_clean[2];
200
201     int block_offset[16+8];
202     int chroma_subblock_offset[16]; //FIXME remove
203     
204     uint16_t *mb2b_xy; //FIXME are these 4 a good idea?
205     uint16_t *mb2b8_xy;
206     int b_stride; //FIXME use s->b4_stride
207     int b8_stride;
208
209     int halfpel_flag;
210     int thirdpel_flag;
211
212     int unknown_svq3_flag;
213     int next_slice_index;
214
215     SPS sps_buffer[MAX_SPS_COUNT];
216     SPS sps; ///< current sps
217     
218     PPS pps_buffer[MAX_PPS_COUNT];
219     /**
220      * current pps
221      */
222     PPS pps; //FIXME move tp Picture perhaps? (->no) do we need that?
223
224     int slice_num;
225     uint8_t *slice_table_base;
226     uint8_t *slice_table;      ///< slice_table_base + mb_stride + 1
227     int slice_type;
228     int slice_type_fixed;
229     
230     //interlacing specific flags
231     int mb_field_decoding_flag;
232     
233     int sub_mb_type[4];
234     
235     //POC stuff
236     int poc_lsb;
237     int poc_msb;
238     int delta_poc_bottom;
239     int delta_poc[2];
240     int frame_num;
241     int prev_poc_msb;             ///< poc_msb of the last reference pic for POC type 0
242     int prev_poc_lsb;             ///< poc_lsb of the last reference pic for POC type 0
243     int frame_num_offset;         ///< for POC type 2
244     int prev_frame_num_offset;    ///< for POC type 2
245     int prev_frame_num;           ///< frame_num of the last pic for POC type 1/2
246
247     /**
248      * frame_num for frames or 2*frame_num for field pics.
249      */
250     int curr_pic_num;
251     
252     /**
253      * max_frame_num or 2*max_frame_num for field pics.
254      */
255     int max_pic_num;
256
257     //Weighted pred stuff
258     int use_weight;
259     int use_weight_chroma;
260     int luma_log2_weight_denom;
261     int chroma_log2_weight_denom;
262     int luma_weight[2][16];
263     int luma_offset[2][16];
264     int chroma_weight[2][16][2];
265     int chroma_offset[2][16][2];
266     int implicit_weight[16][16];
267    
268     //deblock
269     int deblocking_filter;         ///< disable_deblocking_filter_idc with 1<->0 
270     int slice_alpha_c0_offset;
271     int slice_beta_offset;
272      
273     int redundant_pic_count;
274     
275     int direct_spatial_mv_pred;
276     int dist_scale_factor[16];
277     int map_col_to_list0[2][16];
278
279     /**
280      * num_ref_idx_l0/1_active_minus1 + 1
281      */
282     int ref_count[2];// FIXME split for AFF
283     Picture *short_ref[16];
284     Picture *long_ref[16];
285     Picture default_ref_list[2][32];
286     Picture ref_list[2][32]; //FIXME size?
287     Picture field_ref_list[2][32]; //FIXME size?
288     Picture *delayed_pic[16]; //FIXME size?
289     int delayed_output_poc;
290     
291     /**
292      * memory management control operations buffer.
293      */
294     MMCO mmco[MAX_MMCO_COUNT];
295     int mmco_index;
296     
297     int long_ref_count;  ///< number of actual long term references
298     int short_ref_count; ///< number of actual short term references
299     
300     //data partitioning
301     GetBitContext intra_gb;
302     GetBitContext inter_gb;
303     GetBitContext *intra_gb_ptr;
304     GetBitContext *inter_gb_ptr;
305     
306     DCTELEM mb[16*24] __align8;
307
308     /**
309      * Cabac
310      */
311     CABACContext cabac;
312     uint8_t      cabac_state[399];
313     int          cabac_init_idc;
314
315     /* 0x100 -> non null luma_dc, 0x80/0x40 -> non null chroma_dc (cb/cr), 0x?0 -> chroma_cbp(0,1,2), 0x0? luma_cbp */
316     uint16_t     *cbp_table;
317     int top_cbp;
318     int left_cbp;
319     /* chroma_pred_mode for i4x4 or i16x16, else 0 */
320     uint8_t     *chroma_pred_mode_table;
321     int         last_qscale_diff;
322     int16_t     (*mvd_table[2])[2];
323     int16_t     mvd_cache[2][5*8][2] __align8;
324     uint8_t     *direct_table;
325     uint8_t     direct_cache[5*8];
326
327 }H264Context;
328
329 static VLC coeff_token_vlc[4];
330 static VLC chroma_dc_coeff_token_vlc;
331
332 static VLC total_zeros_vlc[15];
333 static VLC chroma_dc_total_zeros_vlc[3];
334
335 static VLC run_vlc[6];
336 static VLC run7_vlc;
337
338 static void svq3_luma_dc_dequant_idct_c(DCTELEM *block, int qp);
339 static void svq3_add_idct_c(uint8_t *dst, DCTELEM *block, int stride, int qp, int dc);
340 static void filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr);
341
342 static inline uint32_t pack16to32(int a, int b){
343 #ifdef WORDS_BIGENDIAN
344    return (b&0xFFFF) + (a<<16);
345 #else
346    return (a&0xFFFF) + (b<<16);
347 #endif
348 }
349
350 /**
351  * fill a rectangle.
352  * @param h height of the rectangle, should be a constant
353  * @param w width of the rectangle, should be a constant
354  * @param size the size of val (1 or 4), should be a constant
355  */
356 static inline void fill_rectangle(void *vp, int w, int h, int stride, uint32_t val, int size){ //FIXME ensure this IS inlined
357     uint8_t *p= (uint8_t*)vp;
358     assert(size==1 || size==4);
359     
360     w      *= size;
361     stride *= size;
362     
363     assert((((int)vp)&(FFMIN(w, STRIDE_ALIGN)-1)) == 0);
364 //FIXME check what gcc generates for 64 bit on x86 and possible write a 32 bit ver of it
365     if(w==2 && h==2){
366         *(uint16_t*)(p + 0)=
367         *(uint16_t*)(p + stride)= size==4 ? val : val*0x0101;
368     }else if(w==2 && h==4){
369         *(uint16_t*)(p + 0*stride)=
370         *(uint16_t*)(p + 1*stride)=
371         *(uint16_t*)(p + 2*stride)=
372         *(uint16_t*)(p + 3*stride)= size==4 ? val : val*0x0101;
373     }else if(w==4 && h==1){
374         *(uint32_t*)(p + 0*stride)= size==4 ? val : val*0x01010101;
375     }else if(w==4 && h==2){
376         *(uint32_t*)(p + 0*stride)=
377         *(uint32_t*)(p + 1*stride)= size==4 ? val : val*0x01010101;
378     }else if(w==4 && h==4){
379         *(uint32_t*)(p + 0*stride)=
380         *(uint32_t*)(p + 1*stride)=
381         *(uint32_t*)(p + 2*stride)=
382         *(uint32_t*)(p + 3*stride)= size==4 ? val : val*0x01010101;
383     }else if(w==8 && h==1){
384         *(uint32_t*)(p + 0)=
385         *(uint32_t*)(p + 4)= size==4 ? val : val*0x01010101;
386     }else if(w==8 && h==2){
387         *(uint32_t*)(p + 0 + 0*stride)=
388         *(uint32_t*)(p + 4 + 0*stride)=
389         *(uint32_t*)(p + 0 + 1*stride)=
390         *(uint32_t*)(p + 4 + 1*stride)=  size==4 ? val : val*0x01010101;
391     }else if(w==8 && h==4){
392         *(uint64_t*)(p + 0*stride)=
393         *(uint64_t*)(p + 1*stride)=
394         *(uint64_t*)(p + 2*stride)=
395         *(uint64_t*)(p + 3*stride)= size==4 ? val*0x0100000001ULL : val*0x0101010101010101ULL;
396     }else if(w==16 && h==2){
397         *(uint64_t*)(p + 0+0*stride)=
398         *(uint64_t*)(p + 8+0*stride)=
399         *(uint64_t*)(p + 0+1*stride)=
400         *(uint64_t*)(p + 8+1*stride)= size==4 ? val*0x0100000001ULL : val*0x0101010101010101ULL;
401     }else if(w==16 && h==4){
402         *(uint64_t*)(p + 0+0*stride)=
403         *(uint64_t*)(p + 8+0*stride)=
404         *(uint64_t*)(p + 0+1*stride)=
405         *(uint64_t*)(p + 8+1*stride)=
406         *(uint64_t*)(p + 0+2*stride)=
407         *(uint64_t*)(p + 8+2*stride)=
408         *(uint64_t*)(p + 0+3*stride)=
409         *(uint64_t*)(p + 8+3*stride)= size==4 ? val*0x0100000001ULL : val*0x0101010101010101ULL;
410     }else
411         assert(0);
412 }
413
414 static inline void fill_caches(H264Context *h, int mb_type, int for_deblock){
415     MpegEncContext * const s = &h->s;
416     const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
417     int topleft_xy, top_xy, topright_xy, left_xy[2];
418     int topleft_type, top_type, topright_type, left_type[2];
419     int left_block[4];
420     int i;
421
422     //wow what a mess, why didnt they simplify the interlacing&intra stuff, i cant imagine that these complex rules are worth it 
423     
424     if(h->sps.mb_aff){
425     //FIXME
426         topleft_xy = 0; /* avoid warning */
427         top_xy = 0; /* avoid warning */
428         topright_xy = 0; /* avoid warning */
429     }else{
430         topleft_xy = mb_xy-1 - s->mb_stride;
431         top_xy     = mb_xy   - s->mb_stride;
432         topright_xy= mb_xy+1 - s->mb_stride;
433         left_xy[0]   = mb_xy-1;
434         left_xy[1]   = mb_xy-1;
435         left_block[0]= 0;
436         left_block[1]= 1;
437         left_block[2]= 2;
438         left_block[3]= 3;
439     }
440
441     if(for_deblock){
442         topleft_type = h->slice_table[topleft_xy ] < 255 ? s->current_picture.mb_type[topleft_xy] : 0;
443         top_type     = h->slice_table[top_xy     ] < 255 ? s->current_picture.mb_type[top_xy]     : 0;
444         topright_type= h->slice_table[topright_xy] < 255 ? s->current_picture.mb_type[topright_xy]: 0;
445         left_type[0] = h->slice_table[left_xy[0] ] < 255 ? s->current_picture.mb_type[left_xy[0]] : 0;
446         left_type[1] = h->slice_table[left_xy[1] ] < 255 ? s->current_picture.mb_type[left_xy[1]] : 0;
447     }else{
448         topleft_type = h->slice_table[topleft_xy ] == h->slice_num ? s->current_picture.mb_type[topleft_xy] : 0;
449         top_type     = h->slice_table[top_xy     ] == h->slice_num ? s->current_picture.mb_type[top_xy]     : 0;
450         topright_type= h->slice_table[topright_xy] == h->slice_num ? s->current_picture.mb_type[topright_xy]: 0;
451         left_type[0] = h->slice_table[left_xy[0] ] == h->slice_num ? s->current_picture.mb_type[left_xy[0]] : 0;
452         left_type[1] = h->slice_table[left_xy[1] ] == h->slice_num ? s->current_picture.mb_type[left_xy[1]] : 0;
453     }
454
455     if(IS_INTRA(mb_type)){
456         h->topleft_samples_available= 
457         h->top_samples_available= 
458         h->left_samples_available= 0xFFFF;
459         h->topright_samples_available= 0xEEEA;
460
461         if(!IS_INTRA(top_type) && (top_type==0 || h->pps.constrained_intra_pred)){
462             h->topleft_samples_available= 0xB3FF;
463             h->top_samples_available= 0x33FF;
464             h->topright_samples_available= 0x26EA;
465         }
466         for(i=0; i<2; i++){
467             if(!IS_INTRA(left_type[i]) && (left_type[i]==0 || h->pps.constrained_intra_pred)){
468                 h->topleft_samples_available&= 0xDF5F;
469                 h->left_samples_available&= 0x5F5F;
470             }
471         }
472         
473         if(!IS_INTRA(topleft_type) && (topleft_type==0 || h->pps.constrained_intra_pred))
474             h->topleft_samples_available&= 0x7FFF;
475         
476         if(!IS_INTRA(topright_type) && (topright_type==0 || h->pps.constrained_intra_pred))
477             h->topright_samples_available&= 0xFBFF;
478     
479         if(IS_INTRA4x4(mb_type)){
480             if(IS_INTRA4x4(top_type)){
481                 h->intra4x4_pred_mode_cache[4+8*0]= h->intra4x4_pred_mode[top_xy][4];
482                 h->intra4x4_pred_mode_cache[5+8*0]= h->intra4x4_pred_mode[top_xy][5];
483                 h->intra4x4_pred_mode_cache[6+8*0]= h->intra4x4_pred_mode[top_xy][6];
484                 h->intra4x4_pred_mode_cache[7+8*0]= h->intra4x4_pred_mode[top_xy][3];
485             }else{
486                 int pred;
487                 if(!top_type || (IS_INTER(top_type) && h->pps.constrained_intra_pred))
488                     pred= -1;
489                 else{
490                     pred= 2;
491                 }
492                 h->intra4x4_pred_mode_cache[4+8*0]=
493                 h->intra4x4_pred_mode_cache[5+8*0]=
494                 h->intra4x4_pred_mode_cache[6+8*0]=
495                 h->intra4x4_pred_mode_cache[7+8*0]= pred;
496             }
497             for(i=0; i<2; i++){
498                 if(IS_INTRA4x4(left_type[i])){
499                     h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[0+2*i]];
500                     h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[1+2*i]];
501                 }else{
502                     int pred;
503                     if(!left_type[i] || (IS_INTER(left_type[i]) && h->pps.constrained_intra_pred))
504                         pred= -1;
505                     else{
506                         pred= 2;
507                     }
508                     h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]=
509                     h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= pred;
510                 }
511             }
512         }
513     }
514     
515     
516 /*
517 0 . T T. T T T T 
518 1 L . .L . . . . 
519 2 L . .L . . . . 
520 3 . T TL . . . . 
521 4 L . .L . . . . 
522 5 L . .. . . . . 
523 */
524 //FIXME constraint_intra_pred & partitioning & nnz (lets hope this is just a typo in the spec)
525     if(top_type){
526         h->non_zero_count_cache[4+8*0]= h->non_zero_count[top_xy][0];
527         h->non_zero_count_cache[5+8*0]= h->non_zero_count[top_xy][1];
528         h->non_zero_count_cache[6+8*0]= h->non_zero_count[top_xy][2];
529         h->non_zero_count_cache[7+8*0]= h->non_zero_count[top_xy][3];
530     
531         h->non_zero_count_cache[1+8*0]= h->non_zero_count[top_xy][7];
532         h->non_zero_count_cache[2+8*0]= h->non_zero_count[top_xy][8];
533     
534         h->non_zero_count_cache[1+8*3]= h->non_zero_count[top_xy][10];
535         h->non_zero_count_cache[2+8*3]= h->non_zero_count[top_xy][11];
536         
537         h->top_cbp= h->cbp_table[top_xy];
538     }else{
539         h->non_zero_count_cache[4+8*0]=      
540         h->non_zero_count_cache[5+8*0]=
541         h->non_zero_count_cache[6+8*0]=
542         h->non_zero_count_cache[7+8*0]=
543     
544         h->non_zero_count_cache[1+8*0]=
545         h->non_zero_count_cache[2+8*0]=
546     
547         h->non_zero_count_cache[1+8*3]=
548         h->non_zero_count_cache[2+8*3]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
549         
550         if(IS_INTRA(mb_type)) h->top_cbp= 0x1C0;
551         else                  h->top_cbp= 0;
552     }
553     
554     if(left_type[0]){
555         h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][6];
556         h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][5];
557         h->non_zero_count_cache[0+8*1]= h->non_zero_count[left_xy[0]][9]; //FIXME left_block
558         h->non_zero_count_cache[0+8*4]= h->non_zero_count[left_xy[0]][12];
559         h->left_cbp= h->cbp_table[left_xy[0]]; //FIXME interlacing
560     }else{
561         h->non_zero_count_cache[3+8*1]= 
562         h->non_zero_count_cache[3+8*2]= 
563         h->non_zero_count_cache[0+8*1]= 
564         h->non_zero_count_cache[0+8*4]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
565         
566         if(IS_INTRA(mb_type)) h->left_cbp= 0x1C0;//FIXME interlacing
567         else                  h->left_cbp= 0;
568     }
569     
570     if(left_type[1]){
571         h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[1]][4];
572         h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[1]][3];
573         h->non_zero_count_cache[0+8*2]= h->non_zero_count[left_xy[1]][8];
574         h->non_zero_count_cache[0+8*5]= h->non_zero_count[left_xy[1]][11];
575     }else{
576         h->non_zero_count_cache[3+8*3]= 
577         h->non_zero_count_cache[3+8*4]= 
578         h->non_zero_count_cache[0+8*2]= 
579         h->non_zero_count_cache[0+8*5]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
580     }
581     
582 #if 1
583     //FIXME direct mb can skip much of this
584     if(IS_INTER(mb_type) || (IS_DIRECT(mb_type) && h->direct_spatial_mv_pred)){
585         int list;
586         for(list=0; list<2; list++){
587             if(!USES_LIST(mb_type, list) && !IS_DIRECT(mb_type) && !for_deblock){
588                 /*if(!h->mv_cache_clean[list]){
589                     memset(h->mv_cache [list],  0, 8*5*2*sizeof(int16_t)); //FIXME clean only input? clean at all?
590                     memset(h->ref_cache[list], PART_NOT_AVAILABLE, 8*5*sizeof(int8_t));
591                     h->mv_cache_clean[list]= 1;
592                 }*/
593                 continue;
594             }
595             h->mv_cache_clean[list]= 0;
596             
597             if(IS_INTER(topleft_type)){
598                 const int b_xy = h->mb2b_xy[topleft_xy] + 3 + 3*h->b_stride;
599                 const int b8_xy= h->mb2b8_xy[topleft_xy] + 1 + h->b8_stride;
600                 *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
601                 h->ref_cache[list][scan8[0] - 1 - 1*8]= s->current_picture.ref_index[list][b8_xy];
602             }else{
603                 *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= 0;
604                 h->ref_cache[list][scan8[0] - 1 - 1*8]= topleft_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
605             }
606             
607             if(IS_INTER(top_type)){
608                 const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
609                 const int b8_xy= h->mb2b8_xy[top_xy] + h->b8_stride;
610                 *(uint32_t*)h->mv_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 0];
611                 *(uint32_t*)h->mv_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 1];
612                 *(uint32_t*)h->mv_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 2];
613                 *(uint32_t*)h->mv_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 3];
614                 h->ref_cache[list][scan8[0] + 0 - 1*8]=
615                 h->ref_cache[list][scan8[0] + 1 - 1*8]= s->current_picture.ref_index[list][b8_xy + 0];
616                 h->ref_cache[list][scan8[0] + 2 - 1*8]=
617                 h->ref_cache[list][scan8[0] + 3 - 1*8]= s->current_picture.ref_index[list][b8_xy + 1];
618             }else{
619                 *(uint32_t*)h->mv_cache [list][scan8[0] + 0 - 1*8]= 
620                 *(uint32_t*)h->mv_cache [list][scan8[0] + 1 - 1*8]= 
621                 *(uint32_t*)h->mv_cache [list][scan8[0] + 2 - 1*8]= 
622                 *(uint32_t*)h->mv_cache [list][scan8[0] + 3 - 1*8]= 0;
623                 *(uint32_t*)&h->ref_cache[list][scan8[0] + 0 - 1*8]= ((top_type ? LIST_NOT_USED : PART_NOT_AVAILABLE)&0xFF)*0x01010101;
624             }
625
626             if(IS_INTER(topright_type)){
627                 const int b_xy= h->mb2b_xy[topright_xy] + 3*h->b_stride;
628                 const int b8_xy= h->mb2b8_xy[topright_xy] + h->b8_stride;
629                 *(uint32_t*)h->mv_cache[list][scan8[0] + 4 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
630                 h->ref_cache[list][scan8[0] + 4 - 1*8]= s->current_picture.ref_index[list][b8_xy];
631             }else{
632                 *(uint32_t*)h->mv_cache [list][scan8[0] + 4 - 1*8]= 0;
633                 h->ref_cache[list][scan8[0] + 4 - 1*8]= topright_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
634             }
635             
636             //FIXME unify cleanup or sth
637             if(IS_INTER(left_type[0])){
638                 const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
639                 const int b8_xy= h->mb2b8_xy[left_xy[0]] + 1;
640                 *(uint32_t*)h->mv_cache[list][scan8[0] - 1 + 0*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[0]];
641                 *(uint32_t*)h->mv_cache[list][scan8[0] - 1 + 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[1]];
642                 h->ref_cache[list][scan8[0] - 1 + 0*8]= 
643                 h->ref_cache[list][scan8[0] - 1 + 1*8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[0]>>1)];
644             }else{
645                 *(uint32_t*)h->mv_cache [list][scan8[0] - 1 + 0*8]=
646                 *(uint32_t*)h->mv_cache [list][scan8[0] - 1 + 1*8]= 0;
647                 h->ref_cache[list][scan8[0] - 1 + 0*8]=
648                 h->ref_cache[list][scan8[0] - 1 + 1*8]= left_type[0] ? LIST_NOT_USED : PART_NOT_AVAILABLE;
649             }
650             
651             if(IS_INTER(left_type[1])){
652                 const int b_xy= h->mb2b_xy[left_xy[1]] + 3;
653                 const int b8_xy= h->mb2b8_xy[left_xy[1]] + 1;
654                 *(uint32_t*)h->mv_cache[list][scan8[0] - 1 + 2*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[2]];
655                 *(uint32_t*)h->mv_cache[list][scan8[0] - 1 + 3*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[3]];
656                 h->ref_cache[list][scan8[0] - 1 + 2*8]= 
657                 h->ref_cache[list][scan8[0] - 1 + 3*8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[2]>>1)];
658             }else{
659                 *(uint32_t*)h->mv_cache [list][scan8[0] - 1 + 2*8]=
660                 *(uint32_t*)h->mv_cache [list][scan8[0] - 1 + 3*8]= 0;
661                 h->ref_cache[list][scan8[0] - 1 + 2*8]=
662                 h->ref_cache[list][scan8[0] - 1 + 3*8]= left_type[0] ? LIST_NOT_USED : PART_NOT_AVAILABLE;
663             }
664
665             if(for_deblock)
666                 continue;
667
668             h->ref_cache[list][scan8[5 ]+1] = 
669             h->ref_cache[list][scan8[7 ]+1] = 
670             h->ref_cache[list][scan8[13]+1] =  //FIXME remove past 3 (init somewher else)
671             h->ref_cache[list][scan8[4 ]] = 
672             h->ref_cache[list][scan8[12]] = PART_NOT_AVAILABLE;
673             *(uint32_t*)h->mv_cache [list][scan8[5 ]+1]=
674             *(uint32_t*)h->mv_cache [list][scan8[7 ]+1]=
675             *(uint32_t*)h->mv_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewher else)
676             *(uint32_t*)h->mv_cache [list][scan8[4 ]]=
677             *(uint32_t*)h->mv_cache [list][scan8[12]]= 0;
678
679             if( h->pps.cabac ) {
680                 /* XXX beurk, Load mvd */
681                 if(IS_INTER(topleft_type)){
682                     const int b_xy = h->mb2b_xy[topleft_xy] + 3 + 3*h->b_stride;
683                     *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy];
684                 }else{
685                     *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 - 1*8]= 0;
686                 }
687
688                 if(IS_INTER(top_type)){
689                     const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
690                     *(uint32_t*)h->mvd_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 0];
691                     *(uint32_t*)h->mvd_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 1];
692                     *(uint32_t*)h->mvd_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 2];
693                     *(uint32_t*)h->mvd_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 3];
694                 }else{
695                     *(uint32_t*)h->mvd_cache [list][scan8[0] + 0 - 1*8]= 
696                     *(uint32_t*)h->mvd_cache [list][scan8[0] + 1 - 1*8]= 
697                     *(uint32_t*)h->mvd_cache [list][scan8[0] + 2 - 1*8]= 
698                     *(uint32_t*)h->mvd_cache [list][scan8[0] + 3 - 1*8]= 0;
699                 }
700                 if(IS_INTER(left_type[0])){
701                     const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
702                     *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 0*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[0]];
703                     *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[1]];
704                 }else{
705                     *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 0*8]=
706                     *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 1*8]= 0;
707                 }
708                 if(IS_INTER(left_type[1])){
709                     const int b_xy= h->mb2b_xy[left_xy[1]] + 3;
710                     *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 2*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[2]];
711                     *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 3*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[3]];
712                 }else{
713                     *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 2*8]=
714                     *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 3*8]= 0;
715                 }
716                 *(uint32_t*)h->mvd_cache [list][scan8[5 ]+1]=
717                 *(uint32_t*)h->mvd_cache [list][scan8[7 ]+1]=
718                 *(uint32_t*)h->mvd_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewher else)
719                 *(uint32_t*)h->mvd_cache [list][scan8[4 ]]=
720                 *(uint32_t*)h->mvd_cache [list][scan8[12]]= 0;
721
722                 if(h->slice_type == B_TYPE){
723                     fill_rectangle(&h->direct_cache[scan8[0]], 4, 4, 8, 0, 1);
724
725                     if(IS_DIRECT(top_type)){
726                         *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0x01010101;
727                     }else if(IS_8X8(top_type)){
728                         int b8_xy = h->mb2b8_xy[top_xy] + h->b8_stride;
729                         h->direct_cache[scan8[0] + 0 - 1*8]= h->direct_table[b8_xy];
730                         h->direct_cache[scan8[0] + 2 - 1*8]= h->direct_table[b8_xy + 1];
731                     }else{
732                         *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0;
733                     }
734                     
735                     //FIXME interlacing
736                     if(IS_DIRECT(left_type[0])){
737                         h->direct_cache[scan8[0] - 1 + 0*8]=
738                         h->direct_cache[scan8[0] - 1 + 2*8]= 1;
739                     }else if(IS_8X8(left_type[0])){
740                         int b8_xy = h->mb2b8_xy[left_xy[0]] + 1;
741                         h->direct_cache[scan8[0] - 1 + 0*8]= h->direct_table[b8_xy];
742                         h->direct_cache[scan8[0] - 1 + 2*8]= h->direct_table[b8_xy + h->b8_stride];
743                     }else{
744                         h->direct_cache[scan8[0] - 1 + 0*8]=
745                         h->direct_cache[scan8[0] - 1 + 2*8]= 0;
746                     }
747                 }
748             }
749         }
750     }
751 #endif
752 }
753
754 static inline void write_back_intra_pred_mode(H264Context *h){
755     MpegEncContext * const s = &h->s;
756     const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
757
758     h->intra4x4_pred_mode[mb_xy][0]= h->intra4x4_pred_mode_cache[7+8*1];
759     h->intra4x4_pred_mode[mb_xy][1]= h->intra4x4_pred_mode_cache[7+8*2];
760     h->intra4x4_pred_mode[mb_xy][2]= h->intra4x4_pred_mode_cache[7+8*3];
761     h->intra4x4_pred_mode[mb_xy][3]= h->intra4x4_pred_mode_cache[7+8*4];
762     h->intra4x4_pred_mode[mb_xy][4]= h->intra4x4_pred_mode_cache[4+8*4];
763     h->intra4x4_pred_mode[mb_xy][5]= h->intra4x4_pred_mode_cache[5+8*4];
764     h->intra4x4_pred_mode[mb_xy][6]= h->intra4x4_pred_mode_cache[6+8*4];
765 }
766
767 /**
768  * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
769  */
770 static inline int check_intra4x4_pred_mode(H264Context *h){
771     MpegEncContext * const s = &h->s;
772     static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
773     static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
774     int i;
775     
776     if(!(h->top_samples_available&0x8000)){
777         for(i=0; i<4; i++){
778             int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
779             if(status<0){
780                 av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
781                 return -1;
782             } else if(status){
783                 h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
784             }
785         }
786     }
787     
788     if(!(h->left_samples_available&0x8000)){
789         for(i=0; i<4; i++){
790             int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
791             if(status<0){
792                 av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
793                 return -1;
794             } else if(status){
795                 h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
796             }
797         }
798     }
799
800     return 0;
801 } //FIXME cleanup like next
802
803 /**
804  * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
805  */
806 static inline int check_intra_pred_mode(H264Context *h, int mode){
807     MpegEncContext * const s = &h->s;
808     static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
809     static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
810     
811     if(mode < 0 || mode > 6) {
812         av_log(h->s.avctx, AV_LOG_ERROR, "out of range intra chroma pred mode at %d %d\n", s->mb_x, s->mb_y);
813         return -1;
814     }
815     
816     if(!(h->top_samples_available&0x8000)){
817         mode= top[ mode ];
818         if(mode<0){
819             av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
820             return -1;
821         }
822     }
823     
824     if(!(h->left_samples_available&0x8000)){
825         mode= left[ mode ];
826         if(mode<0){
827             av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
828             return -1;
829         } 
830     }
831
832     return mode;
833 }
834
835 /**
836  * gets the predicted intra4x4 prediction mode.
837  */
838 static inline int pred_intra_mode(H264Context *h, int n){
839     const int index8= scan8[n];
840     const int left= h->intra4x4_pred_mode_cache[index8 - 1];
841     const int top = h->intra4x4_pred_mode_cache[index8 - 8];
842     const int min= FFMIN(left, top);
843
844     tprintf("mode:%d %d min:%d\n", left ,top, min);
845
846     if(min<0) return DC_PRED;
847     else      return min;
848 }
849
850 static inline void write_back_non_zero_count(H264Context *h){
851     MpegEncContext * const s = &h->s;
852     const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
853
854     h->non_zero_count[mb_xy][0]= h->non_zero_count_cache[4+8*4];
855     h->non_zero_count[mb_xy][1]= h->non_zero_count_cache[5+8*4];
856     h->non_zero_count[mb_xy][2]= h->non_zero_count_cache[6+8*4];
857     h->non_zero_count[mb_xy][3]= h->non_zero_count_cache[7+8*4];
858     h->non_zero_count[mb_xy][4]= h->non_zero_count_cache[7+8*3];
859     h->non_zero_count[mb_xy][5]= h->non_zero_count_cache[7+8*2];
860     h->non_zero_count[mb_xy][6]= h->non_zero_count_cache[7+8*1];
861     
862     h->non_zero_count[mb_xy][7]= h->non_zero_count_cache[1+8*2];
863     h->non_zero_count[mb_xy][8]= h->non_zero_count_cache[2+8*2];
864     h->non_zero_count[mb_xy][9]= h->non_zero_count_cache[2+8*1];
865
866     h->non_zero_count[mb_xy][10]=h->non_zero_count_cache[1+8*5];
867     h->non_zero_count[mb_xy][11]=h->non_zero_count_cache[2+8*5];
868     h->non_zero_count[mb_xy][12]=h->non_zero_count_cache[2+8*4];
869 }
870
871 /**
872  * gets the predicted number of non zero coefficients.
873  * @param n block index
874  */
875 static inline int pred_non_zero_count(H264Context *h, int n){
876     const int index8= scan8[n];
877     const int left= h->non_zero_count_cache[index8 - 1];
878     const int top = h->non_zero_count_cache[index8 - 8];
879     int i= left + top;
880     
881     if(i<64) i= (i+1)>>1;
882
883     tprintf("pred_nnz L%X T%X n%d s%d P%X\n", left, top, n, scan8[n], i&31);
884
885     return i&31;
886 }
887
888 static inline int fetch_diagonal_mv(H264Context *h, const int16_t **C, int i, int list, int part_width){
889     const int topright_ref= h->ref_cache[list][ i - 8 + part_width ];
890
891     if(topright_ref != PART_NOT_AVAILABLE){
892         *C= h->mv_cache[list][ i - 8 + part_width ];
893         return topright_ref;
894     }else{
895         tprintf("topright MV not available\n");
896
897         *C= h->mv_cache[list][ i - 8 - 1 ];
898         return h->ref_cache[list][ i - 8 - 1 ];
899     }
900 }
901
902 /**
903  * gets the predicted MV.
904  * @param n the block index
905  * @param part_width the width of the partition (4, 8,16) -> (1, 2, 4)
906  * @param mx the x component of the predicted motion vector
907  * @param my the y component of the predicted motion vector
908  */
909 static inline void pred_motion(H264Context * const h, int n, int part_width, int list, int ref, int * const mx, int * const my){
910     const int index8= scan8[n];
911     const int top_ref=      h->ref_cache[list][ index8 - 8 ];
912     const int left_ref=     h->ref_cache[list][ index8 - 1 ];
913     const int16_t * const A= h->mv_cache[list][ index8 - 1 ];
914     const int16_t * const B= h->mv_cache[list][ index8 - 8 ];
915     const int16_t * C;
916     int diagonal_ref, match_count;
917
918     assert(part_width==1 || part_width==2 || part_width==4);
919
920 /* mv_cache
921   B . . A T T T T 
922   U . . L . . , .
923   U . . L . . . .
924   U . . L . . , .
925   . . . L . . . .
926 */
927
928     diagonal_ref= fetch_diagonal_mv(h, &C, index8, list, part_width);
929     match_count= (diagonal_ref==ref) + (top_ref==ref) + (left_ref==ref);
930     tprintf("pred_motion match_count=%d\n", match_count);
931     if(match_count > 1){ //most common
932         *mx= mid_pred(A[0], B[0], C[0]);
933         *my= mid_pred(A[1], B[1], C[1]);
934     }else if(match_count==1){
935         if(left_ref==ref){
936             *mx= A[0];
937             *my= A[1];        
938         }else if(top_ref==ref){
939             *mx= B[0];
940             *my= B[1];        
941         }else{
942             *mx= C[0];
943             *my= C[1];        
944         }
945     }else{
946         if(top_ref == PART_NOT_AVAILABLE && diagonal_ref == PART_NOT_AVAILABLE && left_ref != PART_NOT_AVAILABLE){
947             *mx= A[0];
948             *my= A[1];        
949         }else{
950             *mx= mid_pred(A[0], B[0], C[0]);
951             *my= mid_pred(A[1], B[1], C[1]);
952         }
953     }
954         
955     tprintf("pred_motion (%2d %2d %2d) (%2d %2d %2d) (%2d %2d %2d) -> (%2d %2d %2d) at %2d %2d %d list %d\n", top_ref, B[0], B[1],                    diagonal_ref, C[0], C[1], left_ref, A[0], A[1], ref, *mx, *my, h->s.mb_x, h->s.mb_y, n, list);
956 }
957
958 /**
959  * gets the directionally predicted 16x8 MV.
960  * @param n the block index
961  * @param mx the x component of the predicted motion vector
962  * @param my the y component of the predicted motion vector
963  */
964 static inline void pred_16x8_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
965     if(n==0){
966         const int top_ref=      h->ref_cache[list][ scan8[0] - 8 ];
967         const int16_t * const B= h->mv_cache[list][ scan8[0] - 8 ];
968
969         tprintf("pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d\n", top_ref, B[0], B[1], h->s.mb_x, h->s.mb_y, n, list);
970         
971         if(top_ref == ref){
972             *mx= B[0];
973             *my= B[1];
974             return;
975         }
976     }else{
977         const int left_ref=     h->ref_cache[list][ scan8[8] - 1 ];
978         const int16_t * const A= h->mv_cache[list][ scan8[8] - 1 ];
979         
980         tprintf("pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d\n", left_ref, A[0], A[1], h->s.mb_x, h->s.mb_y, n, list);
981
982         if(left_ref == ref){
983             *mx= A[0];
984             *my= A[1];
985             return;
986         }
987     }
988
989     //RARE
990     pred_motion(h, n, 4, list, ref, mx, my);
991 }
992
993 /**
994  * gets the directionally predicted 8x16 MV.
995  * @param n the block index
996  * @param mx the x component of the predicted motion vector
997  * @param my the y component of the predicted motion vector
998  */
999 static inline void pred_8x16_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
1000     if(n==0){
1001         const int left_ref=      h->ref_cache[list][ scan8[0] - 1 ];
1002         const int16_t * const A=  h->mv_cache[list][ scan8[0] - 1 ];
1003         
1004         tprintf("pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d\n", left_ref, A[0], A[1], h->s.mb_x, h->s.mb_y, n, list);
1005
1006         if(left_ref == ref){
1007             *mx= A[0];
1008             *my= A[1];
1009             return;
1010         }
1011     }else{
1012         const int16_t * C;
1013         int diagonal_ref;
1014
1015         diagonal_ref= fetch_diagonal_mv(h, &C, scan8[4], list, 2);
1016         
1017         tprintf("pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d\n", diagonal_ref, C[0], C[1], h->s.mb_x, h->s.mb_y, n, list);
1018
1019         if(diagonal_ref == ref){ 
1020             *mx= C[0];
1021             *my= C[1];
1022             return;
1023         }
1024     }
1025
1026     //RARE
1027     pred_motion(h, n, 2, list, ref, mx, my);
1028 }
1029
1030 static inline void pred_pskip_motion(H264Context * const h, int * const mx, int * const my){
1031     const int top_ref = h->ref_cache[0][ scan8[0] - 8 ];
1032     const int left_ref= h->ref_cache[0][ scan8[0] - 1 ];
1033
1034     tprintf("pred_pskip: (%d) (%d) at %2d %2d\n", top_ref, left_ref, h->s.mb_x, h->s.mb_y);
1035
1036     if(top_ref == PART_NOT_AVAILABLE || left_ref == PART_NOT_AVAILABLE
1037        || (top_ref == 0  && *(uint32_t*)h->mv_cache[0][ scan8[0] - 8 ] == 0)
1038        || (left_ref == 0 && *(uint32_t*)h->mv_cache[0][ scan8[0] - 1 ] == 0)){
1039        
1040         *mx = *my = 0;
1041         return;
1042     }
1043         
1044     pred_motion(h, 0, 4, 0, 0, mx, my);
1045
1046     return;
1047 }
1048
1049 static inline void direct_dist_scale_factor(H264Context * const h){
1050     const int poc = h->s.current_picture_ptr->poc;
1051     const int poc1 = h->ref_list[1][0].poc;
1052     int i;
1053     for(i=0; i<h->ref_count[0]; i++){
1054         int poc0 = h->ref_list[0][i].poc;
1055         int td = clip(poc1 - poc0, -128, 127);
1056         if(td == 0 /* FIXME || pic0 is a long-term ref */){
1057             h->dist_scale_factor[i] = 256;
1058         }else{
1059             int tb = clip(poc - poc0, -128, 127);
1060             int tx = (16384 + (ABS(td) >> 1)) / td;
1061             h->dist_scale_factor[i] = clip((tb*tx + 32) >> 6, -1024, 1023);
1062         }
1063     }
1064 }
1065 static inline void direct_ref_list_init(H264Context * const h){
1066     MpegEncContext * const s = &h->s;
1067     Picture * const ref1 = &h->ref_list[1][0];
1068     Picture * const cur = s->current_picture_ptr;
1069     int list, i, j;
1070     if(cur->pict_type == I_TYPE)
1071         cur->ref_count[0] = 0;
1072     if(cur->pict_type != B_TYPE)
1073         cur->ref_count[1] = 0;
1074     for(list=0; list<2; list++){
1075         cur->ref_count[list] = h->ref_count[list];
1076         for(j=0; j<h->ref_count[list]; j++)
1077             cur->ref_poc[list][j] = h->ref_list[list][j].poc;
1078     }
1079     if(cur->pict_type != B_TYPE || h->direct_spatial_mv_pred)
1080         return;
1081     for(list=0; list<2; list++){
1082         for(i=0; i<ref1->ref_count[list]; i++){
1083             const int poc = ref1->ref_poc[list][i];
1084             h->map_col_to_list0[list][i] = PART_NOT_AVAILABLE;
1085             for(j=0; j<h->ref_count[list]; j++)
1086                 if(h->ref_list[list][j].poc == poc){
1087                     h->map_col_to_list0[list][i] = j;
1088                     break;
1089                 }
1090         }
1091     }
1092 }
1093
1094 static inline void pred_direct_motion(H264Context * const h, int *mb_type){
1095     MpegEncContext * const s = &h->s;
1096     const int mb_xy =   s->mb_x +   s->mb_y*s->mb_stride;
1097     const int b8_xy = 2*s->mb_x + 2*s->mb_y*h->b8_stride;
1098     const int b4_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
1099     const int mb_type_col = h->ref_list[1][0].mb_type[mb_xy];
1100     const int16_t (*l1mv0)[2] = (const int16_t (*)[2]) &h->ref_list[1][0].motion_val[0][b4_xy];
1101     const int8_t *l1ref0 = &h->ref_list[1][0].ref_index[0][b8_xy];
1102     const int8_t *l1ref1 = &h->ref_list[1][0].ref_index[1][b8_xy];
1103     const int is_b8x8 = IS_8X8(*mb_type);
1104     int sub_mb_type;
1105     int i8, i4;
1106
1107     if(IS_8X8(mb_type_col) && !h->sps.direct_8x8_inference_flag){
1108         /* FIXME save sub mb types from previous frames (or derive from MVs)
1109          * so we know exactly what block size to use */
1110         sub_mb_type = MB_TYPE_8x8|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_4x4 */
1111         *mb_type =    MB_TYPE_8x8|MB_TYPE_L0L1;
1112     }else if(!is_b8x8 && (IS_16X16(mb_type_col) || IS_INTRA(mb_type_col))){
1113         sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
1114         *mb_type =    MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_16x16 */
1115     }else{
1116         sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
1117         *mb_type =    MB_TYPE_8x8|MB_TYPE_L0L1;
1118     }
1119     if(!is_b8x8)
1120         *mb_type |= MB_TYPE_DIRECT2;
1121
1122     tprintf("mb_type = %08x, sub_mb_type = %08x, is_b8x8 = %d, mb_type_col = %08x\n", *mb_type, sub_mb_type, is_b8x8, mb_type_col);
1123     
1124     if(h->direct_spatial_mv_pred){
1125         int ref[2];
1126         int mv[2][2];
1127         int list;
1128
1129         /* ref = min(neighbors) */
1130         for(list=0; list<2; list++){
1131             int refa = h->ref_cache[list][scan8[0] - 1];
1132             int refb = h->ref_cache[list][scan8[0] - 8];
1133             int refc = h->ref_cache[list][scan8[0] - 8 + 4];
1134             if(refc == -2)
1135                 refc = h->ref_cache[list][scan8[0] - 8 - 1];
1136             ref[list] = refa;
1137             if(ref[list] < 0 || (refb < ref[list] && refb >= 0))
1138                 ref[list] = refb;
1139             if(ref[list] < 0 || (refc < ref[list] && refc >= 0))
1140                 ref[list] = refc;
1141             if(ref[list] < 0)
1142                 ref[list] = -1;
1143         }
1144
1145         if(ref[0] < 0 && ref[1] < 0){
1146             ref[0] = ref[1] = 0;
1147             mv[0][0] = mv[0][1] =
1148             mv[1][0] = mv[1][1] = 0;
1149         }else{
1150             for(list=0; list<2; list++){
1151                 if(ref[list] >= 0)
1152                     pred_motion(h, 0, 4, list, ref[list], &mv[list][0], &mv[list][1]);
1153                 else
1154                     mv[list][0] = mv[list][1] = 0;
1155             }
1156         }
1157
1158         if(ref[1] < 0){
1159             *mb_type &= ~MB_TYPE_P0L1;
1160             sub_mb_type &= ~MB_TYPE_P0L1;
1161         }else if(ref[0] < 0){
1162             *mb_type &= ~MB_TYPE_P0L0;
1163             sub_mb_type &= ~MB_TYPE_P0L0;
1164         }
1165
1166         if(IS_16X16(*mb_type)){
1167             fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref[0], 1);
1168             fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, ref[1], 1);
1169             if(!IS_INTRA(mb_type_col) && l1ref0[0] == 0 &&
1170                 ABS(l1mv0[0][0]) <= 1 && ABS(l1mv0[0][1]) <= 1){
1171                 if(ref[0] > 0)
1172                     fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mv[0][0],mv[0][1]), 4);
1173                 else
1174                     fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, 0, 4);
1175                 if(ref[1] > 0)
1176                     fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, pack16to32(mv[1][0],mv[1][1]), 4);
1177                 else
1178                     fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, 0, 4);
1179             }else{
1180                 fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mv[0][0],mv[0][1]), 4);
1181                 fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, pack16to32(mv[1][0],mv[1][1]), 4);
1182             }
1183         }else{
1184             for(i8=0; i8<4; i8++){
1185                 const int x8 = i8&1;
1186                 const int y8 = i8>>1;
1187     
1188                 if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1189                     continue;
1190                 h->sub_mb_type[i8] = sub_mb_type;
1191     
1192                 fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mv[0][0],mv[0][1]), 4);
1193                 fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mv[1][0],mv[1][1]), 4);
1194                 fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref[0], 1);
1195                 fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, ref[1], 1);
1196     
1197                 /* col_zero_flag */
1198                 if(!IS_INTRA(mb_type_col) && l1ref0[x8 + y8*h->b8_stride] == 0){
1199                     for(i4=0; i4<4; i4++){
1200                         const int16_t *mv_col = l1mv0[x8*2 + (i4&1) + (y8*2 + (i4>>1))*h->b_stride];
1201                         if(ABS(mv_col[0]) <= 1 && ABS(mv_col[1]) <= 1){
1202                             if(ref[0] == 0)
1203                                 *(uint32_t*)h->mv_cache[0][scan8[i8*4+i4]] = 0;
1204                             if(ref[1] == 0)
1205                                 *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] = 0;
1206                         }
1207                     }
1208                 }
1209             }
1210         }
1211     }else{ /* direct temporal mv pred */
1212         if(IS_16X16(*mb_type)){
1213             fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, 0, 1);
1214             if(IS_INTRA(mb_type_col)){
1215                 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
1216                 fill_rectangle(&h-> mv_cache[0][scan8[0]], 4, 4, 8, 0, 4);
1217                 fill_rectangle(&h-> mv_cache[1][scan8[0]], 4, 4, 8, 0, 4);
1218             }else{
1219                 const int ref0 = l1ref0[0] >= 0 ? h->map_col_to_list0[0][l1ref0[0]]
1220                                                 : h->map_col_to_list0[1][l1ref1[0]];
1221                 assert(ref0 >= 0);
1222                 const int dist_scale_factor = h->dist_scale_factor[ref0];
1223                 const int16_t *mv_col = l1mv0[0];
1224                 int mv_l0[2];
1225                 mv_l0[0] = (dist_scale_factor * mv_col[0] + 128) >> 8;
1226                 mv_l0[1] = (dist_scale_factor * mv_col[1] + 128) >> 8;
1227                 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref0, 1);
1228                 fill_rectangle(&h-> mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mv_l0[0],mv_l0[1]), 4);
1229                 fill_rectangle(&h-> mv_cache[1][scan8[0]], 4, 4, 8, pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]), 4);
1230             }
1231         }else{
1232             for(i8=0; i8<4; i8++){
1233                 const int x8 = i8&1;
1234                 const int y8 = i8>>1;
1235                 int ref0, dist_scale_factor;
1236     
1237                 if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1238                     continue;
1239                 h->sub_mb_type[i8] = sub_mb_type;
1240                 if(IS_INTRA(mb_type_col)){
1241                     fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
1242                     fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
1243                     fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
1244                     fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
1245                     continue;
1246                 }
1247     
1248                 ref0 = l1ref0[x8 + y8*h->b8_stride];
1249                 if(ref0 >= 0)
1250                     ref0 = h->map_col_to_list0[0][ref0];
1251                 else
1252                     ref0 = h->map_col_to_list0[1][l1ref1[x8 + y8*h->b8_stride]];
1253                 assert(ref0 >= 0);
1254                 dist_scale_factor = h->dist_scale_factor[ref0];
1255     
1256                 fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
1257                 fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
1258                 for(i4=0; i4<4; i4++){
1259                     const int16_t *mv_col = l1mv0[x8*2 + (i4&1) + (y8*2 + (i4>>1))*h->b_stride];
1260                     int16_t *mv_l0 = h->mv_cache[0][scan8[i8*4+i4]];
1261                     mv_l0[0] = (dist_scale_factor * mv_col[0] + 128) >> 8;
1262                     mv_l0[1] = (dist_scale_factor * mv_col[1] + 128) >> 8;
1263                     *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] =
1264                         pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
1265                 }
1266             }
1267         }
1268     }
1269 }
1270
1271 static inline void write_back_motion(H264Context *h, int mb_type){
1272     MpegEncContext * const s = &h->s;
1273     const int b_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
1274     const int b8_xy= 2*s->mb_x + 2*s->mb_y*h->b8_stride;
1275     int list;
1276
1277     for(list=0; list<2; list++){
1278         int y;
1279         if(!USES_LIST(mb_type, list)){
1280             if(1){ //FIXME skip or never read if mb_type doesnt use it
1281                 for(y=0; y<4; y++){
1282                     *(uint64_t*)s->current_picture.motion_val[list][b_xy + 0 + y*h->b_stride]=
1283                     *(uint64_t*)s->current_picture.motion_val[list][b_xy + 2 + y*h->b_stride]= 0;
1284                 }
1285                 if( h->pps.cabac ) {
1286                     /* FIXME needed ? */
1287                     for(y=0; y<4; y++){
1288                         *(uint64_t*)h->mvd_table[list][b_xy + 0 + y*h->b_stride]=
1289                         *(uint64_t*)h->mvd_table[list][b_xy + 2 + y*h->b_stride]= 0;
1290                     }
1291                 }
1292                 for(y=0; y<2; y++){
1293                     *(uint16_t*)&s->current_picture.ref_index[list][b8_xy + y*h->b8_stride]= (LIST_NOT_USED&0xFF)*0x0101;
1294                 }
1295             }
1296             continue;
1297         }
1298         
1299         for(y=0; y<4; y++){
1300             *(uint64_t*)s->current_picture.motion_val[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mv_cache[list][scan8[0]+0 + 8*y];
1301             *(uint64_t*)s->current_picture.motion_val[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mv_cache[list][scan8[0]+2 + 8*y];
1302         }
1303         if( h->pps.cabac ) {
1304             for(y=0; y<4; y++){
1305                 *(uint64_t*)h->mvd_table[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+0 + 8*y];
1306                 *(uint64_t*)h->mvd_table[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+2 + 8*y];
1307             }
1308         }
1309         for(y=0; y<2; y++){
1310             s->current_picture.ref_index[list][b8_xy + 0 + y*h->b8_stride]= h->ref_cache[list][scan8[0]+0 + 16*y];
1311             s->current_picture.ref_index[list][b8_xy + 1 + y*h->b8_stride]= h->ref_cache[list][scan8[0]+2 + 16*y];
1312         }
1313     }
1314     
1315     if(h->slice_type == B_TYPE && h->pps.cabac){
1316         if(IS_8X8(mb_type)){
1317             h->direct_table[b8_xy+1+0*h->b8_stride] = IS_DIRECT(h->sub_mb_type[1]) ? 1 : 0;
1318             h->direct_table[b8_xy+0+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[2]) ? 1 : 0;
1319             h->direct_table[b8_xy+1+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[3]) ? 1 : 0;
1320         }
1321     }
1322 }
1323
1324 /**
1325  * Decodes a network abstraction layer unit.
1326  * @param consumed is the number of bytes used as input
1327  * @param length is the length of the array
1328  * @param dst_length is the number of decoded bytes FIXME here or a decode rbsp ttailing?
1329  * @returns decoded bytes, might be src+1 if no escapes 
1330  */
1331 static uint8_t *decode_nal(H264Context *h, uint8_t *src, int *dst_length, int *consumed, int length){
1332     int i, si, di;
1333     uint8_t *dst;
1334
1335 //    src[0]&0x80;              //forbidden bit
1336     h->nal_ref_idc= src[0]>>5;
1337     h->nal_unit_type= src[0]&0x1F;
1338
1339     src++; length--;
1340 #if 0    
1341     for(i=0; i<length; i++)
1342         printf("%2X ", src[i]);
1343 #endif
1344     for(i=0; i+1<length; i+=2){
1345         if(src[i]) continue;
1346         if(i>0 && src[i-1]==0) i--;
1347         if(i+2<length && src[i+1]==0 && src[i+2]<=3){
1348             if(src[i+2]!=3){
1349                 /* startcode, so we must be past the end */
1350                 length=i;
1351             }
1352             break;
1353         }
1354     }
1355
1356     if(i>=length-1){ //no escaped 0
1357         *dst_length= length;
1358         *consumed= length+1; //+1 for the header
1359         return src; 
1360     }
1361
1362     h->rbsp_buffer= av_fast_realloc(h->rbsp_buffer, &h->rbsp_buffer_size, length);
1363     dst= h->rbsp_buffer;
1364
1365 //printf("deoding esc\n");
1366     si=di=0;
1367     while(si<length){ 
1368         //remove escapes (very rare 1:2^22)
1369         if(si+2<length && src[si]==0 && src[si+1]==0 && src[si+2]<=3){
1370             if(src[si+2]==3){ //escape
1371                 dst[di++]= 0;
1372                 dst[di++]= 0;
1373                 si+=3;
1374                 continue;
1375             }else //next start code
1376                 break;
1377         }
1378
1379         dst[di++]= src[si++];
1380     }
1381
1382     *dst_length= di;
1383     *consumed= si + 1;//+1 for the header
1384 //FIXME store exact number of bits in the getbitcontext (its needed for decoding)
1385     return dst;
1386 }
1387
1388 #if 0
1389 /**
1390  * @param src the data which should be escaped
1391  * @param dst the target buffer, dst+1 == src is allowed as a special case
1392  * @param length the length of the src data
1393  * @param dst_length the length of the dst array
1394  * @returns length of escaped data in bytes or -1 if an error occured
1395  */
1396 static int encode_nal(H264Context *h, uint8_t *dst, uint8_t *src, int length, int dst_length){
1397     int i, escape_count, si, di;
1398     uint8_t *temp;
1399     
1400     assert(length>=0);
1401     assert(dst_length>0);
1402     
1403     dst[0]= (h->nal_ref_idc<<5) + h->nal_unit_type;
1404
1405     if(length==0) return 1;
1406
1407     escape_count= 0;
1408     for(i=0; i<length; i+=2){
1409         if(src[i]) continue;
1410         if(i>0 && src[i-1]==0) 
1411             i--;
1412         if(i+2<length && src[i+1]==0 && src[i+2]<=3){
1413             escape_count++;
1414             i+=2;
1415         }
1416     }
1417     
1418     if(escape_count==0){ 
1419         if(dst+1 != src)
1420             memcpy(dst+1, src, length);
1421         return length + 1;
1422     }
1423     
1424     if(length + escape_count + 1> dst_length)
1425         return -1;
1426
1427     //this should be damn rare (hopefully)
1428
1429     h->rbsp_buffer= av_fast_realloc(h->rbsp_buffer, &h->rbsp_buffer_size, length + escape_count);
1430     temp= h->rbsp_buffer;
1431 //printf("encoding esc\n");
1432     
1433     si= 0;
1434     di= 0;
1435     while(si < length){
1436         if(si+2<length && src[si]==0 && src[si+1]==0 && src[si+2]<=3){
1437             temp[di++]= 0; si++;
1438             temp[di++]= 0; si++;
1439             temp[di++]= 3; 
1440             temp[di++]= src[si++];
1441         }
1442         else
1443             temp[di++]= src[si++];
1444     }
1445     memcpy(dst+1, temp, length+escape_count);
1446     
1447     assert(di == length+escape_count);
1448     
1449     return di + 1;
1450 }
1451
1452 /**
1453  * write 1,10,100,1000,... for alignment, yes its exactly inverse to mpeg4
1454  */
1455 static void encode_rbsp_trailing(PutBitContext *pb){
1456     int length;
1457     put_bits(pb, 1, 1);
1458     length= (-put_bits_count(pb))&7;
1459     if(length) put_bits(pb, length, 0);
1460 }
1461 #endif
1462
1463 /**
1464  * identifies the exact end of the bitstream
1465  * @return the length of the trailing, or 0 if damaged
1466  */
1467 static int decode_rbsp_trailing(uint8_t *src){
1468     int v= *src;
1469     int r;
1470
1471     tprintf("rbsp trailing %X\n", v);
1472
1473     for(r=1; r<9; r++){
1474         if(v&1) return r;
1475         v>>=1;
1476     }
1477     return 0;
1478 }
1479
1480 /**
1481  * idct tranforms the 16 dc values and dequantize them.
1482  * @param qp quantization parameter
1483  */
1484 static void h264_luma_dc_dequant_idct_c(DCTELEM *block, int qp){
1485     const int qmul= dequant_coeff[qp][0];
1486 #define stride 16
1487     int i;
1488     int temp[16]; //FIXME check if this is a good idea
1489     static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
1490     static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
1491
1492 //memset(block, 64, 2*256);
1493 //return;
1494     for(i=0; i<4; i++){
1495         const int offset= y_offset[i];
1496         const int z0= block[offset+stride*0] + block[offset+stride*4];
1497         const int z1= block[offset+stride*0] - block[offset+stride*4];
1498         const int z2= block[offset+stride*1] - block[offset+stride*5];
1499         const int z3= block[offset+stride*1] + block[offset+stride*5];
1500
1501         temp[4*i+0]= z0+z3;
1502         temp[4*i+1]= z1+z2;
1503         temp[4*i+2]= z1-z2;
1504         temp[4*i+3]= z0-z3;
1505     }
1506
1507     for(i=0; i<4; i++){
1508         const int offset= x_offset[i];
1509         const int z0= temp[4*0+i] + temp[4*2+i];
1510         const int z1= temp[4*0+i] - temp[4*2+i];
1511         const int z2= temp[4*1+i] - temp[4*3+i];
1512         const int z3= temp[4*1+i] + temp[4*3+i];
1513
1514         block[stride*0 +offset]= ((z0 + z3)*qmul + 2)>>2; //FIXME think about merging this into decode_resdual
1515         block[stride*2 +offset]= ((z1 + z2)*qmul + 2)>>2;
1516         block[stride*8 +offset]= ((z1 - z2)*qmul + 2)>>2;
1517         block[stride*10+offset]= ((z0 - z3)*qmul + 2)>>2;
1518     }
1519 }
1520
1521 #if 0
1522 /**
1523  * dct tranforms the 16 dc values.
1524  * @param qp quantization parameter ??? FIXME
1525  */
1526 static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
1527 //    const int qmul= dequant_coeff[qp][0];
1528     int i;
1529     int temp[16]; //FIXME check if this is a good idea
1530     static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
1531     static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
1532
1533     for(i=0; i<4; i++){
1534         const int offset= y_offset[i];
1535         const int z0= block[offset+stride*0] + block[offset+stride*4];
1536         const int z1= block[offset+stride*0] - block[offset+stride*4];
1537         const int z2= block[offset+stride*1] - block[offset+stride*5];
1538         const int z3= block[offset+stride*1] + block[offset+stride*5];
1539
1540         temp[4*i+0]= z0+z3;
1541         temp[4*i+1]= z1+z2;
1542         temp[4*i+2]= z1-z2;
1543         temp[4*i+3]= z0-z3;
1544     }
1545
1546     for(i=0; i<4; i++){
1547         const int offset= x_offset[i];
1548         const int z0= temp[4*0+i] + temp[4*2+i];
1549         const int z1= temp[4*0+i] - temp[4*2+i];
1550         const int z2= temp[4*1+i] - temp[4*3+i];
1551         const int z3= temp[4*1+i] + temp[4*3+i];
1552
1553         block[stride*0 +offset]= (z0 + z3)>>1;
1554         block[stride*2 +offset]= (z1 + z2)>>1;
1555         block[stride*8 +offset]= (z1 - z2)>>1;
1556         block[stride*10+offset]= (z0 - z3)>>1;
1557     }
1558 }
1559 #endif
1560
1561 #undef xStride
1562 #undef stride
1563
1564 static void chroma_dc_dequant_idct_c(DCTELEM *block, int qp){
1565     const int qmul= dequant_coeff[qp][0];
1566     const int stride= 16*2;
1567     const int xStride= 16;
1568     int a,b,c,d,e;
1569
1570     a= block[stride*0 + xStride*0];
1571     b= block[stride*0 + xStride*1];
1572     c= block[stride*1 + xStride*0];
1573     d= block[stride*1 + xStride*1];
1574
1575     e= a-b;
1576     a= a+b;
1577     b= c-d;
1578     c= c+d;
1579
1580     block[stride*0 + xStride*0]= ((a+c)*qmul + 0)>>1;
1581     block[stride*0 + xStride*1]= ((e+b)*qmul + 0)>>1;
1582     block[stride*1 + xStride*0]= ((a-c)*qmul + 0)>>1;
1583     block[stride*1 + xStride*1]= ((e-b)*qmul + 0)>>1;
1584 }
1585
1586 #if 0
1587 static void chroma_dc_dct_c(DCTELEM *block){
1588     const int stride= 16*2;
1589     const int xStride= 16;
1590     int a,b,c,d,e;
1591
1592     a= block[stride*0 + xStride*0];
1593     b= block[stride*0 + xStride*1];
1594     c= block[stride*1 + xStride*0];
1595     d= block[stride*1 + xStride*1];
1596
1597     e= a-b;
1598     a= a+b;
1599     b= c-d;
1600     c= c+d;
1601
1602     block[stride*0 + xStride*0]= (a+c);
1603     block[stride*0 + xStride*1]= (e+b);
1604     block[stride*1 + xStride*0]= (a-c);
1605     block[stride*1 + xStride*1]= (e-b);
1606 }
1607 #endif
1608
1609 /**
1610  * gets the chroma qp.
1611  */
1612 static inline int get_chroma_qp(H264Context *h, int qscale){
1613     
1614     return chroma_qp[clip(qscale + h->pps.chroma_qp_index_offset, 0, 51)];
1615 }
1616
1617
1618 #if 0
1619 static void h264_diff_dct_c(DCTELEM *block, uint8_t *src1, uint8_t *src2, int stride){
1620     int i;
1621     //FIXME try int temp instead of block
1622     
1623     for(i=0; i<4; i++){
1624         const int d0= src1[0 + i*stride] - src2[0 + i*stride];
1625         const int d1= src1[1 + i*stride] - src2[1 + i*stride];
1626         const int d2= src1[2 + i*stride] - src2[2 + i*stride];
1627         const int d3= src1[3 + i*stride] - src2[3 + i*stride];
1628         const int z0= d0 + d3;
1629         const int z3= d0 - d3;
1630         const int z1= d1 + d2;
1631         const int z2= d1 - d2;
1632         
1633         block[0 + 4*i]=   z0 +   z1;
1634         block[1 + 4*i]= 2*z3 +   z2;
1635         block[2 + 4*i]=   z0 -   z1;
1636         block[3 + 4*i]=   z3 - 2*z2;
1637     }    
1638
1639     for(i=0; i<4; i++){
1640         const int z0= block[0*4 + i] + block[3*4 + i];
1641         const int z3= block[0*4 + i] - block[3*4 + i];
1642         const int z1= block[1*4 + i] + block[2*4 + i];
1643         const int z2= block[1*4 + i] - block[2*4 + i];
1644         
1645         block[0*4 + i]=   z0 +   z1;
1646         block[1*4 + i]= 2*z3 +   z2;
1647         block[2*4 + i]=   z0 -   z1;
1648         block[3*4 + i]=   z3 - 2*z2;
1649     }
1650 }
1651 #endif
1652
1653 //FIXME need to check that this doesnt overflow signed 32 bit for low qp, iam not sure, its very close
1654 //FIXME check that gcc inlines this (and optimizes intra & seperate_dc stuff away)
1655 static inline int quantize_c(DCTELEM *block, uint8_t *scantable, int qscale, int intra, int seperate_dc){
1656     int i;
1657     const int * const quant_table= quant_coeff[qscale];
1658     const int bias= intra ? (1<<QUANT_SHIFT)/3 : (1<<QUANT_SHIFT)/6;
1659     const unsigned int threshold1= (1<<QUANT_SHIFT) - bias - 1;
1660     const unsigned int threshold2= (threshold1<<1);
1661     int last_non_zero;
1662
1663     if(seperate_dc){
1664         if(qscale<=18){
1665             //avoid overflows
1666             const int dc_bias= intra ? (1<<(QUANT_SHIFT-2))/3 : (1<<(QUANT_SHIFT-2))/6;
1667             const unsigned int dc_threshold1= (1<<(QUANT_SHIFT-2)) - dc_bias - 1;
1668             const unsigned int dc_threshold2= (dc_threshold1<<1);
1669
1670             int level= block[0]*quant_coeff[qscale+18][0];
1671             if(((unsigned)(level+dc_threshold1))>dc_threshold2){
1672                 if(level>0){
1673                     level= (dc_bias + level)>>(QUANT_SHIFT-2);
1674                     block[0]= level;
1675                 }else{
1676                     level= (dc_bias - level)>>(QUANT_SHIFT-2);
1677                     block[0]= -level;
1678                 }
1679 //                last_non_zero = i;
1680             }else{
1681                 block[0]=0;
1682             }
1683         }else{
1684             const int dc_bias= intra ? (1<<(QUANT_SHIFT+1))/3 : (1<<(QUANT_SHIFT+1))/6;
1685             const unsigned int dc_threshold1= (1<<(QUANT_SHIFT+1)) - dc_bias - 1;
1686             const unsigned int dc_threshold2= (dc_threshold1<<1);
1687
1688             int level= block[0]*quant_table[0];
1689             if(((unsigned)(level+dc_threshold1))>dc_threshold2){
1690                 if(level>0){
1691                     level= (dc_bias + level)>>(QUANT_SHIFT+1);
1692                     block[0]= level;
1693                 }else{
1694                     level= (dc_bias - level)>>(QUANT_SHIFT+1);
1695                     block[0]= -level;
1696                 }
1697 //                last_non_zero = i;
1698             }else{
1699                 block[0]=0;
1700             }
1701         }
1702         last_non_zero= 0;
1703         i=1;
1704     }else{
1705         last_non_zero= -1;
1706         i=0;
1707     }
1708
1709     for(; i<16; i++){
1710         const int j= scantable[i];
1711         int level= block[j]*quant_table[j];
1712
1713 //        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
1714 //           || bias-level >= (1<<(QMAT_SHIFT - 3))){
1715         if(((unsigned)(level+threshold1))>threshold2){
1716             if(level>0){
1717                 level= (bias + level)>>QUANT_SHIFT;
1718                 block[j]= level;
1719             }else{
1720                 level= (bias - level)>>QUANT_SHIFT;
1721                 block[j]= -level;
1722             }
1723             last_non_zero = i;
1724         }else{
1725             block[j]=0;
1726         }
1727     }
1728
1729     return last_non_zero;
1730 }
1731
1732 static void pred4x4_vertical_c(uint8_t *src, uint8_t *topright, int stride){
1733     const uint32_t a= ((uint32_t*)(src-stride))[0];
1734     ((uint32_t*)(src+0*stride))[0]= a;
1735     ((uint32_t*)(src+1*stride))[0]= a;
1736     ((uint32_t*)(src+2*stride))[0]= a;
1737     ((uint32_t*)(src+3*stride))[0]= a;
1738 }
1739
1740 static void pred4x4_horizontal_c(uint8_t *src, uint8_t *topright, int stride){
1741     ((uint32_t*)(src+0*stride))[0]= src[-1+0*stride]*0x01010101;
1742     ((uint32_t*)(src+1*stride))[0]= src[-1+1*stride]*0x01010101;
1743     ((uint32_t*)(src+2*stride))[0]= src[-1+2*stride]*0x01010101;
1744     ((uint32_t*)(src+3*stride))[0]= src[-1+3*stride]*0x01010101;
1745 }
1746
1747 static void pred4x4_dc_c(uint8_t *src, uint8_t *topright, int stride){
1748     const int dc= (  src[-stride] + src[1-stride] + src[2-stride] + src[3-stride]
1749                    + src[-1+0*stride] + src[-1+1*stride] + src[-1+2*stride] + src[-1+3*stride] + 4) >>3;
1750     
1751     ((uint32_t*)(src+0*stride))[0]= 
1752     ((uint32_t*)(src+1*stride))[0]= 
1753     ((uint32_t*)(src+2*stride))[0]= 
1754     ((uint32_t*)(src+3*stride))[0]= dc* 0x01010101; 
1755 }
1756
1757 static void pred4x4_left_dc_c(uint8_t *src, uint8_t *topright, int stride){
1758     const int dc= (  src[-1+0*stride] + src[-1+1*stride] + src[-1+2*stride] + src[-1+3*stride] + 2) >>2;
1759     
1760     ((uint32_t*)(src+0*stride))[0]= 
1761     ((uint32_t*)(src+1*stride))[0]= 
1762     ((uint32_t*)(src+2*stride))[0]= 
1763     ((uint32_t*)(src+3*stride))[0]= dc* 0x01010101; 
1764 }
1765
1766 static void pred4x4_top_dc_c(uint8_t *src, uint8_t *topright, int stride){
1767     const int dc= (  src[-stride] + src[1-stride] + src[2-stride] + src[3-stride] + 2) >>2;
1768     
1769     ((uint32_t*)(src+0*stride))[0]= 
1770     ((uint32_t*)(src+1*stride))[0]= 
1771     ((uint32_t*)(src+2*stride))[0]= 
1772     ((uint32_t*)(src+3*stride))[0]= dc* 0x01010101; 
1773 }
1774
1775 static void pred4x4_128_dc_c(uint8_t *src, uint8_t *topright, int stride){
1776     ((uint32_t*)(src+0*stride))[0]= 
1777     ((uint32_t*)(src+1*stride))[0]= 
1778     ((uint32_t*)(src+2*stride))[0]= 
1779     ((uint32_t*)(src+3*stride))[0]= 128U*0x01010101U;
1780 }
1781
1782
1783 #define LOAD_TOP_RIGHT_EDGE\
1784     const int t4= topright[0];\
1785     const int t5= topright[1];\
1786     const int t6= topright[2];\
1787     const int t7= topright[3];\
1788
1789 #define LOAD_LEFT_EDGE\
1790     const int l0= src[-1+0*stride];\
1791     const int l1= src[-1+1*stride];\
1792     const int l2= src[-1+2*stride];\
1793     const int l3= src[-1+3*stride];\
1794
1795 #define LOAD_TOP_EDGE\
1796     const int t0= src[ 0-1*stride];\
1797     const int t1= src[ 1-1*stride];\
1798     const int t2= src[ 2-1*stride];\
1799     const int t3= src[ 3-1*stride];\
1800
1801 static void pred4x4_down_right_c(uint8_t *src, uint8_t *topright, int stride){
1802     const int lt= src[-1-1*stride];
1803     LOAD_TOP_EDGE
1804     LOAD_LEFT_EDGE
1805
1806     src[0+3*stride]=(l3 + 2*l2 + l1 + 2)>>2; 
1807     src[0+2*stride]=
1808     src[1+3*stride]=(l2 + 2*l1 + l0 + 2)>>2; 
1809     src[0+1*stride]=
1810     src[1+2*stride]=
1811     src[2+3*stride]=(l1 + 2*l0 + lt + 2)>>2; 
1812     src[0+0*stride]=
1813     src[1+1*stride]=
1814     src[2+2*stride]=
1815     src[3+3*stride]=(l0 + 2*lt + t0 + 2)>>2; 
1816     src[1+0*stride]=
1817     src[2+1*stride]=
1818     src[3+2*stride]=(lt + 2*t0 + t1 + 2)>>2;
1819     src[2+0*stride]=
1820     src[3+1*stride]=(t0 + 2*t1 + t2 + 2)>>2;
1821     src[3+0*stride]=(t1 + 2*t2 + t3 + 2)>>2;
1822 }
1823
1824 static void pred4x4_down_left_c(uint8_t *src, uint8_t *topright, int stride){
1825     LOAD_TOP_EDGE    
1826     LOAD_TOP_RIGHT_EDGE    
1827 //    LOAD_LEFT_EDGE    
1828
1829     src[0+0*stride]=(t0 + t2 + 2*t1 + 2)>>2;
1830     src[1+0*stride]=
1831     src[0+1*stride]=(t1 + t3 + 2*t2 + 2)>>2;
1832     src[2+0*stride]=
1833     src[1+1*stride]=
1834     src[0+2*stride]=(t2 + t4 + 2*t3 + 2)>>2;
1835     src[3+0*stride]=
1836     src[2+1*stride]=
1837     src[1+2*stride]=
1838     src[0+3*stride]=(t3 + t5 + 2*t4 + 2)>>2;
1839     src[3+1*stride]=
1840     src[2+2*stride]=
1841     src[1+3*stride]=(t4 + t6 + 2*t5 + 2)>>2;
1842     src[3+2*stride]=
1843     src[2+3*stride]=(t5 + t7 + 2*t6 + 2)>>2;
1844     src[3+3*stride]=(t6 + 3*t7 + 2)>>2;
1845 }
1846
1847 static void pred4x4_vertical_right_c(uint8_t *src, uint8_t *topright, int stride){
1848     const int lt= src[-1-1*stride];
1849     LOAD_TOP_EDGE    
1850     LOAD_LEFT_EDGE    
1851     const __attribute__((unused)) int unu= l3;
1852
1853     src[0+0*stride]=
1854     src[1+2*stride]=(lt + t0 + 1)>>1;
1855     src[1+0*stride]=
1856     src[2+2*stride]=(t0 + t1 + 1)>>1;
1857     src[2+0*stride]=
1858     src[3+2*stride]=(t1 + t2 + 1)>>1;
1859     src[3+0*stride]=(t2 + t3 + 1)>>1;
1860     src[0+1*stride]=
1861     src[1+3*stride]=(l0 + 2*lt + t0 + 2)>>2;
1862     src[1+1*stride]=
1863     src[2+3*stride]=(lt + 2*t0 + t1 + 2)>>2;
1864     src[2+1*stride]=
1865     src[3+3*stride]=(t0 + 2*t1 + t2 + 2)>>2;
1866     src[3+1*stride]=(t1 + 2*t2 + t3 + 2)>>2;
1867     src[0+2*stride]=(lt + 2*l0 + l1 + 2)>>2;
1868     src[0+3*stride]=(l0 + 2*l1 + l2 + 2)>>2;
1869 }
1870
1871 static void pred4x4_vertical_left_c(uint8_t *src, uint8_t *topright, int stride){
1872     LOAD_TOP_EDGE    
1873     LOAD_TOP_RIGHT_EDGE    
1874     const __attribute__((unused)) int unu= t7;
1875
1876     src[0+0*stride]=(t0 + t1 + 1)>>1;
1877     src[1+0*stride]=
1878     src[0+2*stride]=(t1 + t2 + 1)>>1;
1879     src[2+0*stride]=
1880     src[1+2*stride]=(t2 + t3 + 1)>>1;
1881     src[3+0*stride]=
1882     src[2+2*stride]=(t3 + t4+ 1)>>1;
1883     src[3+2*stride]=(t4 + t5+ 1)>>1;
1884     src[0+1*stride]=(t0 + 2*t1 + t2 + 2)>>2;
1885     src[1+1*stride]=
1886     src[0+3*stride]=(t1 + 2*t2 + t3 + 2)>>2;
1887     src[2+1*stride]=
1888     src[1+3*stride]=(t2 + 2*t3 + t4 + 2)>>2;
1889     src[3+1*stride]=
1890     src[2+3*stride]=(t3 + 2*t4 + t5 + 2)>>2;
1891     src[3+3*stride]=(t4 + 2*t5 + t6 + 2)>>2;
1892 }
1893
1894 static void pred4x4_horizontal_up_c(uint8_t *src, uint8_t *topright, int stride){
1895     LOAD_LEFT_EDGE    
1896
1897     src[0+0*stride]=(l0 + l1 + 1)>>1;
1898     src[1+0*stride]=(l0 + 2*l1 + l2 + 2)>>2;
1899     src[2+0*stride]=
1900     src[0+1*stride]=(l1 + l2 + 1)>>1;
1901     src[3+0*stride]=
1902     src[1+1*stride]=(l1 + 2*l2 + l3 + 2)>>2;
1903     src[2+1*stride]=
1904     src[0+2*stride]=(l2 + l3 + 1)>>1;
1905     src[3+1*stride]=
1906     src[1+2*stride]=(l2 + 2*l3 + l3 + 2)>>2;
1907     src[3+2*stride]=
1908     src[1+3*stride]=
1909     src[0+3*stride]=
1910     src[2+2*stride]=
1911     src[2+3*stride]=
1912     src[3+3*stride]=l3;
1913 }
1914     
1915 static void pred4x4_horizontal_down_c(uint8_t *src, uint8_t *topright, int stride){
1916     const int lt= src[-1-1*stride];
1917     LOAD_TOP_EDGE    
1918     LOAD_LEFT_EDGE    
1919     const __attribute__((unused)) int unu= t3;
1920
1921     src[0+0*stride]=
1922     src[2+1*stride]=(lt + l0 + 1)>>1;
1923     src[1+0*stride]=
1924     src[3+1*stride]=(l0 + 2*lt + t0 + 2)>>2;
1925     src[2+0*stride]=(lt + 2*t0 + t1 + 2)>>2;
1926     src[3+0*stride]=(t0 + 2*t1 + t2 + 2)>>2;
1927     src[0+1*stride]=
1928     src[2+2*stride]=(l0 + l1 + 1)>>1;
1929     src[1+1*stride]=
1930     src[3+2*stride]=(lt + 2*l0 + l1 + 2)>>2;
1931     src[0+2*stride]=
1932     src[2+3*stride]=(l1 + l2+ 1)>>1;
1933     src[1+2*stride]=
1934     src[3+3*stride]=(l0 + 2*l1 + l2 + 2)>>2;
1935     src[0+3*stride]=(l2 + l3 + 1)>>1;
1936     src[1+3*stride]=(l1 + 2*l2 + l3 + 2)>>2;
1937 }
1938
1939 static void pred16x16_vertical_c(uint8_t *src, int stride){
1940     int i;
1941     const uint32_t a= ((uint32_t*)(src-stride))[0];
1942     const uint32_t b= ((uint32_t*)(src-stride))[1];
1943     const uint32_t c= ((uint32_t*)(src-stride))[2];
1944     const uint32_t d= ((uint32_t*)(src-stride))[3];
1945     
1946     for(i=0; i<16; i++){
1947         ((uint32_t*)(src+i*stride))[0]= a;
1948         ((uint32_t*)(src+i*stride))[1]= b;
1949         ((uint32_t*)(src+i*stride))[2]= c;
1950         ((uint32_t*)(src+i*stride))[3]= d;
1951     }
1952 }
1953
1954 static void pred16x16_horizontal_c(uint8_t *src, int stride){
1955     int i;
1956
1957     for(i=0; i<16; i++){
1958         ((uint32_t*)(src+i*stride))[0]=
1959         ((uint32_t*)(src+i*stride))[1]=
1960         ((uint32_t*)(src+i*stride))[2]=
1961         ((uint32_t*)(src+i*stride))[3]= src[-1+i*stride]*0x01010101;
1962     }
1963 }
1964
1965 static void pred16x16_dc_c(uint8_t *src, int stride){
1966     int i, dc=0;
1967
1968     for(i=0;i<16; i++){
1969         dc+= src[-1+i*stride];
1970     }
1971     
1972     for(i=0;i<16; i++){
1973         dc+= src[i-stride];
1974     }
1975
1976     dc= 0x01010101*((dc + 16)>>5);
1977
1978     for(i=0; i<16; i++){
1979         ((uint32_t*)(src+i*stride))[0]=
1980         ((uint32_t*)(src+i*stride))[1]=
1981         ((uint32_t*)(src+i*stride))[2]=
1982         ((uint32_t*)(src+i*stride))[3]= dc;
1983     }
1984 }
1985
1986 static void pred16x16_left_dc_c(uint8_t *src, int stride){
1987     int i, dc=0;
1988
1989     for(i=0;i<16; i++){
1990         dc+= src[-1+i*stride];
1991     }
1992     
1993     dc= 0x01010101*((dc + 8)>>4);
1994
1995     for(i=0; i<16; i++){
1996         ((uint32_t*)(src+i*stride))[0]=
1997         ((uint32_t*)(src+i*stride))[1]=
1998         ((uint32_t*)(src+i*stride))[2]=
1999         ((uint32_t*)(src+i*stride))[3]= dc;
2000     }
2001 }
2002
2003 static void pred16x16_top_dc_c(uint8_t *src, int stride){
2004     int i, dc=0;
2005
2006     for(i=0;i<16; i++){
2007         dc+= src[i-stride];
2008     }
2009     dc= 0x01010101*((dc + 8)>>4);
2010
2011     for(i=0; i<16; i++){
2012         ((uint32_t*)(src+i*stride))[0]=
2013         ((uint32_t*)(src+i*stride))[1]=
2014         ((uint32_t*)(src+i*stride))[2]=
2015         ((uint32_t*)(src+i*stride))[3]= dc;
2016     }
2017 }
2018
2019 static void pred16x16_128_dc_c(uint8_t *src, int stride){
2020     int i;
2021
2022     for(i=0; i<16; i++){
2023         ((uint32_t*)(src+i*stride))[0]=
2024         ((uint32_t*)(src+i*stride))[1]=
2025         ((uint32_t*)(src+i*stride))[2]=
2026         ((uint32_t*)(src+i*stride))[3]= 0x01010101U*128U;
2027     }
2028 }
2029
2030 static inline void pred16x16_plane_compat_c(uint8_t *src, int stride, const int svq3){
2031   int i, j, k;
2032   int a;
2033   uint8_t *cm = cropTbl + MAX_NEG_CROP;
2034   const uint8_t * const src0 = src+7-stride;
2035   const uint8_t *src1 = src+8*stride-1;
2036   const uint8_t *src2 = src1-2*stride;      // == src+6*stride-1;
2037   int H = src0[1] - src0[-1];
2038   int V = src1[0] - src2[ 0];
2039   for(k=2; k<=8; ++k) {
2040     src1 += stride; src2 -= stride;
2041     H += k*(src0[k] - src0[-k]);
2042     V += k*(src1[0] - src2[ 0]);
2043   }
2044   if(svq3){
2045     H = ( 5*(H/4) ) / 16;
2046     V = ( 5*(V/4) ) / 16;
2047
2048     /* required for 100% accuracy */
2049     i = H; H = V; V = i;
2050   }else{
2051     H = ( 5*H+32 ) >> 6;
2052     V = ( 5*V+32 ) >> 6;
2053   }
2054
2055   a = 16*(src1[0] + src2[16] + 1) - 7*(V+H);
2056   for(j=16; j>0; --j) {
2057     int b = a;
2058     a += V;
2059     for(i=-16; i<0; i+=4) {
2060       src[16+i] = cm[ (b    ) >> 5 ];
2061       src[17+i] = cm[ (b+  H) >> 5 ];
2062       src[18+i] = cm[ (b+2*H) >> 5 ];
2063       src[19+i] = cm[ (b+3*H) >> 5 ];
2064       b += 4*H;
2065     }
2066     src += stride;
2067   }
2068 }
2069
2070 static void pred16x16_plane_c(uint8_t *src, int stride){
2071     pred16x16_plane_compat_c(src, stride, 0);
2072 }
2073
2074 static void pred8x8_vertical_c(uint8_t *src, int stride){
2075     int i;
2076     const uint32_t a= ((uint32_t*)(src-stride))[0];
2077     const uint32_t b= ((uint32_t*)(src-stride))[1];
2078     
2079     for(i=0; i<8; i++){
2080         ((uint32_t*)(src+i*stride))[0]= a;
2081         ((uint32_t*)(src+i*stride))[1]= b;
2082     }
2083 }
2084
2085 static void pred8x8_horizontal_c(uint8_t *src, int stride){
2086     int i;
2087
2088     for(i=0; i<8; i++){
2089         ((uint32_t*)(src+i*stride))[0]=
2090         ((uint32_t*)(src+i*stride))[1]= src[-1+i*stride]*0x01010101;
2091     }
2092 }
2093
2094 static void pred8x8_128_dc_c(uint8_t *src, int stride){
2095     int i;
2096
2097     for(i=0; i<4; i++){
2098         ((uint32_t*)(src+i*stride))[0]= 
2099         ((uint32_t*)(src+i*stride))[1]= 0x01010101U*128U;
2100     }
2101     for(i=4; i<8; i++){
2102         ((uint32_t*)(src+i*stride))[0]= 
2103         ((uint32_t*)(src+i*stride))[1]= 0x01010101U*128U;
2104     }
2105 }
2106
2107 static void pred8x8_left_dc_c(uint8_t *src, int stride){
2108     int i;
2109     int dc0, dc2;
2110
2111     dc0=dc2=0;
2112     for(i=0;i<4; i++){
2113         dc0+= src[-1+i*stride];
2114         dc2+= src[-1+(i+4)*stride];
2115     }
2116     dc0= 0x01010101*((dc0 + 2)>>2);
2117     dc2= 0x01010101*((dc2 + 2)>>2);
2118
2119     for(i=0; i<4; i++){
2120         ((uint32_t*)(src+i*stride))[0]=
2121         ((uint32_t*)(src+i*stride))[1]= dc0;
2122     }
2123     for(i=4; i<8; i++){
2124         ((uint32_t*)(src+i*stride))[0]=
2125         ((uint32_t*)(src+i*stride))[1]= dc2;
2126     }
2127 }
2128
2129 static void pred8x8_top_dc_c(uint8_t *src, int stride){
2130     int i;
2131     int dc0, dc1;
2132
2133     dc0=dc1=0;
2134     for(i=0;i<4; i++){
2135         dc0+= src[i-stride];
2136         dc1+= src[4+i-stride];
2137     }
2138     dc0= 0x01010101*((dc0 + 2)>>2);
2139     dc1= 0x01010101*((dc1 + 2)>>2);
2140
2141     for(i=0; i<4; i++){
2142         ((uint32_t*)(src+i*stride))[0]= dc0;
2143         ((uint32_t*)(src+i*stride))[1]= dc1;
2144     }
2145     for(i=4; i<8; i++){
2146         ((uint32_t*)(src+i*stride))[0]= dc0;
2147         ((uint32_t*)(src+i*stride))[1]= dc1;
2148     }
2149 }
2150
2151
2152 static void pred8x8_dc_c(uint8_t *src, int stride){
2153     int i;
2154     int dc0, dc1, dc2, dc3;
2155
2156     dc0=dc1=dc2=0;
2157     for(i=0;i<4; i++){
2158         dc0+= src[-1+i*stride] + src[i-stride];
2159         dc1+= src[4+i-stride];
2160         dc2+= src[-1+(i+4)*stride];
2161     }
2162     dc3= 0x01010101*((dc1 + dc2 + 4)>>3);
2163     dc0= 0x01010101*((dc0 + 4)>>3);
2164     dc1= 0x01010101*((dc1 + 2)>>2);
2165     dc2= 0x01010101*((dc2 + 2)>>2);
2166
2167     for(i=0; i<4; i++){
2168         ((uint32_t*)(src+i*stride))[0]= dc0;
2169         ((uint32_t*)(src+i*stride))[1]= dc1;
2170     }
2171     for(i=4; i<8; i++){
2172         ((uint32_t*)(src+i*stride))[0]= dc2;
2173         ((uint32_t*)(src+i*stride))[1]= dc3;
2174     }
2175 }
2176
2177 static void pred8x8_plane_c(uint8_t *src, int stride){
2178   int j, k;
2179   int a;
2180   uint8_t *cm = cropTbl + MAX_NEG_CROP;
2181   const uint8_t * const src0 = src+3-stride;
2182   const uint8_t *src1 = src+4*stride-1;
2183   const uint8_t *src2 = src1-2*stride;      // == src+2*stride-1;
2184   int H = src0[1] - src0[-1];
2185   int V = src1[0] - src2[ 0];
2186   for(k=2; k<=4; ++k) {
2187     src1 += stride; src2 -= stride;
2188     H += k*(src0[k] - src0[-k]);
2189     V += k*(src1[0] - src2[ 0]);
2190   }
2191   H = ( 17*H+16 ) >> 5;
2192   V = ( 17*V+16 ) >> 5;
2193
2194   a = 16*(src1[0] + src2[8]+1) - 3*(V+H);
2195   for(j=8; j>0; --j) {
2196     int b = a;
2197     a += V;
2198     src[0] = cm[ (b    ) >> 5 ];
2199     src[1] = cm[ (b+  H) >> 5 ];
2200     src[2] = cm[ (b+2*H) >> 5 ];
2201     src[3] = cm[ (b+3*H) >> 5 ];
2202     src[4] = cm[ (b+4*H) >> 5 ];
2203     src[5] = cm[ (b+5*H) >> 5 ];
2204     src[6] = cm[ (b+6*H) >> 5 ];
2205     src[7] = cm[ (b+7*H) >> 5 ];
2206     src += stride;
2207   }
2208 }
2209
2210 static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
2211                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
2212                            int src_x_offset, int src_y_offset,
2213                            qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
2214     MpegEncContext * const s = &h->s;
2215     const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
2216     const int my= h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
2217     const int luma_xy= (mx&3) + ((my&3)<<2);
2218     uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*s->linesize;
2219     uint8_t * src_cb= pic->data[1] + (mx>>3) + (my>>3)*s->uvlinesize;
2220     uint8_t * src_cr= pic->data[2] + (mx>>3) + (my>>3)*s->uvlinesize;
2221     int extra_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16; //FIXME increase edge?, IMHO not worth it
2222     int extra_height= extra_width;
2223     int emu=0;
2224     const int full_mx= mx>>2;
2225     const int full_my= my>>2;
2226     
2227     assert(pic->data[0]);
2228     
2229     if(mx&7) extra_width -= 3;
2230     if(my&7) extra_height -= 3;
2231     
2232     if(   full_mx < 0-extra_width 
2233        || full_my < 0-extra_height 
2234        || full_mx + 16/*FIXME*/ > s->width + extra_width 
2235        || full_my + 16/*FIXME*/ > s->height + extra_height){
2236         ff_emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*s->linesize, s->linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, s->width, s->height);
2237             src_y= s->edge_emu_buffer + 2 + 2*s->linesize;
2238         emu=1;
2239     }
2240     
2241     qpix_op[luma_xy](dest_y, src_y, s->linesize); //FIXME try variable height perhaps?
2242     if(!square){
2243         qpix_op[luma_xy](dest_y + delta, src_y + delta, s->linesize);
2244     }
2245     
2246     if(s->flags&CODEC_FLAG_GRAY) return;
2247     
2248     if(emu){
2249         ff_emulated_edge_mc(s->edge_emu_buffer, src_cb, s->uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), s->width>>1, s->height>>1);
2250             src_cb= s->edge_emu_buffer;
2251     }
2252     chroma_op(dest_cb, src_cb, s->uvlinesize, chroma_height, mx&7, my&7);
2253
2254     if(emu){
2255         ff_emulated_edge_mc(s->edge_emu_buffer, src_cr, s->uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), s->width>>1, s->height>>1);
2256             src_cr= s->edge_emu_buffer;
2257     }
2258     chroma_op(dest_cr, src_cr, s->uvlinesize, chroma_height, mx&7, my&7);
2259 }
2260
2261 static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
2262                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
2263                            int x_offset, int y_offset,
2264                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
2265                            qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
2266                            int list0, int list1){
2267     MpegEncContext * const s = &h->s;
2268     qpel_mc_func *qpix_op=  qpix_put;
2269     h264_chroma_mc_func chroma_op= chroma_put;
2270     
2271     dest_y  += 2*x_offset + 2*y_offset*s->  linesize;
2272     dest_cb +=   x_offset +   y_offset*s->uvlinesize;
2273     dest_cr +=   x_offset +   y_offset*s->uvlinesize;
2274     x_offset += 8*s->mb_x;
2275     y_offset += 8*s->mb_y;
2276     
2277     if(list0){
2278         Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
2279         mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
2280                            dest_y, dest_cb, dest_cr, x_offset, y_offset,
2281                            qpix_op, chroma_op);
2282
2283         qpix_op=  qpix_avg;
2284         chroma_op= chroma_avg;
2285     }
2286
2287     if(list1){
2288         Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
2289         mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
2290                            dest_y, dest_cb, dest_cr, x_offset, y_offset,
2291                            qpix_op, chroma_op);
2292     }
2293 }
2294
2295 static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
2296                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
2297                            int x_offset, int y_offset,
2298                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
2299                            h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
2300                            h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
2301                            int list0, int list1){
2302     MpegEncContext * const s = &h->s;
2303
2304     dest_y  += 2*x_offset + 2*y_offset*s->  linesize;
2305     dest_cb +=   x_offset +   y_offset*s->uvlinesize;
2306     dest_cr +=   x_offset +   y_offset*s->uvlinesize;
2307     x_offset += 8*s->mb_x;
2308     y_offset += 8*s->mb_y;
2309     
2310     if(list0 && list1){
2311         /* don't optimize for luma-only case, since B-frames usually
2312          * use implicit weights => chroma too. */
2313         uint8_t *tmp_cb = s->obmc_scratchpad;
2314         uint8_t *tmp_cr = tmp_cb + 8*s->uvlinesize;
2315         uint8_t *tmp_y  = tmp_cr + 8*s->uvlinesize;
2316         int refn0 = h->ref_cache[0][ scan8[n] ];
2317         int refn1 = h->ref_cache[1][ scan8[n] ];
2318
2319         mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
2320                     dest_y, dest_cb, dest_cr,
2321                     x_offset, y_offset, qpix_put, chroma_put);
2322         mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
2323                     tmp_y, tmp_cb, tmp_cr,
2324                     x_offset, y_offset, qpix_put, chroma_put);
2325
2326         if(h->use_weight == 2){
2327             int weight0 = h->implicit_weight[refn0][refn1];
2328             int weight1 = 64 - weight0;
2329             luma_weight_avg(  dest_y,  tmp_y,  s->  linesize, 5, weight0, weight1, 0, 0);
2330             chroma_weight_avg(dest_cb, tmp_cb, s->uvlinesize, 5, weight0, weight1, 0, 0);
2331             chroma_weight_avg(dest_cr, tmp_cr, s->uvlinesize, 5, weight0, weight1, 0, 0);
2332         }else{
2333             luma_weight_avg(dest_y, tmp_y, s->linesize, h->luma_log2_weight_denom,
2334                             h->luma_weight[0][refn0], h->luma_weight[1][refn1], 
2335                             h->luma_offset[0][refn0], h->luma_offset[1][refn1]);
2336             chroma_weight_avg(dest_cb, tmp_cb, s->uvlinesize, h->chroma_log2_weight_denom,
2337                             h->chroma_weight[0][refn0][0], h->chroma_weight[1][refn1][0], 
2338                             h->chroma_offset[0][refn0][0], h->chroma_offset[1][refn1][0]);
2339             chroma_weight_avg(dest_cr, tmp_cr, s->uvlinesize, h->chroma_log2_weight_denom,
2340                             h->chroma_weight[0][refn0][1], h->chroma_weight[1][refn1][1], 
2341                             h->chroma_offset[0][refn0][1], h->chroma_offset[1][refn1][1]);
2342         }
2343     }else{
2344         int list = list1 ? 1 : 0;
2345         int refn = h->ref_cache[list][ scan8[n] ];
2346         Picture *ref= &h->ref_list[list][refn];
2347         mc_dir_part(h, ref, n, square, chroma_height, delta, list,
2348                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
2349                     qpix_put, chroma_put);
2350
2351         luma_weight_op(dest_y, s->linesize, h->luma_log2_weight_denom,
2352                        h->luma_weight[list][refn], h->luma_offset[list][refn]);
2353         if(h->use_weight_chroma){
2354             chroma_weight_op(dest_cb, s->uvlinesize, h->chroma_log2_weight_denom,
2355                              h->chroma_weight[list][refn][0], h->chroma_offset[list][refn][0]);
2356             chroma_weight_op(dest_cr, s->uvlinesize, h->chroma_log2_weight_denom,
2357                              h->chroma_weight[list][refn][1], h->chroma_offset[list][refn][1]);
2358         }
2359     }
2360 }
2361
2362 static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
2363                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
2364                            int x_offset, int y_offset,
2365                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
2366                            qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
2367                            h264_weight_func *weight_op, h264_biweight_func *weight_avg, 
2368                            int list0, int list1){
2369     if((h->use_weight==2 && list0 && list1
2370         && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ] != 32))
2371        || h->use_weight==1)
2372         mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
2373                          x_offset, y_offset, qpix_put, chroma_put,
2374                          weight_op[0], weight_op[3], weight_avg[0], weight_avg[3], list0, list1);
2375     else
2376         mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
2377                     x_offset, y_offset, qpix_put, chroma_put, qpix_avg, chroma_avg, list0, list1);
2378 }
2379
2380 static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
2381                       qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
2382                       qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
2383                       h264_weight_func *weight_op, h264_biweight_func *weight_avg){
2384     MpegEncContext * const s = &h->s;
2385     const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
2386     const int mb_type= s->current_picture.mb_type[mb_xy];
2387     
2388     assert(IS_INTER(mb_type));
2389     
2390     if(IS_16X16(mb_type)){
2391         mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
2392                 qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
2393                 &weight_op[0], &weight_avg[0],
2394                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
2395     }else if(IS_16X8(mb_type)){
2396         mc_part(h, 0, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 0,
2397                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
2398                 &weight_op[1], &weight_avg[1],
2399                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
2400         mc_part(h, 8, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 4,
2401                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
2402                 &weight_op[1], &weight_avg[1],
2403                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
2404     }else if(IS_8X16(mb_type)){
2405         mc_part(h, 0, 0, 8, 8*s->linesize, dest_y, dest_cb, dest_cr, 0, 0,
2406                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
2407                 &weight_op[2], &weight_avg[2],
2408                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
2409         mc_part(h, 4, 0, 8, 8*s->linesize, dest_y, dest_cb, dest_cr, 4, 0,
2410                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
2411                 &weight_op[2], &weight_avg[2],
2412                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
2413     }else{
2414         int i;
2415         
2416         assert(IS_8X8(mb_type));
2417
2418         for(i=0; i<4; i++){
2419             const int sub_mb_type= h->sub_mb_type[i];
2420             const int n= 4*i;
2421             int x_offset= (i&1)<<2;
2422             int y_offset= (i&2)<<1;
2423
2424             if(IS_SUB_8X8(sub_mb_type)){
2425                 mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
2426                     qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
2427                     &weight_op[3], &weight_avg[3],
2428                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2429             }else if(IS_SUB_8X4(sub_mb_type)){
2430                 mc_part(h, n  , 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset,
2431                     qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
2432                     &weight_op[4], &weight_avg[4],
2433                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2434                 mc_part(h, n+2, 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
2435                     qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
2436                     &weight_op[4], &weight_avg[4],
2437                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2438             }else if(IS_SUB_4X8(sub_mb_type)){
2439                 mc_part(h, n  , 0, 4, 4*s->linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
2440                     qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
2441                     &weight_op[5], &weight_avg[5],
2442                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2443                 mc_part(h, n+1, 0, 4, 4*s->linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
2444                     qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
2445                     &weight_op[5], &weight_avg[5],
2446                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2447             }else{
2448                 int j;
2449                 assert(IS_SUB_4X4(sub_mb_type));
2450                 for(j=0; j<4; j++){
2451                     int sub_x_offset= x_offset + 2*(j&1);
2452                     int sub_y_offset= y_offset +   (j&2);
2453                     mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
2454                         qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
2455                         &weight_op[6], &weight_avg[6],
2456                         IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2457                 }
2458             }
2459         }
2460     }
2461 }
2462
2463 static void decode_init_vlc(H264Context *h){
2464     static int done = 0;
2465
2466     if (!done) {
2467         int i;
2468         done = 1;
2469
2470         init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5, 
2471                  &chroma_dc_coeff_token_len [0], 1, 1,
2472                  &chroma_dc_coeff_token_bits[0], 1, 1, 1);
2473
2474         for(i=0; i<4; i++){
2475             init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17, 
2476                      &coeff_token_len [i][0], 1, 1,
2477                      &coeff_token_bits[i][0], 1, 1, 1);
2478         }
2479
2480         for(i=0; i<3; i++){
2481             init_vlc(&chroma_dc_total_zeros_vlc[i], CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,
2482                      &chroma_dc_total_zeros_len [i][0], 1, 1,
2483                      &chroma_dc_total_zeros_bits[i][0], 1, 1, 1);
2484         }
2485         for(i=0; i<15; i++){
2486             init_vlc(&total_zeros_vlc[i], TOTAL_ZEROS_VLC_BITS, 16, 
2487                      &total_zeros_len [i][0], 1, 1,
2488                      &total_zeros_bits[i][0], 1, 1, 1);
2489         }
2490
2491         for(i=0; i<6; i++){
2492             init_vlc(&run_vlc[i], RUN_VLC_BITS, 7, 
2493                      &run_len [i][0], 1, 1,
2494                      &run_bits[i][0], 1, 1, 1);
2495         }
2496         init_vlc(&run7_vlc, RUN7_VLC_BITS, 16, 
2497                  &run_len [6][0], 1, 1,
2498                  &run_bits[6][0], 1, 1, 1);
2499     }
2500 }
2501
2502 /**
2503  * Sets the intra prediction function pointers.
2504  */
2505 static void init_pred_ptrs(H264Context *h){
2506 //    MpegEncContext * const s = &h->s;
2507
2508     h->pred4x4[VERT_PRED           ]= pred4x4_vertical_c;
2509     h->pred4x4[HOR_PRED            ]= pred4x4_horizontal_c;
2510     h->pred4x4[DC_PRED             ]= pred4x4_dc_c;
2511     h->pred4x4[DIAG_DOWN_LEFT_PRED ]= pred4x4_down_left_c;
2512     h->pred4x4[DIAG_DOWN_RIGHT_PRED]= pred4x4_down_right_c;
2513     h->pred4x4[VERT_RIGHT_PRED     ]= pred4x4_vertical_right_c;
2514     h->pred4x4[HOR_DOWN_PRED       ]= pred4x4_horizontal_down_c;
2515     h->pred4x4[VERT_LEFT_PRED      ]= pred4x4_vertical_left_c;
2516     h->pred4x4[HOR_UP_PRED         ]= pred4x4_horizontal_up_c;
2517     h->pred4x4[LEFT_DC_PRED        ]= pred4x4_left_dc_c;
2518     h->pred4x4[TOP_DC_PRED         ]= pred4x4_top_dc_c;
2519     h->pred4x4[DC_128_PRED         ]= pred4x4_128_dc_c;
2520
2521     h->pred8x8[DC_PRED8x8     ]= pred8x8_dc_c;
2522     h->pred8x8[VERT_PRED8x8   ]= pred8x8_vertical_c;
2523     h->pred8x8[HOR_PRED8x8    ]= pred8x8_horizontal_c;
2524     h->pred8x8[PLANE_PRED8x8  ]= pred8x8_plane_c;
2525     h->pred8x8[LEFT_DC_PRED8x8]= pred8x8_left_dc_c;
2526     h->pred8x8[TOP_DC_PRED8x8 ]= pred8x8_top_dc_c;
2527     h->pred8x8[DC_128_PRED8x8 ]= pred8x8_128_dc_c;
2528
2529     h->pred16x16[DC_PRED8x8     ]= pred16x16_dc_c;
2530     h->pred16x16[VERT_PRED8x8   ]= pred16x16_vertical_c;
2531     h->pred16x16[HOR_PRED8x8    ]= pred16x16_horizontal_c;
2532     h->pred16x16[PLANE_PRED8x8  ]= pred16x16_plane_c;
2533     h->pred16x16[LEFT_DC_PRED8x8]= pred16x16_left_dc_c;
2534     h->pred16x16[TOP_DC_PRED8x8 ]= pred16x16_top_dc_c;
2535     h->pred16x16[DC_128_PRED8x8 ]= pred16x16_128_dc_c;
2536 }
2537
2538 static void free_tables(H264Context *h){
2539     av_freep(&h->intra4x4_pred_mode);
2540     av_freep(&h->chroma_pred_mode_table);
2541     av_freep(&h->cbp_table);
2542     av_freep(&h->mvd_table[0]);
2543     av_freep(&h->mvd_table[1]);
2544     av_freep(&h->direct_table);
2545     av_freep(&h->non_zero_count);
2546     av_freep(&h->slice_table_base);
2547     av_freep(&h->top_border);
2548     h->slice_table= NULL;
2549
2550     av_freep(&h->mb2b_xy);
2551     av_freep(&h->mb2b8_xy);
2552
2553     av_freep(&h->s.obmc_scratchpad);
2554 }
2555
2556 /**
2557  * allocates tables.
2558  * needs widzh/height
2559  */
2560 static int alloc_tables(H264Context *h){
2561     MpegEncContext * const s = &h->s;
2562     const int big_mb_num= s->mb_stride * (s->mb_height+1);
2563     int x,y;
2564
2565     CHECKED_ALLOCZ(h->intra4x4_pred_mode, big_mb_num * 8  * sizeof(uint8_t))
2566
2567     CHECKED_ALLOCZ(h->non_zero_count    , big_mb_num * 16 * sizeof(uint8_t))
2568     CHECKED_ALLOCZ(h->slice_table_base  , big_mb_num * sizeof(uint8_t))
2569     CHECKED_ALLOCZ(h->top_border       , s->mb_width * (16+8+8) * sizeof(uint8_t))
2570     CHECKED_ALLOCZ(h->cbp_table, big_mb_num * sizeof(uint16_t))
2571
2572     if( h->pps.cabac ) {
2573         CHECKED_ALLOCZ(h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t))
2574         CHECKED_ALLOCZ(h->mvd_table[0], 32*big_mb_num * sizeof(uint16_t));
2575         CHECKED_ALLOCZ(h->mvd_table[1], 32*big_mb_num * sizeof(uint16_t));
2576         CHECKED_ALLOCZ(h->direct_table, 32*big_mb_num * sizeof(uint8_t));
2577     }
2578
2579     memset(h->slice_table_base, -1, big_mb_num  * sizeof(uint8_t));
2580     h->slice_table= h->slice_table_base + s->mb_stride + 1;
2581
2582     CHECKED_ALLOCZ(h->mb2b_xy  , big_mb_num * sizeof(uint16_t));
2583     CHECKED_ALLOCZ(h->mb2b8_xy , big_mb_num * sizeof(uint16_t));
2584     for(y=0; y<s->mb_height; y++){
2585         for(x=0; x<s->mb_width; x++){
2586             const int mb_xy= x + y*s->mb_stride;
2587             const int b_xy = 4*x + 4*y*h->b_stride;
2588             const int b8_xy= 2*x + 2*y*h->b8_stride;
2589         
2590             h->mb2b_xy [mb_xy]= b_xy;
2591             h->mb2b8_xy[mb_xy]= b8_xy;
2592         }
2593     }
2594
2595     s->obmc_scratchpad = NULL;
2596
2597     return 0;
2598 fail:
2599     free_tables(h);
2600     return -1;
2601 }
2602
2603 static void common_init(H264Context *h){
2604     MpegEncContext * const s = &h->s;
2605
2606     s->width = s->avctx->width;
2607     s->height = s->avctx->height;
2608     s->codec_id= s->avctx->codec->id;
2609     
2610     init_pred_ptrs(h);
2611
2612     s->unrestricted_mv=1;
2613     s->decode=1; //FIXME
2614 }
2615
2616 static int decode_init(AVCodecContext *avctx){
2617     H264Context *h= avctx->priv_data;
2618     MpegEncContext * const s = &h->s;
2619
2620     MPV_decode_defaults(s);
2621     
2622     s->avctx = avctx;
2623     common_init(h);
2624
2625     s->out_format = FMT_H264;
2626     s->workaround_bugs= avctx->workaround_bugs;
2627
2628     // set defaults
2629 //    s->decode_mb= ff_h263_decode_mb;
2630     s->low_delay= 1;
2631     avctx->pix_fmt= PIX_FMT_YUV420P;
2632
2633     decode_init_vlc(h);
2634     
2635     if(avctx->codec_tag != 0x31637661 && avctx->codec_tag != 0x31435641) // avc1
2636         h->is_avc = 0;
2637     else {
2638         if((avctx->extradata_size == 0) || (avctx->extradata == NULL)) {
2639             av_log(avctx, AV_LOG_ERROR, "AVC codec requires avcC data\n");
2640             return -1;
2641         }
2642         h->is_avc = 1;
2643         h->got_avcC = 0;
2644     }
2645
2646     return 0;
2647 }
2648
2649 static void frame_start(H264Context *h){
2650     MpegEncContext * const s = &h->s;
2651     int i;
2652
2653     MPV_frame_start(s, s->avctx);
2654     ff_er_frame_start(s);
2655
2656     assert(s->linesize && s->uvlinesize);
2657
2658     for(i=0; i<16; i++){
2659         h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
2660         h->chroma_subblock_offset[i]= 2*((scan8[i] - scan8[0])&7) + 2*s->uvlinesize*((scan8[i] - scan8[0])>>3);
2661     }
2662     for(i=0; i<4; i++){
2663         h->block_offset[16+i]=
2664         h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
2665     }
2666
2667     /* can't be in alloc_tables because linesize isn't known there.
2668      * FIXME: redo bipred weight to not require extra buffer? */
2669     if(!s->obmc_scratchpad)
2670         s->obmc_scratchpad = av_malloc(16*s->linesize + 2*8*s->uvlinesize);
2671
2672 //    s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
2673 }
2674
2675 static inline void backup_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize){
2676     MpegEncContext * const s = &h->s;
2677     int i;
2678     
2679     src_y  -=   linesize;
2680     src_cb -= uvlinesize;
2681     src_cr -= uvlinesize;
2682
2683     h->left_border[0]= h->top_border[s->mb_x][15];
2684     for(i=1; i<17; i++){
2685         h->left_border[i]= src_y[15+i*  linesize];
2686     }
2687     
2688     *(uint64_t*)(h->top_border[s->mb_x]+0)= *(uint64_t*)(src_y +  16*linesize);
2689     *(uint64_t*)(h->top_border[s->mb_x]+8)= *(uint64_t*)(src_y +8+16*linesize);
2690
2691     if(!(s->flags&CODEC_FLAG_GRAY)){
2692         h->left_border[17  ]= h->top_border[s->mb_x][16+7];
2693         h->left_border[17+9]= h->top_border[s->mb_x][24+7];
2694         for(i=1; i<9; i++){
2695             h->left_border[i+17  ]= src_cb[7+i*uvlinesize];
2696             h->left_border[i+17+9]= src_cr[7+i*uvlinesize];
2697         }
2698         *(uint64_t*)(h->top_border[s->mb_x]+16)= *(uint64_t*)(src_cb+8*uvlinesize);
2699         *(uint64_t*)(h->top_border[s->mb_x]+24)= *(uint64_t*)(src_cr+8*uvlinesize);
2700     }
2701 }
2702
2703 static inline void xchg_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg){
2704     MpegEncContext * const s = &h->s;
2705     int temp8, i;
2706     uint64_t temp64;
2707     int deblock_left = (s->mb_x > 0);
2708     int deblock_top  = (s->mb_y > 0);
2709
2710     src_y  -=   linesize + 1;
2711     src_cb -= uvlinesize + 1;
2712     src_cr -= uvlinesize + 1;
2713
2714 #define XCHG(a,b,t,xchg)\
2715 t= a;\
2716 if(xchg)\
2717     a= b;\
2718 b= t;
2719
2720     if(deblock_left){
2721         for(i = !deblock_top; i<17; i++){
2722             XCHG(h->left_border[i     ], src_y [i*  linesize], temp8, xchg);
2723         }
2724     }
2725
2726     if(deblock_top){
2727         XCHG(*(uint64_t*)(h->top_border[s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
2728         XCHG(*(uint64_t*)(h->top_border[s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
2729     }
2730
2731     if(!(s->flags&CODEC_FLAG_GRAY)){
2732         if(deblock_left){
2733             for(i = !deblock_top; i<9; i++){
2734                 XCHG(h->left_border[i+17  ], src_cb[i*uvlinesize], temp8, xchg);
2735                 XCHG(h->left_border[i+17+9], src_cr[i*uvlinesize], temp8, xchg);
2736             }
2737         }
2738         if(deblock_top){
2739             XCHG(*(uint64_t*)(h->top_border[s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
2740             XCHG(*(uint64_t*)(h->top_border[s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
2741         }
2742     }
2743 }
2744
2745 static void hl_decode_mb(H264Context *h){
2746     MpegEncContext * const s = &h->s;
2747     const int mb_x= s->mb_x;
2748     const int mb_y= s->mb_y;
2749     const int mb_xy= mb_x + mb_y*s->mb_stride;
2750     const int mb_type= s->current_picture.mb_type[mb_xy];
2751     uint8_t  *dest_y, *dest_cb, *dest_cr;
2752     int linesize, uvlinesize /*dct_offset*/;
2753     int i;
2754
2755     if(!s->decode)
2756         return;
2757
2758     if(s->mb_skiped){
2759     }
2760
2761     dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
2762     dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2763     dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2764
2765     if (h->mb_field_decoding_flag) {
2766         linesize = s->linesize * 2;
2767         uvlinesize = s->uvlinesize * 2;
2768         if(mb_y&1){ //FIXME move out of this func?
2769             dest_y -= s->linesize*15;
2770             dest_cb-= s->linesize*7;
2771             dest_cr-= s->linesize*7;
2772         }
2773     } else {
2774         linesize = s->linesize;
2775         uvlinesize = s->uvlinesize;
2776 //        dct_offset = s->linesize * 16;
2777     }
2778
2779     if (IS_INTRA_PCM(mb_type)) {
2780         unsigned int x, y;
2781
2782         // The pixels are stored in h->mb array in the same order as levels,
2783         // copy them in output in the correct order.
2784         for(i=0; i<16; i++) {
2785             for (y=0; y<4; y++) {
2786                 for (x=0; x<4; x++) {
2787                     *(dest_y + h->block_offset[i] + y*linesize + x) = h->mb[i*16+y*4+x];
2788                 }
2789             }
2790         }
2791         for(i=16; i<16+4; i++) {
2792             for (y=0; y<4; y++) {
2793                 for (x=0; x<4; x++) {
2794                     *(dest_cb + h->block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];
2795                 }
2796             }
2797         }
2798         for(i=20; i<20+4; i++) {
2799             for (y=0; y<4; y++) {
2800                 for (x=0; x<4; x++) {
2801                     *(dest_cr + h->block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];
2802                 }
2803             }
2804         }
2805     } else {
2806         if(IS_INTRA(mb_type)){
2807             if(h->deblocking_filter)
2808                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1);
2809
2810             if(!(s->flags&CODEC_FLAG_GRAY)){
2811                 h->pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
2812                 h->pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
2813             }
2814
2815             if(IS_INTRA4x4(mb_type)){
2816                 if(!s->encoding){
2817                     for(i=0; i<16; i++){
2818                         uint8_t * const ptr= dest_y + h->block_offset[i];
2819                         uint8_t *topright;
2820                         const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
2821                         int tr;
2822
2823                         if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
2824                             const int topright_avail= (h->topright_samples_available<<i)&0x8000;
2825                             assert(mb_y || linesize <= h->block_offset[i]);
2826                             if(!topright_avail){
2827                                 tr= ptr[3 - linesize]*0x01010101;
2828                                 topright= (uint8_t*) &tr;
2829                             }else if(i==5 && h->deblocking_filter){
2830                                 tr= *(uint32_t*)h->top_border[mb_x+1];
2831                                 topright= (uint8_t*) &tr;
2832                             }else
2833                                 topright= ptr + 4 - linesize;
2834                         }else
2835                             topright= NULL;
2836
2837                         h->pred4x4[ dir ](ptr, topright, linesize);
2838                         if(h->non_zero_count_cache[ scan8[i] ]){
2839                             if(s->codec_id == CODEC_ID_H264)
2840                                 s->dsp.h264_idct_add(ptr, h->mb + i*16, linesize);
2841                             else
2842                                 svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
2843                         }
2844                     }
2845                 }
2846             }else{
2847                 h->pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
2848                 if(s->codec_id == CODEC_ID_H264)
2849                     h264_luma_dc_dequant_idct_c(h->mb, s->qscale);
2850                 else
2851                     svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
2852             }
2853             if(h->deblocking_filter)
2854                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
2855         }else if(s->codec_id == CODEC_ID_H264){
2856             hl_motion(h, dest_y, dest_cb, dest_cr,
2857                       s->dsp.put_h264_qpel_pixels_tab, s->dsp.put_h264_chroma_pixels_tab, 
2858                       s->dsp.avg_h264_qpel_pixels_tab, s->dsp.avg_h264_chroma_pixels_tab,
2859                       s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);
2860         }
2861
2862
2863         if(!IS_INTRA4x4(mb_type)){
2864             if(s->codec_id == CODEC_ID_H264){
2865                 for(i=0; i<16; i++){
2866                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
2867                         uint8_t * const ptr= dest_y + h->block_offset[i];
2868                         s->dsp.h264_idct_add(ptr, h->mb + i*16, linesize);
2869                     }
2870                 }
2871             }else{
2872                 for(i=0; i<16; i++){
2873                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
2874                         uint8_t * const ptr= dest_y + h->block_offset[i];
2875                         svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
2876                     }
2877                 }
2878             }
2879         }
2880
2881         if(!(s->flags&CODEC_FLAG_GRAY)){
2882             chroma_dc_dequant_idct_c(h->mb + 16*16, h->chroma_qp);
2883             chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->chroma_qp);
2884             if(s->codec_id == CODEC_ID_H264){
2885                 for(i=16; i<16+4; i++){
2886                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2887                         uint8_t * const ptr= dest_cb + h->block_offset[i];
2888                         s->dsp.h264_idct_add(ptr, h->mb + i*16, uvlinesize);
2889                     }
2890                 }
2891                 for(i=20; i<20+4; i++){
2892                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2893                         uint8_t * const ptr= dest_cr + h->block_offset[i];
2894                         s->dsp.h264_idct_add(ptr, h->mb + i*16, uvlinesize);
2895                     }
2896                 }
2897             }else{
2898                 for(i=16; i<16+4; i++){
2899                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2900                         uint8_t * const ptr= dest_cb + h->block_offset[i];
2901                         svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
2902                     }
2903                 }
2904                 for(i=20; i<20+4; i++){
2905                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2906                         uint8_t * const ptr= dest_cr + h->block_offset[i];
2907                         svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
2908                     }
2909                 }
2910             }
2911         }
2912     }
2913     if(h->deblocking_filter) {
2914         backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2915         fill_caches(h, mb_type, 1); //FIXME dont fill stuff which isnt used by filter_mb
2916         filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr);
2917     }
2918 }
2919
2920 /**
2921  * fills the default_ref_list.
2922  */
2923 static int fill_default_ref_list(H264Context *h){
2924     MpegEncContext * const s = &h->s;
2925     int i;
2926     int smallest_poc_greater_than_current = -1;
2927     Picture sorted_short_ref[16];
2928     
2929     if(h->slice_type==B_TYPE){
2930         int out_i;
2931         int limit= -1;
2932
2933         /* sort frame according to poc in B slice */
2934         for(out_i=0; out_i<h->short_ref_count; out_i++){
2935             int best_i=-1;
2936             int best_poc=INT_MAX;
2937
2938             for(i=0; i<h->short_ref_count; i++){
2939                 const int poc= h->short_ref[i]->poc;
2940                 if(poc > limit && poc < best_poc){
2941                     best_poc= poc;
2942                     best_i= i;
2943                 }
2944             }
2945             
2946             assert(best_i != -1);
2947             
2948             limit= best_poc;
2949             sorted_short_ref[out_i]= *h->short_ref[best_i];
2950             tprintf("sorted poc: %d->%d poc:%d fn:%d\n", best_i, out_i, sorted_short_ref[out_i].poc, sorted_short_ref[out_i].frame_num);
2951             if (-1 == smallest_poc_greater_than_current) {
2952                 if (h->short_ref[best_i]->poc >= s->current_picture_ptr->poc) {
2953                     smallest_poc_greater_than_current = out_i;
2954                 }
2955             }
2956         }
2957     }
2958
2959     if(s->picture_structure == PICT_FRAME){
2960         if(h->slice_type==B_TYPE){
2961             int list;
2962             tprintf("current poc: %d, smallest_poc_greater_than_current: %d\n", s->current_picture_ptr->poc, smallest_poc_greater_than_current);
2963
2964             // find the largest poc
2965             for(list=0; list<2; list++){
2966                 int index = 0;
2967                 int j= -99;
2968                 int step= list ? -1 : 1;
2969
2970                 for(i=0; i<h->short_ref_count && index < h->ref_count[list]; i++, j+=step) {
2971                     while(j<0 || j>= h->short_ref_count){
2972                         step = -step;
2973                         j= smallest_poc_greater_than_current + (step>>1);
2974                     }
2975                     if(sorted_short_ref[j].reference != 3) continue;
2976                     h->default_ref_list[list][index  ]= sorted_short_ref[j];
2977                     h->default_ref_list[list][index++].pic_id= sorted_short_ref[j].frame_num;
2978                 }
2979
2980                 for(i = 0; i < 16 && index < h->ref_count[ list ]; i++){
2981                     if(h->long_ref[i] == NULL) continue;
2982                     if(h->long_ref[i]->reference != 3) continue;
2983
2984                     h->default_ref_list[ list ][index  ]= *h->long_ref[i];
2985                     h->default_ref_list[ list ][index++].pic_id= i;;
2986                 }
2987                 
2988                 if(list && (smallest_poc_greater_than_current<=0 || smallest_poc_greater_than_current>=h->short_ref_count) && (1 < index)){
2989                     // swap the two first elements of L1 when
2990                     // L0 and L1 are identical
2991                     Picture temp= h->default_ref_list[1][0];
2992                     h->default_ref_list[1][0] = h->default_ref_list[1][1];
2993                     h->default_ref_list[1][0] = temp;
2994                 }
2995
2996                 if(index < h->ref_count[ list ])
2997                     memset(&h->default_ref_list[list][index], 0, sizeof(Picture)*(h->ref_count[ list ] - index));
2998             }
2999         }else{
3000             int index=0;
3001             for(i=0; i<h->short_ref_count; i++){
3002                 if(h->short_ref[i]->reference != 3) continue; //FIXME refernce field shit
3003                 h->default_ref_list[0][index  ]= *h->short_ref[i];
3004                 h->default_ref_list[0][index++].pic_id= h->short_ref[i]->frame_num;
3005             }
3006             for(i = 0; i < 16; i++){
3007                 if(h->long_ref[i] == NULL) continue;
3008                 if(h->long_ref[i]->reference != 3) continue;
3009                 h->default_ref_list[0][index  ]= *h->long_ref[i];
3010                 h->default_ref_list[0][index++].pic_id= i;;
3011             }
3012             if(index < h->ref_count[0])
3013                 memset(&h->default_ref_list[0][index], 0, sizeof(Picture)*(h->ref_count[0] - index));
3014         }
3015     }else{ //FIELD
3016         if(h->slice_type==B_TYPE){
3017         }else{
3018             //FIXME second field balh
3019         }
3020     }
3021 #ifdef TRACE
3022     for (i=0; i<h->ref_count[0]; i++) {
3023         tprintf("List0: %s fn:%d 0x%p\n", (h->default_ref_list[0][i].long_ref ? "LT" : "ST"), h->default_ref_list[0][i].pic_id, h->default_ref_list[0][i].data[0]);
3024     }
3025     if(h->slice_type==B_TYPE){
3026         for (i=0; i<h->ref_count[1]; i++) {
3027             tprintf("List1: %s fn:%d 0x%p\n", (h->default_ref_list[1][i].long_ref ? "LT" : "ST"), h->default_ref_list[1][i].pic_id, h->default_ref_list[0][i].data[0]);
3028         }
3029     }
3030 #endif
3031     return 0;
3032 }
3033
3034 static void print_short_term(H264Context *h);
3035 static void print_long_term(H264Context *h);
3036
3037 static int decode_ref_pic_list_reordering(H264Context *h){
3038     MpegEncContext * const s = &h->s;
3039     int list;
3040     
3041     print_short_term(h);
3042     print_long_term(h);
3043     if(h->slice_type==I_TYPE || h->slice_type==SI_TYPE) return 0; //FIXME move beofre func
3044     
3045     for(list=0; list<2; list++){
3046         memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);
3047
3048         if(get_bits1(&s->gb)){
3049             int pred= h->curr_pic_num;
3050             int index;
3051
3052             for(index=0; ; index++){
3053                 int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
3054                 int pic_id;
3055                 int i;
3056                 Picture *ref = NULL;
3057                 
3058                 if(reordering_of_pic_nums_idc==3) 
3059                     break;
3060                 
3061                 if(index >= h->ref_count[list]){
3062                     av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
3063                     return -1;
3064                 }
3065                 
3066                 if(reordering_of_pic_nums_idc<3){
3067                     if(reordering_of_pic_nums_idc<2){
3068                         const int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
3069
3070                         if(abs_diff_pic_num >= h->max_pic_num){
3071                             av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
3072                             return -1;
3073                         }
3074
3075                         if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
3076                         else                                pred+= abs_diff_pic_num;
3077                         pred &= h->max_pic_num - 1;
3078                     
3079                         for(i= h->short_ref_count-1; i>=0; i--){
3080                             ref = h->short_ref[i];
3081                             if(ref->data[0] != NULL && ref->frame_num == pred && ref->long_ref == 0) // ignore non existing pictures by testing data[0] pointer
3082                                 break;
3083                         }
3084                     }else{
3085                         pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
3086                         ref = h->long_ref[pic_id];
3087                     }
3088
3089                     if (i < 0) {
3090                         av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
3091                         memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
3092                     } else {
3093                         h->ref_list[list][index]= *ref;
3094                     }
3095                 }else{
3096                     av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
3097                     return -1;
3098                 }
3099             }
3100         }
3101
3102         if(h->slice_type!=B_TYPE) break;
3103     }
3104     
3105     if(h->slice_type==B_TYPE && !h->direct_spatial_mv_pred)
3106         direct_dist_scale_factor(h);
3107     direct_ref_list_init(h);
3108     return 0;    
3109 }
3110
3111 static int pred_weight_table(H264Context *h){
3112     MpegEncContext * const s = &h->s;
3113     int list, i;
3114     int luma_def, chroma_def;
3115     
3116     h->use_weight= 0;
3117     h->use_weight_chroma= 0;
3118     h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
3119     h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
3120     luma_def = 1<<h->luma_log2_weight_denom;
3121     chroma_def = 1<<h->chroma_log2_weight_denom;
3122
3123     for(list=0; list<2; list++){
3124         for(i=0; i<h->ref_count[list]; i++){
3125             int luma_weight_flag, chroma_weight_flag;
3126             
3127             luma_weight_flag= get_bits1(&s->gb);
3128             if(luma_weight_flag){
3129                 h->luma_weight[list][i]= get_se_golomb(&s->gb);
3130                 h->luma_offset[list][i]= get_se_golomb(&s->gb);
3131                 if(   h->luma_weight[list][i] != luma_def
3132                    || h->luma_offset[list][i] != 0)
3133                     h->use_weight= 1;
3134             }else{
3135                 h->luma_weight[list][i]= luma_def;
3136                 h->luma_offset[list][i]= 0;
3137             }
3138
3139             chroma_weight_flag= get_bits1(&s->gb);
3140             if(chroma_weight_flag){
3141                 int j;
3142                 for(j=0; j<2; j++){
3143                     h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
3144                     h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
3145                     if(   h->chroma_weight[list][i][j] != chroma_def
3146                        || h->chroma_offset[list][i][j] != 0)
3147                         h->use_weight_chroma= 1;
3148                 }
3149             }else{
3150                 int j;
3151                 for(j=0; j<2; j++){
3152                     h->chroma_weight[list][i][j]= chroma_def;
3153                     h->chroma_offset[list][i][j]= 0;
3154                 }
3155             }
3156         }
3157         if(h->slice_type != B_TYPE) break;
3158     }
3159     h->use_weight= h->use_weight || h->use_weight_chroma;
3160     return 0;
3161 }
3162
3163 static void implicit_weight_table(H264Context *h){
3164     MpegEncContext * const s = &h->s;
3165     int ref0, ref1;
3166     int cur_poc = s->current_picture_ptr->poc;
3167
3168     if(   h->ref_count[0] == 1 && h->ref_count[1] == 1
3169        && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
3170         h->use_weight= 0;
3171         h->use_weight_chroma= 0;
3172         return;
3173     }
3174
3175     h->use_weight= 2;
3176     h->use_weight_chroma= 2;
3177     h->luma_log2_weight_denom= 5;
3178     h->chroma_log2_weight_denom= 5;
3179
3180     /* FIXME: MBAFF */
3181     for(ref0=0; ref0 < h->ref_count[0]; ref0++){
3182         int poc0 = h->ref_list[0][ref0].poc;
3183         for(ref1=0; ref1 < h->ref_count[1]; ref1++){
3184             int poc1 = h->ref_list[1][ref1].poc;
3185             int td = clip(poc1 - poc0, -128, 127);
3186             if(td){
3187                 int tb = clip(cur_poc - poc0, -128, 127);
3188                 int tx = (16384 + (ABS(td) >> 1)) / td;
3189                 int dist_scale_factor = clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
3190                 if(dist_scale_factor < -64 || dist_scale_factor > 128)
3191                     h->implicit_weight[ref0][ref1] = 32;
3192                 else
3193                     h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
3194             }else
3195                 h->implicit_weight[ref0][ref1] = 32;
3196         }
3197     }
3198 }
3199
3200 /**
3201  * instantaneous decoder refresh.
3202  */
3203 static void idr(H264Context *h){
3204     int i,j;
3205
3206 #define CHECK_DELAY(pic) \
3207     for(j = 0; h->delayed_pic[j]; j++) \
3208         if(pic == h->delayed_pic[j]){ \
3209             pic->reference=1; \
3210             break; \
3211         }
3212
3213     for(i=0; i<16; i++){
3214         if (h->long_ref[i] != NULL) {
3215             h->long_ref[i]->reference=0;
3216             CHECK_DELAY(h->long_ref[i]);
3217             h->long_ref[i]= NULL;
3218         }
3219     }
3220     h->long_ref_count=0;
3221
3222     for(i=0; i<h->short_ref_count; i++){
3223         h->short_ref[i]->reference=0;
3224         CHECK_DELAY(h->short_ref[i]);
3225         h->short_ref[i]= NULL;
3226     }
3227     h->short_ref_count=0;
3228 }
3229 #undef CHECK_DELAY
3230
3231 /**
3232  *
3233  * @return the removed picture or NULL if an error occures
3234  */
3235 static Picture * remove_short(H264Context *h, int frame_num){
3236     MpegEncContext * const s = &h->s;
3237     int i;
3238     
3239     if(s->avctx->debug&FF_DEBUG_MMCO)
3240         av_log(h->s.avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
3241     
3242     for(i=0; i<h->short_ref_count; i++){
3243         Picture *pic= h->short_ref[i];
3244         if(s->avctx->debug&FF_DEBUG_MMCO)
3245             av_log(h->s.avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
3246         if(pic->frame_num == frame_num){
3247             h->short_ref[i]= NULL;
3248             memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i - 1)*sizeof(Picture*));
3249             h->short_ref_count--;
3250             return pic;
3251         }
3252     }
3253     return NULL;
3254 }
3255
3256 /**
3257  *
3258  * @return the removed picture or NULL if an error occures
3259  */
3260 static Picture * remove_long(H264Context *h, int i){
3261     Picture *pic;
3262
3263     pic= h->long_ref[i];
3264     h->long_ref[i]= NULL;
3265     if(pic) h->long_ref_count--;
3266
3267     return pic;
3268 }
3269
3270 /**
3271  * print short term list
3272  */
3273 static void print_short_term(H264Context *h) {
3274     uint32_t i;
3275     if(h->s.avctx->debug&FF_DEBUG_MMCO) {
3276         av_log(h->s.avctx, AV_LOG_DEBUG, "short term list:\n");
3277         for(i=0; i<h->short_ref_count; i++){
3278             Picture *pic= h->short_ref[i];
3279             av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
3280         }
3281     }
3282 }
3283
3284 /**
3285  * print long term list
3286  */
3287 static void print_long_term(H264Context *h) {
3288     uint32_t i;
3289     if(h->s.avctx->debug&FF_DEBUG_MMCO) {
3290         av_log(h->s.avctx, AV_LOG_DEBUG, "long term list:\n");
3291         for(i = 0; i < 16; i++){
3292             Picture *pic= h->long_ref[i];
3293             if (pic) {
3294                 av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
3295             }
3296         }
3297     }
3298 }
3299
3300 /**
3301  * Executes the reference picture marking (memory management control operations).
3302  */
3303 static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
3304     MpegEncContext * const s = &h->s;
3305     int i, j;
3306     int current_is_long=0;
3307     Picture *pic;
3308     
3309     if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)
3310         av_log(h->s.avctx, AV_LOG_DEBUG, "no mmco here\n");
3311         
3312     for(i=0; i<mmco_count; i++){
3313         if(s->avctx->debug&FF_DEBUG_MMCO)
3314             av_log(h->s.avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode, h->mmco[i].short_frame_num, h->mmco[i].long_index);
3315
3316         switch(mmco[i].opcode){
3317         case MMCO_SHORT2UNUSED:
3318             pic= remove_short(h, mmco[i].short_frame_num);
3319             if(pic==NULL) return -1;
3320             pic->reference= 0;
3321             break;
3322         case MMCO_SHORT2LONG:
3323             pic= remove_long(h, mmco[i].long_index);
3324             if(pic) pic->reference=0;
3325             
3326             h->long_ref[ mmco[i].long_index ]= remove_short(h, mmco[i].short_frame_num);
3327             h->long_ref[ mmco[i].long_index ]->long_ref=1;
3328             h->long_ref_count++;
3329             break;
3330         case MMCO_LONG2UNUSED:
3331             pic= remove_long(h, mmco[i].long_index);
3332             if(pic==NULL) return -1;
3333             pic->reference= 0;
3334             break;
3335         case MMCO_LONG:
3336             pic= remove_long(h, mmco[i].long_index);
3337             if(pic) pic->reference=0;
3338             
3339             h->long_ref[ mmco[i].long_index ]= s->current_picture_ptr;
3340             h->long_ref[ mmco[i].long_index ]->long_ref=1;
3341             h->long_ref_count++;
3342             
3343             current_is_long=1;
3344             break;
3345         case MMCO_SET_MAX_LONG:
3346             assert(mmco[i].long_index <= 16);
3347             // just remove the long term which index is greater than new max
3348             for(j = mmco[i].long_index; j<16; j++){
3349                 pic = remove_long(h, j);
3350                 if (pic) pic->reference=0;
3351             }
3352             break;
3353         case MMCO_RESET:
3354             while(h->short_ref_count){
3355                 pic= remove_short(h, h->short_ref[0]->frame_num);
3356                 pic->reference=0;
3357             }
3358             for(j = 0; j < 16; j++) {
3359                 pic= remove_long(h, j);
3360                 if(pic) pic->reference=0;
3361             }
3362             break;
3363         default: assert(0);
3364         }
3365     }
3366     
3367     if(!current_is_long){
3368         pic= remove_short(h, s->current_picture_ptr->frame_num);
3369         if(pic){
3370             pic->reference=0;
3371             av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
3372         }
3373         
3374         if(h->short_ref_count)
3375             memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
3376
3377         h->short_ref[0]= s->current_picture_ptr;
3378         h->short_ref[0]->long_ref=0;
3379         h->short_ref_count++;
3380     }
3381     
3382     print_short_term(h);
3383     print_long_term(h);
3384     return 0; 
3385 }
3386
3387 static int decode_ref_pic_marking(H264Context *h){
3388     MpegEncContext * const s = &h->s;
3389     int i;
3390     
3391     if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields
3392         s->broken_link= get_bits1(&s->gb) -1;
3393         h->mmco[0].long_index= get_bits1(&s->gb) - 1; // current_long_term_idx
3394         if(h->mmco[0].long_index == -1)
3395             h->mmco_index= 0;
3396         else{
3397             h->mmco[0].opcode= MMCO_LONG;
3398             h->mmco_index= 1;
3399         } 
3400     }else{
3401         if(get_bits1(&s->gb)){ // adaptive_ref_pic_marking_mode_flag
3402             for(i= 0; i<MAX_MMCO_COUNT; i++) { 
3403                 MMCOOpcode opcode= get_ue_golomb(&s->gb);;
3404
3405                 h->mmco[i].opcode= opcode;
3406                 if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){
3407                     h->mmco[i].short_frame_num= (h->frame_num - get_ue_golomb(&s->gb) - 1) & ((1<<h->sps.log2_max_frame_num)-1); //FIXME fields
3408 /*                    if(h->mmco[i].short_frame_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_frame_num ] == NULL){
3409                         fprintf(stderr, "illegal short ref in memory management control operation %d\n", mmco);
3410                         return -1;
3411                     }*/
3412                 }
3413                 if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){
3414                     h->mmco[i].long_index= get_ue_golomb(&s->gb);
3415                     if(/*h->mmco[i].long_index >= h->long_ref_count || h->long_ref[ h->mmco[i].long_index ] == NULL*/ h->mmco[i].long_index >= 16){
3416                         av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);
3417                         return -1;
3418                     }
3419                 }
3420                     
3421                 if(opcode > MMCO_LONG){
3422                     av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);
3423                     return -1;
3424                 }
3425                 if(opcode == MMCO_END)
3426                     break;
3427             }
3428             h->mmco_index= i;
3429         }else{
3430             assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
3431
3432             if(h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count){ //FIXME fields
3433                 h->mmco[0].opcode= MMCO_SHORT2UNUSED;
3434                 h->mmco[0].short_frame_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
3435                 h->mmco_index= 1;
3436             }else
3437                 h->mmco_index= 0;
3438         }
3439     }
3440     
3441     return 0; 
3442 }
3443
3444 static int init_poc(H264Context *h){
3445     MpegEncContext * const s = &h->s;
3446     const int max_frame_num= 1<<h->sps.log2_max_frame_num;
3447     int field_poc[2];
3448
3449     if(h->nal_unit_type == NAL_IDR_SLICE){
3450         h->frame_num_offset= 0;
3451     }else{
3452         if(h->frame_num < h->prev_frame_num)
3453             h->frame_num_offset= h->prev_frame_num_offset + max_frame_num;
3454         else
3455             h->frame_num_offset= h->prev_frame_num_offset;
3456     }
3457
3458     if(h->sps.poc_type==0){
3459         const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
3460
3461         if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
3462             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
3463         else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
3464             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
3465         else
3466             h->poc_msb = h->prev_poc_msb;
3467 //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
3468         field_poc[0] = 
3469         field_poc[1] = h->poc_msb + h->poc_lsb;
3470         if(s->picture_structure == PICT_FRAME) 
3471             field_poc[1] += h->delta_poc_bottom;
3472     }else if(h->sps.poc_type==1){
3473         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
3474         int i;
3475
3476         if(h->sps.poc_cycle_length != 0)
3477             abs_frame_num = h->frame_num_offset + h->frame_num;
3478         else
3479             abs_frame_num = 0;
3480
3481         if(h->nal_ref_idc==0 && abs_frame_num > 0)
3482             abs_frame_num--;
3483             
3484         expected_delta_per_poc_cycle = 0;
3485         for(i=0; i < h->sps.poc_cycle_length; i++)
3486             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
3487
3488         if(abs_frame_num > 0){
3489             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
3490             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
3491
3492             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
3493             for(i = 0; i <= frame_num_in_poc_cycle; i++)
3494                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
3495         } else
3496             expectedpoc = 0;
3497
3498         if(h->nal_ref_idc == 0) 
3499             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
3500         
3501         field_poc[0] = expectedpoc + h->delta_poc[0];
3502         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
3503
3504         if(s->picture_structure == PICT_FRAME)
3505             field_poc[1] += h->delta_poc[1];
3506     }else{
3507         int poc;
3508         if(h->nal_unit_type == NAL_IDR_SLICE){
3509             poc= 0;
3510         }else{
3511             if(h->nal_ref_idc) poc= 2*(h->frame_num_offset + h->frame_num);
3512             else               poc= 2*(h->frame_num_offset + h->frame_num) - 1;
3513         }
3514         field_poc[0]= poc;
3515         field_poc[1]= poc;
3516     }
3517     
3518     if(s->picture_structure != PICT_BOTTOM_FIELD)
3519         s->current_picture_ptr->field_poc[0]= field_poc[0];
3520     if(s->picture_structure != PICT_TOP_FIELD)
3521         s->current_picture_ptr->field_poc[1]= field_poc[1];
3522     if(s->picture_structure == PICT_FRAME) // FIXME field pix?
3523         s->current_picture_ptr->poc= FFMIN(field_poc[0], field_poc[1]);
3524
3525     return 0;
3526 }
3527
3528 /**
3529  * decodes a slice header.
3530  * this will allso call MPV_common_init() and frame_start() as needed
3531  */
3532 static int decode_slice_header(H264Context *h){
3533     MpegEncContext * const s = &h->s;
3534     int first_mb_in_slice, pps_id;
3535     int num_ref_idx_active_override_flag;
3536     static const uint8_t slice_type_map[5]= {P_TYPE, B_TYPE, I_TYPE, SP_TYPE, SI_TYPE};
3537     int slice_type;
3538     int default_ref_list_done = 0;
3539
3540     s->current_picture.reference= h->nal_ref_idc != 0;
3541     s->dropable= h->nal_ref_idc == 0;
3542
3543     first_mb_in_slice= get_ue_golomb(&s->gb);
3544
3545     slice_type= get_ue_golomb(&s->gb);
3546     if(slice_type > 9){
3547         av_log(h->s.avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", h->slice_type, s->mb_x, s->mb_y);
3548         return -1;
3549     }
3550     if(slice_type > 4){
3551         slice_type -= 5;
3552         h->slice_type_fixed=1;
3553     }else
3554         h->slice_type_fixed=0;
3555     
3556     slice_type= slice_type_map[ slice_type ];
3557     if (slice_type == I_TYPE
3558         || (h->slice_num != 0 && slice_type == h->slice_type) ) {
3559         default_ref_list_done = 1;
3560     }
3561     h->slice_type= slice_type;
3562
3563     s->pict_type= h->slice_type; // to make a few old func happy, its wrong though
3564         
3565     pps_id= get_ue_golomb(&s->gb);
3566     if(pps_id>255){
3567         av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
3568         return -1;
3569     }
3570     h->pps= h->pps_buffer[pps_id];
3571     if(h->pps.slice_group_count == 0){
3572         av_log(h->s.avctx, AV_LOG_ERROR, "non existing PPS referenced\n");
3573         return -1;
3574     }
3575
3576     h->sps= h->sps_buffer[ h->pps.sps_id ];
3577     if(h->sps.log2_max_frame_num == 0){
3578         av_log(h->s.avctx, AV_LOG_ERROR, "non existing SPS referenced\n");
3579         return -1;
3580     }
3581     
3582     s->mb_width= h->sps.mb_width;
3583     s->mb_height= h->sps.mb_height;
3584     
3585     h->b_stride=  s->mb_width*4 + 1;
3586     h->b8_stride= s->mb_width*2 + 1;
3587
3588     s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
3589     s->resync_mb_y = s->mb_y = first_mb_in_slice / s->mb_width; //FIXME AFFW
3590     
3591     s->width = 16*s->mb_width - 2*(h->sps.crop_left + h->sps.crop_right );
3592     if(h->sps.frame_mbs_only_flag)
3593         s->height= 16*s->mb_height - 2*(h->sps.crop_top  + h->sps.crop_bottom);
3594     else
3595         s->height= 16*s->mb_height - 4*(h->sps.crop_top  + h->sps.crop_bottom); //FIXME recheck
3596     
3597     if (s->context_initialized 
3598         && (   s->width != s->avctx->width || s->height != s->avctx->height)) {
3599         free_tables(h);
3600         MPV_common_end(s);
3601     }
3602     if (!s->context_initialized) {
3603         if (MPV_common_init(s) < 0)
3604             return -1;
3605
3606         alloc_tables(h);
3607
3608         s->avctx->width = s->width;
3609         s->avctx->height = s->height;
3610         s->avctx->sample_aspect_ratio= h->sps.sar;
3611         if(!s->avctx->sample_aspect_ratio.den)
3612             s->avctx->sample_aspect_ratio.den = 1;
3613
3614         if(h->sps.timing_info_present_flag && h->sps.fixed_frame_rate_flag){
3615             s->avctx->frame_rate = h->sps.time_scale;
3616             s->avctx->frame_rate_base = h->sps.num_units_in_tick;
3617         }
3618     }
3619
3620     if(h->slice_num == 0){
3621         frame_start(h);
3622     }
3623
3624     s->current_picture_ptr->frame_num= //FIXME frame_num cleanup
3625     h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
3626
3627     if(h->sps.frame_mbs_only_flag){
3628         s->picture_structure= PICT_FRAME;
3629     }else{
3630         if(get_bits1(&s->gb)) //field_pic_flag
3631             s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
3632         else
3633             s->picture_structure= PICT_FRAME;
3634     }
3635
3636     if(s->picture_structure==PICT_FRAME){
3637         h->curr_pic_num=   h->frame_num;
3638         h->max_pic_num= 1<< h->sps.log2_max_frame_num;
3639     }else{
3640         h->curr_pic_num= 2*h->frame_num;
3641         h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
3642     }
3643         
3644     if(h->nal_unit_type == NAL_IDR_SLICE){
3645         get_ue_golomb(&s->gb); /* idr_pic_id */
3646     }
3647    
3648     if(h->sps.poc_type==0){
3649         h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3650         
3651         if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
3652             h->delta_poc_bottom= get_se_golomb(&s->gb);
3653         }
3654     }
3655     
3656     if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
3657         h->delta_poc[0]= get_se_golomb(&s->gb);
3658         
3659         if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
3660             h->delta_poc[1]= get_se_golomb(&s->gb);
3661     }
3662     
3663     init_poc(h);
3664     
3665     if(h->pps.redundant_pic_cnt_present){
3666         h->redundant_pic_count= get_ue_golomb(&s->gb);
3667     }
3668
3669     //set defaults, might be overriden a few line later
3670     h->ref_count[0]= h->pps.ref_count[0];
3671     h->ref_count[1]= h->pps.ref_count[1];
3672
3673     if(h->slice_type == P_TYPE || h->slice_type == SP_TYPE || h->slice_type == B_TYPE){
3674         if(h->slice_type == B_TYPE){
3675             h->direct_spatial_mv_pred= get_bits1(&s->gb);
3676         }
3677         num_ref_idx_active_override_flag= get_bits1(&s->gb);
3678     
3679         if(num_ref_idx_active_override_flag){
3680             h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
3681             if(h->slice_type==B_TYPE)
3682                 h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
3683
3684             if(h->ref_count[0] > 32 || h->ref_count[1] > 32){
3685                 av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3686                 return -1;
3687             }
3688         }
3689     }
3690
3691     if(!default_ref_list_done){
3692         fill_default_ref_list(h);
3693     }
3694
3695     decode_ref_pic_list_reordering(h);
3696
3697     if(   (h->pps.weighted_pred          && (h->slice_type == P_TYPE || h->slice_type == SP_TYPE )) 
3698        || (h->pps.weighted_bipred_idc==1 && h->slice_type==B_TYPE ) )
3699         pred_weight_table(h);
3700     else if(h->pps.weighted_bipred_idc==2 && h->slice_type==B_TYPE)
3701         implicit_weight_table(h);
3702     else
3703         h->use_weight = 0;
3704     
3705     if(s->current_picture.reference)
3706         decode_ref_pic_marking(h);
3707
3708     if( h->slice_type != I_TYPE && h->slice_type != SI_TYPE && h->pps.cabac )
3709         h->cabac_init_idc = get_ue_golomb(&s->gb);
3710
3711     h->last_qscale_diff = 0;
3712     s->qscale = h->pps.init_qp + get_se_golomb(&s->gb);
3713     if(s->qscale<0 || s->qscale>51){
3714         av_log(s->avctx, AV_LOG_ERROR, "QP %d out of range\n", s->qscale);
3715         return -1;
3716     }
3717     h->chroma_qp = get_chroma_qp(h, s->qscale);
3718     //FIXME qscale / qp ... stuff
3719     if(h->slice_type == SP_TYPE){
3720         get_bits1(&s->gb); /* sp_for_switch_flag */
3721     }
3722     if(h->slice_type==SP_TYPE || h->slice_type == SI_TYPE){
3723         get_se_golomb(&s->gb); /* slice_qs_delta */
3724     }
3725
3726     h->deblocking_filter = 1;
3727     h->slice_alpha_c0_offset = 0;
3728     h->slice_beta_offset = 0;
3729     if( h->pps.deblocking_filter_parameters_present ) {
3730         h->deblocking_filter= get_ue_golomb(&s->gb);
3731         if(h->deblocking_filter < 2) 
3732             h->deblocking_filter^= 1; // 1<->0
3733
3734         if( h->deblocking_filter ) {
3735             h->slice_alpha_c0_offset = get_se_golomb(&s->gb) << 1;
3736             h->slice_beta_offset = get_se_golomb(&s->gb) << 1;
3737         }
3738     }
3739
3740 #if 0 //FMO
3741     if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
3742         slice_group_change_cycle= get_bits(&s->gb, ?);
3743 #endif
3744
3745     h->slice_num++;
3746
3747     if(s->avctx->debug&FF_DEBUG_PICT_INFO){
3748         av_log(h->s.avctx, AV_LOG_DEBUG, "slice:%d mb:%d %c pps:%d frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d weight:%d%s\n", 
3749                h->slice_num, first_mb_in_slice, 
3750                av_get_pict_type_char(h->slice_type),
3751                pps_id, h->frame_num,
3752                s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
3753                h->ref_count[0], h->ref_count[1],
3754                s->qscale,
3755                h->deblocking_filter,
3756                h->use_weight,
3757                h->use_weight==1 && h->use_weight_chroma ? "c" : ""
3758                );
3759     }
3760
3761     return 0;
3762 }
3763
3764 /**
3765  *
3766  */
3767 static inline int get_level_prefix(GetBitContext *gb){
3768     unsigned int buf;
3769     int log;
3770     
3771     OPEN_READER(re, gb);
3772     UPDATE_CACHE(re, gb);
3773     buf=GET_CACHE(re, gb);
3774     
3775     log= 32 - av_log2(buf);
3776 #ifdef TRACE
3777     print_bin(buf>>(32-log), log);
3778     av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d lpr @%5d in %s get_level_prefix\n", buf>>(32-log), log, log-1, get_bits_count(gb), __FILE__);
3779 #endif
3780
3781     LAST_SKIP_BITS(re, gb, log);
3782     CLOSE_READER(re, gb);
3783
3784     return log-1;
3785 }
3786
3787 /**
3788  * decodes a residual block.
3789  * @param n block index
3790  * @param scantable scantable
3791  * @param max_coeff number of coefficients in the block
3792  * @return <0 if an error occured
3793  */
3794 static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, int qp, int max_coeff){
3795     MpegEncContext * const s = &h->s;
3796     const uint16_t *qmul= dequant_coeff[qp];
3797     static const int coeff_token_table_index[17]= {0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3};
3798     int level[16], run[16];
3799     int suffix_length, zeros_left, coeff_num, coeff_token, total_coeff, i, trailing_ones;
3800
3801     //FIXME put trailing_onex into the context
3802
3803     if(n == CHROMA_DC_BLOCK_INDEX){
3804         coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
3805         total_coeff= coeff_token>>2;
3806     }else{    
3807         if(n == LUMA_DC_BLOCK_INDEX){
3808             total_coeff= pred_non_zero_count(h, 0);
3809             coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
3810             total_coeff= coeff_token>>2;
3811         }else{
3812             total_coeff= pred_non_zero_count(h, n);
3813             coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
3814             total_coeff= coeff_token>>2;
3815             h->non_zero_count_cache[ scan8[n] ]= total_coeff;
3816         }
3817     }
3818
3819     //FIXME set last_non_zero?
3820
3821     if(total_coeff==0)
3822         return 0;
3823         
3824     trailing_ones= coeff_token&3;
3825     tprintf("trailing:%d, total:%d\n", trailing_ones, total_coeff);
3826     assert(total_coeff<=16);
3827     
3828     for(i=0; i<trailing_ones; i++){
3829         level[i]= 1 - 2*get_bits1(gb);
3830     }
3831
3832     suffix_length= total_coeff > 10 && trailing_ones < 3;
3833
3834     for(; i<total_coeff; i++){
3835         const int prefix= get_level_prefix(gb);
3836         int level_code, mask;
3837
3838         if(prefix<14){ //FIXME try to build a large unified VLC table for all this
3839             if(suffix_length)
3840                 level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
3841             else
3842                 level_code= (prefix<<suffix_length); //part
3843         }else if(prefix==14){
3844             if(suffix_length)
3845                 level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
3846             else
3847                 level_code= prefix + get_bits(gb, 4); //part
3848         }else if(prefix==15){
3849             level_code= (prefix<<suffix_length) + get_bits(gb, 12); //part
3850             if(suffix_length==0) level_code+=15; //FIXME doesnt make (much)sense
3851         }else{
3852             av_log(h->s.avctx, AV_LOG_ERROR, "prefix too large at %d %d\n", s->mb_x, s->mb_y);
3853             return -1;
3854         }
3855
3856         if(i==trailing_ones && i<3) level_code+= 2; //FIXME split first iteration
3857
3858         mask= -(level_code&1);
3859         level[i]= (((2+level_code)>>1) ^ mask) - mask;
3860
3861         if(suffix_length==0) suffix_length=1; //FIXME split first iteration
3862
3863 #if 1
3864         if(ABS(level[i]) > (3<<(suffix_length-1)) && suffix_length<6) suffix_length++;
3865 #else        
3866         if((2+level_code)>>1) > (3<<(suffix_length-1)) && suffix_length<6) suffix_length++;
3867         /* ? == prefix > 2 or sth */
3868 #endif
3869         tprintf("level: %d suffix_length:%d\n", level[i], suffix_length);
3870     }
3871
3872     if(total_coeff == max_coeff)
3873         zeros_left=0;
3874     else{
3875         if(n == CHROMA_DC_BLOCK_INDEX)
3876             zeros_left= get_vlc2(gb, chroma_dc_total_zeros_vlc[ total_coeff-1 ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
3877         else
3878             zeros_left= get_vlc2(gb, total_zeros_vlc[ total_coeff-1 ].table, TOTAL_ZEROS_VLC_BITS, 1);
3879     }
3880     
3881     for(i=0; i<total_coeff-1; i++){
3882         if(zeros_left <=0)
3883             break;
3884         else if(zeros_left < 7){
3885             run[i]= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
3886         }else{
3887             run[i]= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
3888         }
3889         zeros_left -= run[i];
3890     }
3891
3892     if(zeros_left<0){
3893         av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);
3894         return -1;
3895     }
3896     
3897     for(; i<total_coeff-1; i++){
3898         run[i]= 0;
3899     }
3900
3901     run[i]= zeros_left;
3902
3903     coeff_num=-1;
3904     if(n > 24){
3905         for(i=total_coeff-1; i>=0; i--){ //FIXME merge into rundecode?
3906             int j;
3907
3908             coeff_num += run[i] + 1; //FIXME add 1 earlier ?
3909             j= scantable[ coeff_num ];
3910
3911             block[j]= level[i];
3912         }
3913     }else{
3914         for(i=total_coeff-1; i>=0; i--){ //FIXME merge into  rundecode?
3915             int j;
3916
3917             coeff_num += run[i] + 1; //FIXME add 1 earlier ?
3918             j= scantable[ coeff_num ];
3919
3920             block[j]= level[i] * qmul[j];
3921 //            printf("%d %d  ", block[j], qmul[j]);
3922         }
3923     }
3924     return 0;
3925 }
3926
3927 /**
3928  * decodes a P_SKIP or B_SKIP macroblock
3929  */
3930 static void decode_mb_skip(H264Context *h){
3931     MpegEncContext * const s = &h->s;
3932     const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3933     int mb_type;
3934     
3935     memset(h->non_zero_count[mb_xy], 0, 16);
3936     memset(h->non_zero_count_cache + 8, 0, 8*5); //FIXME ugly, remove pfui
3937
3938     if( h->slice_type == B_TYPE )
3939     {
3940         // just for fill_caches. pred_direct_motion will set the real mb_type
3941         mb_type= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_SKIP;
3942         //FIXME mbaff
3943
3944         fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
3945         pred_direct_motion(h, &mb_type);
3946         if(h->pps.cabac){
3947             fill_rectangle(h->mvd_cache[0][scan8[0]], 4, 4, 8, 0, 4);
3948             fill_rectangle(h->mvd_cache[1][scan8[0]], 4, 4, 8, 0, 4);
3949         }
3950     }
3951     else
3952     {
3953         int mx, my;
3954         mb_type= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P1L0|MB_TYPE_SKIP;
3955
3956         if(h->sps.mb_aff && s->mb_skip_run==0 && (s->mb_y&1)==0){
3957             h->mb_field_decoding_flag= get_bits1(&s->gb);
3958         }
3959         if(h->mb_field_decoding_flag)
3960             mb_type|= MB_TYPE_INTERLACED;
3961         
3962         fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
3963         pred_pskip_motion(h, &mx, &my);
3964         fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
3965         fill_rectangle(  h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx,my), 4);
3966         if(h->pps.cabac)
3967             fill_rectangle(h->mvd_cache[0][scan8[0]], 4, 4, 8, 0, 4);
3968     }
3969
3970     write_back_motion(h, mb_type);
3971     s->current_picture.mb_type[mb_xy]= mb_type|MB_TYPE_SKIP;
3972     s->current_picture.qscale_table[mb_xy]= s->qscale;
3973     h->slice_table[ mb_xy ]= h->slice_num;
3974     h->prev_mb_skiped= 1;
3975 }
3976
3977 /**
3978  * decodes a macroblock
3979  * @returns 0 if ok, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
3980  */
3981 static int decode_mb_cavlc(H264Context *h){
3982     MpegEncContext * const s = &h->s;
3983     const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3984     int mb_type, partition_count, cbp;
3985
3986     s->dsp.clear_blocks(h->mb); //FIXME avoid if allready clear (move after skip handlong?    
3987
3988     tprintf("pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
3989     cbp = 0; /* avoid warning. FIXME: find a solution without slowing
3990                 down the code */
3991     if(h->slice_type != I_TYPE && h->slice_type != SI_TYPE){
3992         if(s->mb_skip_run==-1)
3993             s->mb_skip_run= get_ue_golomb(&s->gb);
3994         
3995         if (s->mb_skip_run--) {
3996             decode_mb_skip(h);
3997             return 0;
3998         }
3999     }
4000     if(h->sps.mb_aff /* && !field pic FIXME needed? */){
4001         if((s->mb_y&1)==0)
4002             h->mb_field_decoding_flag = get_bits1(&s->gb);
4003     }else
4004         h->mb_field_decoding_flag=0; //FIXME som ed note ?!
4005     
4006     h->prev_mb_skiped= 0;
4007     
4008     mb_type= get_ue_golomb(&s->gb);
4009     if(h->slice_type == B_TYPE){
4010         if(mb_type < 23){
4011             partition_count= b_mb_type_info[mb_type].partition_count;
4012             mb_type=         b_mb_type_info[mb_type].type;
4013         }else{
4014             mb_type -= 23;
4015             goto decode_intra_mb;
4016         }
4017     }else if(h->slice_type == P_TYPE /*|| h->slice_type == SP_TYPE */){
4018         if(mb_type < 5){
4019             partition_count= p_mb_type_info[mb_type].partition_count;
4020             mb_type=         p_mb_type_info[mb_type].type;
4021         }else{
4022             mb_type -= 5;
4023             goto decode_intra_mb;
4024         }
4025     }else{
4026        assert(h->slice_type == I_TYPE);
4027 decode_intra_mb:
4028         if(mb_type > 25){
4029             av_log(h->s.avctx, AV_LOG_ERROR, "mb_type %d in %c slice to large at %d %d\n", mb_type, av_get_pict_type_char(h->slice_type), s->mb_x, s->mb_y);
4030             return -1;
4031         }
4032         partition_count=0;
4033         cbp= i_mb_type_info[mb_type].cbp;
4034         h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
4035         mb_type= i_mb_type_info[mb_type].type;
4036     }
4037
4038     if(h->mb_field_decoding_flag)
4039         mb_type |= MB_TYPE_INTERLACED;
4040
4041     s->current_picture.mb_type[mb_xy]= mb_type;
4042     h->slice_table[ mb_xy ]= h->slice_num;
4043     
4044     if(IS_INTRA_PCM(mb_type)){
4045         unsigned int x, y;
4046         
4047         // we assume these blocks are very rare so we dont optimize it
4048         align_get_bits(&s->gb);
4049         
4050         // The pixels are stored in the same order as levels in h->mb array.
4051         for(y=0; y<16; y++){
4052             const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);
4053             for(x=0; x<16; x++){
4054                 tprintf("LUMA ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
4055                 h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= get_bits(&s->gb, 8);
4056             }
4057         }
4058         for(y=0; y<8; y++){
4059             const int index= 256 + 4*(y&3) + 32*(y>>2);
4060             for(x=0; x<8; x++){
4061                 tprintf("CHROMA U ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
4062                 h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
4063             }
4064         }
4065         for(y=0; y<8; y++){
4066             const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
4067             for(x=0; x<8; x++){
4068                 tprintf("CHROMA V ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
4069                 h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
4070             }
4071         }
4072     
4073         // In deblocking, the quantiser is 0
4074         s->current_picture.qscale_table[mb_xy]= 0;
4075         h->chroma_qp = get_chroma_qp(h, 0);
4076         // All coeffs are presents
4077         memset(h->non_zero_count[mb_xy], 16, 16);
4078         
4079         return 0;
4080     }
4081         
4082     fill_caches(h, mb_type, 0);
4083
4084     //mb_pred
4085     if(IS_INTRA(mb_type)){
4086 //            init_top_left_availability(h);
4087             if(IS_INTRA4x4(mb_type)){
4088                 int i;
4089
4090 //                fill_intra4x4_pred_table(h);
4091                 for(i=0; i<16; i++){
4092                     const int mode_coded= !get_bits1(&s->gb);
4093                     const int predicted_mode=  pred_intra_mode(h, i);
4094                     int mode;
4095
4096                     if(mode_coded){
4097                         const int rem_mode= get_bits(&s->gb, 3);
4098                         if(rem_mode<predicted_mode)
4099                             mode= rem_mode;
4100                         else
4101                             mode= rem_mode + 1;
4102                     }else{
4103                         mode= predicted_mode;
4104                     }
4105                     
4106                     h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;
4107                 }
4108                 write_back_intra_pred_mode(h);
4109                 if( check_intra4x4_pred_mode(h) < 0)
4110                     return -1;
4111             }else{
4112                 h->intra16x16_pred_mode= check_intra_pred_mode(h, h->intra16x16_pred_mode);
4113                 if(h->intra16x16_pred_mode < 0)
4114                     return -1;
4115             }
4116             h->chroma_pred_mode= get_ue_golomb(&s->gb);
4117
4118             h->chroma_pred_mode= check_intra_pred_mode(h, h->chroma_pred_mode);
4119             if(h->chroma_pred_mode < 0)
4120                 return -1;
4121     }else if(partition_count==4){
4122         int i, j, sub_partition_count[4], list, ref[2][4];
4123         
4124         if(h->slice_type == B_TYPE){
4125             for(i=0; i<4; i++){
4126                 h->sub_mb_type[i]= get_ue_golomb(&s->gb);
4127                 if(h->sub_mb_type[i] >=13){
4128                     av_log(h->s.avctx, AV_LOG_ERROR, "B sub_mb_type %d out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);
4129                     return -1;
4130                 }
4131                 sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
4132                 h->sub_mb_type[i]=      b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
4133             }
4134             if(   IS_DIRECT(h->sub_mb_type[0]) || IS_DIRECT(h->sub_mb_type[1])
4135                || IS_DIRECT(h->sub_mb_type[2]) || IS_DIRECT(h->sub_mb_type[3]))
4136                 pred_direct_motion(h, &mb_type);
4137         }else{
4138             assert(h->slice_type == P_TYPE || h->slice_type == SP_TYPE); //FIXME SP correct ?
4139             for(i=0; i<4; i++){
4140                 h->sub_mb_type[i]= get_ue_golomb(&s->gb);
4141                 if(h->sub_mb_type[i] >=4){
4142                     av_log(h->s.avctx, AV_LOG_ERROR, "P sub_mb_type %d out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);
4143                     return -1;
4144                 }
4145                 sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
4146                 h->sub_mb_type[i]=      p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
4147             }
4148         }
4149         
4150         for(list=0; list<2; list++){
4151             const int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
4152             if(ref_count == 0) continue;
4153             for(i=0; i<4; i++){
4154                 if(IS_DIRECT(h->sub_mb_type[i])) continue;
4155                 if(IS_DIR(h->sub_mb_type[i], 0, list)){
4156                     ref[list][i] = get_te0_golomb(&s->gb, ref_count); //FIXME init to 0 before and skip?
4157                 }else{
4158                  //FIXME
4159                     ref[list][i] = -1;
4160                 }
4161             }
4162         }
4163         
4164         for(list=0; list<2; list++){
4165             const int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
4166             if(ref_count == 0) continue;
4167
4168             for(i=0; i<4; i++){
4169                 if(IS_DIRECT(h->sub_mb_type[i])) continue;
4170                 h->ref_cache[list][ scan8[4*i]   ]=h->ref_cache[list][ scan8[4*i]+1 ]=
4171                 h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
4172
4173                 if(IS_DIR(h->sub_mb_type[i], 0, list)){
4174                     const int sub_mb_type= h->sub_mb_type[i];
4175                     const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
4176                     for(j=0; j<sub_partition_count[i]; j++){
4177                         int mx, my;
4178                         const int index= 4*i + block_width*j;
4179                         int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
4180                         pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);
4181                         mx += get_se_golomb(&s->gb);
4182                         my += get_se_golomb(&s->gb);
4183                         tprintf("final mv:%d %d\n", mx, my);
4184
4185                         if(IS_SUB_8X8(sub_mb_type)){
4186                             mv_cache[ 0 ][0]= mv_cache[ 1 ][0]= 
4187                             mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
4188                             mv_cache[ 0 ][1]= mv_cache[ 1 ][1]= 
4189                             mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
4190                         }else if(IS_SUB_8X4(sub_mb_type)){
4191                             mv_cache[ 0 ][0]= mv_cache[ 1 ][0]= mx;
4192                             mv_cache[ 0 ][1]= mv_cache[ 1 ][1]= my;
4193                         }else if(IS_SUB_4X8(sub_mb_type)){
4194                             mv_cache[ 0 ][0]= mv_cache[ 8 ][0]= mx;
4195                             mv_cache[ 0 ][1]= mv_cache[ 8 ][1]= my;
4196                         }else{
4197                             assert(IS_SUB_4X4(sub_mb_type));
4198                             mv_cache[ 0 ][0]= mx;
4199                             mv_cache[ 0 ][1]= my;
4200                         }
4201                     }
4202                 }else{
4203                     uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
4204                     p[0] = p[1]=
4205                     p[8] = p[9]= 0;
4206                 }
4207             }
4208         }
4209     }else if(IS_DIRECT(mb_type)){
4210   &