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