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