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