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