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