Remove odd pairwise deblock filtering applied to MBAFF MBs.
[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 h264.c
24  * H.264 / AVC / MPEG4 part10 codec.
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #include "dsputil.h"
29 #include "avcodec.h"
30 #include "mpegvideo.h"
31 #include "h264.h"
32 #include "h264data.h"
33 #include "h264_parser.h"
34 #include "golomb.h"
35 #include "rectangle.h"
36
37 #include "cabac.h"
38 #ifdef ARCH_X86
39 #include "i386/h264_i386.h"
40 #endif
41
42 //#undef NDEBUG
43 #include <assert.h>
44
45 /**
46  * Value of Picture.reference when Picture is not a reference picture, but
47  * is held for delayed output.
48  */
49 #define DELAYED_PIC_REF 4
50
51 static VLC coeff_token_vlc[4];
52 static VLC_TYPE coeff_token_vlc_tables[520+332+280+256][2];
53 static const int coeff_token_vlc_tables_size[4]={520,332,280,256};
54
55 static VLC chroma_dc_coeff_token_vlc;
56 static VLC_TYPE chroma_dc_coeff_token_vlc_table[256][2];
57 static const int chroma_dc_coeff_token_vlc_table_size = 256;
58
59 static VLC total_zeros_vlc[15];
60 static VLC_TYPE total_zeros_vlc_tables[15][512][2];
61 static const int total_zeros_vlc_tables_size = 512;
62
63 static VLC chroma_dc_total_zeros_vlc[3];
64 static VLC_TYPE chroma_dc_total_zeros_vlc_tables[3][8][2];
65 static const int chroma_dc_total_zeros_vlc_tables_size = 8;
66
67 static VLC run_vlc[6];
68 static VLC_TYPE run_vlc_tables[6][8][2];
69 static const int run_vlc_tables_size = 8;
70
71 static VLC run7_vlc;
72 static VLC_TYPE run7_vlc_table[96][2];
73 static const int run7_vlc_table_size = 96;
74
75 static void svq3_luma_dc_dequant_idct_c(DCTELEM *block, int qp);
76 static void svq3_add_idct_c(uint8_t *dst, DCTELEM *block, int stride, int qp, int dc);
77 static void filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize);
78 static void filter_mb_fast( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize);
79 static Picture * remove_long(H264Context *h, int i, int ref_mask);
80
81 static av_always_inline uint32_t pack16to32(int a, int b){
82 #ifdef WORDS_BIGENDIAN
83    return (b&0xFFFF) + (a<<16);
84 #else
85    return (a&0xFFFF) + (b<<16);
86 #endif
87 }
88
89 const uint8_t ff_rem6[52]={
90 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,
91 };
92
93 const uint8_t ff_div6[52]={
94 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,
95 };
96
97 static const int left_block_options[4][8]={
98     {0,1,2,3,7,10,8,11},
99     {2,2,3,3,8,11,8,11},
100     {0,0,1,1,7,10,7,10},
101     {0,2,0,2,7,10,7,10}
102 };
103
104 static void fill_caches(H264Context *h, int mb_type, int for_deblock){
105     MpegEncContext * const s = &h->s;
106     const int mb_xy= h->mb_xy;
107     int topleft_xy, top_xy, topright_xy, left_xy[2];
108     int topleft_type, top_type, topright_type, left_type[2];
109     int * left_block;
110     int topleft_partition= -1;
111     int i;
112
113     top_xy     = mb_xy  - (s->mb_stride << FIELD_PICTURE);
114
115     //FIXME deblocking could skip the intra and nnz parts.
116     if(for_deblock && (h->slice_num == 1 || h->slice_table[mb_xy] == h->slice_table[top_xy]) && !FRAME_MBAFF)
117         return;
118
119     /* Wow, what a mess, why didn't they simplify the interlacing & intra
120      * stuff, I can't imagine that these complex rules are worth it. */
121
122     topleft_xy = top_xy - 1;
123     topright_xy= top_xy + 1;
124     left_xy[1] = left_xy[0] = mb_xy-1;
125     left_block = left_block_options[0];
126     if(FRAME_MBAFF){
127         const int pair_xy          = s->mb_x     + (s->mb_y & ~1)*s->mb_stride;
128         const int top_pair_xy      = pair_xy     - s->mb_stride;
129         const int topleft_pair_xy  = top_pair_xy - 1;
130         const int topright_pair_xy = top_pair_xy + 1;
131         const int topleft_mb_frame_flag  = !IS_INTERLACED(s->current_picture.mb_type[topleft_pair_xy]);
132         const int top_mb_frame_flag      = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);
133         const int topright_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[topright_pair_xy]);
134         const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);
135         const int curr_mb_frame_flag = !IS_INTERLACED(mb_type);
136         const int bottom = (s->mb_y & 1);
137         tprintf(s->avctx, "fill_caches: curr_mb_frame_flag:%d, left_mb_frame_flag:%d, topleft_mb_frame_flag:%d, top_mb_frame_flag:%d, topright_mb_frame_flag:%d\n", curr_mb_frame_flag, left_mb_frame_flag, topleft_mb_frame_flag, top_mb_frame_flag, topright_mb_frame_flag);
138         if (bottom
139                 ? !curr_mb_frame_flag // bottom macroblock
140                 : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock
141                 ) {
142             top_xy -= s->mb_stride;
143         }
144         if (bottom
145                 ? !curr_mb_frame_flag // bottom macroblock
146                 : (!curr_mb_frame_flag && !topleft_mb_frame_flag) // top macroblock
147                 ) {
148             topleft_xy -= s->mb_stride;
149         } else if(bottom && curr_mb_frame_flag && !left_mb_frame_flag) {
150             topleft_xy += s->mb_stride;
151             // take top left mv from the middle of the mb, as opposed to all other modes which use the bottom right partition
152             topleft_partition = 0;
153         }
154         if (bottom
155                 ? !curr_mb_frame_flag // bottom macroblock
156                 : (!curr_mb_frame_flag && !topright_mb_frame_flag) // top macroblock
157                 ) {
158             topright_xy -= s->mb_stride;
159         }
160         if (left_mb_frame_flag != curr_mb_frame_flag) {
161             left_xy[1] = left_xy[0] = pair_xy - 1;
162             if (curr_mb_frame_flag) {
163                 if (bottom) {
164                     left_block = left_block_options[1];
165                 } else {
166                     left_block= left_block_options[2];
167                 }
168             } else {
169                 left_xy[1] += s->mb_stride;
170                 left_block = left_block_options[3];
171             }
172         }
173     }
174
175     h->top_mb_xy = top_xy;
176     h->left_mb_xy[0] = left_xy[0];
177     h->left_mb_xy[1] = left_xy[1];
178     if(for_deblock){
179         topleft_type = 0;
180         topright_type = 0;
181         top_type     = h->slice_table[top_xy     ] < 255 ? s->current_picture.mb_type[top_xy]     : 0;
182         left_type[0] = h->slice_table[left_xy[0] ] < 255 ? s->current_picture.mb_type[left_xy[0]] : 0;
183         left_type[1] = h->slice_table[left_xy[1] ] < 255 ? s->current_picture.mb_type[left_xy[1]] : 0;
184
185         if(FRAME_MBAFF && !IS_INTRA(mb_type)){
186             int list;
187             for(list=0; list<h->list_count; list++){
188                 if(USES_LIST(mb_type,list)){
189                     uint32_t *src = (uint32_t*)s->current_picture.motion_val[list][h->mb2b_xy[mb_xy]];
190                     uint32_t *dst = (uint32_t*)h->mv_cache[list][scan8[0]];
191                     int8_t *ref = &s->current_picture.ref_index[list][h->mb2b8_xy[mb_xy]];
192                     for(i=0; i<4; i++, dst+=8, src+=h->b_stride){
193                         dst[0] = src[0];
194                         dst[1] = src[1];
195                         dst[2] = src[2];
196                         dst[3] = src[3];
197                     }
198                     *(uint32_t*)&h->ref_cache[list][scan8[ 0]] =
199                     *(uint32_t*)&h->ref_cache[list][scan8[ 2]] = pack16to32(ref[0],ref[1])*0x0101;
200                     ref += h->b8_stride;
201                     *(uint32_t*)&h->ref_cache[list][scan8[ 8]] =
202                     *(uint32_t*)&h->ref_cache[list][scan8[10]] = pack16to32(ref[0],ref[1])*0x0101;
203                 }else{
204                     fill_rectangle(&h-> mv_cache[list][scan8[ 0]], 4, 4, 8, 0, 4);
205                     fill_rectangle(&h->ref_cache[list][scan8[ 0]], 4, 4, 8, (uint8_t)LIST_NOT_USED, 1);
206                 }
207             }
208         }
209     }else{
210         topleft_type = h->slice_table[topleft_xy ] == h->slice_num ? s->current_picture.mb_type[topleft_xy] : 0;
211         top_type     = h->slice_table[top_xy     ] == h->slice_num ? s->current_picture.mb_type[top_xy]     : 0;
212         topright_type= h->slice_table[topright_xy] == h->slice_num ? s->current_picture.mb_type[topright_xy]: 0;
213         left_type[0] = h->slice_table[left_xy[0] ] == h->slice_num ? s->current_picture.mb_type[left_xy[0]] : 0;
214         left_type[1] = h->slice_table[left_xy[1] ] == h->slice_num ? s->current_picture.mb_type[left_xy[1]] : 0;
215     }
216
217     if(IS_INTRA(mb_type)){
218         h->topleft_samples_available=
219         h->top_samples_available=
220         h->left_samples_available= 0xFFFF;
221         h->topright_samples_available= 0xEEEA;
222
223         if(!IS_INTRA(top_type) && (top_type==0 || h->pps.constrained_intra_pred)){
224             h->topleft_samples_available= 0xB3FF;
225             h->top_samples_available= 0x33FF;
226             h->topright_samples_available= 0x26EA;
227         }
228         for(i=0; i<2; i++){
229             if(!IS_INTRA(left_type[i]) && (left_type[i]==0 || h->pps.constrained_intra_pred)){
230                 h->topleft_samples_available&= 0xDF5F;
231                 h->left_samples_available&= 0x5F5F;
232             }
233         }
234
235         if(!IS_INTRA(topleft_type) && (topleft_type==0 || h->pps.constrained_intra_pred))
236             h->topleft_samples_available&= 0x7FFF;
237
238         if(!IS_INTRA(topright_type) && (topright_type==0 || h->pps.constrained_intra_pred))
239             h->topright_samples_available&= 0xFBFF;
240
241         if(IS_INTRA4x4(mb_type)){
242             if(IS_INTRA4x4(top_type)){
243                 h->intra4x4_pred_mode_cache[4+8*0]= h->intra4x4_pred_mode[top_xy][4];
244                 h->intra4x4_pred_mode_cache[5+8*0]= h->intra4x4_pred_mode[top_xy][5];
245                 h->intra4x4_pred_mode_cache[6+8*0]= h->intra4x4_pred_mode[top_xy][6];
246                 h->intra4x4_pred_mode_cache[7+8*0]= h->intra4x4_pred_mode[top_xy][3];
247             }else{
248                 int pred;
249                 if(!top_type || (IS_INTER(top_type) && h->pps.constrained_intra_pred))
250                     pred= -1;
251                 else{
252                     pred= 2;
253                 }
254                 h->intra4x4_pred_mode_cache[4+8*0]=
255                 h->intra4x4_pred_mode_cache[5+8*0]=
256                 h->intra4x4_pred_mode_cache[6+8*0]=
257                 h->intra4x4_pred_mode_cache[7+8*0]= pred;
258             }
259             for(i=0; i<2; i++){
260                 if(IS_INTRA4x4(left_type[i])){
261                     h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[0+2*i]];
262                     h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[1+2*i]];
263                 }else{
264                     int pred;
265                     if(!left_type[i] || (IS_INTER(left_type[i]) && h->pps.constrained_intra_pred))
266                         pred= -1;
267                     else{
268                         pred= 2;
269                     }
270                     h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]=
271                     h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= pred;
272                 }
273             }
274         }
275     }
276
277
278 /*
279 0 . T T. T T T T
280 1 L . .L . . . .
281 2 L . .L . . . .
282 3 . T TL . . . .
283 4 L . .L . . . .
284 5 L . .. . . . .
285 */
286 //FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
287     if(top_type){
288         h->non_zero_count_cache[4+8*0]= h->non_zero_count[top_xy][4];
289         h->non_zero_count_cache[5+8*0]= h->non_zero_count[top_xy][5];
290         h->non_zero_count_cache[6+8*0]= h->non_zero_count[top_xy][6];
291         h->non_zero_count_cache[7+8*0]= h->non_zero_count[top_xy][3];
292
293         h->non_zero_count_cache[1+8*0]= h->non_zero_count[top_xy][9];
294         h->non_zero_count_cache[2+8*0]= h->non_zero_count[top_xy][8];
295
296         h->non_zero_count_cache[1+8*3]= h->non_zero_count[top_xy][12];
297         h->non_zero_count_cache[2+8*3]= h->non_zero_count[top_xy][11];
298
299     }else{
300         h->non_zero_count_cache[4+8*0]=
301         h->non_zero_count_cache[5+8*0]=
302         h->non_zero_count_cache[6+8*0]=
303         h->non_zero_count_cache[7+8*0]=
304
305         h->non_zero_count_cache[1+8*0]=
306         h->non_zero_count_cache[2+8*0]=
307
308         h->non_zero_count_cache[1+8*3]=
309         h->non_zero_count_cache[2+8*3]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
310
311     }
312
313     for (i=0; i<2; i++) {
314         if(left_type[i]){
315             h->non_zero_count_cache[3+8*1 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[0+2*i]];
316             h->non_zero_count_cache[3+8*2 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[1+2*i]];
317             h->non_zero_count_cache[0+8*1 +   8*i]= h->non_zero_count[left_xy[i]][left_block[4+2*i]];
318             h->non_zero_count_cache[0+8*4 +   8*i]= h->non_zero_count[left_xy[i]][left_block[5+2*i]];
319         }else{
320             h->non_zero_count_cache[3+8*1 + 2*8*i]=
321             h->non_zero_count_cache[3+8*2 + 2*8*i]=
322             h->non_zero_count_cache[0+8*1 +   8*i]=
323             h->non_zero_count_cache[0+8*4 +   8*i]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
324         }
325     }
326
327     if( h->pps.cabac ) {
328         // top_cbp
329         if(top_type) {
330             h->top_cbp = h->cbp_table[top_xy];
331         } else if(IS_INTRA(mb_type)) {
332             h->top_cbp = 0x1C0;
333         } else {
334             h->top_cbp = 0;
335         }
336         // left_cbp
337         if (left_type[0]) {
338             h->left_cbp = h->cbp_table[left_xy[0]] & 0x1f0;
339         } else if(IS_INTRA(mb_type)) {
340             h->left_cbp = 0x1C0;
341         } else {
342             h->left_cbp = 0;
343         }
344         if (left_type[0]) {
345             h->left_cbp |= ((h->cbp_table[left_xy[0]]>>((left_block[0]&(~1))+1))&0x1) << 1;
346         }
347         if (left_type[1]) {
348             h->left_cbp |= ((h->cbp_table[left_xy[1]]>>((left_block[2]&(~1))+1))&0x1) << 3;
349         }
350     }
351
352 #if 1
353     if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
354         int list;
355         for(list=0; list<h->list_count; list++){
356             if(!USES_LIST(mb_type, list) && !IS_DIRECT(mb_type) && !h->deblocking_filter){
357                 /*if(!h->mv_cache_clean[list]){
358                     memset(h->mv_cache [list],  0, 8*5*2*sizeof(int16_t)); //FIXME clean only input? clean at all?
359                     memset(h->ref_cache[list], PART_NOT_AVAILABLE, 8*5*sizeof(int8_t));
360                     h->mv_cache_clean[list]= 1;
361                 }*/
362                 continue;
363             }
364             h->mv_cache_clean[list]= 0;
365
366             if(USES_LIST(top_type, list)){
367                 const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
368                 const int b8_xy= h->mb2b8_xy[top_xy] + h->b8_stride;
369                 *(uint32_t*)h->mv_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 0];
370                 *(uint32_t*)h->mv_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 1];
371                 *(uint32_t*)h->mv_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 2];
372                 *(uint32_t*)h->mv_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 3];
373                 h->ref_cache[list][scan8[0] + 0 - 1*8]=
374                 h->ref_cache[list][scan8[0] + 1 - 1*8]= s->current_picture.ref_index[list][b8_xy + 0];
375                 h->ref_cache[list][scan8[0] + 2 - 1*8]=
376                 h->ref_cache[list][scan8[0] + 3 - 1*8]= s->current_picture.ref_index[list][b8_xy + 1];
377             }else{
378                 *(uint32_t*)h->mv_cache [list][scan8[0] + 0 - 1*8]=
379                 *(uint32_t*)h->mv_cache [list][scan8[0] + 1 - 1*8]=
380                 *(uint32_t*)h->mv_cache [list][scan8[0] + 2 - 1*8]=
381                 *(uint32_t*)h->mv_cache [list][scan8[0] + 3 - 1*8]= 0;
382                 *(uint32_t*)&h->ref_cache[list][scan8[0] + 0 - 1*8]= ((top_type ? LIST_NOT_USED : PART_NOT_AVAILABLE)&0xFF)*0x01010101;
383             }
384
385             for(i=0; i<2; i++){
386                 int cache_idx = scan8[0] - 1 + i*2*8;
387                 if(USES_LIST(left_type[i], list)){
388                     const int b_xy= h->mb2b_xy[left_xy[i]] + 3;
389                     const int b8_xy= h->mb2b8_xy[left_xy[i]] + 1;
390                     *(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]];
391                     *(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]];
392                     h->ref_cache[list][cache_idx  ]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[0+i*2]>>1)];
393                     h->ref_cache[list][cache_idx+8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[1+i*2]>>1)];
394                 }else{
395                     *(uint32_t*)h->mv_cache [list][cache_idx  ]=
396                     *(uint32_t*)h->mv_cache [list][cache_idx+8]= 0;
397                     h->ref_cache[list][cache_idx  ]=
398                     h->ref_cache[list][cache_idx+8]= left_type[i] ? LIST_NOT_USED : PART_NOT_AVAILABLE;
399                 }
400             }
401
402             if((for_deblock || (IS_DIRECT(mb_type) && !h->direct_spatial_mv_pred)) && !FRAME_MBAFF)
403                 continue;
404
405             if(USES_LIST(topleft_type, list)){
406                 const int b_xy = h->mb2b_xy[topleft_xy] + 3 + h->b_stride + (topleft_partition & 2*h->b_stride);
407                 const int b8_xy= h->mb2b8_xy[topleft_xy] + 1 + (topleft_partition & h->b8_stride);
408                 *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
409                 h->ref_cache[list][scan8[0] - 1 - 1*8]= s->current_picture.ref_index[list][b8_xy];
410             }else{
411                 *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= 0;
412                 h->ref_cache[list][scan8[0] - 1 - 1*8]= topleft_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
413             }
414
415             if(USES_LIST(topright_type, list)){
416                 const int b_xy= h->mb2b_xy[topright_xy] + 3*h->b_stride;
417                 const int b8_xy= h->mb2b8_xy[topright_xy] + h->b8_stride;
418                 *(uint32_t*)h->mv_cache[list][scan8[0] + 4 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
419                 h->ref_cache[list][scan8[0] + 4 - 1*8]= s->current_picture.ref_index[list][b8_xy];
420             }else{
421                 *(uint32_t*)h->mv_cache [list][scan8[0] + 4 - 1*8]= 0;
422                 h->ref_cache[list][scan8[0] + 4 - 1*8]= topright_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
423             }
424
425             if((IS_SKIP(mb_type) || IS_DIRECT(mb_type)) && !FRAME_MBAFF)
426                 continue;
427
428             h->ref_cache[list][scan8[5 ]+1] =
429             h->ref_cache[list][scan8[7 ]+1] =
430             h->ref_cache[list][scan8[13]+1] =  //FIXME remove past 3 (init somewhere else)
431             h->ref_cache[list][scan8[4 ]] =
432             h->ref_cache[list][scan8[12]] = PART_NOT_AVAILABLE;
433             *(uint32_t*)h->mv_cache [list][scan8[5 ]+1]=
434             *(uint32_t*)h->mv_cache [list][scan8[7 ]+1]=
435             *(uint32_t*)h->mv_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)
436             *(uint32_t*)h->mv_cache [list][scan8[4 ]]=
437             *(uint32_t*)h->mv_cache [list][scan8[12]]= 0;
438
439             if( h->pps.cabac ) {
440                 /* XXX beurk, Load mvd */
441                 if(USES_LIST(top_type, list)){
442                     const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
443                     *(uint32_t*)h->mvd_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 0];
444                     *(uint32_t*)h->mvd_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 1];
445                     *(uint32_t*)h->mvd_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 2];
446                     *(uint32_t*)h->mvd_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 3];
447                 }else{
448                     *(uint32_t*)h->mvd_cache [list][scan8[0] + 0 - 1*8]=
449                     *(uint32_t*)h->mvd_cache [list][scan8[0] + 1 - 1*8]=
450                     *(uint32_t*)h->mvd_cache [list][scan8[0] + 2 - 1*8]=
451                     *(uint32_t*)h->mvd_cache [list][scan8[0] + 3 - 1*8]= 0;
452                 }
453                 if(USES_LIST(left_type[0], list)){
454                     const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
455                     *(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]];
456                     *(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]];
457                 }else{
458                     *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 0*8]=
459                     *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 1*8]= 0;
460                 }
461                 if(USES_LIST(left_type[1], list)){
462                     const int b_xy= h->mb2b_xy[left_xy[1]] + 3;
463                     *(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]];
464                     *(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]];
465                 }else{
466                     *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 2*8]=
467                     *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 3*8]= 0;
468                 }
469                 *(uint32_t*)h->mvd_cache [list][scan8[5 ]+1]=
470                 *(uint32_t*)h->mvd_cache [list][scan8[7 ]+1]=
471                 *(uint32_t*)h->mvd_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)
472                 *(uint32_t*)h->mvd_cache [list][scan8[4 ]]=
473                 *(uint32_t*)h->mvd_cache [list][scan8[12]]= 0;
474
475                 if(h->slice_type_nos == FF_B_TYPE){
476                     fill_rectangle(&h->direct_cache[scan8[0]], 4, 4, 8, 0, 1);
477
478                     if(IS_DIRECT(top_type)){
479                         *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0x01010101;
480                     }else if(IS_8X8(top_type)){
481                         int b8_xy = h->mb2b8_xy[top_xy] + h->b8_stride;
482                         h->direct_cache[scan8[0] + 0 - 1*8]= h->direct_table[b8_xy];
483                         h->direct_cache[scan8[0] + 2 - 1*8]= h->direct_table[b8_xy + 1];
484                     }else{
485                         *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0;
486                     }
487
488                     if(IS_DIRECT(left_type[0]))
489                         h->direct_cache[scan8[0] - 1 + 0*8]= 1;
490                     else if(IS_8X8(left_type[0]))
491                         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)];
492                     else
493                         h->direct_cache[scan8[0] - 1 + 0*8]= 0;
494
495                     if(IS_DIRECT(left_type[1]))
496                         h->direct_cache[scan8[0] - 1 + 2*8]= 1;
497                     else if(IS_8X8(left_type[1]))
498                         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)];
499                     else
500                         h->direct_cache[scan8[0] - 1 + 2*8]= 0;
501                 }
502             }
503
504             if(FRAME_MBAFF){
505 #define MAP_MVS\
506                     MAP_F2F(scan8[0] - 1 - 1*8, topleft_type)\
507                     MAP_F2F(scan8[0] + 0 - 1*8, top_type)\
508                     MAP_F2F(scan8[0] + 1 - 1*8, top_type)\
509                     MAP_F2F(scan8[0] + 2 - 1*8, top_type)\
510                     MAP_F2F(scan8[0] + 3 - 1*8, top_type)\
511                     MAP_F2F(scan8[0] + 4 - 1*8, topright_type)\
512                     MAP_F2F(scan8[0] - 1 + 0*8, left_type[0])\
513                     MAP_F2F(scan8[0] - 1 + 1*8, left_type[0])\
514                     MAP_F2F(scan8[0] - 1 + 2*8, left_type[1])\
515                     MAP_F2F(scan8[0] - 1 + 3*8, left_type[1])
516                 if(MB_FIELD){
517 #define MAP_F2F(idx, mb_type)\
518                     if(!IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\
519                         h->ref_cache[list][idx] <<= 1;\
520                         h->mv_cache[list][idx][1] /= 2;\
521                         h->mvd_cache[list][idx][1] /= 2;\
522                     }
523                     MAP_MVS
524 #undef MAP_F2F
525                 }else{
526 #define MAP_F2F(idx, mb_type)\
527                     if(IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\
528                         h->ref_cache[list][idx] >>= 1;\
529                         h->mv_cache[list][idx][1] <<= 1;\
530                         h->mvd_cache[list][idx][1] <<= 1;\
531                     }
532                     MAP_MVS
533 #undef MAP_F2F
534                 }
535             }
536         }
537     }
538 #endif
539
540     h->neighbor_transform_size= !!IS_8x8DCT(top_type) + !!IS_8x8DCT(left_type[0]);
541 }
542
543 static inline void write_back_intra_pred_mode(H264Context *h){
544     const int mb_xy= h->mb_xy;
545
546     h->intra4x4_pred_mode[mb_xy][0]= h->intra4x4_pred_mode_cache[7+8*1];
547     h->intra4x4_pred_mode[mb_xy][1]= h->intra4x4_pred_mode_cache[7+8*2];
548     h->intra4x4_pred_mode[mb_xy][2]= h->intra4x4_pred_mode_cache[7+8*3];
549     h->intra4x4_pred_mode[mb_xy][3]= h->intra4x4_pred_mode_cache[7+8*4];
550     h->intra4x4_pred_mode[mb_xy][4]= h->intra4x4_pred_mode_cache[4+8*4];
551     h->intra4x4_pred_mode[mb_xy][5]= h->intra4x4_pred_mode_cache[5+8*4];
552     h->intra4x4_pred_mode[mb_xy][6]= h->intra4x4_pred_mode_cache[6+8*4];
553 }
554
555 /**
556  * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
557  */
558 static inline int check_intra4x4_pred_mode(H264Context *h){
559     MpegEncContext * const s = &h->s;
560     static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
561     static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
562     int i;
563
564     if(!(h->top_samples_available&0x8000)){
565         for(i=0; i<4; i++){
566             int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
567             if(status<0){
568                 av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
569                 return -1;
570             } else if(status){
571                 h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
572             }
573         }
574     }
575
576     if(!(h->left_samples_available&0x8000)){
577         for(i=0; i<4; i++){
578             int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
579             if(status<0){
580                 av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
581                 return -1;
582             } else if(status){
583                 h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
584             }
585         }
586     }
587
588     return 0;
589 } //FIXME cleanup like next
590
591 /**
592  * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
593  */
594 static inline int check_intra_pred_mode(H264Context *h, int mode){
595     MpegEncContext * const s = &h->s;
596     static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
597     static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
598
599     if(mode > 6U) {
600         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);
601         return -1;
602     }
603
604     if(!(h->top_samples_available&0x8000)){
605         mode= top[ mode ];
606         if(mode<0){
607             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);
608             return -1;
609         }
610     }
611
612     if(!(h->left_samples_available&0x8000)){
613         mode= left[ mode ];
614         if(mode<0){
615             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);
616             return -1;
617         }
618     }
619
620     return mode;
621 }
622
623 /**
624  * gets the predicted intra4x4 prediction mode.
625  */
626 static inline int pred_intra_mode(H264Context *h, int n){
627     const int index8= scan8[n];
628     const int left= h->intra4x4_pred_mode_cache[index8 - 1];
629     const int top = h->intra4x4_pred_mode_cache[index8 - 8];
630     const int min= FFMIN(left, top);
631
632     tprintf(h->s.avctx, "mode:%d %d min:%d\n", left ,top, min);
633
634     if(min<0) return DC_PRED;
635     else      return min;
636 }
637
638 static inline void write_back_non_zero_count(H264Context *h){
639     const int mb_xy= h->mb_xy;
640
641     h->non_zero_count[mb_xy][0]= h->non_zero_count_cache[7+8*1];
642     h->non_zero_count[mb_xy][1]= h->non_zero_count_cache[7+8*2];
643     h->non_zero_count[mb_xy][2]= h->non_zero_count_cache[7+8*3];
644     h->non_zero_count[mb_xy][3]= h->non_zero_count_cache[7+8*4];
645     h->non_zero_count[mb_xy][4]= h->non_zero_count_cache[4+8*4];
646     h->non_zero_count[mb_xy][5]= h->non_zero_count_cache[5+8*4];
647     h->non_zero_count[mb_xy][6]= h->non_zero_count_cache[6+8*4];
648
649     h->non_zero_count[mb_xy][9]= h->non_zero_count_cache[1+8*2];
650     h->non_zero_count[mb_xy][8]= h->non_zero_count_cache[2+8*2];
651     h->non_zero_count[mb_xy][7]= h->non_zero_count_cache[2+8*1];
652
653     h->non_zero_count[mb_xy][12]=h->non_zero_count_cache[1+8*5];
654     h->non_zero_count[mb_xy][11]=h->non_zero_count_cache[2+8*5];
655     h->non_zero_count[mb_xy][10]=h->non_zero_count_cache[2+8*4];
656 }
657
658 /**
659  * gets the predicted number of non-zero coefficients.
660  * @param n block index
661  */
662 static inline int pred_non_zero_count(H264Context *h, int n){
663     const int index8= scan8[n];
664     const int left= h->non_zero_count_cache[index8 - 1];
665     const int top = h->non_zero_count_cache[index8 - 8];
666     int i= left + top;
667
668     if(i<64) i= (i+1)>>1;
669
670     tprintf(h->s.avctx, "pred_nnz L%X T%X n%d s%d P%X\n", left, top, n, scan8[n], i&31);
671
672     return i&31;
673 }
674
675 static inline int fetch_diagonal_mv(H264Context *h, const int16_t **C, int i, int list, int part_width){
676     const int topright_ref= h->ref_cache[list][ i - 8 + part_width ];
677     MpegEncContext *s = &h->s;
678
679     /* there is no consistent mapping of mvs to neighboring locations that will
680      * make mbaff happy, so we can't move all this logic to fill_caches */
681     if(FRAME_MBAFF){
682         const uint32_t *mb_types = s->current_picture_ptr->mb_type;
683         const int16_t *mv;
684         *(uint32_t*)h->mv_cache[list][scan8[0]-2] = 0;
685         *C = h->mv_cache[list][scan8[0]-2];
686
687         if(!MB_FIELD
688            && (s->mb_y&1) && i < scan8[0]+8 && topright_ref != PART_NOT_AVAILABLE){
689             int topright_xy = s->mb_x + (s->mb_y-1)*s->mb_stride + (i == scan8[0]+3);
690             if(IS_INTERLACED(mb_types[topright_xy])){
691 #define SET_DIAG_MV(MV_OP, REF_OP, X4, Y4)\
692                 const int x4 = X4, y4 = Y4;\
693                 const int mb_type = mb_types[(x4>>2)+(y4>>2)*s->mb_stride];\
694                 if(!USES_LIST(mb_type,list))\
695                     return LIST_NOT_USED;\
696                 mv = s->current_picture_ptr->motion_val[list][x4 + y4*h->b_stride];\
697                 h->mv_cache[list][scan8[0]-2][0] = mv[0];\
698                 h->mv_cache[list][scan8[0]-2][1] = mv[1] MV_OP;\
699                 return s->current_picture_ptr->ref_index[list][(x4>>1) + (y4>>1)*h->b8_stride] REF_OP;
700
701                 SET_DIAG_MV(*2, >>1, s->mb_x*4+(i&7)-4+part_width, s->mb_y*4-1);
702             }
703         }
704         if(topright_ref == PART_NOT_AVAILABLE
705            && ((s->mb_y&1) || i >= scan8[0]+8) && (i&7)==4
706            && h->ref_cache[list][scan8[0]-1] != PART_NOT_AVAILABLE){
707             if(!MB_FIELD
708                && IS_INTERLACED(mb_types[h->left_mb_xy[0]])){
709                 SET_DIAG_MV(*2, >>1, s->mb_x*4-1, (s->mb_y|1)*4+(s->mb_y&1)*2+(i>>4)-1);
710             }
711             if(MB_FIELD
712                && !IS_INTERLACED(mb_types[h->left_mb_xy[0]])
713                && i >= scan8[0]+8){
714                 // left shift will turn LIST_NOT_USED into PART_NOT_AVAILABLE, but that's OK.
715                 SET_DIAG_MV(/2, <<1, s->mb_x*4-1, (s->mb_y&~1)*4 - 1 + ((i-scan8[0])>>3)*2);
716             }
717         }
718 #undef SET_DIAG_MV
719     }
720
721     if(topright_ref != PART_NOT_AVAILABLE){
722         *C= h->mv_cache[list][ i - 8 + part_width ];
723         return topright_ref;
724     }else{
725         tprintf(s->avctx, "topright MV not available\n");
726
727         *C= h->mv_cache[list][ i - 8 - 1 ];
728         return h->ref_cache[list][ i - 8 - 1 ];
729     }
730 }
731
732 /**
733  * gets the predicted MV.
734  * @param n the block index
735  * @param part_width the width of the partition (4, 8,16) -> (1, 2, 4)
736  * @param mx the x component of the predicted motion vector
737  * @param my the y component of the predicted motion vector
738  */
739 static inline void pred_motion(H264Context * const h, int n, int part_width, int list, int ref, int * const mx, int * const my){
740     const int index8= scan8[n];
741     const int top_ref=      h->ref_cache[list][ index8 - 8 ];
742     const int left_ref=     h->ref_cache[list][ index8 - 1 ];
743     const int16_t * const A= h->mv_cache[list][ index8 - 1 ];
744     const int16_t * const B= h->mv_cache[list][ index8 - 8 ];
745     const int16_t * C;
746     int diagonal_ref, match_count;
747
748     assert(part_width==1 || part_width==2 || part_width==4);
749
750 /* mv_cache
751   B . . A T T T T
752   U . . L . . , .
753   U . . L . . . .
754   U . . L . . , .
755   . . . L . . . .
756 */
757
758     diagonal_ref= fetch_diagonal_mv(h, &C, index8, list, part_width);
759     match_count= (diagonal_ref==ref) + (top_ref==ref) + (left_ref==ref);
760     tprintf(h->s.avctx, "pred_motion match_count=%d\n", match_count);
761     if(match_count > 1){ //most common
762         *mx= mid_pred(A[0], B[0], C[0]);
763         *my= mid_pred(A[1], B[1], C[1]);
764     }else if(match_count==1){
765         if(left_ref==ref){
766             *mx= A[0];
767             *my= A[1];
768         }else if(top_ref==ref){
769             *mx= B[0];
770             *my= B[1];
771         }else{
772             *mx= C[0];
773             *my= C[1];
774         }
775     }else{
776         if(top_ref == PART_NOT_AVAILABLE && diagonal_ref == PART_NOT_AVAILABLE && left_ref != PART_NOT_AVAILABLE){
777             *mx= A[0];
778             *my= A[1];
779         }else{
780             *mx= mid_pred(A[0], B[0], C[0]);
781             *my= mid_pred(A[1], B[1], C[1]);
782         }
783     }
784
785     tprintf(h->s.avctx, "pred_motion (%2d %2d %2d) (%2d %2d %2d) (%2d %2d %2d) -> (%2d %2d %2d) at %2d %2d %d list %d\n", top_ref, B[0], B[1],                    diagonal_ref, C[0], C[1], left_ref, A[0], A[1], ref, *mx, *my, h->s.mb_x, h->s.mb_y, n, list);
786 }
787
788 /**
789  * gets the directionally predicted 16x8 MV.
790  * @param n the block index
791  * @param mx the x component of the predicted motion vector
792  * @param my the y component of the predicted motion vector
793  */
794 static inline void pred_16x8_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
795     if(n==0){
796         const int top_ref=      h->ref_cache[list][ scan8[0] - 8 ];
797         const int16_t * const B= h->mv_cache[list][ scan8[0] - 8 ];
798
799         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);
800
801         if(top_ref == ref){
802             *mx= B[0];
803             *my= B[1];
804             return;
805         }
806     }else{
807         const int left_ref=     h->ref_cache[list][ scan8[8] - 1 ];
808         const int16_t * const A= h->mv_cache[list][ scan8[8] - 1 ];
809
810         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);
811
812         if(left_ref == ref){
813             *mx= A[0];
814             *my= A[1];
815             return;
816         }
817     }
818
819     //RARE
820     pred_motion(h, n, 4, list, ref, mx, my);
821 }
822
823 /**
824  * gets the directionally predicted 8x16 MV.
825  * @param n the block index
826  * @param mx the x component of the predicted motion vector
827  * @param my the y component of the predicted motion vector
828  */
829 static inline void pred_8x16_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
830     if(n==0){
831         const int left_ref=      h->ref_cache[list][ scan8[0] - 1 ];
832         const int16_t * const A=  h->mv_cache[list][ scan8[0] - 1 ];
833
834         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);
835
836         if(left_ref == ref){
837             *mx= A[0];
838             *my= A[1];
839             return;
840         }
841     }else{
842         const int16_t * C;
843         int diagonal_ref;
844
845         diagonal_ref= fetch_diagonal_mv(h, &C, scan8[4], list, 2);
846
847         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);
848
849         if(diagonal_ref == ref){
850             *mx= C[0];
851             *my= C[1];
852             return;
853         }
854     }
855
856     //RARE
857     pred_motion(h, n, 2, list, ref, mx, my);
858 }
859
860 static inline void pred_pskip_motion(H264Context * const h, int * const mx, int * const my){
861     const int top_ref = h->ref_cache[0][ scan8[0] - 8 ];
862     const int left_ref= h->ref_cache[0][ scan8[0] - 1 ];
863
864     tprintf(h->s.avctx, "pred_pskip: (%d) (%d) at %2d %2d\n", top_ref, left_ref, h->s.mb_x, h->s.mb_y);
865
866     if(top_ref == PART_NOT_AVAILABLE || left_ref == PART_NOT_AVAILABLE
867        || (top_ref == 0  && *(uint32_t*)h->mv_cache[0][ scan8[0] - 8 ] == 0)
868        || (left_ref == 0 && *(uint32_t*)h->mv_cache[0][ scan8[0] - 1 ] == 0)){
869
870         *mx = *my = 0;
871         return;
872     }
873
874     pred_motion(h, 0, 4, 0, 0, mx, my);
875
876     return;
877 }
878
879 static inline void direct_dist_scale_factor(H264Context * const h){
880     MpegEncContext * const s = &h->s;
881     const int poc = h->s.current_picture_ptr->field_poc[ s->picture_structure == PICT_BOTTOM_FIELD ];
882     const int poc1 = h->ref_list[1][0].poc;
883     int i;
884     for(i=0; i<h->ref_count[0]; i++){
885         int poc0 = h->ref_list[0][i].poc;
886         int td = av_clip(poc1 - poc0, -128, 127);
887         if(td == 0 || h->ref_list[0][i].long_ref){
888             h->dist_scale_factor[i] = 256;
889         }else{
890             int tb = av_clip(poc - poc0, -128, 127);
891             int tx = (16384 + (FFABS(td) >> 1)) / td;
892             h->dist_scale_factor[i] = av_clip((tb*tx + 32) >> 6, -1024, 1023);
893         }
894     }
895     if(FRAME_MBAFF){
896         for(i=0; i<h->ref_count[0]; i++){
897             h->dist_scale_factor_field[2*i] =
898             h->dist_scale_factor_field[2*i+1] = h->dist_scale_factor[i];
899         }
900     }
901 }
902 static inline void direct_ref_list_init(H264Context * const h){
903     MpegEncContext * const s = &h->s;
904     Picture * const ref1 = &h->ref_list[1][0];
905     Picture * const cur = s->current_picture_ptr;
906     int list, i, j;
907     int sidx= s->picture_structure&1;
908     int ref1sidx= ref1->reference&1;
909     for(list=0; list<2; list++){
910         cur->ref_count[sidx][list] = h->ref_count[list];
911         for(j=0; j<h->ref_count[list]; j++)
912             cur->ref_poc[sidx][list][j] = 4*h->ref_list[list][j].frame_num + (h->ref_list[list][j].reference&3);
913     }
914     if(s->picture_structure == PICT_FRAME){
915         memcpy(cur->ref_count[0], cur->ref_count[1], sizeof(cur->ref_count[0]));
916         memcpy(cur->ref_poc  [0], cur->ref_poc  [1], sizeof(cur->ref_poc  [0]));
917     }
918     if(cur->pict_type != FF_B_TYPE || h->direct_spatial_mv_pred)
919         return;
920     for(list=0; list<2; list++){
921         for(i=0; i<ref1->ref_count[ref1sidx][list]; i++){
922             int poc = ref1->ref_poc[ref1sidx][list][i];
923             if(((poc&3) == 3) != (s->picture_structure == PICT_FRAME))
924                 poc= (poc&~3) + s->picture_structure;
925             h->map_col_to_list0[list][i] = 0; /* bogus; fills in for missing frames */
926             for(j=0; j<h->ref_count[list]; j++)
927                 if(4*h->ref_list[list][j].frame_num + (h->ref_list[list][j].reference&3) == poc){
928                     h->map_col_to_list0[list][i] = j;
929                     break;
930                 }
931         }
932     }
933     if(FRAME_MBAFF){
934         for(list=0; list<2; list++){
935             for(i=0; i<ref1->ref_count[ref1sidx][list]; i++){
936                 j = h->map_col_to_list0[list][i];
937                 h->map_col_to_list0_field[list][2*i] = 2*j;
938                 h->map_col_to_list0_field[list][2*i+1] = 2*j+1;
939             }
940         }
941     }
942 }
943
944 static inline void pred_direct_motion(H264Context * const h, int *mb_type){
945     MpegEncContext * const s = &h->s;
946     int b8_stride = h->b8_stride;
947     int b4_stride = h->b_stride;
948     int mb_xy = h->mb_xy;
949     int mb_type_col[2];
950     const int16_t (*l1mv0)[2], (*l1mv1)[2];
951     const int8_t *l1ref0, *l1ref1;
952     const int is_b8x8 = IS_8X8(*mb_type);
953     unsigned int sub_mb_type;
954     int i8, i4;
955
956 #define MB_TYPE_16x16_OR_INTRA (MB_TYPE_16x16|MB_TYPE_INTRA4x4|MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM)
957
958     if(IS_INTERLACED(h->ref_list[1][0].mb_type[mb_xy])){ // AFL/AFR/FR/FL -> AFL/FL
959         if(h->ref_list[1][0].reference == PICT_FRAME){   // AFL/AFR/FR/FL -> AFL
960             if(!IS_INTERLACED(*mb_type)){                //     AFR/FR    -> AFL
961                 int cur_poc = s->current_picture_ptr->poc;
962                 int *col_poc = h->ref_list[1]->field_poc;
963                 int col_parity = FFABS(col_poc[0] - cur_poc) >= FFABS(col_poc[1] - cur_poc);
964                 mb_xy= s->mb_x + ((s->mb_y&~1) + col_parity)*s->mb_stride;
965                 b8_stride = 0;
966             }
967         }else if(!(s->picture_structure & h->ref_list[1][0].reference)){// FL -> FL & differ parity
968             int fieldoff= 2*(h->ref_list[1][0].reference)-3;
969             mb_xy += s->mb_stride*fieldoff;
970         }
971         goto single_col;
972     }else{                                               // AFL/AFR/FR/FL -> AFR/FR
973         if(IS_INTERLACED(*mb_type)){                     // AFL       /FL -> AFR/FR
974             mb_xy= s->mb_x + (s->mb_y&~1)*s->mb_stride;
975             mb_type_col[0] = h->ref_list[1][0].mb_type[mb_xy];
976             mb_type_col[1] = h->ref_list[1][0].mb_type[mb_xy + s->mb_stride];
977             b8_stride *= 3;
978             b4_stride *= 6;
979             //FIXME IS_8X8(mb_type_col[0]) && !h->sps.direct_8x8_inference_flag
980             if(    (mb_type_col[0] & MB_TYPE_16x16_OR_INTRA)
981                 && (mb_type_col[1] & MB_TYPE_16x16_OR_INTRA)
982                 && !is_b8x8){
983                 sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
984                 *mb_type   |= MB_TYPE_16x8 |MB_TYPE_L0L1|MB_TYPE_DIRECT2; /* B_16x8 */
985             }else{
986                 sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
987                 *mb_type   |= MB_TYPE_8x8|MB_TYPE_L0L1;
988             }
989         }else{                                           //     AFR/FR    -> AFR/FR
990 single_col:
991             mb_type_col[0] =
992             mb_type_col[1] = h->ref_list[1][0].mb_type[mb_xy];
993             if(IS_8X8(mb_type_col[0]) && !h->sps.direct_8x8_inference_flag){
994                 /* FIXME save sub mb types from previous frames (or derive from MVs)
995                 * so we know exactly what block size to use */
996                 sub_mb_type = MB_TYPE_8x8|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_4x4 */
997                 *mb_type   |= MB_TYPE_8x8|MB_TYPE_L0L1;
998             }else if(!is_b8x8 && (mb_type_col[0] & MB_TYPE_16x16_OR_INTRA)){
999                 sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
1000                 *mb_type   |= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_16x16 */
1001             }else{
1002                 sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
1003                 *mb_type   |= MB_TYPE_8x8|MB_TYPE_L0L1;
1004             }
1005         }
1006     }
1007
1008     l1mv0  = &h->ref_list[1][0].motion_val[0][h->mb2b_xy [mb_xy]];
1009     l1mv1  = &h->ref_list[1][0].motion_val[1][h->mb2b_xy [mb_xy]];
1010     l1ref0 = &h->ref_list[1][0].ref_index [0][h->mb2b8_xy[mb_xy]];
1011     l1ref1 = &h->ref_list[1][0].ref_index [1][h->mb2b8_xy[mb_xy]];
1012     if(!b8_stride){
1013         if(s->mb_y&1){
1014             l1ref0 += h->b8_stride;
1015             l1ref1 += h->b8_stride;
1016             l1mv0  +=  2*b4_stride;
1017             l1mv1  +=  2*b4_stride;
1018         }
1019     }
1020
1021     if(h->direct_spatial_mv_pred){
1022         int ref[2];
1023         int mv[2][2];
1024         int list;
1025
1026         /* FIXME interlacing + spatial direct uses wrong colocated block positions */
1027
1028         /* ref = min(neighbors) */
1029         for(list=0; list<2; list++){
1030             int refa = h->ref_cache[list][scan8[0] - 1];
1031             int refb = h->ref_cache[list][scan8[0] - 8];
1032             int refc = h->ref_cache[list][scan8[0] - 8 + 4];
1033             if(refc == PART_NOT_AVAILABLE)
1034                 refc = h->ref_cache[list][scan8[0] - 8 - 1];
1035             ref[list] = FFMIN3((unsigned)refa, (unsigned)refb, (unsigned)refc);
1036             if(ref[list] < 0)
1037                 ref[list] = -1;
1038         }
1039
1040         if(ref[0] < 0 && ref[1] < 0){
1041             ref[0] = ref[1] = 0;
1042             mv[0][0] = mv[0][1] =
1043             mv[1][0] = mv[1][1] = 0;
1044         }else{
1045             for(list=0; list<2; list++){
1046                 if(ref[list] >= 0)
1047                     pred_motion(h, 0, 4, list, ref[list], &mv[list][0], &mv[list][1]);
1048                 else
1049                     mv[list][0] = mv[list][1] = 0;
1050             }
1051         }
1052
1053         if(ref[1] < 0){
1054             if(!is_b8x8)
1055                 *mb_type &= ~MB_TYPE_L1;
1056             sub_mb_type &= ~MB_TYPE_L1;
1057         }else if(ref[0] < 0){
1058             if(!is_b8x8)
1059                 *mb_type &= ~MB_TYPE_L0;
1060             sub_mb_type &= ~MB_TYPE_L0;
1061         }
1062
1063         if(IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col[0])){
1064             for(i8=0; i8<4; i8++){
1065                 int x8 = i8&1;
1066                 int y8 = i8>>1;
1067                 int xy8 = x8+y8*b8_stride;
1068                 int xy4 = 3*x8+y8*b4_stride;
1069                 int a=0, b=0;
1070
1071                 if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1072                     continue;
1073                 h->sub_mb_type[i8] = sub_mb_type;
1074
1075                 fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[0], 1);
1076                 fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[1], 1);
1077                 if(!IS_INTRA(mb_type_col[y8])
1078                    && (   (l1ref0[xy8] == 0 && FFABS(l1mv0[xy4][0]) <= 1 && FFABS(l1mv0[xy4][1]) <= 1)
1079                        || (l1ref0[xy8]  < 0 && l1ref1[xy8] == 0 && FFABS(l1mv1[xy4][0]) <= 1 && FFABS(l1mv1[xy4][1]) <= 1))){
1080                     if(ref[0] > 0)
1081                         a= pack16to32(mv[0][0],mv[0][1]);
1082                     if(ref[1] > 0)
1083                         b= pack16to32(mv[1][0],mv[1][1]);
1084                 }else{
1085                     a= pack16to32(mv[0][0],mv[0][1]);
1086                     b= pack16to32(mv[1][0],mv[1][1]);
1087                 }
1088                 fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, a, 4);
1089                 fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, b, 4);
1090             }
1091         }else if(IS_16X16(*mb_type)){
1092             int a=0, b=0;
1093
1094             fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);
1095             fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);
1096             if(!IS_INTRA(mb_type_col[0])
1097                && (   (l1ref0[0] == 0 && FFABS(l1mv0[0][0]) <= 1 && FFABS(l1mv0[0][1]) <= 1)
1098                    || (l1ref0[0]  < 0 && l1ref1[0] == 0 && FFABS(l1mv1[0][0]) <= 1 && FFABS(l1mv1[0][1]) <= 1
1099                        && (h->x264_build>33 || !h->x264_build)))){
1100                 if(ref[0] > 0)
1101                     a= pack16to32(mv[0][0],mv[0][1]);
1102                 if(ref[1] > 0)
1103                     b= pack16to32(mv[1][0],mv[1][1]);
1104             }else{
1105                 a= pack16to32(mv[0][0],mv[0][1]);
1106                 b= pack16to32(mv[1][0],mv[1][1]);
1107             }
1108             fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);
1109             fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);
1110         }else{
1111             for(i8=0; i8<4; i8++){
1112                 const int x8 = i8&1;
1113                 const int y8 = i8>>1;
1114
1115                 if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1116                     continue;
1117                 h->sub_mb_type[i8] = sub_mb_type;
1118
1119                 fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mv[0][0],mv[0][1]), 4);
1120                 fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mv[1][0],mv[1][1]), 4);
1121                 fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[0], 1);
1122                 fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[1], 1);
1123
1124                 /* col_zero_flag */
1125                 if(!IS_INTRA(mb_type_col[0]) && (   l1ref0[x8 + y8*b8_stride] == 0
1126                                               || (l1ref0[x8 + y8*b8_stride] < 0 && l1ref1[x8 + y8*b8_stride] == 0
1127                                                   && (h->x264_build>33 || !h->x264_build)))){
1128                     const int16_t (*l1mv)[2]= l1ref0[x8 + y8*b8_stride] == 0 ? l1mv0 : l1mv1;
1129                     if(IS_SUB_8X8(sub_mb_type)){
1130                         const int16_t *mv_col = l1mv[x8*3 + y8*3*b4_stride];
1131                         if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){
1132                             if(ref[0] == 0)
1133                                 fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
1134                             if(ref[1] == 0)
1135                                 fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
1136                         }
1137                     }else
1138                     for(i4=0; i4<4; i4++){
1139                         const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*b4_stride];
1140                         if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){
1141                             if(ref[0] == 0)
1142                                 *(uint32_t*)h->mv_cache[0][scan8[i8*4+i4]] = 0;
1143                             if(ref[1] == 0)
1144                                 *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] = 0;
1145                         }
1146                     }
1147                 }
1148             }
1149         }
1150     }else{ /* direct temporal mv pred */
1151         const int *map_col_to_list0[2] = {h->map_col_to_list0[0], h->map_col_to_list0[1]};
1152         const int *dist_scale_factor = h->dist_scale_factor;
1153
1154         if(FRAME_MBAFF && IS_INTERLACED(*mb_type)){
1155             map_col_to_list0[0] = h->map_col_to_list0_field[0];
1156             map_col_to_list0[1] = h->map_col_to_list0_field[1];
1157             dist_scale_factor = h->dist_scale_factor_field;
1158         }
1159         if(IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col[0])){
1160             /* FIXME assumes direct_8x8_inference == 1 */
1161             int y_shift  = 2*!IS_INTERLACED(*mb_type);
1162             int ref_shift= FRAME_MBAFF ? y_shift : 1;
1163
1164             for(i8=0; i8<4; i8++){
1165                 const int x8 = i8&1;
1166                 const int y8 = i8>>1;
1167                 int ref0, scale;
1168                 const int16_t (*l1mv)[2]= l1mv0;
1169
1170                 if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1171                     continue;
1172                 h->sub_mb_type[i8] = sub_mb_type;
1173
1174                 fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
1175                 if(IS_INTRA(mb_type_col[y8])){
1176                     fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
1177                     fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
1178                     fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
1179                     continue;
1180                 }
1181
1182                 ref0 = l1ref0[x8 + y8*b8_stride];
1183                 if(ref0 >= 0)
1184                     ref0 = map_col_to_list0[0][ref0*2>>ref_shift];
1185                 else{
1186                     ref0 = map_col_to_list0[1][l1ref1[x8 + y8*b8_stride]*2>>ref_shift];
1187                     l1mv= l1mv1;
1188                 }
1189                 scale = dist_scale_factor[ref0];
1190                 fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
1191
1192                 {
1193                     const int16_t *mv_col = l1mv[x8*3 + y8*b4_stride];
1194                     int my_col = (mv_col[1]<<y_shift)/2;
1195                     int mx = (scale * mv_col[0] + 128) >> 8;
1196                     int my = (scale * my_col + 128) >> 8;
1197                     fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mx,my), 4);
1198                     fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mx-mv_col[0],my-my_col), 4);
1199                 }
1200             }
1201             return;
1202         }
1203
1204         /* one-to-one mv scaling */
1205
1206         if(IS_16X16(*mb_type)){
1207             int ref, mv0, mv1;
1208
1209             fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, 0, 1);
1210             if(IS_INTRA(mb_type_col[0])){
1211                 ref=mv0=mv1=0;
1212             }else{
1213                 const int ref0 = l1ref0[0] >= 0 ? map_col_to_list0[0][l1ref0[0]]
1214                                                 : map_col_to_list0[1][l1ref1[0]];
1215                 const int scale = dist_scale_factor[ref0];
1216                 const int16_t *mv_col = l1ref0[0] >= 0 ? l1mv0[0] : l1mv1[0];
1217                 int mv_l0[2];
1218                 mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
1219                 mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
1220                 ref= ref0;
1221                 mv0= pack16to32(mv_l0[0],mv_l0[1]);
1222                 mv1= pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
1223             }
1224             fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
1225             fill_rectangle(&h-> mv_cache[0][scan8[0]], 4, 4, 8, mv0, 4);
1226             fill_rectangle(&h-> mv_cache[1][scan8[0]], 4, 4, 8, mv1, 4);
1227         }else{
1228             for(i8=0; i8<4; i8++){
1229                 const int x8 = i8&1;
1230                 const int y8 = i8>>1;
1231                 int ref0, scale;
1232                 const int16_t (*l1mv)[2]= l1mv0;
1233
1234                 if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1235                     continue;
1236                 h->sub_mb_type[i8] = sub_mb_type;
1237                 fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
1238                 if(IS_INTRA(mb_type_col[0])){
1239                     fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
1240                     fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
1241                     fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
1242                     continue;
1243                 }
1244
1245                 ref0 = l1ref0[x8 + y8*b8_stride];
1246                 if(ref0 >= 0)
1247                     ref0 = map_col_to_list0[0][ref0];
1248                 else{
1249                     ref0 = map_col_to_list0[1][l1ref1[x8 + y8*b8_stride]];
1250                     l1mv= l1mv1;
1251                 }
1252                 scale = dist_scale_factor[ref0];
1253
1254                 fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
1255                 if(IS_SUB_8X8(sub_mb_type)){
1256                     const int16_t *mv_col = l1mv[x8*3 + y8*3*b4_stride];
1257                     int mx = (scale * mv_col[0] + 128) >> 8;
1258                     int my = (scale * mv_col[1] + 128) >> 8;
1259                     fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mx,my), 4);
1260                     fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mx-mv_col[0],my-mv_col[1]), 4);
1261                 }else
1262                 for(i4=0; i4<4; i4++){
1263                     const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*b4_stride];
1264                     int16_t *mv_l0 = h->mv_cache[0][scan8[i8*4+i4]];
1265                     mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
1266                     mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
1267                     *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] =
1268                         pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
1269                 }
1270             }
1271         }
1272     }
1273 }
1274
1275 static inline void write_back_motion(H264Context *h, int mb_type){
1276     MpegEncContext * const s = &h->s;
1277     const int b_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
1278     const int b8_xy= 2*s->mb_x + 2*s->mb_y*h->b8_stride;
1279     int list;
1280
1281     if(!USES_LIST(mb_type, 0))
1282         fill_rectangle(&s->current_picture.ref_index[0][b8_xy], 2, 2, h->b8_stride, (uint8_t)LIST_NOT_USED, 1);
1283
1284     for(list=0; list<h->list_count; list++){
1285         int y;
1286         if(!USES_LIST(mb_type, list))
1287             continue;
1288
1289         for(y=0; y<4; y++){
1290             *(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];
1291             *(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];
1292         }
1293         if( h->pps.cabac ) {
1294             if(IS_SKIP(mb_type))
1295                 fill_rectangle(h->mvd_table[list][b_xy], 4, 4, h->b_stride, 0, 4);
1296             else
1297             for(y=0; y<4; y++){
1298                 *(uint64_t*)h->mvd_table[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+0 + 8*y];
1299                 *(uint64_t*)h->mvd_table[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+2 + 8*y];
1300             }
1301         }
1302
1303         {
1304             int8_t *ref_index = &s->current_picture.ref_index[list][b8_xy];
1305             ref_index[0+0*h->b8_stride]= h->ref_cache[list][scan8[0]];
1306             ref_index[1+0*h->b8_stride]= h->ref_cache[list][scan8[4]];
1307             ref_index[0+1*h->b8_stride]= h->ref_cache[list][scan8[8]];
1308             ref_index[1+1*h->b8_stride]= h->ref_cache[list][scan8[12]];
1309         }
1310     }
1311
1312     if(h->slice_type_nos == FF_B_TYPE && h->pps.cabac){
1313         if(IS_8X8(mb_type)){
1314             uint8_t *direct_table = &h->direct_table[b8_xy];
1315             direct_table[1+0*h->b8_stride] = IS_DIRECT(h->sub_mb_type[1]) ? 1 : 0;
1316             direct_table[0+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[2]) ? 1 : 0;
1317             direct_table[1+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[3]) ? 1 : 0;
1318         }
1319     }
1320 }
1321
1322 /**
1323  * Decodes a network abstraction layer unit.
1324  * @param consumed is the number of bytes used as input
1325  * @param length is the length of the array
1326  * @param dst_length is the number of decoded bytes FIXME here or a decode rbsp tailing?
1327  * @returns decoded bytes, might be src+1 if no escapes
1328  */
1329 static const uint8_t *decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
1330     int i, si, di;
1331     uint8_t *dst;
1332     int bufidx;
1333
1334 //    src[0]&0x80;                //forbidden bit
1335     h->nal_ref_idc= src[0]>>5;
1336     h->nal_unit_type= src[0]&0x1F;
1337
1338     src++; length--;
1339 #if 0
1340     for(i=0; i<length; i++)
1341         printf("%2X ", src[i]);
1342 #endif
1343     for(i=0; i+1<length; i+=2){
1344         if(src[i]) continue;
1345         if(i>0 && src[i-1]==0) i--;
1346         if(i+2<length && src[i+1]==0 && src[i+2]<=3){
1347             if(src[i+2]!=3){
1348                 /* startcode, so we must be past the end */
1349                 length=i;
1350             }
1351             break;
1352         }
1353     }
1354
1355     if(i>=length-1){ //no escaped 0
1356         *dst_length= length;
1357         *consumed= length+1; //+1 for the header
1358         return src;
1359     }
1360
1361     bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
1362     h->rbsp_buffer[bufidx]= av_fast_realloc(h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length);
1363     dst= h->rbsp_buffer[bufidx];
1364
1365     if (dst == NULL){
1366         return NULL;
1367     }
1368
1369 //printf("decoding esc\n");
1370     si=di=0;
1371     while(si<length){
1372         //remove escapes (very rare 1:2^22)
1373         if(si+2<length && src[si]==0 && src[si+1]==0 && src[si+2]<=3){
1374             if(src[si+2]==3){ //escape
1375                 dst[di++]= 0;
1376                 dst[di++]= 0;
1377                 si+=3;
1378                 continue;
1379             }else //next start code
1380                 break;
1381         }
1382
1383         dst[di++]= src[si++];
1384     }
1385
1386     *dst_length= di;
1387     *consumed= si + 1;//+1 for the header
1388 //FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
1389     return dst;
1390 }
1391
1392 /**
1393  * identifies the exact end of the bitstream
1394  * @return the length of the trailing, or 0 if damaged
1395  */
1396 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src){
1397     int v= *src;
1398     int r;
1399
1400     tprintf(h->s.avctx, "rbsp trailing %X\n", v);
1401
1402     for(r=1; r<9; r++){
1403         if(v&1) return r;
1404         v>>=1;
1405     }
1406     return 0;
1407 }
1408
1409 /**
1410  * IDCT transforms the 16 dc values and dequantizes them.
1411  * @param qp quantization parameter
1412  */
1413 static void h264_luma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
1414 #define stride 16
1415     int i;
1416     int temp[16]; //FIXME check if this is a good idea
1417     static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
1418     static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
1419
1420 //memset(block, 64, 2*256);
1421 //return;
1422     for(i=0; i<4; i++){
1423         const int offset= y_offset[i];
1424         const int z0= block[offset+stride*0] + block[offset+stride*4];
1425         const int z1= block[offset+stride*0] - block[offset+stride*4];
1426         const int z2= block[offset+stride*1] - block[offset+stride*5];
1427         const int z3= block[offset+stride*1] + block[offset+stride*5];
1428
1429         temp[4*i+0]= z0+z3;
1430         temp[4*i+1]= z1+z2;
1431         temp[4*i+2]= z1-z2;
1432         temp[4*i+3]= z0-z3;
1433     }
1434
1435     for(i=0; i<4; i++){
1436         const int offset= x_offset[i];
1437         const int z0= temp[4*0+i] + temp[4*2+i];
1438         const int z1= temp[4*0+i] - temp[4*2+i];
1439         const int z2= temp[4*1+i] - temp[4*3+i];
1440         const int z3= temp[4*1+i] + temp[4*3+i];
1441
1442         block[stride*0 +offset]= ((((z0 + z3)*qmul + 128 ) >> 8)); //FIXME think about merging this into decode_residual
1443         block[stride*2 +offset]= ((((z1 + z2)*qmul + 128 ) >> 8));
1444         block[stride*8 +offset]= ((((z1 - z2)*qmul + 128 ) >> 8));
1445         block[stride*10+offset]= ((((z0 - z3)*qmul + 128 ) >> 8));
1446     }
1447 }
1448
1449 #if 0
1450 /**
1451  * DCT transforms the 16 dc values.
1452  * @param qp quantization parameter ??? FIXME
1453  */
1454 static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
1455 //    const int qmul= dequant_coeff[qp][0];
1456     int i;
1457     int temp[16]; //FIXME check if this is a good idea
1458     static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
1459     static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
1460
1461     for(i=0; i<4; i++){
1462         const int offset= y_offset[i];
1463         const int z0= block[offset+stride*0] + block[offset+stride*4];
1464         const int z1= block[offset+stride*0] - block[offset+stride*4];
1465         const int z2= block[offset+stride*1] - block[offset+stride*5];
1466         const int z3= block[offset+stride*1] + block[offset+stride*5];
1467
1468         temp[4*i+0]= z0+z3;
1469         temp[4*i+1]= z1+z2;
1470         temp[4*i+2]= z1-z2;
1471         temp[4*i+3]= z0-z3;
1472     }
1473
1474     for(i=0; i<4; i++){
1475         const int offset= x_offset[i];
1476         const int z0= temp[4*0+i] + temp[4*2+i];
1477         const int z1= temp[4*0+i] - temp[4*2+i];
1478         const int z2= temp[4*1+i] - temp[4*3+i];
1479         const int z3= temp[4*1+i] + temp[4*3+i];
1480
1481         block[stride*0 +offset]= (z0 + z3)>>1;
1482         block[stride*2 +offset]= (z1 + z2)>>1;
1483         block[stride*8 +offset]= (z1 - z2)>>1;
1484         block[stride*10+offset]= (z0 - z3)>>1;
1485     }
1486 }
1487 #endif
1488
1489 #undef xStride
1490 #undef stride
1491
1492 static void chroma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
1493     const int stride= 16*2;
1494     const int xStride= 16;
1495     int a,b,c,d,e;
1496
1497     a= block[stride*0 + xStride*0];
1498     b= block[stride*0 + xStride*1];
1499     c= block[stride*1 + xStride*0];
1500     d= block[stride*1 + xStride*1];
1501
1502     e= a-b;
1503     a= a+b;
1504     b= c-d;
1505     c= c+d;
1506
1507     block[stride*0 + xStride*0]= ((a+c)*qmul) >> 7;
1508     block[stride*0 + xStride*1]= ((e+b)*qmul) >> 7;
1509     block[stride*1 + xStride*0]= ((a-c)*qmul) >> 7;
1510     block[stride*1 + xStride*1]= ((e-b)*qmul) >> 7;
1511 }
1512
1513 #if 0
1514 static void chroma_dc_dct_c(DCTELEM *block){
1515     const int stride= 16*2;
1516     const int xStride= 16;
1517     int a,b,c,d,e;
1518
1519     a= block[stride*0 + xStride*0];
1520     b= block[stride*0 + xStride*1];
1521     c= block[stride*1 + xStride*0];
1522     d= block[stride*1 + xStride*1];
1523
1524     e= a-b;
1525     a= a+b;
1526     b= c-d;
1527     c= c+d;
1528
1529     block[stride*0 + xStride*0]= (a+c);
1530     block[stride*0 + xStride*1]= (e+b);
1531     block[stride*1 + xStride*0]= (a-c);
1532     block[stride*1 + xStride*1]= (e-b);
1533 }
1534 #endif
1535
1536 /**
1537  * gets the chroma qp.
1538  */
1539 static inline int get_chroma_qp(H264Context *h, int t, int qscale){
1540     return h->pps.chroma_qp_table[t][qscale];
1541 }
1542
1543 //FIXME need to check that this does not overflow signed 32 bit for low qp, I am not sure, it's very close
1544 //FIXME check that gcc inlines this (and optimizes intra & separate_dc stuff away)
1545 static inline int quantize_c(DCTELEM *block, uint8_t *scantable, int qscale, int intra, int separate_dc){
1546     int i;
1547     const int * const quant_table= quant_coeff[qscale];
1548     const int bias= intra ? (1<<QUANT_SHIFT)/3 : (1<<QUANT_SHIFT)/6;
1549     const unsigned int threshold1= (1<<QUANT_SHIFT) - bias - 1;
1550     const unsigned int threshold2= (threshold1<<1);
1551     int last_non_zero;
1552
1553     if(separate_dc){
1554         if(qscale<=18){
1555             //avoid overflows
1556             const int dc_bias= intra ? (1<<(QUANT_SHIFT-2))/3 : (1<<(QUANT_SHIFT-2))/6;
1557             const unsigned int dc_threshold1= (1<<(QUANT_SHIFT-2)) - dc_bias - 1;
1558             const unsigned int dc_threshold2= (dc_threshold1<<1);
1559
1560             int level= block[0]*quant_coeff[qscale+18][0];
1561             if(((unsigned)(level+dc_threshold1))>dc_threshold2){
1562                 if(level>0){
1563                     level= (dc_bias + level)>>(QUANT_SHIFT-2);
1564                     block[0]= level;
1565                 }else{
1566                     level= (dc_bias - level)>>(QUANT_SHIFT-2);
1567                     block[0]= -level;
1568                 }
1569 //                last_non_zero = i;
1570             }else{
1571                 block[0]=0;
1572             }
1573         }else{
1574             const int dc_bias= intra ? (1<<(QUANT_SHIFT+1))/3 : (1<<(QUANT_SHIFT+1))/6;
1575             const unsigned int dc_threshold1= (1<<(QUANT_SHIFT+1)) - dc_bias - 1;
1576             const unsigned int dc_threshold2= (dc_threshold1<<1);
1577
1578             int level= block[0]*quant_table[0];
1579             if(((unsigned)(level+dc_threshold1))>dc_threshold2){
1580                 if(level>0){
1581                     level= (dc_bias + level)>>(QUANT_SHIFT+1);
1582                     block[0]= level;
1583                 }else{
1584                     level= (dc_bias - level)>>(QUANT_SHIFT+1);
1585                     block[0]= -level;
1586                 }
1587 //                last_non_zero = i;
1588             }else{
1589                 block[0]=0;
1590             }
1591         }
1592         last_non_zero= 0;
1593         i=1;
1594     }else{
1595         last_non_zero= -1;
1596         i=0;
1597     }
1598
1599     for(; i<16; i++){
1600         const int j= scantable[i];
1601         int level= block[j]*quant_table[j];
1602
1603 //        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
1604 //           || bias-level >= (1<<(QMAT_SHIFT - 3))){
1605         if(((unsigned)(level+threshold1))>threshold2){
1606             if(level>0){
1607                 level= (bias + level)>>QUANT_SHIFT;
1608                 block[j]= level;
1609             }else{
1610                 level= (bias - level)>>QUANT_SHIFT;
1611                 block[j]= -level;
1612             }
1613             last_non_zero = i;
1614         }else{
1615             block[j]=0;
1616         }
1617     }
1618
1619     return last_non_zero;
1620 }
1621
1622 static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
1623                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1624                            int src_x_offset, int src_y_offset,
1625                            qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
1626     MpegEncContext * const s = &h->s;
1627     const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
1628     int my=       h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
1629     const int luma_xy= (mx&3) + ((my&3)<<2);
1630     uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*h->mb_linesize;
1631     uint8_t * src_cb, * src_cr;
1632     int extra_width= h->emu_edge_width;
1633     int extra_height= h->emu_edge_height;
1634     int emu=0;
1635     const int full_mx= mx>>2;
1636     const int full_my= my>>2;
1637     const int pic_width  = 16*s->mb_width;
1638     const int pic_height = 16*s->mb_height >> MB_FIELD;
1639
1640     if(!pic->data[0]) //FIXME this is unacceptable, some sensible error concealment must be done for missing reference frames
1641         return;
1642
1643     if(mx&7) extra_width -= 3;
1644     if(my&7) extra_height -= 3;
1645
1646     if(   full_mx < 0-extra_width
1647        || full_my < 0-extra_height
1648        || full_mx + 16/*FIXME*/ > pic_width + extra_width
1649        || full_my + 16/*FIXME*/ > pic_height + extra_height){
1650         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);
1651             src_y= s->edge_emu_buffer + 2 + 2*h->mb_linesize;
1652         emu=1;
1653     }
1654
1655     qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
1656     if(!square){
1657         qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
1658     }
1659
1660     if(ENABLE_GRAY && s->flags&CODEC_FLAG_GRAY) return;
1661
1662     if(MB_FIELD){
1663         // chroma offset when predicting from a field of opposite parity
1664         my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
1665         emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
1666     }
1667     src_cb= pic->data[1] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
1668     src_cr= pic->data[2] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
1669
1670     if(emu){
1671         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);
1672             src_cb= s->edge_emu_buffer;
1673     }
1674     chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
1675
1676     if(emu){
1677         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);
1678             src_cr= s->edge_emu_buffer;
1679     }
1680     chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
1681 }
1682
1683 static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
1684                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1685                            int x_offset, int y_offset,
1686                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1687                            qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
1688                            int list0, int list1){
1689     MpegEncContext * const s = &h->s;
1690     qpel_mc_func *qpix_op=  qpix_put;
1691     h264_chroma_mc_func chroma_op= chroma_put;
1692
1693     dest_y  += 2*x_offset + 2*y_offset*h->  mb_linesize;
1694     dest_cb +=   x_offset +   y_offset*h->mb_uvlinesize;
1695     dest_cr +=   x_offset +   y_offset*h->mb_uvlinesize;
1696     x_offset += 8*s->mb_x;
1697     y_offset += 8*(s->mb_y >> MB_FIELD);
1698
1699     if(list0){
1700         Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
1701         mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
1702                            dest_y, dest_cb, dest_cr, x_offset, y_offset,
1703                            qpix_op, chroma_op);
1704
1705         qpix_op=  qpix_avg;
1706         chroma_op= chroma_avg;
1707     }
1708
1709     if(list1){
1710         Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
1711         mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
1712                            dest_y, dest_cb, dest_cr, x_offset, y_offset,
1713                            qpix_op, chroma_op);
1714     }
1715 }
1716
1717 static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
1718                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1719                            int x_offset, int y_offset,
1720                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1721                            h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
1722                            h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
1723                            int list0, int list1){
1724     MpegEncContext * const s = &h->s;
1725
1726     dest_y  += 2*x_offset + 2*y_offset*h->  mb_linesize;
1727     dest_cb +=   x_offset +   y_offset*h->mb_uvlinesize;
1728     dest_cr +=   x_offset +   y_offset*h->mb_uvlinesize;
1729     x_offset += 8*s->mb_x;
1730     y_offset += 8*(s->mb_y >> MB_FIELD);
1731
1732     if(list0 && list1){
1733         /* don't optimize for luma-only case, since B-frames usually
1734          * use implicit weights => chroma too. */
1735         uint8_t *tmp_cb = s->obmc_scratchpad;
1736         uint8_t *tmp_cr = s->obmc_scratchpad + 8;
1737         uint8_t *tmp_y  = s->obmc_scratchpad + 8*h->mb_uvlinesize;
1738         int refn0 = h->ref_cache[0][ scan8[n] ];
1739         int refn1 = h->ref_cache[1][ scan8[n] ];
1740
1741         mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
1742                     dest_y, dest_cb, dest_cr,
1743                     x_offset, y_offset, qpix_put, chroma_put);
1744         mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
1745                     tmp_y, tmp_cb, tmp_cr,
1746                     x_offset, y_offset, qpix_put, chroma_put);
1747
1748         if(h->use_weight == 2){
1749             int weight0 = h->implicit_weight[refn0][refn1];
1750             int weight1 = 64 - weight0;
1751             luma_weight_avg(  dest_y,  tmp_y,  h->  mb_linesize, 5, weight0, weight1, 0);
1752             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
1753             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
1754         }else{
1755             luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
1756                             h->luma_weight[0][refn0], h->luma_weight[1][refn1],
1757                             h->luma_offset[0][refn0] + h->luma_offset[1][refn1]);
1758             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1759                             h->chroma_weight[0][refn0][0], h->chroma_weight[1][refn1][0],
1760                             h->chroma_offset[0][refn0][0] + h->chroma_offset[1][refn1][0]);
1761             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1762                             h->chroma_weight[0][refn0][1], h->chroma_weight[1][refn1][1],
1763                             h->chroma_offset[0][refn0][1] + h->chroma_offset[1][refn1][1]);
1764         }
1765     }else{
1766         int list = list1 ? 1 : 0;
1767         int refn = h->ref_cache[list][ scan8[n] ];
1768         Picture *ref= &h->ref_list[list][refn];
1769         mc_dir_part(h, ref, n, square, chroma_height, delta, list,
1770                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
1771                     qpix_put, chroma_put);
1772
1773         luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
1774                        h->luma_weight[list][refn], h->luma_offset[list][refn]);
1775         if(h->use_weight_chroma){
1776             chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1777                              h->chroma_weight[list][refn][0], h->chroma_offset[list][refn][0]);
1778             chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1779                              h->chroma_weight[list][refn][1], h->chroma_offset[list][refn][1]);
1780         }
1781     }
1782 }
1783
1784 static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
1785                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1786                            int x_offset, int y_offset,
1787                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1788                            qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
1789                            h264_weight_func *weight_op, h264_biweight_func *weight_avg,
1790                            int list0, int list1){
1791     if((h->use_weight==2 && list0 && list1
1792         && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ] != 32))
1793        || h->use_weight==1)
1794         mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
1795                          x_offset, y_offset, qpix_put, chroma_put,
1796                          weight_op[0], weight_op[3], weight_avg[0], weight_avg[3], list0, list1);
1797     else
1798         mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
1799                     x_offset, y_offset, qpix_put, chroma_put, qpix_avg, chroma_avg, list0, list1);
1800 }
1801
1802 static inline void prefetch_motion(H264Context *h, int list){
1803     /* fetch pixels for estimated mv 4 macroblocks ahead
1804      * optimized for 64byte cache lines */
1805     MpegEncContext * const s = &h->s;
1806     const int refn = h->ref_cache[list][scan8[0]];
1807     if(refn >= 0){
1808         const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
1809         const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
1810         uint8_t **src= h->ref_list[list][refn].data;
1811         int off= mx + (my + (s->mb_x&3)*4)*h->mb_linesize + 64;
1812         s->dsp.prefetch(src[0]+off, s->linesize, 4);
1813         off= (mx>>1) + ((my>>1) + (s->mb_x&7))*s->uvlinesize + 64;
1814         s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
1815     }
1816 }
1817
1818 static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1819                       qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
1820                       qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
1821                       h264_weight_func *weight_op, h264_biweight_func *weight_avg){
1822     MpegEncContext * const s = &h->s;
1823     const int mb_xy= h->mb_xy;
1824     const int mb_type= s->current_picture.mb_type[mb_xy];
1825
1826     assert(IS_INTER(mb_type));
1827
1828     prefetch_motion(h, 0);
1829
1830     if(IS_16X16(mb_type)){
1831         mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
1832                 qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
1833                 &weight_op[0], &weight_avg[0],
1834                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1835     }else if(IS_16X8(mb_type)){
1836         mc_part(h, 0, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 0,
1837                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
1838                 &weight_op[1], &weight_avg[1],
1839                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1840         mc_part(h, 8, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 4,
1841                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
1842                 &weight_op[1], &weight_avg[1],
1843                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
1844     }else if(IS_8X16(mb_type)){
1845         mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
1846                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1847                 &weight_op[2], &weight_avg[2],
1848                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1849         mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
1850                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1851                 &weight_op[2], &weight_avg[2],
1852                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
1853     }else{
1854         int i;
1855
1856         assert(IS_8X8(mb_type));
1857
1858         for(i=0; i<4; i++){
1859             const int sub_mb_type= h->sub_mb_type[i];
1860             const int n= 4*i;
1861             int x_offset= (i&1)<<2;
1862             int y_offset= (i&2)<<1;
1863
1864             if(IS_SUB_8X8(sub_mb_type)){
1865                 mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1866                     qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1867                     &weight_op[3], &weight_avg[3],
1868                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1869             }else if(IS_SUB_8X4(sub_mb_type)){
1870                 mc_part(h, n  , 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1871                     qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
1872                     &weight_op[4], &weight_avg[4],
1873                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1874                 mc_part(h, n+2, 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
1875                     qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
1876                     &weight_op[4], &weight_avg[4],
1877                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1878             }else if(IS_SUB_4X8(sub_mb_type)){
1879                 mc_part(h, n  , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1880                     qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1881                     &weight_op[5], &weight_avg[5],
1882                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1883                 mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
1884                     qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1885                     &weight_op[5], &weight_avg[5],
1886                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1887             }else{
1888                 int j;
1889                 assert(IS_SUB_4X4(sub_mb_type));
1890                 for(j=0; j<4; j++){
1891                     int sub_x_offset= x_offset + 2*(j&1);
1892                     int sub_y_offset= y_offset +   (j&2);
1893                     mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
1894                         qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1895                         &weight_op[6], &weight_avg[6],
1896                         IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1897                 }
1898             }
1899         }
1900     }
1901
1902     prefetch_motion(h, 1);
1903 }
1904
1905 static av_cold void decode_init_vlc(void){
1906     static int done = 0;
1907
1908     if (!done) {
1909         int i;
1910         int offset;
1911         done = 1;
1912
1913         chroma_dc_coeff_token_vlc.table = chroma_dc_coeff_token_vlc_table;
1914         chroma_dc_coeff_token_vlc.table_allocated = chroma_dc_coeff_token_vlc_table_size;
1915         init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5,
1916                  &chroma_dc_coeff_token_len [0], 1, 1,
1917                  &chroma_dc_coeff_token_bits[0], 1, 1,
1918                  INIT_VLC_USE_NEW_STATIC);
1919
1920         offset = 0;
1921         for(i=0; i<4; i++){
1922             coeff_token_vlc[i].table = coeff_token_vlc_tables+offset;
1923             coeff_token_vlc[i].table_allocated = coeff_token_vlc_tables_size[i];
1924             init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17,
1925                      &coeff_token_len [i][0], 1, 1,
1926                      &coeff_token_bits[i][0], 1, 1,
1927                      INIT_VLC_USE_NEW_STATIC);
1928             offset += coeff_token_vlc_tables_size[i];
1929         }
1930         /*
1931          * This is a one time safety check to make sure that
1932          * the packed static coeff_token_vlc table sizes
1933          * were initialized correctly.
1934          */
1935         assert(offset == sizeof(coeff_token_vlc_tables)/(sizeof(VLC_TYPE)*2));
1936
1937         for(i=0; i<3; i++){
1938             chroma_dc_total_zeros_vlc[i].table = chroma_dc_total_zeros_vlc_tables[i];
1939             chroma_dc_total_zeros_vlc[i].table_allocated = chroma_dc_total_zeros_vlc_tables_size;
1940             init_vlc(&chroma_dc_total_zeros_vlc[i],
1941                      CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,
1942                      &chroma_dc_total_zeros_len [i][0], 1, 1,
1943                      &chroma_dc_total_zeros_bits[i][0], 1, 1,
1944                      INIT_VLC_USE_NEW_STATIC);
1945         }
1946         for(i=0; i<15; i++){
1947             total_zeros_vlc[i].table = total_zeros_vlc_tables[i];
1948             total_zeros_vlc[i].table_allocated = total_zeros_vlc_tables_size;
1949             init_vlc(&total_zeros_vlc[i],
1950                      TOTAL_ZEROS_VLC_BITS, 16,
1951                      &total_zeros_len [i][0], 1, 1,
1952                      &total_zeros_bits[i][0], 1, 1,
1953                      INIT_VLC_USE_NEW_STATIC);
1954         }
1955
1956         for(i=0; i<6; i++){
1957             run_vlc[i].table = run_vlc_tables[i];
1958             run_vlc[i].table_allocated = run_vlc_tables_size;
1959             init_vlc(&run_vlc[i],
1960                      RUN_VLC_BITS, 7,
1961                      &run_len [i][0], 1, 1,
1962                      &run_bits[i][0], 1, 1,
1963                      INIT_VLC_USE_NEW_STATIC);
1964         }
1965         run7_vlc.table = run7_vlc_table,
1966         run7_vlc.table_allocated = run7_vlc_table_size;
1967         init_vlc(&run7_vlc, RUN7_VLC_BITS, 16,
1968                  &run_len [6][0], 1, 1,
1969                  &run_bits[6][0], 1, 1,
1970                  INIT_VLC_USE_NEW_STATIC);
1971     }
1972 }
1973
1974 static void free_tables(H264Context *h){
1975     int i;
1976     H264Context *hx;
1977     av_freep(&h->intra4x4_pred_mode);
1978     av_freep(&h->chroma_pred_mode_table);
1979     av_freep(&h->cbp_table);
1980     av_freep(&h->mvd_table[0]);
1981     av_freep(&h->mvd_table[1]);
1982     av_freep(&h->direct_table);
1983     av_freep(&h->non_zero_count);
1984     av_freep(&h->slice_table_base);
1985     h->slice_table= NULL;
1986
1987     av_freep(&h->mb2b_xy);
1988     av_freep(&h->mb2b8_xy);
1989
1990     for(i = 0; i < MAX_SPS_COUNT; i++)
1991         av_freep(h->sps_buffers + i);
1992
1993     for(i = 0; i < MAX_PPS_COUNT; i++)
1994         av_freep(h->pps_buffers + i);
1995
1996     for(i = 0; i < h->s.avctx->thread_count; i++) {
1997         hx = h->thread_context[i];
1998         if(!hx) continue;
1999         av_freep(&hx->top_borders[1]);
2000         av_freep(&hx->top_borders[0]);
2001         av_freep(&hx->s.obmc_scratchpad);
2002     }
2003 }
2004
2005 static void init_dequant8_coeff_table(H264Context *h){
2006     int i,q,x;
2007     const int transpose = (h->s.dsp.h264_idct8_add != ff_h264_idct8_add_c); //FIXME ugly
2008     h->dequant8_coeff[0] = h->dequant8_buffer[0];
2009     h->dequant8_coeff[1] = h->dequant8_buffer[1];
2010
2011     for(i=0; i<2; i++ ){
2012         if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
2013             h->dequant8_coeff[1] = h->dequant8_buffer[0];
2014             break;
2015         }
2016
2017         for(q=0; q<52; q++){
2018             int shift = ff_div6[q];
2019             int idx = ff_rem6[q];
2020             for(x=0; x<64; x++)
2021                 h->dequant8_coeff[i][q][transpose ? (x>>3)|((x&7)<<3) : x] =
2022                     ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
2023                     h->pps.scaling_matrix8[i][x]) << shift;
2024         }
2025     }
2026 }
2027
2028 static void init_dequant4_coeff_table(H264Context *h){
2029     int i,j,q,x;
2030     const int transpose = (h->s.dsp.h264_idct_add != ff_h264_idct_add_c); //FIXME ugly
2031     for(i=0; i<6; i++ ){
2032         h->dequant4_coeff[i] = h->dequant4_buffer[i];
2033         for(j=0; j<i; j++){
2034             if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
2035                 h->dequant4_coeff[i] = h->dequant4_buffer[j];
2036                 break;
2037             }
2038         }
2039         if(j<i)
2040             continue;
2041
2042         for(q=0; q<52; q++){
2043             int shift = ff_div6[q] + 2;
2044             int idx = ff_rem6[q];
2045             for(x=0; x<16; x++)
2046                 h->dequant4_coeff[i][q][transpose ? (x>>2)|((x<<2)&0xF) : x] =
2047                     ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
2048                     h->pps.scaling_matrix4[i][x]) << shift;
2049         }
2050     }
2051 }
2052
2053 static void init_dequant_tables(H264Context *h){
2054     int i,x;
2055     init_dequant4_coeff_table(h);
2056     if(h->pps.transform_8x8_mode)
2057         init_dequant8_coeff_table(h);
2058     if(h->sps.transform_bypass){
2059         for(i=0; i<6; i++)
2060             for(x=0; x<16; x++)
2061                 h->dequant4_coeff[i][0][x] = 1<<6;
2062         if(h->pps.transform_8x8_mode)
2063             for(i=0; i<2; i++)
2064                 for(x=0; x<64; x++)
2065                     h->dequant8_coeff[i][0][x] = 1<<6;
2066     }
2067 }
2068
2069
2070 /**
2071  * allocates tables.
2072  * needs width/height
2073  */
2074 static int alloc_tables(H264Context *h){
2075     MpegEncContext * const s = &h->s;
2076     const int big_mb_num= s->mb_stride * (s->mb_height+1);
2077     int x,y;
2078
2079     CHECKED_ALLOCZ(h->intra4x4_pred_mode, big_mb_num * 8  * sizeof(uint8_t))
2080
2081     CHECKED_ALLOCZ(h->non_zero_count    , big_mb_num * 16 * sizeof(uint8_t))
2082     CHECKED_ALLOCZ(h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(uint8_t))
2083     CHECKED_ALLOCZ(h->cbp_table, big_mb_num * sizeof(uint16_t))
2084
2085     CHECKED_ALLOCZ(h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t))
2086     CHECKED_ALLOCZ(h->mvd_table[0], 32*big_mb_num * sizeof(uint16_t));
2087     CHECKED_ALLOCZ(h->mvd_table[1], 32*big_mb_num * sizeof(uint16_t));
2088     CHECKED_ALLOCZ(h->direct_table, 32*big_mb_num * sizeof(uint8_t));
2089
2090     memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(uint8_t));
2091     h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
2092
2093     CHECKED_ALLOCZ(h->mb2b_xy  , big_mb_num * sizeof(uint32_t));
2094     CHECKED_ALLOCZ(h->mb2b8_xy , big_mb_num * sizeof(uint32_t));
2095     for(y=0; y<s->mb_height; y++){
2096         for(x=0; x<s->mb_width; x++){
2097             const int mb_xy= x + y*s->mb_stride;
2098             const int b_xy = 4*x + 4*y*h->b_stride;
2099             const int b8_xy= 2*x + 2*y*h->b8_stride;
2100
2101             h->mb2b_xy [mb_xy]= b_xy;
2102             h->mb2b8_xy[mb_xy]= b8_xy;
2103         }
2104     }
2105
2106     s->obmc_scratchpad = NULL;
2107
2108     if(!h->dequant4_coeff[0])
2109         init_dequant_tables(h);
2110
2111     return 0;
2112 fail:
2113     free_tables(h);
2114     return -1;
2115 }
2116
2117 /**
2118  * Mimic alloc_tables(), but for every context thread.
2119  */
2120 static void clone_tables(H264Context *dst, H264Context *src){
2121     dst->intra4x4_pred_mode       = src->intra4x4_pred_mode;
2122     dst->non_zero_count           = src->non_zero_count;
2123     dst->slice_table              = src->slice_table;
2124     dst->cbp_table                = src->cbp_table;
2125     dst->mb2b_xy                  = src->mb2b_xy;
2126     dst->mb2b8_xy                 = src->mb2b8_xy;
2127     dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;
2128     dst->mvd_table[0]             = src->mvd_table[0];
2129     dst->mvd_table[1]             = src->mvd_table[1];
2130     dst->direct_table             = src->direct_table;
2131
2132     dst->s.obmc_scratchpad = NULL;
2133     ff_h264_pred_init(&dst->hpc, src->s.codec_id);
2134 }
2135
2136 /**
2137  * Init context
2138  * Allocate buffers which are not shared amongst multiple threads.
2139  */
2140 static int context_init(H264Context *h){
2141     CHECKED_ALLOCZ(h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
2142     CHECKED_ALLOCZ(h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
2143
2144     return 0;
2145 fail:
2146     return -1; // free_tables will clean up for us
2147 }
2148
2149 static av_cold void common_init(H264Context *h){
2150     MpegEncContext * const s = &h->s;
2151
2152     s->width = s->avctx->width;
2153     s->height = s->avctx->height;
2154     s->codec_id= s->avctx->codec->id;
2155
2156     ff_h264_pred_init(&h->hpc, s->codec_id);
2157
2158     h->dequant_coeff_pps= -1;
2159     s->unrestricted_mv=1;
2160     s->decode=1; //FIXME
2161
2162     memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
2163     memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
2164 }
2165
2166 static av_cold int decode_init(AVCodecContext *avctx){
2167     H264Context *h= avctx->priv_data;
2168     MpegEncContext * const s = &h->s;
2169
2170     MPV_decode_defaults(s);
2171
2172     s->avctx = avctx;
2173     common_init(h);
2174
2175     s->out_format = FMT_H264;
2176     s->workaround_bugs= avctx->workaround_bugs;
2177
2178     // set defaults
2179 //    s->decode_mb= ff_h263_decode_mb;
2180     s->quarter_sample = 1;
2181     s->low_delay= 1;
2182
2183     if(avctx->codec_id == CODEC_ID_SVQ3)
2184         avctx->pix_fmt= PIX_FMT_YUVJ420P;
2185     else
2186         avctx->pix_fmt= PIX_FMT_YUV420P;
2187
2188     decode_init_vlc();
2189
2190     if(avctx->extradata_size > 0 && avctx->extradata &&
2191        *(char *)avctx->extradata == 1){
2192         h->is_avc = 1;
2193         h->got_avcC = 0;
2194     } else {
2195         h->is_avc = 0;
2196     }
2197
2198     h->thread_context[0] = h;
2199     h->outputed_poc = INT_MIN;
2200     return 0;
2201 }
2202
2203 static int frame_start(H264Context *h){
2204     MpegEncContext * const s = &h->s;
2205     int i;
2206
2207     if(MPV_frame_start(s, s->avctx) < 0)
2208         return -1;
2209     ff_er_frame_start(s);
2210     /*
2211      * MPV_frame_start uses pict_type to derive key_frame.
2212      * This is incorrect for H.264; IDR markings must be used.
2213      * Zero here; IDR markings per slice in frame or fields are ORed in later.
2214      * See decode_nal_units().
2215      */
2216     s->current_picture_ptr->key_frame= 0;
2217
2218     assert(s->linesize && s->uvlinesize);
2219
2220     for(i=0; i<16; i++){
2221         h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
2222         h->block_offset[24+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
2223     }
2224     for(i=0; i<4; i++){
2225         h->block_offset[16+i]=
2226         h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
2227         h->block_offset[24+16+i]=
2228         h->block_offset[24+20+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
2229     }
2230
2231     /* can't be in alloc_tables because linesize isn't known there.
2232      * FIXME: redo bipred weight to not require extra buffer? */
2233     for(i = 0; i < s->avctx->thread_count; i++)
2234         if(!h->thread_context[i]->s.obmc_scratchpad)
2235             h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
2236
2237     /* some macroblocks will be accessed before they're available */
2238     if(FRAME_MBAFF || s->avctx->thread_count > 1)
2239         memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(uint8_t));
2240
2241 //    s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
2242
2243     // We mark the current picture as non-reference after allocating it, so
2244     // that if we break out due to an error it can be released automatically
2245     // in the next MPV_frame_start().
2246     // SVQ3 as well as most other codecs have only last/next/current and thus
2247     // get released even with set reference, besides SVQ3 and others do not
2248     // mark frames as reference later "naturally".
2249     if(s->codec_id != CODEC_ID_SVQ3)
2250         s->current_picture_ptr->reference= 0;
2251
2252     s->current_picture_ptr->field_poc[0]=
2253     s->current_picture_ptr->field_poc[1]= INT_MAX;
2254     assert(s->current_picture_ptr->long_ref==0);
2255
2256     return 0;
2257 }
2258
2259 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){
2260     MpegEncContext * const s = &h->s;
2261     int i;
2262     int step    = 1;
2263     int offset  = 1;
2264     int uvoffset= 1;
2265     int top_idx = 1;
2266     int skiplast= 0;
2267
2268     src_y  -=   linesize;
2269     src_cb -= uvlinesize;
2270     src_cr -= uvlinesize;
2271
2272     if(!simple && FRAME_MBAFF){
2273         if(s->mb_y&1){
2274             offset  = MB_MBAFF ? 1 : 17;
2275             uvoffset= MB_MBAFF ? 1 : 9;
2276             if(!MB_MBAFF){
2277                 *(uint64_t*)(h->top_borders[0][s->mb_x]+ 0)= *(uint64_t*)(src_y +  15*linesize);
2278                 *(uint64_t*)(h->top_borders[0][s->mb_x]+ 8)= *(uint64_t*)(src_y +8+15*linesize);
2279                 if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2280                     *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+7*uvlinesize);
2281                     *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+7*uvlinesize);
2282                 }
2283             }
2284         }else{
2285             if(!MB_MBAFF){
2286                 h->left_border[0]= h->top_borders[0][s->mb_x][15];
2287                 if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2288                     h->left_border[34   ]= h->top_borders[0][s->mb_x][16+7  ];
2289                     h->left_border[34+18]= h->top_borders[0][s->mb_x][16+8+7];
2290                 }
2291                 skiplast= 1;
2292             }
2293             offset  =
2294             uvoffset=
2295             top_idx = MB_MBAFF ? 0 : 1;
2296         }
2297         step= MB_MBAFF ? 2 : 1;
2298     }
2299
2300     // There are two lines saved, the line above the the top macroblock of a pair,
2301     // and the line above the bottom macroblock
2302     h->left_border[offset]= h->top_borders[top_idx][s->mb_x][15];
2303     for(i=1; i<17 - skiplast; i++){
2304         h->left_border[offset+i*step]= src_y[15+i*  linesize];
2305     }
2306
2307     *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+0)= *(uint64_t*)(src_y +  16*linesize);
2308     *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+8)= *(uint64_t*)(src_y +8+16*linesize);
2309
2310     if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2311         h->left_border[uvoffset+34   ]= h->top_borders[top_idx][s->mb_x][16+7];
2312         h->left_border[uvoffset+34+18]= h->top_borders[top_idx][s->mb_x][24+7];
2313         for(i=1; i<9 - skiplast; i++){
2314             h->left_border[uvoffset+34   +i*step]= src_cb[7+i*uvlinesize];
2315             h->left_border[uvoffset+34+18+i*step]= src_cr[7+i*uvlinesize];
2316         }
2317         *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+16)= *(uint64_t*)(src_cb+8*uvlinesize);
2318         *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+24)= *(uint64_t*)(src_cr+8*uvlinesize);
2319     }
2320 }
2321
2322 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){
2323     MpegEncContext * const s = &h->s;
2324     int temp8, i;
2325     uint64_t temp64;
2326     int deblock_left;
2327     int deblock_top;
2328     int mb_xy;
2329     int step    = 1;
2330     int offset  = 1;
2331     int uvoffset= 1;
2332     int top_idx = 1;
2333
2334     if(!simple && FRAME_MBAFF){
2335         if(s->mb_y&1){
2336             offset  = MB_MBAFF ? 1 : 17;
2337             uvoffset= MB_MBAFF ? 1 : 9;
2338         }else{
2339             offset  =
2340             uvoffset=
2341             top_idx = MB_MBAFF ? 0 : 1;
2342         }
2343         step= MB_MBAFF ? 2 : 1;
2344     }
2345
2346     if(h->deblocking_filter == 2) {
2347         mb_xy = h->mb_xy;
2348         deblock_left = h->slice_table[mb_xy] == h->slice_table[mb_xy - 1];
2349         deblock_top  = h->slice_table[mb_xy] == h->slice_table[h->top_mb_xy];
2350     } else {
2351         deblock_left = (s->mb_x > 0);
2352         deblock_top =  (s->mb_y > 0);
2353     }
2354
2355     src_y  -=   linesize + 1;
2356     src_cb -= uvlinesize + 1;
2357     src_cr -= uvlinesize + 1;
2358
2359 #define XCHG(a,b,t,xchg)\
2360 t= a;\
2361 if(xchg)\
2362     a= b;\
2363 b= t;
2364
2365     if(deblock_left){
2366         for(i = !deblock_top; i<16; i++){
2367             XCHG(h->left_border[offset+i*step], src_y [i*  linesize], temp8, xchg);
2368         }
2369         XCHG(h->left_border[offset+i*step], src_y [i*  linesize], temp8, 1);
2370     }
2371
2372     if(deblock_top){
2373         XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
2374         XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
2375         if(s->mb_x+1 < s->mb_width){
2376             XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
2377         }
2378     }
2379
2380     if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2381         if(deblock_left){
2382             for(i = !deblock_top; i<8; i++){
2383                 XCHG(h->left_border[uvoffset+34   +i*step], src_cb[i*uvlinesize], temp8, xchg);
2384                 XCHG(h->left_border[uvoffset+34+18+i*step], src_cr[i*uvlinesize], temp8, xchg);
2385             }
2386             XCHG(h->left_border[uvoffset+34   +i*step], src_cb[i*uvlinesize], temp8, 1);
2387             XCHG(h->left_border[uvoffset+34+18+i*step], src_cr[i*uvlinesize], temp8, 1);
2388         }
2389         if(deblock_top){
2390             XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
2391             XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
2392         }
2393     }
2394 }
2395
2396 static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
2397     MpegEncContext * const s = &h->s;
2398     const int mb_x= s->mb_x;
2399     const int mb_y= s->mb_y;
2400     const int mb_xy= h->mb_xy;
2401     const int mb_type= s->current_picture.mb_type[mb_xy];
2402     uint8_t  *dest_y, *dest_cb, *dest_cr;
2403     int linesize, uvlinesize /*dct_offset*/;
2404     int i;
2405     int *block_offset = &h->block_offset[0];
2406     const unsigned int bottom = mb_y & 1;
2407     const int transform_bypass = (s->qscale == 0 && h->sps.transform_bypass), is_h264 = (simple || s->codec_id == CODEC_ID_H264);
2408     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
2409     void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
2410
2411     dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
2412     dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2413     dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2414
2415     s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + 64, s->linesize, 4);
2416     s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + 64, dest_cr - dest_cb, 2);
2417
2418     if (!simple && MB_FIELD) {
2419         linesize   = h->mb_linesize   = s->linesize * 2;
2420         uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2421         block_offset = &h->block_offset[24];
2422         if(mb_y&1){ //FIXME move out of this function?
2423             dest_y -= s->linesize*15;
2424             dest_cb-= s->uvlinesize*7;
2425             dest_cr-= s->uvlinesize*7;
2426         }
2427         if(FRAME_MBAFF) {
2428             int list;
2429             for(list=0; list<h->list_count; list++){
2430                 if(!USES_LIST(mb_type, list))
2431                     continue;
2432                 if(IS_16X16(mb_type)){
2433                     int8_t *ref = &h->ref_cache[list][scan8[0]];
2434                     fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
2435                 }else{
2436                     for(i=0; i<16; i+=4){
2437                         //FIXME can refs be smaller than 8x8 when !direct_8x8_inference ?
2438                         int ref = h->ref_cache[list][scan8[i]];
2439                         if(ref >= 0)
2440                             fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
2441                     }
2442                 }
2443             }
2444         }
2445     } else {
2446         linesize   = h->mb_linesize   = s->linesize;
2447         uvlinesize = h->mb_uvlinesize = s->uvlinesize;
2448 //        dct_offset = s->linesize * 16;
2449     }
2450
2451     if(transform_bypass){
2452         idct_dc_add =
2453         idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
2454     }else if(IS_8x8DCT(mb_type)){
2455         idct_dc_add = s->dsp.h264_idct8_dc_add;
2456         idct_add = s->dsp.h264_idct8_add;
2457     }else{
2458         idct_dc_add = s->dsp.h264_idct_dc_add;
2459         idct_add = s->dsp.h264_idct_add;
2460     }
2461
2462     if (!simple && IS_INTRA_PCM(mb_type)) {
2463         for (i=0; i<16; i++) {
2464             memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
2465         }
2466         for (i=0; i<8; i++) {
2467             memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4,  8);
2468             memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4,  8);
2469         }
2470     } else {
2471         if(IS_INTRA(mb_type)){
2472             if(h->deblocking_filter)
2473                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
2474
2475             if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2476                 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
2477                 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
2478             }
2479
2480             if(IS_INTRA4x4(mb_type)){
2481                 if(simple || !s->encoding){
2482                     if(IS_8x8DCT(mb_type)){
2483                         for(i=0; i<16; i+=4){
2484                             uint8_t * const ptr= dest_y + block_offset[i];
2485                             const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
2486                             const int nnz = h->non_zero_count_cache[ scan8[i] ];
2487                             h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
2488                                                    (h->topright_samples_available<<i)&0x4000, linesize);
2489                             if(nnz){
2490                                 if(nnz == 1 && h->mb[i*16])
2491                                     idct_dc_add(ptr, h->mb + i*16, linesize);
2492                                 else
2493                                     idct_add(ptr, h->mb + i*16, linesize);
2494                             }
2495                         }
2496                     }else
2497                     for(i=0; i<16; i++){
2498                         uint8_t * const ptr= dest_y + block_offset[i];
2499                         uint8_t *topright;
2500                         const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
2501                         int nnz, tr;
2502
2503                         if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
2504                             const int topright_avail= (h->topright_samples_available<<i)&0x8000;
2505                             assert(mb_y || linesize <= block_offset[i]);
2506                             if(!topright_avail){
2507                                 tr= ptr[3 - linesize]*0x01010101;
2508                                 topright= (uint8_t*) &tr;
2509                             }else
2510                                 topright= ptr + 4 - linesize;
2511                         }else
2512                             topright= NULL;
2513
2514                         h->hpc.pred4x4[ dir ](ptr, topright, linesize);
2515                         nnz = h->non_zero_count_cache[ scan8[i] ];
2516                         if(nnz){
2517                             if(is_h264){
2518                                 if(nnz == 1 && h->mb[i*16])
2519                                     idct_dc_add(ptr, h->mb + i*16, linesize);
2520                                 else
2521                                     idct_add(ptr, h->mb + i*16, linesize);
2522                             }else
2523                                 svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
2524                         }
2525                     }
2526                 }
2527             }else{
2528                 h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
2529                 if(is_h264){
2530                     if(!transform_bypass)
2531                         h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[0][s->qscale][0]);
2532                 }else
2533                     svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
2534             }
2535             if(h->deblocking_filter)
2536                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
2537         }else if(is_h264){
2538             hl_motion(h, dest_y, dest_cb, dest_cr,
2539                       s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2540                       s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2541                       s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);
2542         }
2543
2544
2545         if(!IS_INTRA4x4(mb_type)){
2546             if(is_h264){
2547                 if(IS_INTRA16x16(mb_type)){
2548                     for(i=0; i<16; i++){
2549                         if(h->non_zero_count_cache[ scan8[i] ])
2550                             idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2551                         else if(h->mb[i*16])
2552                             idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2553                     }
2554                 }else{
2555                     const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2556                     for(i=0; i<16; i+=di){
2557                         int nnz = h->non_zero_count_cache[ scan8[i] ];
2558                         if(nnz){
2559                             if(nnz==1 && h->mb[i*16])
2560                                 idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2561                             else
2562                                 idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2563                         }
2564                     }
2565                 }
2566             }else{
2567                 for(i=0; i<16; i++){
2568                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
2569                         uint8_t * const ptr= dest_y + block_offset[i];
2570                         svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
2571                     }
2572                 }
2573             }
2574         }
2575
2576         if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2577             uint8_t *dest[2] = {dest_cb, dest_cr};
2578             if(transform_bypass){
2579                 idct_add = idct_dc_add = s->dsp.add_pixels4;
2580             }else{
2581                 idct_add = s->dsp.h264_idct_add;
2582                 idct_dc_add = s->dsp.h264_idct_dc_add;
2583                 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]);
2584                 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]);
2585             }
2586             if(is_h264){
2587                 for(i=16; i<16+8; i++){
2588                     if(h->non_zero_count_cache[ scan8[i] ])
2589                         idct_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2590                     else if(h->mb[i*16])
2591                         idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2592                 }
2593             }else{
2594                 for(i=16; i<16+8; i++){
2595                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2596                         uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
2597                         svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
2598                     }
2599                 }
2600             }
2601         }
2602     }
2603     if(h->deblocking_filter) {
2604         backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, simple);
2605         fill_caches(h, mb_type, 1); //FIXME don't fill stuff which isn't used by filter_mb
2606         h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2607         h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2608         if (!simple && FRAME_MBAFF) {
2609             filter_mb     (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2610         } else {
2611             filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2612         }
2613     }
2614 }
2615
2616 /**
2617  * Process a macroblock; this case avoids checks for expensive uncommon cases.
2618  */
2619 static void hl_decode_mb_simple(H264Context *h){
2620     hl_decode_mb_internal(h, 1);
2621 }
2622
2623 /**
2624  * Process a macroblock; this handles edge cases, such as interlacing.
2625  */
2626 static void av_noinline hl_decode_mb_complex(H264Context *h){
2627     hl_decode_mb_internal(h, 0);
2628 }
2629
2630 static void hl_decode_mb(H264Context *h){
2631     MpegEncContext * const s = &h->s;
2632     const int mb_xy= h->mb_xy;
2633     const int mb_type= s->current_picture.mb_type[mb_xy];
2634     int is_complex = FRAME_MBAFF || MB_FIELD || IS_INTRA_PCM(mb_type) || s->codec_id != CODEC_ID_H264 ||
2635                     (ENABLE_GRAY && (s->flags&CODEC_FLAG_GRAY)) || (ENABLE_H264_ENCODER && s->encoding) || ENABLE_SMALL;
2636
2637     if(ENABLE_H264_ENCODER && !s->decode)
2638         return;
2639
2640     if (is_complex)
2641         hl_decode_mb_complex(h);
2642     else hl_decode_mb_simple(h);
2643 }
2644
2645 static void pic_as_field(Picture *pic, const int parity){
2646     int i;
2647     for (i = 0; i < 4; ++i) {
2648         if (parity == PICT_BOTTOM_FIELD)
2649             pic->data[i] += pic->linesize[i];
2650         pic->reference = parity;
2651         pic->linesize[i] *= 2;
2652     }
2653     pic->poc= pic->field_poc[parity == PICT_BOTTOM_FIELD];
2654 }
2655
2656 static int split_field_copy(Picture *dest, Picture *src,
2657                             int parity, int id_add){
2658     int match = !!(src->reference & parity);
2659
2660     if (match) {
2661         *dest = *src;
2662         if(parity != PICT_FRAME){
2663             pic_as_field(dest, parity);
2664             dest->pic_id *= 2;
2665             dest->pic_id += id_add;
2666         }
2667     }
2668
2669     return match;
2670 }
2671
2672 static int build_def_list(Picture *def, Picture **in, int len, int is_long, int sel){
2673     int i[2]={0};
2674     int index=0;
2675
2676     while(i[0]<len || i[1]<len){
2677         while(i[0]<len && !(in[ i[0] ] && (in[ i[0] ]->reference & sel)))
2678             i[0]++;
2679         while(i[1]<len && !(in[ i[1] ] && (in[ i[1] ]->reference & (sel^3))))
2680             i[1]++;
2681         if(i[0] < len){
2682             in[ i[0] ]->pic_id= is_long ? i[0] : in[ i[0] ]->frame_num;
2683             split_field_copy(&def[index++], in[ i[0]++ ], sel  , 1);
2684         }
2685         if(i[1] < len){
2686             in[ i[1] ]->pic_id= is_long ? i[1] : in[ i[1] ]->frame_num;
2687             split_field_copy(&def[index++], in[ i[1]++ ], sel^3, 0);
2688         }
2689     }
2690
2691     return index;
2692 }
2693
2694 static int add_sorted(Picture **sorted, Picture **src, int len, int limit, int dir){
2695     int i, best_poc;
2696     int out_i= 0;
2697
2698     for(;;){
2699         best_poc= dir ? INT_MIN : INT_MAX;
2700
2701         for(i=0; i<len; i++){
2702             const int poc= src[i]->poc;
2703             if(((poc > limit) ^ dir) && ((poc < best_poc) ^ dir)){
2704                 best_poc= poc;
2705                 sorted[out_i]= src[i];
2706             }
2707         }
2708         if(best_poc == (dir ? INT_MIN : INT_MAX))
2709             break;
2710         limit= sorted[out_i++]->poc - dir;
2711     }
2712     return out_i;
2713 }
2714
2715 /**
2716  * fills the default_ref_list.
2717  */
2718 static int fill_default_ref_list(H264Context *h){
2719     MpegEncContext * const s = &h->s;
2720     int i, len;
2721
2722     if(h->slice_type_nos==FF_B_TYPE){
2723         Picture *sorted[32];
2724         int cur_poc, list;
2725         int lens[2];
2726
2727         if(FIELD_PICTURE)
2728             cur_poc= s->current_picture_ptr->field_poc[ s->picture_structure == PICT_BOTTOM_FIELD ];
2729         else
2730             cur_poc= s->current_picture_ptr->poc;
2731
2732         for(list= 0; list<2; list++){
2733             len= add_sorted(sorted    , h->short_ref, h->short_ref_count, cur_poc, 1^list);
2734             len+=add_sorted(sorted+len, h->short_ref, h->short_ref_count, cur_poc, 0^list);
2735             assert(len<=32);
2736             len= build_def_list(h->default_ref_list[list]    , sorted     , len, 0, s->picture_structure);
2737             len+=build_def_list(h->default_ref_list[list]+len, h->long_ref, 16 , 1, s->picture_structure);
2738             assert(len<=32);
2739
2740             if(len < h->ref_count[list])
2741                 memset(&h->default_ref_list[list][len], 0, sizeof(Picture)*(h->ref_count[list] - len));
2742             lens[list]= len;
2743         }
2744
2745         if(lens[0] == lens[1] && lens[1] > 1){
2746             for(i=0; h->default_ref_list[0][i].data[0] == h->default_ref_list[1][i].data[0] && i<lens[0]; i++);
2747             if(i == lens[0])
2748                 FFSWAP(Picture, h->default_ref_list[1][0], h->default_ref_list[1][1]);
2749         }
2750     }else{
2751         len = build_def_list(h->default_ref_list[0]    , h->short_ref, h->short_ref_count, 0, s->picture_structure);
2752         len+= build_def_list(h->default_ref_list[0]+len, h-> long_ref, 16                , 1, s->picture_structure);
2753         assert(len <= 32);
2754         if(len < h->ref_count[0])
2755             memset(&h->default_ref_list[0][len], 0, sizeof(Picture)*(h->ref_count[0] - len));
2756     }
2757 #ifdef TRACE
2758     for (i=0; i<h->ref_count[0]; i++) {
2759         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]);
2760     }
2761     if(h->slice_type_nos==FF_B_TYPE){
2762         for (i=0; i<h->ref_count[1]; i++) {
2763             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]);
2764         }
2765     }
2766 #endif
2767     return 0;
2768 }
2769
2770 static void print_short_term(H264Context *h);
2771 static void print_long_term(H264Context *h);
2772
2773 /**
2774  * Extract structure information about the picture described by pic_num in
2775  * the current decoding context (frame or field). Note that pic_num is
2776  * picture number without wrapping (so, 0<=pic_num<max_pic_num).
2777  * @param pic_num picture number for which to extract structure information
2778  * @param structure one of PICT_XXX describing structure of picture
2779  *                      with pic_num
2780  * @return frame number (short term) or long term index of picture
2781  *         described by pic_num
2782  */
2783 static int pic_num_extract(H264Context *h, int pic_num, int *structure){
2784     MpegEncContext * const s = &h->s;
2785
2786     *structure = s->picture_structure;
2787     if(FIELD_PICTURE){
2788         if (!(pic_num & 1))
2789             /* opposite field */
2790             *structure ^= PICT_FRAME;
2791         pic_num >>= 1;
2792     }
2793
2794     return pic_num;
2795 }
2796
2797 static int decode_ref_pic_list_reordering(H264Context *h){
2798     MpegEncContext * const s = &h->s;
2799     int list, index, pic_structure;
2800
2801     print_short_term(h);
2802     print_long_term(h);
2803
2804     for(list=0; list<h->list_count; list++){
2805         memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);
2806
2807         if(get_bits1(&s->gb)){
2808             int pred= h->curr_pic_num;
2809
2810             for(index=0; ; index++){
2811                 unsigned int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
2812                 unsigned int pic_id;
2813                 int i;
2814                 Picture *ref = NULL;
2815
2816                 if(reordering_of_pic_nums_idc==3)
2817                     break;
2818
2819                 if(index >= h->ref_count[list]){
2820                     av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
2821                     return -1;
2822                 }
2823
2824                 if(reordering_of_pic_nums_idc<3){
2825                     if(reordering_of_pic_nums_idc<2){
2826                         const unsigned int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
2827                         int frame_num;
2828
2829                         if(abs_diff_pic_num > h->max_pic_num){
2830                             av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
2831                             return -1;
2832                         }
2833
2834                         if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
2835                         else                                pred+= abs_diff_pic_num;
2836                         pred &= h->max_pic_num - 1;
2837
2838                         frame_num = pic_num_extract(h, pred, &pic_structure);
2839
2840                         for(i= h->short_ref_count-1; i>=0; i--){
2841                             ref = h->short_ref[i];
2842                             assert(ref->reference);
2843                             assert(!ref->long_ref);
2844                             if(
2845                                    ref->frame_num == frame_num &&
2846                                    (ref->reference & pic_structure)
2847                               )
2848                                 break;
2849                         }
2850                         if(i>=0)
2851                             ref->pic_id= pred;
2852                     }else{
2853                         int long_idx;
2854                         pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
2855
2856                         long_idx= pic_num_extract(h, pic_id, &pic_structure);
2857
2858                         if(long_idx>31){
2859                             av_log(h->s.avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
2860                             return -1;
2861                         }
2862                         ref = h->long_ref[long_idx];
2863                         assert(!(ref && !ref->reference));
2864                         if(ref && (ref->reference & pic_structure)){
2865                             ref->pic_id= pic_id;
2866                             assert(ref->long_ref);
2867                             i=0;
2868                         }else{
2869                             i=-1;
2870                         }
2871                     }
2872
2873                     if (i < 0) {
2874                         av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
2875                         memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
2876                     } else {
2877                         for(i=index; i+1<h->ref_count[list]; i++){
2878                             if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)
2879                                 break;
2880                         }
2881                         for(; i > index; i--){
2882                             h->ref_list[list][i]= h->ref_list[list][i-1];
2883                         }
2884                         h->ref_list[list][index]= *ref;
2885                         if (FIELD_PICTURE){
2886                             pic_as_field(&h->ref_list[list][index], pic_structure);
2887                         }
2888                     }
2889                 }else{
2890                     av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
2891                     return -1;
2892                 }
2893             }
2894         }
2895     }
2896     for(list=0; list<h->list_count; list++){
2897         for(index= 0; index < h->ref_count[list]; index++){
2898             if(!h->ref_list[list][index].data[0]){
2899                 av_log(h->s.avctx, AV_LOG_ERROR, "Missing reference picture\n");
2900                 h->ref_list[list][index]= s->current_picture; //FIXME this is not a sensible solution
2901             }
2902         }
2903     }
2904
2905     if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2906         direct_dist_scale_factor(h);
2907     direct_ref_list_init(h);
2908     return 0;
2909 }
2910
2911 static void fill_mbaff_ref_list(H264Context *h){
2912     int list, i, j;
2913     for(list=0; list<2; list++){ //FIXME try list_count
2914         for(i=0; i<h->ref_count[list]; i++){
2915             Picture *frame = &h->ref_list[list][i];
2916             Picture *field = &h->ref_list[list][16+2*i];
2917             field[0] = *frame;
2918             for(j=0; j<3; j++)
2919                 field[0].linesize[j] <<= 1;
2920             field[0].reference = PICT_TOP_FIELD;
2921             field[1] = field[0];
2922             for(j=0; j<3; j++)
2923                 field[1].data[j] += frame->linesize[j];
2924             field[1].reference = PICT_BOTTOM_FIELD;
2925
2926             h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i];
2927             h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i];
2928             for(j=0; j<2; j++){
2929                 h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j];
2930                 h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j];
2931             }
2932         }
2933     }
2934     for(j=0; j<h->ref_count[1]; j++){
2935         for(i=0; i<h->ref_count[0]; i++)
2936             h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i];
2937         memcpy(h->implicit_weight[16+2*j],   h->implicit_weight[j], sizeof(*h->implicit_weight));
2938         memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight));
2939     }
2940 }
2941
2942 static int pred_weight_table(H264Context *h){
2943     MpegEncContext * const s = &h->s;
2944     int list, i;
2945     int luma_def, chroma_def;
2946
2947     h->use_weight= 0;
2948     h->use_weight_chroma= 0;
2949     h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
2950     h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
2951     luma_def = 1<<h->luma_log2_weight_denom;
2952     chroma_def = 1<<h->chroma_log2_weight_denom;
2953
2954     for(list=0; list<2; list++){
2955         for(i=0; i<h->ref_count[list]; i++){
2956             int luma_weight_flag, chroma_weight_flag;
2957
2958             luma_weight_flag= get_bits1(&s->gb);
2959             if(luma_weight_flag){
2960                 h->luma_weight[list][i]= get_se_golomb(&s->gb);
2961                 h->luma_offset[list][i]= get_se_golomb(&s->gb);
2962                 if(   h->luma_weight[list][i] != luma_def
2963                    || h->luma_offset[list][i] != 0)
2964                     h->use_weight= 1;
2965             }else{
2966                 h->luma_weight[list][i]= luma_def;
2967                 h->luma_offset[list][i]= 0;
2968             }
2969
2970             if(CHROMA){
2971                 chroma_weight_flag= get_bits1(&s->gb);
2972                 if(chroma_weight_flag){
2973                     int j;
2974                     for(j=0; j<2; j++){
2975                         h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
2976                         h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
2977                         if(   h->chroma_weight[list][i][j] != chroma_def
2978                         || h->chroma_offset[list][i][j] != 0)
2979                             h->use_weight_chroma= 1;
2980                     }
2981                 }else{
2982                     int j;
2983                     for(j=0; j<2; j++){
2984                         h->chroma_weight[list][i][j]= chroma_def;
2985                         h->chroma_offset[list][i][j]= 0;
2986                     }
2987                 }
2988             }
2989         }
2990         if(h->slice_type_nos != FF_B_TYPE) break;
2991     }
2992     h->use_weight= h->use_weight || h->use_weight_chroma;
2993     return 0;
2994 }
2995
2996 static void implicit_weight_table(H264Context *h){
2997     MpegEncContext * const s = &h->s;
2998     int ref0, ref1;
2999     int cur_poc = s->current_picture_ptr->poc;
3000
3001     if(   h->ref_count[0] == 1 && h->ref_count[1] == 1
3002        && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
3003         h->use_weight= 0;
3004         h->use_weight_chroma= 0;
3005         return;
3006     }
3007
3008     h->use_weight= 2;
3009     h->use_weight_chroma= 2;
3010     h->luma_log2_weight_denom= 5;
3011     h->chroma_log2_weight_denom= 5;
3012
3013     for(ref0=0; ref0 < h->ref_count[0]; ref0++){
3014         int poc0 = h->ref_list[0][ref0].poc;
3015         for(ref1=0; ref1 < h->ref_count[1]; ref1++){
3016             int poc1 = h->ref_list[1][ref1].poc;
3017             int td = av_clip(poc1 - poc0, -128, 127);
3018             if(td){
3019                 int tb = av_clip(cur_poc - poc0, -128, 127);
3020                 int tx = (16384 + (FFABS(td) >> 1)) / td;
3021                 int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
3022                 if(dist_scale_factor < -64 || dist_scale_factor > 128)
3023                     h->implicit_weight[ref0][ref1] = 32;
3024                 else
3025                     h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
3026             }else
3027                 h->implicit_weight[ref0][ref1] = 32;
3028         }
3029     }
3030 }
3031
3032 /**
3033  * Mark a picture as no longer needed for reference. The refmask
3034  * argument allows unreferencing of individual fields or the whole frame.
3035  * If the picture becomes entirely unreferenced, but is being held for
3036  * display purposes, it is marked as such.
3037  * @param refmask mask of fields to unreference; the mask is bitwise
3038  *                anded with the reference marking of pic
3039  * @return non-zero if pic becomes entirely unreferenced (except possibly
3040  *         for display purposes) zero if one of the fields remains in
3041  *         reference
3042  */
3043 static inline int unreference_pic(H264Context *h, Picture *pic, int refmask){
3044     int i;
3045     if (pic->reference &= refmask) {
3046         return 0;
3047     } else {
3048         for(i = 0; h->delayed_pic[i]; i++)
3049             if(pic == h->delayed_pic[i]){
3050                 pic->reference=DELAYED_PIC_REF;
3051                 break;
3052             }
3053         return 1;
3054     }
3055 }
3056
3057 /**
3058  * instantaneous decoder refresh.
3059  */
3060 static void idr(H264Context *h){
3061     int i;
3062
3063     for(i=0; i<16; i++){
3064         remove_long(h, i, 0);
3065     }
3066     assert(h->long_ref_count==0);
3067
3068     for(i=0; i<h->short_ref_count; i++){
3069         unreference_pic(h, h->short_ref[i], 0);
3070         h->short_ref[i]= NULL;
3071     }
3072     h->short_ref_count=0;
3073     h->prev_frame_num= 0;
3074     h->prev_frame_num_offset= 0;
3075     h->prev_poc_msb=
3076     h->prev_poc_lsb= 0;
3077 }
3078
3079 /* forget old pics after a seek */
3080 static void flush_dpb(AVCodecContext *avctx){
3081     H264Context *h= avctx->priv_data;
3082     int i;
3083     for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
3084         if(h->delayed_pic[i])
3085             h->delayed_pic[i]->reference= 0;
3086         h->delayed_pic[i]= NULL;
3087     }
3088     h->outputed_poc= INT_MIN;
3089     idr(h);
3090     if(h->s.current_picture_ptr)
3091         h->s.current_picture_ptr->reference= 0;
3092     h->s.first_field= 0;
3093     ff_mpeg_flush(avctx);
3094 }
3095
3096 /**
3097  * Find a Picture in the short term reference list by frame number.
3098  * @param frame_num frame number to search for
3099  * @param idx the index into h->short_ref where returned picture is found
3100  *            undefined if no picture found.
3101  * @return pointer to the found picture, or NULL if no pic with the provided
3102  *                 frame number is found
3103  */
3104 static Picture * find_short(H264Context *h, int frame_num, int *idx){
3105     MpegEncContext * const s = &h->s;
3106     int i;
3107
3108     for(i=0; i<h->short_ref_count; i++){
3109         Picture *pic= h->short_ref[i];
3110         if(s->avctx->debug&FF_DEBUG_MMCO)
3111             av_log(h->s.avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
3112         if(pic->frame_num == frame_num) {
3113             *idx = i;
3114             return pic;
3115         }
3116     }
3117     return NULL;
3118 }
3119
3120 /**
3121  * Remove a picture from the short term reference list by its index in
3122  * that list.  This does no checking on the provided index; it is assumed
3123  * to be valid. Other list entries are shifted down.
3124  * @param i index into h->short_ref of picture to remove.
3125  */
3126 static void remove_short_at_index(H264Context *h, int i){
3127     assert(i >= 0 && i < h->short_ref_count);
3128     h->short_ref[i]= NULL;
3129     if (--h->short_ref_count)
3130         memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i)*sizeof(Picture*));
3131 }
3132
3133 /**
3134  *
3135  * @return the removed picture or NULL if an error occurs
3136  */
3137 static Picture * remove_short(H264Context *h, int frame_num, int ref_mask){
3138     MpegEncContext * const s = &h->s;
3139     Picture *pic;
3140     int i;
3141
3142     if(s->avctx->debug&FF_DEBUG_MMCO)
3143         av_log(h->s.avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
3144
3145     pic = find_short(h, frame_num, &i);
3146     if (pic){
3147         if(unreference_pic(h, pic, ref_mask))
3148         remove_short_at_index(h, i);
3149     }
3150
3151     return pic;
3152 }
3153
3154 /**
3155  * Remove a picture from the long term reference list by its index in
3156  * that list.
3157  * @return the removed picture or NULL if an error occurs
3158  */
3159 static Picture * remove_long(H264Context *h, int i, int ref_mask){
3160     Picture *pic;
3161
3162     pic= h->long_ref[i];
3163     if (pic){
3164         if(unreference_pic(h, pic, ref_mask)){
3165             assert(h->long_ref[i]->long_ref == 1);
3166             h->long_ref[i]->long_ref= 0;
3167             h->long_ref[i]= NULL;
3168             h->long_ref_count--;
3169         }
3170     }
3171
3172     return pic;
3173 }
3174
3175 /**
3176  * print short term list
3177  */
3178 static void print_short_term(H264Context *h) {
3179     uint32_t i;
3180     if(h->s.avctx->debug&FF_DEBUG_MMCO) {
3181         av_log(h->s.avctx, AV_LOG_DEBUG, "short term list:\n");
3182         for(i=0; i<h->short_ref_count; i++){
3183             Picture *pic= h->short_ref[i];
3184             av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
3185         }
3186     }
3187 }
3188
3189 /**
3190  * print long term list
3191  */
3192 static void print_long_term(H264Context *h) {
3193     uint32_t i;
3194     if(h->s.avctx->debug&FF_DEBUG_MMCO) {
3195         av_log(h->s.avctx, AV_LOG_DEBUG, "long term list:\n");
3196         for(i = 0; i < 16; i++){
3197             Picture *pic= h->long_ref[i];
3198             if (pic) {
3199                 av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
3200             }
3201         }
3202     }
3203 }
3204
3205 /**
3206  * Executes the reference picture marking (memory management control operations).
3207  */
3208 static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
3209     MpegEncContext * const s = &h->s;
3210     int i, j;
3211     int current_ref_assigned=0;
3212     Picture *pic;
3213
3214     if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)
3215         av_log(h->s.avctx, AV_LOG_DEBUG, "no mmco here\n");
3216
3217     for(i=0; i<mmco_count; i++){
3218         int structure, frame_num;
3219         if(s->avctx->debug&FF_DEBUG_MMCO)
3220             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);
3221
3222         if(   mmco[i].opcode == MMCO_SHORT2UNUSED
3223            || mmco[i].opcode == MMCO_SHORT2LONG){
3224             frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
3225             pic = find_short(h, frame_num, &j);
3226             if(!pic){
3227                 if(mmco[i].opcode != MMCO_SHORT2LONG || !h->long_ref[mmco[i].long_arg]
3228                    || h->long_ref[mmco[i].long_arg]->frame_num != frame_num)
3229                 av_log(h->s.avctx, AV_LOG_ERROR, "mmco: unref short failure\n");
3230                 continue;
3231             }
3232         }
3233
3234         switch(mmco[i].opcode){
3235         case MMCO_SHORT2UNUSED:
3236             if(s->avctx->debug&FF_DEBUG_MMCO)
3237                 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);
3238             remove_short(h, frame_num, structure ^ PICT_FRAME);
3239             break;
3240         case MMCO_SHORT2LONG:
3241                 if (h->long_ref[mmco[i].long_arg] != pic)
3242                     remove_long(h, mmco[i].long_arg, 0);
3243
3244                 remove_short_at_index(h, j);
3245                 h->long_ref[ mmco[i].long_arg ]= pic;
3246                 if (h->long_ref[ mmco[i].long_arg ]){
3247                     h->long_ref[ mmco[i].long_arg ]->long_ref=1;
3248                     h->long_ref_count++;
3249                 }
3250             break;
3251         case MMCO_LONG2UNUSED:
3252             j = pic_num_extract(h, mmco[i].long_arg, &structure);
3253             pic = h->long_ref[j];
3254             if (pic) {
3255                 remove_long(h, j, structure ^ PICT_FRAME);
3256             } else if(s->avctx->debug&FF_DEBUG_MMCO)
3257                 av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
3258             break;
3259         case MMCO_LONG:
3260                     // Comment below left from previous code as it is an interresting note.
3261                     /* First field in pair is in short term list or
3262                      * at a different long term index.
3263                      * This is not allowed; see 7.4.3.3, notes 2 and 3.
3264                      * Report the problem and keep the pair where it is,
3265                      * and mark this field valid.
3266                      */
3267
3268             if (h->long_ref[mmco[i].long_arg] != s->current_picture_ptr) {
3269                 remove_long(h, mmco[i].long_arg, 0);
3270
3271                 h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;
3272                 h->long_ref[ mmco[i].long_arg ]->long_ref=1;
3273                 h->long_ref_count++;
3274             }
3275
3276             s->current_picture_ptr->reference |= s->picture_structure;
3277             current_ref_assigned=1;
3278             break;
3279         case MMCO_SET_MAX_LONG:
3280             assert(mmco[i].long_arg <= 16);
3281             // just remove the long term which index is greater than new max
3282             for(j = mmco[i].long_arg; j<16; j++){
3283                 remove_long(h, j, 0);
3284             }
3285             break;
3286         case MMCO_RESET:
3287             while(h->short_ref_count){
3288                 remove_short(h, h->short_ref[0]->frame_num, 0);
3289             }
3290             for(j = 0; j < 16; j++) {
3291                 remove_long(h, j, 0);
3292             }
3293             s->current_picture_ptr->poc=
3294             s->current_picture_ptr->field_poc[0]=
3295             s->current_picture_ptr->field_poc[1]=
3296             h->poc_lsb=
3297             h->poc_msb=
3298             h->frame_num=
3299             s->current_picture_ptr->frame_num= 0;
3300             break;
3301         default: assert(0);
3302         }
3303     }
3304
3305     if (!current_ref_assigned) {
3306         /* Second field of complementary field pair; the first field of
3307          * which is already referenced. If short referenced, it
3308          * should be first entry in short_ref. If not, it must exist
3309          * in long_ref; trying to put it on the short list here is an
3310          * error in the encoded bit stream (ref: 7.4.3.3, NOTE 2 and 3).
3311          */
3312         if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {
3313             /* Just mark the second field valid */
3314             s->current_picture_ptr->reference = PICT_FRAME;
3315         } else if (s->current_picture_ptr->long_ref) {
3316             av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "
3317                                              "assignment for second field "
3318                                              "in complementary field pair "
3319                                              "(first field is long term)\n");
3320         } else {
3321             pic= remove_short(h, s->current_picture_ptr->frame_num, 0);
3322             if(pic){
3323                 av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
3324             }
3325
3326             if(h->short_ref_count)
3327                 memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
3328
3329             h->short_ref[0]= s->current_picture_ptr;
3330             h->short_ref_count++;
3331             s->current_picture_ptr->reference |= s->picture_structure;
3332         }
3333     }
3334
3335     if (h->long_ref_count + h->short_ref_count > h->sps.ref_frame_count){
3336
3337         /* We have too many reference frames, probably due to corrupted
3338          * stream. Need to discard one frame. Prevents overrun of the
3339          * short_ref and long_ref buffers.
3340          */
3341         av_log(h->s.avctx, AV_LOG_ERROR,
3342                "number of reference frames exceeds max (probably "
3343                "corrupt input), discarding one\n");
3344
3345         if (h->long_ref_count && !h->short_ref_count) {
3346             for (i = 0; i < 16; ++i)
3347                 if (h->long_ref[i])
3348                     break;
3349
3350             assert(i < 16);
3351             remove_long(h, i, 0);
3352         } else {
3353             pic = h->short_ref[h->short_ref_count - 1];
3354             remove_short(h, pic->frame_num, 0);
3355         }
3356     }
3357
3358     print_short_term(h);
3359     print_long_term(h);
3360     return 0;
3361 }
3362
3363 static int decode_ref_pic_marking(H264Context *h, GetBitContext *gb){
3364     MpegEncContext * const s = &h->s;
3365     int i;
3366
3367     h->mmco_index= 0;
3368     if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields
3369         s->broken_link= get_bits1(gb) -1;
3370         if(get_bits1(gb)){
3371             h->mmco[0].opcode= MMCO_LONG;
3372             h->mmco[0].long_arg= 0;
3373             h->mmco_index= 1;
3374         }
3375     }else{
3376         if(get_bits1(gb)){ // adaptive_ref_pic_marking_mode_flag
3377             for(i= 0; i<MAX_MMCO_COUNT; i++) {
3378                 MMCOOpcode opcode= get_ue_golomb(gb);
3379
3380                 h->mmco[i].opcode= opcode;
3381                 if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){
3382                     h->mmco[i].short_pic_num= (h->curr_pic_num - get_ue_golomb(gb) - 1) & (h->max_pic_num - 1);
3383 /*                    if(h->mmco[i].short_pic_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_pic_num ] == NULL){
3384                         av_log(s->avctx, AV_LOG_ERROR, "illegal short ref in memory management control operation %d\n", mmco);
3385                         return -1;
3386                     }*/
3387                 }
3388                 if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){
3389                     unsigned int long_arg= get_ue_golomb(gb);
3390                     if(long_arg >= 32 || (long_arg >= 16 && !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){
3391                         av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);
3392                         return -1;
3393                     }
3394                     h->mmco[i].long_arg= long_arg;
3395                 }
3396
3397                 if(opcode > (unsigned)MMCO_LONG){
3398                     av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);
3399                     return -1;
3400                 }
3401                 if(opcode == MMCO_END)
3402                     break;
3403             }
3404             h->mmco_index= i;
3405         }else{
3406             assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
3407
3408             if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
3409                     !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {
3410                 h->mmco[0].opcode= MMCO_SHORT2UNUSED;
3411                 h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
3412                 h->mmco_index= 1;
3413                 if (FIELD_PICTURE) {
3414                     h->mmco[0].short_pic_num *= 2;
3415                     h->mmco[1].opcode= MMCO_SHORT2UNUSED;
3416                     h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;
3417                     h->mmco_index= 2;
3418                 }
3419             }
3420         }
3421     }
3422
3423     return 0;
3424 }
3425
3426 static int init_poc(H264Context *h){
3427     MpegEncContext * const s = &h->s;
3428     const int max_frame_num= 1<<h->sps.log2_max_frame_num;
3429     int field_poc[2];
3430     Picture *cur = s->current_picture_ptr;
3431
3432     h->frame_num_offset= h->prev_frame_num_offset;
3433     if(h->frame_num < h->prev_frame_num)
3434         h->frame_num_offset += max_frame_num;
3435