mb_field_decoding_flag was not initialized
[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 /* FIXME || pic0 is a long-term 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 mb_xy =   h->mb_xy;
940     const int b8_xy = 2*s->mb_x + 2*s->mb_y*h->b8_stride;
941     const int b4_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
942     const int mb_type_col = h->ref_list[1][0].mb_type[mb_xy];
943     const int16_t (*l1mv0)[2] = (const int16_t (*)[2]) &h->ref_list[1][0].motion_val[0][b4_xy];
944     const int16_t (*l1mv1)[2] = (const int16_t (*)[2]) &h->ref_list[1][0].motion_val[1][b4_xy];
945     const int8_t *l1ref0 = &h->ref_list[1][0].ref_index[0][b8_xy];
946     const int8_t *l1ref1 = &h->ref_list[1][0].ref_index[1][b8_xy];
947     const int is_b8x8 = IS_8X8(*mb_type);
948     unsigned int sub_mb_type;
949     int i8, i4;
950
951 #define MB_TYPE_16x16_OR_INTRA (MB_TYPE_16x16|MB_TYPE_INTRA4x4|MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM)
952     if(IS_8X8(mb_type_col) && !h->sps.direct_8x8_inference_flag){
953         /* FIXME save sub mb types from previous frames (or derive from MVs)
954          * so we know exactly what block size to use */
955         sub_mb_type = MB_TYPE_8x8|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_4x4 */
956         *mb_type =    MB_TYPE_8x8|MB_TYPE_L0L1;
957     }else if(!is_b8x8 && (mb_type_col & MB_TYPE_16x16_OR_INTRA)){
958         sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
959         *mb_type =    MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_16x16 */
960     }else{
961         sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
962         *mb_type =    MB_TYPE_8x8|MB_TYPE_L0L1;
963     }
964     if(!is_b8x8)
965         *mb_type |= MB_TYPE_DIRECT2;
966     if(MB_FIELD)
967         *mb_type |= MB_TYPE_INTERLACED;
968
969     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);
970
971     if(h->direct_spatial_mv_pred){
972         int ref[2];
973         int mv[2][2];
974         int list;
975
976         /* FIXME interlacing + spatial direct uses wrong colocated block positions */
977
978         /* ref = min(neighbors) */
979         for(list=0; list<2; list++){
980             int refa = h->ref_cache[list][scan8[0] - 1];
981             int refb = h->ref_cache[list][scan8[0] - 8];
982             int refc = h->ref_cache[list][scan8[0] - 8 + 4];
983             if(refc == PART_NOT_AVAILABLE)
984                 refc = h->ref_cache[list][scan8[0] - 8 - 1];
985             ref[list] = FFMIN3((unsigned)refa, (unsigned)refb, (unsigned)refc);
986             if(ref[list] < 0)
987                 ref[list] = -1;
988         }
989
990         if(ref[0] < 0 && ref[1] < 0){
991             ref[0] = ref[1] = 0;
992             mv[0][0] = mv[0][1] =
993             mv[1][0] = mv[1][1] = 0;
994         }else{
995             for(list=0; list<2; list++){
996                 if(ref[list] >= 0)
997                     pred_motion(h, 0, 4, list, ref[list], &mv[list][0], &mv[list][1]);
998                 else
999                     mv[list][0] = mv[list][1] = 0;
1000             }
1001         }
1002
1003         if(ref[1] < 0){
1004             if(!is_b8x8)
1005                 *mb_type &= ~MB_TYPE_L1;
1006             sub_mb_type &= ~MB_TYPE_L1;
1007         }else if(ref[0] < 0){
1008             if(!is_b8x8)
1009                 *mb_type &= ~MB_TYPE_L0;
1010             sub_mb_type &= ~MB_TYPE_L0;
1011         }
1012
1013         if(IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col)){
1014             int pair_xy = s->mb_x + (s->mb_y&~1)*s->mb_stride;
1015             int mb_types_col[2];
1016             int b8_stride = h->b8_stride;
1017             int b4_stride = h->b_stride;
1018
1019             *mb_type = (*mb_type & ~MB_TYPE_16x16) | MB_TYPE_8x8;
1020
1021             if(IS_INTERLACED(*mb_type)){
1022                 mb_types_col[0] = h->ref_list[1][0].mb_type[pair_xy];
1023                 mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy+s->mb_stride];
1024                 if(s->mb_y&1){
1025                     l1ref0 -= 2*b8_stride;
1026                     l1ref1 -= 2*b8_stride;
1027                     l1mv0 -= 4*b4_stride;
1028                     l1mv1 -= 4*b4_stride;
1029                 }
1030                 b8_stride *= 3;
1031                 b4_stride *= 6;
1032             }else{
1033                 int cur_poc = s->current_picture_ptr->poc;
1034                 int *col_poc = h->ref_list[1]->field_poc;
1035                 int col_parity = FFABS(col_poc[0] - cur_poc) >= FFABS(col_poc[1] - cur_poc);
1036                 int dy = 2*col_parity - (s->mb_y&1);
1037                 mb_types_col[0] =
1038                 mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy + col_parity*s->mb_stride];
1039                 l1ref0 += dy*b8_stride;
1040                 l1ref1 += dy*b8_stride;
1041                 l1mv0 += 2*dy*b4_stride;
1042                 l1mv1 += 2*dy*b4_stride;
1043                 b8_stride = 0;
1044             }
1045
1046             for(i8=0; i8<4; i8++){
1047                 int x8 = i8&1;
1048                 int y8 = i8>>1;
1049                 int xy8 = x8+y8*b8_stride;
1050                 int xy4 = 3*x8+y8*b4_stride;
1051                 int a=0, b=0;
1052
1053                 if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1054                     continue;
1055                 h->sub_mb_type[i8] = sub_mb_type;
1056
1057                 fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[0], 1);
1058                 fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[1], 1);
1059                 if(!IS_INTRA(mb_types_col[y8])
1060                    && (   (l1ref0[xy8] == 0 && FFABS(l1mv0[xy4][0]) <= 1 && FFABS(l1mv0[xy4][1]) <= 1)
1061                        || (l1ref0[xy8]  < 0 && l1ref1[xy8] == 0 && FFABS(l1mv1[xy4][0]) <= 1 && FFABS(l1mv1[xy4][1]) <= 1))){
1062                     if(ref[0] > 0)
1063                         a= pack16to32(mv[0][0],mv[0][1]);
1064                     if(ref[1] > 0)
1065                         b= pack16to32(mv[1][0],mv[1][1]);
1066                 }else{
1067                     a= pack16to32(mv[0][0],mv[0][1]);
1068                     b= pack16to32(mv[1][0],mv[1][1]);
1069                 }
1070                 fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, a, 4);
1071                 fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, b, 4);
1072             }
1073         }else if(IS_16X16(*mb_type)){
1074             int a=0, b=0;
1075
1076             fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);
1077             fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);
1078             if(!IS_INTRA(mb_type_col)
1079                && (   (l1ref0[0] == 0 && FFABS(l1mv0[0][0]) <= 1 && FFABS(l1mv0[0][1]) <= 1)
1080                    || (l1ref0[0]  < 0 && l1ref1[0] == 0 && FFABS(l1mv1[0][0]) <= 1 && FFABS(l1mv1[0][1]) <= 1
1081                        && (h->x264_build>33 || !h->x264_build)))){
1082                 if(ref[0] > 0)
1083                     a= pack16to32(mv[0][0],mv[0][1]);
1084                 if(ref[1] > 0)
1085                     b= pack16to32(mv[1][0],mv[1][1]);
1086             }else{
1087                 a= pack16to32(mv[0][0],mv[0][1]);
1088                 b= pack16to32(mv[1][0],mv[1][1]);
1089             }
1090             fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);
1091             fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);
1092         }else{
1093             for(i8=0; i8<4; i8++){
1094                 const int x8 = i8&1;
1095                 const int y8 = i8>>1;
1096
1097                 if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1098                     continue;
1099                 h->sub_mb_type[i8] = sub_mb_type;
1100
1101                 fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mv[0][0],mv[0][1]), 4);
1102                 fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mv[1][0],mv[1][1]), 4);
1103                 fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[0], 1);
1104                 fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[1], 1);
1105
1106                 /* col_zero_flag */
1107                 if(!IS_INTRA(mb_type_col) && (   l1ref0[x8 + y8*h->b8_stride] == 0
1108                                               || (l1ref0[x8 + y8*h->b8_stride] < 0 && l1ref1[x8 + y8*h->b8_stride] == 0
1109                                                   && (h->x264_build>33 || !h->x264_build)))){
1110                     const int16_t (*l1mv)[2]= l1ref0[x8 + y8*h->b8_stride] == 0 ? l1mv0 : l1mv1;
1111                     if(IS_SUB_8X8(sub_mb_type)){
1112                         const int16_t *mv_col = l1mv[x8*3 + y8*3*h->b_stride];
1113                         if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){
1114                             if(ref[0] == 0)
1115                                 fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
1116                             if(ref[1] == 0)
1117                                 fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
1118                         }
1119                     }else
1120                     for(i4=0; i4<4; i4++){
1121                         const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*h->b_stride];
1122                         if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){
1123                             if(ref[0] == 0)
1124                                 *(uint32_t*)h->mv_cache[0][scan8[i8*4+i4]] = 0;
1125                             if(ref[1] == 0)
1126                                 *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] = 0;
1127                         }
1128                     }
1129                 }
1130             }
1131         }
1132     }else{ /* direct temporal mv pred */
1133         const int *map_col_to_list0[2] = {h->map_col_to_list0[0], h->map_col_to_list0[1]};
1134         const int *dist_scale_factor = h->dist_scale_factor;
1135
1136         if(FRAME_MBAFF){
1137             if(IS_INTERLACED(*mb_type)){
1138                 map_col_to_list0[0] = h->map_col_to_list0_field[0];
1139                 map_col_to_list0[1] = h->map_col_to_list0_field[1];
1140                 dist_scale_factor = h->dist_scale_factor_field;
1141             }
1142             if(IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col)){
1143                 /* FIXME assumes direct_8x8_inference == 1 */
1144                 const int pair_xy = s->mb_x + (s->mb_y&~1)*s->mb_stride;
1145                 int mb_types_col[2];
1146                 int y_shift;
1147
1148                 *mb_type = MB_TYPE_8x8|MB_TYPE_L0L1
1149                          | (is_b8x8 ? 0 : MB_TYPE_DIRECT2)
1150                          | (*mb_type & MB_TYPE_INTERLACED);
1151                 sub_mb_type = MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_16x16;
1152
1153                 if(IS_INTERLACED(*mb_type)){
1154                     /* frame to field scaling */
1155                     mb_types_col[0] = h->ref_list[1][0].mb_type[pair_xy];
1156                     mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy+s->mb_stride];
1157                     if(s->mb_y&1){
1158                         l1ref0 -= 2*h->b8_stride;
1159                         l1ref1 -= 2*h->b8_stride;
1160                         l1mv0 -= 4*h->b_stride;
1161                         l1mv1 -= 4*h->b_stride;
1162                     }
1163                     y_shift = 0;
1164
1165                     if(   (mb_types_col[0] & MB_TYPE_16x16_OR_INTRA)
1166                        && (mb_types_col[1] & MB_TYPE_16x16_OR_INTRA)
1167                        && !is_b8x8)
1168                         *mb_type |= MB_TYPE_16x8;
1169                     else
1170                         *mb_type |= MB_TYPE_8x8;
1171                 }else{
1172                     /* field to frame scaling */
1173                     /* col_mb_y = (mb_y&~1) + (topAbsDiffPOC < bottomAbsDiffPOC ? 0 : 1)
1174                      * but in MBAFF, top and bottom POC are equal */
1175                     int dy = (s->mb_y&1) ? 1 : 2;
1176                     mb_types_col[0] =
1177                     mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy+s->mb_stride];
1178                     l1ref0 += dy*h->b8_stride;
1179                     l1ref1 += dy*h->b8_stride;
1180                     l1mv0 += 2*dy*h->b_stride;
1181                     l1mv1 += 2*dy*h->b_stride;
1182                     y_shift = 2;
1183
1184                     if((mb_types_col[0] & (MB_TYPE_16x16_OR_INTRA|MB_TYPE_16x8))
1185                        && !is_b8x8)
1186                         *mb_type |= MB_TYPE_16x16;
1187                     else
1188                         *mb_type |= MB_TYPE_8x8;
1189                 }
1190
1191                 for(i8=0; i8<4; i8++){
1192                     const int x8 = i8&1;
1193                     const int y8 = i8>>1;
1194                     int ref0, scale;
1195                     const int16_t (*l1mv)[2]= l1mv0;
1196
1197                     if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1198                         continue;
1199                     h->sub_mb_type[i8] = sub_mb_type;
1200
1201                     fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
1202                     if(IS_INTRA(mb_types_col[y8])){
1203                         fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
1204                         fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
1205                         fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
1206                         continue;
1207                     }
1208
1209                     ref0 = l1ref0[x8 + (y8*2>>y_shift)*h->b8_stride];
1210                     if(ref0 >= 0)
1211                         ref0 = map_col_to_list0[0][ref0*2>>y_shift];
1212                     else{
1213                         ref0 = map_col_to_list0[1][l1ref1[x8 + (y8*2>>y_shift)*h->b8_stride]*2>>y_shift];
1214                         l1mv= l1mv1;
1215                     }
1216                     scale = dist_scale_factor[ref0];
1217                     fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
1218
1219                     {
1220                         const int16_t *mv_col = l1mv[x8*3 + (y8*6>>y_shift)*h->b_stride];
1221                         int my_col = (mv_col[1]<<y_shift)/2;
1222                         int mx = (scale * mv_col[0] + 128) >> 8;
1223                         int my = (scale * my_col + 128) >> 8;
1224                         fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mx,my), 4);
1225                         fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mx-mv_col[0],my-my_col), 4);
1226                     }
1227                 }
1228                 return;
1229             }
1230         }
1231
1232         /* one-to-one mv scaling */
1233
1234         if(IS_16X16(*mb_type)){
1235             int ref, mv0, mv1;
1236
1237             fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, 0, 1);
1238             if(IS_INTRA(mb_type_col)){
1239                 ref=mv0=mv1=0;
1240             }else{
1241                 const int ref0 = l1ref0[0] >= 0 ? map_col_to_list0[0][l1ref0[0]]
1242                                                 : map_col_to_list0[1][l1ref1[0]];
1243                 const int scale = dist_scale_factor[ref0];
1244                 const int16_t *mv_col = l1ref0[0] >= 0 ? l1mv0[0] : l1mv1[0];
1245                 int mv_l0[2];
1246                 mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
1247                 mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
1248                 ref= ref0;
1249                 mv0= pack16to32(mv_l0[0],mv_l0[1]);
1250                 mv1= pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
1251             }
1252             fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
1253             fill_rectangle(&h-> mv_cache[0][scan8[0]], 4, 4, 8, mv0, 4);
1254             fill_rectangle(&h-> mv_cache[1][scan8[0]], 4, 4, 8, mv1, 4);
1255         }else{
1256             for(i8=0; i8<4; i8++){
1257                 const int x8 = i8&1;
1258                 const int y8 = i8>>1;
1259                 int ref0, scale;
1260                 const int16_t (*l1mv)[2]= l1mv0;
1261
1262                 if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1263                     continue;
1264                 h->sub_mb_type[i8] = sub_mb_type;
1265                 fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
1266                 if(IS_INTRA(mb_type_col)){
1267                     fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
1268                     fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
1269                     fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
1270                     continue;
1271                 }
1272
1273                 ref0 = l1ref0[x8 + y8*h->b8_stride];
1274                 if(ref0 >= 0)
1275                     ref0 = map_col_to_list0[0][ref0];
1276                 else{
1277                     ref0 = map_col_to_list0[1][l1ref1[x8 + y8*h->b8_stride]];
1278                     l1mv= l1mv1;
1279                 }
1280                 scale = dist_scale_factor[ref0];
1281
1282                 fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
1283                 if(IS_SUB_8X8(sub_mb_type)){
1284                     const int16_t *mv_col = l1mv[x8*3 + y8*3*h->b_stride];
1285                     int mx = (scale * mv_col[0] + 128) >> 8;
1286                     int my = (scale * mv_col[1] + 128) >> 8;
1287                     fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mx,my), 4);
1288                     fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mx-mv_col[0],my-mv_col[1]), 4);
1289                 }else
1290                 for(i4=0; i4<4; i4++){
1291                     const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*h->b_stride];
1292                     int16_t *mv_l0 = h->mv_cache[0][scan8[i8*4+i4]];
1293                     mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
1294                     mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
1295                     *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] =
1296                         pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
1297                 }
1298             }
1299         }
1300     }
1301 }
1302
1303 static inline void write_back_motion(H264Context *h, int mb_type){
1304     MpegEncContext * const s = &h->s;
1305     const int b_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
1306     const int b8_xy= 2*s->mb_x + 2*s->mb_y*h->b8_stride;
1307     int list;
1308
1309     if(!USES_LIST(mb_type, 0))
1310         fill_rectangle(&s->current_picture.ref_index[0][b8_xy], 2, 2, h->b8_stride, (uint8_t)LIST_NOT_USED, 1);
1311
1312     for(list=0; list<h->list_count; list++){
1313         int y;
1314         if(!USES_LIST(mb_type, list))
1315             continue;
1316
1317         for(y=0; y<4; y++){
1318             *(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];
1319             *(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];
1320         }
1321         if( h->pps.cabac ) {
1322             if(IS_SKIP(mb_type))
1323                 fill_rectangle(h->mvd_table[list][b_xy], 4, 4, h->b_stride, 0, 4);
1324             else
1325             for(y=0; y<4; y++){
1326                 *(uint64_t*)h->mvd_table[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+0 + 8*y];
1327                 *(uint64_t*)h->mvd_table[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+2 + 8*y];
1328             }
1329         }
1330
1331         {
1332             int8_t *ref_index = &s->current_picture.ref_index[list][b8_xy];
1333             ref_index[0+0*h->b8_stride]= h->ref_cache[list][scan8[0]];
1334             ref_index[1+0*h->b8_stride]= h->ref_cache[list][scan8[4]];
1335             ref_index[0+1*h->b8_stride]= h->ref_cache[list][scan8[8]];
1336             ref_index[1+1*h->b8_stride]= h->ref_cache[list][scan8[12]];
1337         }
1338     }
1339
1340     if(h->slice_type_nos == FF_B_TYPE && h->pps.cabac){
1341         if(IS_8X8(mb_type)){
1342             uint8_t *direct_table = &h->direct_table[b8_xy];
1343             direct_table[1+0*h->b8_stride] = IS_DIRECT(h->sub_mb_type[1]) ? 1 : 0;
1344             direct_table[0+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[2]) ? 1 : 0;
1345             direct_table[1+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[3]) ? 1 : 0;
1346         }
1347     }
1348 }
1349
1350 /**
1351  * Decodes a network abstraction layer unit.
1352  * @param consumed is the number of bytes used as input
1353  * @param length is the length of the array
1354  * @param dst_length is the number of decoded bytes FIXME here or a decode rbsp tailing?
1355  * @returns decoded bytes, might be src+1 if no escapes
1356  */
1357 static const uint8_t *decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
1358     int i, si, di;
1359     uint8_t *dst;
1360     int bufidx;
1361
1362 //    src[0]&0x80;                //forbidden bit
1363     h->nal_ref_idc= src[0]>>5;
1364     h->nal_unit_type= src[0]&0x1F;
1365
1366     src++; length--;
1367 #if 0
1368     for(i=0; i<length; i++)
1369         printf("%2X ", src[i]);
1370 #endif
1371     for(i=0; i+1<length; i+=2){
1372         if(src[i]) continue;
1373         if(i>0 && src[i-1]==0) i--;
1374         if(i+2<length && src[i+1]==0 && src[i+2]<=3){
1375             if(src[i+2]!=3){
1376                 /* startcode, so we must be past the end */
1377                 length=i;
1378             }
1379             break;
1380         }
1381     }
1382
1383     if(i>=length-1){ //no escaped 0
1384         *dst_length= length;
1385         *consumed= length+1; //+1 for the header
1386         return src;
1387     }
1388
1389     bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
1390     h->rbsp_buffer[bufidx]= av_fast_realloc(h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length);
1391     dst= h->rbsp_buffer[bufidx];
1392
1393     if (dst == NULL){
1394         return NULL;
1395     }
1396
1397 //printf("decoding esc\n");
1398     si=di=0;
1399     while(si<length){
1400         //remove escapes (very rare 1:2^22)
1401         if(si+2<length && src[si]==0 && src[si+1]==0 && src[si+2]<=3){
1402             if(src[si+2]==3){ //escape
1403                 dst[di++]= 0;
1404                 dst[di++]= 0;
1405                 si+=3;
1406                 continue;
1407             }else //next start code
1408                 break;
1409         }
1410
1411         dst[di++]= src[si++];
1412     }
1413
1414     *dst_length= di;
1415     *consumed= si + 1;//+1 for the header
1416 //FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
1417     return dst;
1418 }
1419
1420 /**
1421  * identifies the exact end of the bitstream
1422  * @return the length of the trailing, or 0 if damaged
1423  */
1424 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src){
1425     int v= *src;
1426     int r;
1427
1428     tprintf(h->s.avctx, "rbsp trailing %X\n", v);
1429
1430     for(r=1; r<9; r++){
1431         if(v&1) return r;
1432         v>>=1;
1433     }
1434     return 0;
1435 }
1436
1437 /**
1438  * IDCT transforms the 16 dc values and dequantizes them.
1439  * @param qp quantization parameter
1440  */
1441 static void h264_luma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
1442 #define stride 16
1443     int i;
1444     int temp[16]; //FIXME check if this is a good idea
1445     static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
1446     static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
1447
1448 //memset(block, 64, 2*256);
1449 //return;
1450     for(i=0; i<4; i++){
1451         const int offset= y_offset[i];
1452         const int z0= block[offset+stride*0] + block[offset+stride*4];
1453         const int z1= block[offset+stride*0] - block[offset+stride*4];
1454         const int z2= block[offset+stride*1] - block[offset+stride*5];
1455         const int z3= block[offset+stride*1] + block[offset+stride*5];
1456
1457         temp[4*i+0]= z0+z3;
1458         temp[4*i+1]= z1+z2;
1459         temp[4*i+2]= z1-z2;
1460         temp[4*i+3]= z0-z3;
1461     }
1462
1463     for(i=0; i<4; i++){
1464         const int offset= x_offset[i];
1465         const int z0= temp[4*0+i] + temp[4*2+i];
1466         const int z1= temp[4*0+i] - temp[4*2+i];
1467         const int z2= temp[4*1+i] - temp[4*3+i];
1468         const int z3= temp[4*1+i] + temp[4*3+i];
1469
1470         block[stride*0 +offset]= ((((z0 + z3)*qmul + 128 ) >> 8)); //FIXME think about merging this into decode_residual
1471         block[stride*2 +offset]= ((((z1 + z2)*qmul + 128 ) >> 8));
1472         block[stride*8 +offset]= ((((z1 - z2)*qmul + 128 ) >> 8));
1473         block[stride*10+offset]= ((((z0 - z3)*qmul + 128 ) >> 8));
1474     }
1475 }
1476
1477 #if 0
1478 /**
1479  * DCT transforms the 16 dc values.
1480  * @param qp quantization parameter ??? FIXME
1481  */
1482 static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
1483 //    const int qmul= dequant_coeff[qp][0];
1484     int i;
1485     int temp[16]; //FIXME check if this is a good idea
1486     static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
1487     static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
1488
1489     for(i=0; i<4; i++){
1490         const int offset= y_offset[i];
1491         const int z0= block[offset+stride*0] + block[offset+stride*4];
1492         const int z1= block[offset+stride*0] - block[offset+stride*4];
1493         const int z2= block[offset+stride*1] - block[offset+stride*5];
1494         const int z3= block[offset+stride*1] + block[offset+stride*5];
1495
1496         temp[4*i+0]= z0+z3;
1497         temp[4*i+1]= z1+z2;
1498         temp[4*i+2]= z1-z2;
1499         temp[4*i+3]= z0-z3;
1500     }
1501
1502     for(i=0; i<4; i++){
1503         const int offset= x_offset[i];
1504         const int z0= temp[4*0+i] + temp[4*2+i];
1505         const int z1= temp[4*0+i] - temp[4*2+i];
1506         const int z2= temp[4*1+i] - temp[4*3+i];
1507         const int z3= temp[4*1+i] + temp[4*3+i];
1508
1509         block[stride*0 +offset]= (z0 + z3)>>1;
1510         block[stride*2 +offset]= (z1 + z2)>>1;
1511         block[stride*8 +offset]= (z1 - z2)>>1;
1512         block[stride*10+offset]= (z0 - z3)>>1;
1513     }
1514 }
1515 #endif
1516
1517 #undef xStride
1518 #undef stride
1519
1520 static void chroma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
1521     const int stride= 16*2;
1522     const int xStride= 16;
1523     int a,b,c,d,e;
1524
1525     a= block[stride*0 + xStride*0];
1526     b= block[stride*0 + xStride*1];
1527     c= block[stride*1 + xStride*0];
1528     d= block[stride*1 + xStride*1];
1529
1530     e= a-b;
1531     a= a+b;
1532     b= c-d;
1533     c= c+d;
1534
1535     block[stride*0 + xStride*0]= ((a+c)*qmul) >> 7;
1536     block[stride*0 + xStride*1]= ((e+b)*qmul) >> 7;
1537     block[stride*1 + xStride*0]= ((a-c)*qmul) >> 7;
1538     block[stride*1 + xStride*1]= ((e-b)*qmul) >> 7;
1539 }
1540
1541 #if 0
1542 static void chroma_dc_dct_c(DCTELEM *block){
1543     const int stride= 16*2;
1544     const int xStride= 16;
1545     int a,b,c,d,e;
1546
1547     a= block[stride*0 + xStride*0];
1548     b= block[stride*0 + xStride*1];
1549     c= block[stride*1 + xStride*0];
1550     d= block[stride*1 + xStride*1];
1551
1552     e= a-b;
1553     a= a+b;
1554     b= c-d;
1555     c= c+d;
1556
1557     block[stride*0 + xStride*0]= (a+c);
1558     block[stride*0 + xStride*1]= (e+b);
1559     block[stride*1 + xStride*0]= (a-c);
1560     block[stride*1 + xStride*1]= (e-b);
1561 }
1562 #endif
1563
1564 /**
1565  * gets the chroma qp.
1566  */
1567 static inline int get_chroma_qp(H264Context *h, int t, int qscale){
1568     return h->pps.chroma_qp_table[t][qscale];
1569 }
1570
1571 //FIXME need to check that this does not overflow signed 32 bit for low qp, I am not sure, it's very close
1572 //FIXME check that gcc inlines this (and optimizes intra & separate_dc stuff away)
1573 static inline int quantize_c(DCTELEM *block, uint8_t *scantable, int qscale, int intra, int separate_dc){
1574     int i;
1575     const int * const quant_table= quant_coeff[qscale];
1576     const int bias= intra ? (1<<QUANT_SHIFT)/3 : (1<<QUANT_SHIFT)/6;
1577     const unsigned int threshold1= (1<<QUANT_SHIFT) - bias - 1;
1578     const unsigned int threshold2= (threshold1<<1);
1579     int last_non_zero;
1580
1581     if(separate_dc){
1582         if(qscale<=18){
1583             //avoid overflows
1584             const int dc_bias= intra ? (1<<(QUANT_SHIFT-2))/3 : (1<<(QUANT_SHIFT-2))/6;
1585             const unsigned int dc_threshold1= (1<<(QUANT_SHIFT-2)) - dc_bias - 1;
1586             const unsigned int dc_threshold2= (dc_threshold1<<1);
1587
1588             int level= block[0]*quant_coeff[qscale+18][0];
1589             if(((unsigned)(level+dc_threshold1))>dc_threshold2){
1590                 if(level>0){
1591                     level= (dc_bias + level)>>(QUANT_SHIFT-2);
1592                     block[0]= level;
1593                 }else{
1594                     level= (dc_bias - level)>>(QUANT_SHIFT-2);
1595                     block[0]= -level;
1596                 }
1597 //                last_non_zero = i;
1598             }else{
1599                 block[0]=0;
1600             }
1601         }else{
1602             const int dc_bias= intra ? (1<<(QUANT_SHIFT+1))/3 : (1<<(QUANT_SHIFT+1))/6;
1603             const unsigned int dc_threshold1= (1<<(QUANT_SHIFT+1)) - dc_bias - 1;
1604             const unsigned int dc_threshold2= (dc_threshold1<<1);
1605
1606             int level= block[0]*quant_table[0];
1607             if(((unsigned)(level+dc_threshold1))>dc_threshold2){
1608                 if(level>0){
1609                     level= (dc_bias + level)>>(QUANT_SHIFT+1);
1610                     block[0]= level;
1611                 }else{
1612                     level= (dc_bias - level)>>(QUANT_SHIFT+1);
1613                     block[0]= -level;
1614                 }
1615 //                last_non_zero = i;
1616             }else{
1617                 block[0]=0;
1618             }
1619         }
1620         last_non_zero= 0;
1621         i=1;
1622     }else{
1623         last_non_zero= -1;
1624         i=0;
1625     }
1626
1627     for(; i<16; i++){
1628         const int j= scantable[i];
1629         int level= block[j]*quant_table[j];
1630
1631 //        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
1632 //           || bias-level >= (1<<(QMAT_SHIFT - 3))){
1633         if(((unsigned)(level+threshold1))>threshold2){
1634             if(level>0){
1635                 level= (bias + level)>>QUANT_SHIFT;
1636                 block[j]= level;
1637             }else{
1638                 level= (bias - level)>>QUANT_SHIFT;
1639                 block[j]= -level;
1640             }
1641             last_non_zero = i;
1642         }else{
1643             block[j]=0;
1644         }
1645     }
1646
1647     return last_non_zero;
1648 }
1649
1650 static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
1651                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1652                            int src_x_offset, int src_y_offset,
1653                            qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
1654     MpegEncContext * const s = &h->s;
1655     const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
1656     int my=       h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
1657     const int luma_xy= (mx&3) + ((my&3)<<2);
1658     uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*h->mb_linesize;
1659     uint8_t * src_cb, * src_cr;
1660     int extra_width= h->emu_edge_width;
1661     int extra_height= h->emu_edge_height;
1662     int emu=0;
1663     const int full_mx= mx>>2;
1664     const int full_my= my>>2;
1665     const int pic_width  = 16*s->mb_width;
1666     const int pic_height = 16*s->mb_height >> MB_FIELD;
1667
1668     if(!pic->data[0]) //FIXME this is unacceptable, some sensible error concealment must be done for missing reference frames
1669         return;
1670
1671     if(mx&7) extra_width -= 3;
1672     if(my&7) extra_height -= 3;
1673
1674     if(   full_mx < 0-extra_width
1675        || full_my < 0-extra_height
1676        || full_mx + 16/*FIXME*/ > pic_width + extra_width
1677        || full_my + 16/*FIXME*/ > pic_height + extra_height){
1678         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);
1679             src_y= s->edge_emu_buffer + 2 + 2*h->mb_linesize;
1680         emu=1;
1681     }
1682
1683     qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
1684     if(!square){
1685         qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
1686     }
1687
1688     if(ENABLE_GRAY && s->flags&CODEC_FLAG_GRAY) return;
1689
1690     if(MB_FIELD){
1691         // chroma offset when predicting from a field of opposite parity
1692         my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
1693         emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
1694     }
1695     src_cb= pic->data[1] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
1696     src_cr= pic->data[2] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
1697
1698     if(emu){
1699         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);
1700             src_cb= s->edge_emu_buffer;
1701     }
1702     chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
1703
1704     if(emu){
1705         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);
1706             src_cr= s->edge_emu_buffer;
1707     }
1708     chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
1709 }
1710
1711 static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
1712                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1713                            int x_offset, int y_offset,
1714                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1715                            qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
1716                            int list0, int list1){
1717     MpegEncContext * const s = &h->s;
1718     qpel_mc_func *qpix_op=  qpix_put;
1719     h264_chroma_mc_func chroma_op= chroma_put;
1720
1721     dest_y  += 2*x_offset + 2*y_offset*h->  mb_linesize;
1722     dest_cb +=   x_offset +   y_offset*h->mb_uvlinesize;
1723     dest_cr +=   x_offset +   y_offset*h->mb_uvlinesize;
1724     x_offset += 8*s->mb_x;
1725     y_offset += 8*(s->mb_y >> MB_FIELD);
1726
1727     if(list0){
1728         Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
1729         mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
1730                            dest_y, dest_cb, dest_cr, x_offset, y_offset,
1731                            qpix_op, chroma_op);
1732
1733         qpix_op=  qpix_avg;
1734         chroma_op= chroma_avg;
1735     }
1736
1737     if(list1){
1738         Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
1739         mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
1740                            dest_y, dest_cb, dest_cr, x_offset, y_offset,
1741                            qpix_op, chroma_op);
1742     }
1743 }
1744
1745 static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
1746                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1747                            int x_offset, int y_offset,
1748                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1749                            h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
1750                            h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
1751                            int list0, int list1){
1752     MpegEncContext * const s = &h->s;
1753
1754     dest_y  += 2*x_offset + 2*y_offset*h->  mb_linesize;
1755     dest_cb +=   x_offset +   y_offset*h->mb_uvlinesize;
1756     dest_cr +=   x_offset +   y_offset*h->mb_uvlinesize;
1757     x_offset += 8*s->mb_x;
1758     y_offset += 8*(s->mb_y >> MB_FIELD);
1759
1760     if(list0 && list1){
1761         /* don't optimize for luma-only case, since B-frames usually
1762          * use implicit weights => chroma too. */
1763         uint8_t *tmp_cb = s->obmc_scratchpad;
1764         uint8_t *tmp_cr = s->obmc_scratchpad + 8;
1765         uint8_t *tmp_y  = s->obmc_scratchpad + 8*h->mb_uvlinesize;
1766         int refn0 = h->ref_cache[0][ scan8[n] ];
1767         int refn1 = h->ref_cache[1][ scan8[n] ];
1768
1769         mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
1770                     dest_y, dest_cb, dest_cr,
1771                     x_offset, y_offset, qpix_put, chroma_put);
1772         mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
1773                     tmp_y, tmp_cb, tmp_cr,
1774                     x_offset, y_offset, qpix_put, chroma_put);
1775
1776         if(h->use_weight == 2){
1777             int weight0 = h->implicit_weight[refn0][refn1];
1778             int weight1 = 64 - weight0;
1779             luma_weight_avg(  dest_y,  tmp_y,  h->  mb_linesize, 5, weight0, weight1, 0);
1780             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
1781             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
1782         }else{
1783             luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
1784                             h->luma_weight[0][refn0], h->luma_weight[1][refn1],
1785                             h->luma_offset[0][refn0] + h->luma_offset[1][refn1]);
1786             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1787                             h->chroma_weight[0][refn0][0], h->chroma_weight[1][refn1][0],
1788                             h->chroma_offset[0][refn0][0] + h->chroma_offset[1][refn1][0]);
1789             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1790                             h->chroma_weight[0][refn0][1], h->chroma_weight[1][refn1][1],
1791                             h->chroma_offset[0][refn0][1] + h->chroma_offset[1][refn1][1]);
1792         }
1793     }else{
1794         int list = list1 ? 1 : 0;
1795         int refn = h->ref_cache[list][ scan8[n] ];
1796         Picture *ref= &h->ref_list[list][refn];
1797         mc_dir_part(h, ref, n, square, chroma_height, delta, list,
1798                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
1799                     qpix_put, chroma_put);
1800
1801         luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
1802                        h->luma_weight[list][refn], h->luma_offset[list][refn]);
1803         if(h->use_weight_chroma){
1804             chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1805                              h->chroma_weight[list][refn][0], h->chroma_offset[list][refn][0]);
1806             chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1807                              h->chroma_weight[list][refn][1], h->chroma_offset[list][refn][1]);
1808         }
1809     }
1810 }
1811
1812 static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
1813                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1814                            int x_offset, int y_offset,
1815                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1816                            qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
1817                            h264_weight_func *weight_op, h264_biweight_func *weight_avg,
1818                            int list0, int list1){
1819     if((h->use_weight==2 && list0 && list1
1820         && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ] != 32))
1821        || h->use_weight==1)
1822         mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
1823                          x_offset, y_offset, qpix_put, chroma_put,
1824                          weight_op[0], weight_op[3], weight_avg[0], weight_avg[3], list0, list1);
1825     else
1826         mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
1827                     x_offset, y_offset, qpix_put, chroma_put, qpix_avg, chroma_avg, list0, list1);
1828 }
1829
1830 static inline void prefetch_motion(H264Context *h, int list){
1831     /* fetch pixels for estimated mv 4 macroblocks ahead
1832      * optimized for 64byte cache lines */
1833     MpegEncContext * const s = &h->s;
1834     const int refn = h->ref_cache[list][scan8[0]];
1835     if(refn >= 0){
1836         const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
1837         const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
1838         uint8_t **src= h->ref_list[list][refn].data;
1839         int off= mx + (my + (s->mb_x&3)*4)*h->mb_linesize + 64;
1840         s->dsp.prefetch(src[0]+off, s->linesize, 4);
1841         off= (mx>>1) + ((my>>1) + (s->mb_x&7))*s->uvlinesize + 64;
1842         s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
1843     }
1844 }
1845
1846 static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1847                       qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
1848                       qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
1849                       h264_weight_func *weight_op, h264_biweight_func *weight_avg){
1850     MpegEncContext * const s = &h->s;
1851     const int mb_xy= h->mb_xy;
1852     const int mb_type= s->current_picture.mb_type[mb_xy];
1853
1854     assert(IS_INTER(mb_type));
1855
1856     prefetch_motion(h, 0);
1857
1858     if(IS_16X16(mb_type)){
1859         mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
1860                 qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
1861                 &weight_op[0], &weight_avg[0],
1862                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1863     }else if(IS_16X8(mb_type)){
1864         mc_part(h, 0, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 0,
1865                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
1866                 &weight_op[1], &weight_avg[1],
1867                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1868         mc_part(h, 8, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 4,
1869                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
1870                 &weight_op[1], &weight_avg[1],
1871                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
1872     }else if(IS_8X16(mb_type)){
1873         mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
1874                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1875                 &weight_op[2], &weight_avg[2],
1876                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1877         mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
1878                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1879                 &weight_op[2], &weight_avg[2],
1880                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
1881     }else{
1882         int i;
1883
1884         assert(IS_8X8(mb_type));
1885
1886         for(i=0; i<4; i++){
1887             const int sub_mb_type= h->sub_mb_type[i];
1888             const int n= 4*i;
1889             int x_offset= (i&1)<<2;
1890             int y_offset= (i&2)<<1;
1891
1892             if(IS_SUB_8X8(sub_mb_type)){
1893                 mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1894                     qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1895                     &weight_op[3], &weight_avg[3],
1896                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1897             }else if(IS_SUB_8X4(sub_mb_type)){
1898                 mc_part(h, n  , 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1899                     qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
1900                     &weight_op[4], &weight_avg[4],
1901                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1902                 mc_part(h, n+2, 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
1903                     qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
1904                     &weight_op[4], &weight_avg[4],
1905                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1906             }else if(IS_SUB_4X8(sub_mb_type)){
1907                 mc_part(h, n  , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1908                     qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1909                     &weight_op[5], &weight_avg[5],
1910                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1911                 mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
1912                     qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1913                     &weight_op[5], &weight_avg[5],
1914                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1915             }else{
1916                 int j;
1917                 assert(IS_SUB_4X4(sub_mb_type));
1918                 for(j=0; j<4; j++){
1919                     int sub_x_offset= x_offset + 2*(j&1);
1920                     int sub_y_offset= y_offset +   (j&2);
1921                     mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
1922                         qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1923                         &weight_op[6], &weight_avg[6],
1924                         IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1925                 }
1926             }
1927         }
1928     }
1929
1930     prefetch_motion(h, 1);
1931 }
1932
1933 static av_cold void decode_init_vlc(void){
1934     static int done = 0;
1935
1936     if (!done) {
1937         int i;
1938         done = 1;
1939
1940         init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5,
1941                  &chroma_dc_coeff_token_len [0], 1, 1,
1942                  &chroma_dc_coeff_token_bits[0], 1, 1, 1);
1943
1944         for(i=0; i<4; i++){
1945             init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17,
1946                      &coeff_token_len [i][0], 1, 1,
1947                      &coeff_token_bits[i][0], 1, 1, 1);
1948         }
1949
1950         for(i=0; i<3; i++){
1951             init_vlc(&chroma_dc_total_zeros_vlc[i], CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,
1952                      &chroma_dc_total_zeros_len [i][0], 1, 1,
1953                      &chroma_dc_total_zeros_bits[i][0], 1, 1, 1);
1954         }
1955         for(i=0; i<15; i++){
1956             init_vlc(&total_zeros_vlc[i], TOTAL_ZEROS_VLC_BITS, 16,
1957                      &total_zeros_len [i][0], 1, 1,
1958                      &total_zeros_bits[i][0], 1, 1, 1);
1959         }
1960
1961         for(i=0; i<6; i++){
1962             init_vlc(&run_vlc[i], RUN_VLC_BITS, 7,
1963                      &run_len [i][0], 1, 1,
1964                      &run_bits[i][0], 1, 1, 1);
1965         }
1966         init_vlc(&run7_vlc, RUN7_VLC_BITS, 16,
1967                  &run_len [6][0], 1, 1,
1968                  &run_bits[6][0], 1, 1, 1);
1969     }
1970 }
1971
1972 static void free_tables(H264Context *h){
1973     int i;
1974     H264Context *hx;
1975     av_freep(&h->intra4x4_pred_mode);
1976     av_freep(&h->chroma_pred_mode_table);
1977     av_freep(&h->cbp_table);
1978     av_freep(&h->mvd_table[0]);
1979     av_freep(&h->mvd_table[1]);
1980     av_freep(&h->direct_table);
1981     av_freep(&h->non_zero_count);
1982     av_freep(&h->slice_table_base);
1983     h->slice_table= NULL;
1984
1985     av_freep(&h->mb2b_xy);
1986     av_freep(&h->mb2b8_xy);
1987
1988     for(i = 0; i < MAX_SPS_COUNT; i++)
1989         av_freep(h->sps_buffers + i);
1990
1991     for(i = 0; i < MAX_PPS_COUNT; i++)
1992         av_freep(h->pps_buffers + i);
1993
1994     for(i = 0; i < h->s.avctx->thread_count; i++) {
1995         hx = h->thread_context[i];
1996         if(!hx) continue;
1997         av_freep(&hx->top_borders[1]);
1998         av_freep(&hx->top_borders[0]);
1999         av_freep(&hx->s.obmc_scratchpad);
2000     }
2001 }
2002
2003 static void init_dequant8_coeff_table(H264Context *h){
2004     int i,q,x;
2005     const int transpose = (h->s.dsp.h264_idct8_add != ff_h264_idct8_add_c); //FIXME ugly
2006     h->dequant8_coeff[0] = h->dequant8_buffer[0];
2007     h->dequant8_coeff[1] = h->dequant8_buffer[1];
2008
2009     for(i=0; i<2; i++ ){
2010         if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
2011             h->dequant8_coeff[1] = h->dequant8_buffer[0];
2012             break;
2013         }
2014
2015         for(q=0; q<52; q++){
2016             int shift = ff_div6[q];
2017             int idx = ff_rem6[q];
2018             for(x=0; x<64; x++)
2019                 h->dequant8_coeff[i][q][transpose ? (x>>3)|((x&7)<<3) : x] =
2020                     ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
2021                     h->pps.scaling_matrix8[i][x]) << shift;
2022         }
2023     }
2024 }
2025
2026 static void init_dequant4_coeff_table(H264Context *h){
2027     int i,j,q,x;
2028     const int transpose = (h->s.dsp.h264_idct_add != ff_h264_idct_add_c); //FIXME ugly
2029     for(i=0; i<6; i++ ){
2030         h->dequant4_coeff[i] = h->dequant4_buffer[i];
2031         for(j=0; j<i; j++){
2032             if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
2033                 h->dequant4_coeff[i] = h->dequant4_buffer[j];
2034                 break;
2035             }
2036         }
2037         if(j<i)
2038             continue;
2039
2040         for(q=0; q<52; q++){
2041             int shift = ff_div6[q] + 2;
2042             int idx = ff_rem6[q];
2043             for(x=0; x<16; x++)
2044                 h->dequant4_coeff[i][q][transpose ? (x>>2)|((x<<2)&0xF) : x] =
2045                     ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
2046                     h->pps.scaling_matrix4[i][x]) << shift;
2047         }
2048     }
2049 }
2050
2051 static void init_dequant_tables(H264Context *h){
2052     int i,x;
2053     init_dequant4_coeff_table(h);
2054     if(h->pps.transform_8x8_mode)
2055         init_dequant8_coeff_table(h);
2056     if(h->sps.transform_bypass){
2057         for(i=0; i<6; i++)
2058             for(x=0; x<16; x++)
2059                 h->dequant4_coeff[i][0][x] = 1<<6;
2060         if(h->pps.transform_8x8_mode)
2061             for(i=0; i<2; i++)
2062                 for(x=0; x<64; x++)
2063                     h->dequant8_coeff[i][0][x] = 1<<6;
2064     }
2065 }
2066
2067
2068 /**
2069  * allocates tables.
2070  * needs width/height
2071  */
2072 static int alloc_tables(H264Context *h){
2073     MpegEncContext * const s = &h->s;
2074     const int big_mb_num= s->mb_stride * (s->mb_height+1);
2075     int x,y;
2076
2077     CHECKED_ALLOCZ(h->intra4x4_pred_mode, big_mb_num * 8  * sizeof(uint8_t))
2078
2079     CHECKED_ALLOCZ(h->non_zero_count    , big_mb_num * 16 * sizeof(uint8_t))
2080     CHECKED_ALLOCZ(h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(uint8_t))
2081     CHECKED_ALLOCZ(h->cbp_table, big_mb_num * sizeof(uint16_t))
2082
2083     CHECKED_ALLOCZ(h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t))
2084     CHECKED_ALLOCZ(h->mvd_table[0], 32*big_mb_num * sizeof(uint16_t));
2085     CHECKED_ALLOCZ(h->mvd_table[1], 32*big_mb_num * sizeof(uint16_t));
2086     CHECKED_ALLOCZ(h->direct_table, 32*big_mb_num * sizeof(uint8_t));
2087
2088     memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(uint8_t));
2089     h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
2090
2091     CHECKED_ALLOCZ(h->mb2b_xy  , big_mb_num * sizeof(uint32_t));
2092     CHECKED_ALLOCZ(h->mb2b8_xy , big_mb_num * sizeof(uint32_t));
2093     for(y=0; y<s->mb_height; y++){
2094         for(x=0; x<s->mb_width; x++){
2095             const int mb_xy= x + y*s->mb_stride;
2096             const int b_xy = 4*x + 4*y*h->b_stride;
2097             const int b8_xy= 2*x + 2*y*h->b8_stride;
2098
2099             h->mb2b_xy [mb_xy]= b_xy;
2100             h->mb2b8_xy[mb_xy]= b8_xy;
2101         }
2102     }
2103
2104     s->obmc_scratchpad = NULL;
2105
2106     if(!h->dequant4_coeff[0])
2107         init_dequant_tables(h);
2108
2109     return 0;
2110 fail:
2111     free_tables(h);
2112     return -1;
2113 }
2114
2115 /**
2116  * Mimic alloc_tables(), but for every context thread.
2117  */
2118 static void clone_tables(H264Context *dst, H264Context *src){
2119     dst->intra4x4_pred_mode       = src->intra4x4_pred_mode;
2120     dst->non_zero_count           = src->non_zero_count;
2121     dst->slice_table              = src->slice_table;
2122     dst->cbp_table                = src->cbp_table;
2123     dst->mb2b_xy                  = src->mb2b_xy;
2124     dst->mb2b8_xy                 = src->mb2b8_xy;
2125     dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;
2126     dst->mvd_table[0]             = src->mvd_table[0];
2127     dst->mvd_table[1]             = src->mvd_table[1];
2128     dst->direct_table             = src->direct_table;
2129
2130     dst->s.obmc_scratchpad = NULL;
2131     ff_h264_pred_init(&dst->hpc, src->s.codec_id);
2132 }
2133
2134 /**
2135  * Init context
2136  * Allocate buffers which are not shared amongst multiple threads.
2137  */
2138 static int context_init(H264Context *h){
2139     CHECKED_ALLOCZ(h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
2140     CHECKED_ALLOCZ(h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
2141
2142     return 0;
2143 fail:
2144     return -1; // free_tables will clean up for us
2145 }
2146
2147 static av_cold void common_init(H264Context *h){
2148     MpegEncContext * const s = &h->s;
2149
2150     s->width = s->avctx->width;
2151     s->height = s->avctx->height;
2152     s->codec_id= s->avctx->codec->id;
2153
2154     ff_h264_pred_init(&h->hpc, s->codec_id);
2155
2156     h->dequant_coeff_pps= -1;
2157     s->unrestricted_mv=1;
2158     s->decode=1; //FIXME
2159
2160     memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
2161     memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
2162 }
2163
2164 static av_cold int decode_init(AVCodecContext *avctx){
2165     H264Context *h= avctx->priv_data;
2166     MpegEncContext * const s = &h->s;
2167
2168     MPV_decode_defaults(s);
2169
2170     s->avctx = avctx;
2171     common_init(h);
2172
2173     s->out_format = FMT_H264;
2174     s->workaround_bugs= avctx->workaround_bugs;
2175
2176     // set defaults
2177 //    s->decode_mb= ff_h263_decode_mb;
2178     s->quarter_sample = 1;
2179     s->low_delay= 1;
2180
2181     if(avctx->codec_id == CODEC_ID_SVQ3)
2182         avctx->pix_fmt= PIX_FMT_YUVJ420P;
2183     else
2184         avctx->pix_fmt= PIX_FMT_YUV420P;
2185
2186     decode_init_vlc();
2187
2188     if(avctx->extradata_size > 0 && avctx->extradata &&
2189        *(char *)avctx->extradata == 1){
2190         h->is_avc = 1;
2191         h->got_avcC = 0;
2192     } else {
2193         h->is_avc = 0;
2194     }
2195
2196     h->thread_context[0] = h;
2197     h->outputed_poc = INT_MIN;
2198     return 0;
2199 }
2200
2201 static int frame_start(H264Context *h){
2202     MpegEncContext * const s = &h->s;
2203     int i;
2204
2205     if(MPV_frame_start(s, s->avctx) < 0)
2206         return -1;
2207     ff_er_frame_start(s);
2208     /*
2209      * MPV_frame_start uses pict_type to derive key_frame.
2210      * This is incorrect for H.264; IDR markings must be used.
2211      * Zero here; IDR markings per slice in frame or fields are ORed in later.
2212      * See decode_nal_units().
2213      */
2214     s->current_picture_ptr->key_frame= 0;
2215
2216     assert(s->linesize && s->uvlinesize);
2217
2218     for(i=0; i<16; i++){
2219         h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
2220         h->block_offset[24+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
2221     }
2222     for(i=0; i<4; i++){
2223         h->block_offset[16+i]=
2224         h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
2225         h->block_offset[24+16+i]=
2226         h->block_offset[24+20+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
2227     }
2228
2229     /* can't be in alloc_tables because linesize isn't known there.
2230      * FIXME: redo bipred weight to not require extra buffer? */
2231     for(i = 0; i < s->avctx->thread_count; i++)
2232         if(!h->thread_context[i]->s.obmc_scratchpad)
2233             h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
2234
2235     /* some macroblocks will be accessed before they're available */
2236     if(FRAME_MBAFF || s->avctx->thread_count > 1)
2237         memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(uint8_t));
2238
2239 //    s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
2240
2241     // We mark the current picture as non-reference after allocating it, so
2242     // that if we break out due to an error it can be released automatically
2243     // in the next MPV_frame_start().
2244     // SVQ3 as well as most other codecs have only last/next/current and thus
2245     // get released even with set reference, besides SVQ3 and others do not
2246     // mark frames as reference later "naturally".
2247     if(s->codec_id != CODEC_ID_SVQ3)
2248         s->current_picture_ptr->reference= 0;
2249
2250     s->current_picture_ptr->field_poc[0]=
2251     s->current_picture_ptr->field_poc[1]= INT_MAX;
2252     assert(s->current_picture_ptr->long_ref==0);
2253
2254     return 0;
2255 }
2256
2257 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){
2258     MpegEncContext * const s = &h->s;
2259     int i;
2260
2261     src_y  -=   linesize;
2262     src_cb -= uvlinesize;
2263     src_cr -= uvlinesize;
2264
2265     // There are two lines saved, the line above the the top macroblock of a pair,
2266     // and the line above the bottom macroblock
2267     h->left_border[0]= h->top_borders[0][s->mb_x][15];
2268     for(i=1; i<17; i++){
2269         h->left_border[i]= src_y[15+i*  linesize];
2270     }
2271
2272     *(uint64_t*)(h->top_borders[0][s->mb_x]+0)= *(uint64_t*)(src_y +  16*linesize);
2273     *(uint64_t*)(h->top_borders[0][s->mb_x]+8)= *(uint64_t*)(src_y +8+16*linesize);
2274
2275     if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2276         h->left_border[17  ]= h->top_borders[0][s->mb_x][16+7];
2277         h->left_border[17+9]= h->top_borders[0][s->mb_x][24+7];
2278         for(i=1; i<9; i++){
2279             h->left_border[i+17  ]= src_cb[7+i*uvlinesize];
2280             h->left_border[i+17+9]= src_cr[7+i*uvlinesize];
2281         }
2282         *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+8*uvlinesize);
2283         *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+8*uvlinesize);
2284     }
2285 }
2286
2287 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){
2288     MpegEncContext * const s = &h->s;
2289     int temp8, i;
2290     uint64_t temp64;
2291     int deblock_left;
2292     int deblock_top;
2293     int mb_xy;
2294
2295     if(h->deblocking_filter == 2) {
2296         mb_xy = h->mb_xy;
2297         deblock_left = h->slice_table[mb_xy] == h->slice_table[mb_xy - 1];
2298         deblock_top  = h->slice_table[mb_xy] == h->slice_table[h->top_mb_xy];
2299     } else {
2300         deblock_left = (s->mb_x > 0);
2301         deblock_top =  (s->mb_y > 0);
2302     }
2303
2304     src_y  -=   linesize + 1;
2305     src_cb -= uvlinesize + 1;
2306     src_cr -= uvlinesize + 1;
2307
2308 #define XCHG(a,b,t,xchg)\
2309 t= a;\
2310 if(xchg)\
2311     a= b;\
2312 b= t;
2313
2314     if(deblock_left){
2315         for(i = !deblock_top; i<17; i++){
2316             XCHG(h->left_border[i     ], src_y [i*  linesize], temp8, xchg);
2317         }
2318     }
2319
2320     if(deblock_top){
2321         XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
2322         XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
2323         if(s->mb_x+1 < s->mb_width){
2324             XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
2325         }
2326     }
2327
2328     if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2329         if(deblock_left){
2330             for(i = !deblock_top; i<9; i++){
2331                 XCHG(h->left_border[i+17  ], src_cb[i*uvlinesize], temp8, xchg);
2332                 XCHG(h->left_border[i+17+9], src_cr[i*uvlinesize], temp8, xchg);
2333             }
2334         }
2335         if(deblock_top){
2336             XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
2337             XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
2338         }
2339     }
2340 }
2341
2342 static inline void backup_pair_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize){
2343     MpegEncContext * const s = &h->s;
2344     int i;
2345
2346     src_y  -= 2 *   linesize;
2347     src_cb -= 2 * uvlinesize;
2348     src_cr -= 2 * uvlinesize;
2349
2350     // There are two lines saved, the line above the the top macroblock of a pair,
2351     // and the line above the bottom macroblock
2352     h->left_border[0]= h->top_borders[0][s->mb_x][15];
2353     h->left_border[1]= h->top_borders[1][s->mb_x][15];
2354     for(i=2; i<34; i++){
2355         h->left_border[i]= src_y[15+i*  linesize];
2356     }
2357
2358     *(uint64_t*)(h->top_borders[0][s->mb_x]+0)= *(uint64_t*)(src_y +  32*linesize);
2359     *(uint64_t*)(h->top_borders[0][s->mb_x]+8)= *(uint64_t*)(src_y +8+32*linesize);
2360     *(uint64_t*)(h->top_borders[1][s->mb_x]+0)= *(uint64_t*)(src_y +  33*linesize);
2361     *(uint64_t*)(h->top_borders[1][s->mb_x]+8)= *(uint64_t*)(src_y +8+33*linesize);
2362
2363     if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2364         h->left_border[34     ]= h->top_borders[0][s->mb_x][16+7];
2365         h->left_border[34+   1]= h->top_borders[1][s->mb_x][16+7];
2366         h->left_border[34+18  ]= h->top_borders[0][s->mb_x][24+7];
2367         h->left_border[34+18+1]= h->top_borders[1][s->mb_x][24+7];
2368         for(i=2; i<18; i++){
2369             h->left_border[i+34   ]= src_cb[7+i*uvlinesize];
2370             h->left_border[i+34+18]= src_cr[7+i*uvlinesize];
2371         }
2372         *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+16*uvlinesize);
2373         *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+16*uvlinesize);
2374         *(uint64_t*)(h->top_borders[1][s->mb_x]+16)= *(uint64_t*)(src_cb+17*uvlinesize);
2375         *(uint64_t*)(h->top_borders[1][s->mb_x]+24)= *(uint64_t*)(src_cr+17*uvlinesize);
2376     }
2377 }
2378
2379 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){
2380     MpegEncContext * const s = &h->s;
2381     int temp8, i;
2382     uint64_t temp64;
2383     int deblock_left = (s->mb_x > 0);
2384     int deblock_top  = (s->mb_y > 1);
2385
2386     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);
2387
2388     src_y  -= 2 *   linesize + 1;
2389     src_cb -= 2 * uvlinesize + 1;
2390     src_cr -= 2 * uvlinesize + 1;
2391
2392 #define XCHG(a,b,t,xchg)\
2393 t= a;\
2394 if(xchg)\
2395     a= b;\
2396 b= t;
2397
2398     if(deblock_left){
2399         for(i = (!deblock_top)<<1; i<34; i++){
2400             XCHG(h->left_border[i     ], src_y [i*  linesize], temp8, xchg);
2401         }
2402     }
2403
2404     if(deblock_top){
2405         XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
2406         XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
2407         XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+0), *(uint64_t*)(src_y +1 +linesize), temp64, xchg);
2408         XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+8), *(uint64_t*)(src_y +9 +linesize), temp64, 1);
2409         if(s->mb_x+1 < s->mb_width){
2410             XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
2411             XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x+1]), *(uint64_t*)(src_y +17 +linesize), temp64, 1);
2412         }
2413     }
2414
2415     if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2416         if(deblock_left){
2417             for(i = (!deblock_top) << 1; i<18; i++){
2418                 XCHG(h->left_border[i+34   ], src_cb[i*uvlinesize], temp8, xchg);
2419                 XCHG(h->left_border[i+34+18], src_cr[i*uvlinesize], temp8, xchg);
2420             }
2421         }
2422         if(deblock_top){
2423             XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
2424             XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
2425             XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+16), *(uint64_t*)(src_cb+1 +uvlinesize), temp64, 1);
2426             XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+24), *(uint64_t*)(src_cr+1 +uvlinesize), temp64, 1);
2427         }
2428     }
2429 }
2430
2431 static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
2432     MpegEncContext * const s = &h->s;
2433     const int mb_x= s->mb_x;
2434     const int mb_y= s->mb_y;
2435     const int mb_xy= h->mb_xy;
2436     const int mb_type= s->current_picture.mb_type[mb_xy];
2437     uint8_t  *dest_y, *dest_cb, *dest_cr;
2438     int linesize, uvlinesize /*dct_offset*/;
2439     int i;
2440     int *block_offset = &h->block_offset[0];
2441     const unsigned int bottom = mb_y & 1;
2442     const int transform_bypass = (s->qscale == 0 && h->sps.transform_bypass), is_h264 = (simple || s->codec_id == CODEC_ID_H264);
2443     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
2444     void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
2445
2446     dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
2447     dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2448     dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2449
2450     s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + 64, s->linesize, 4);
2451     s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + 64, dest_cr - dest_cb, 2);
2452
2453     if (!simple && MB_FIELD) {
2454         linesize   = h->mb_linesize   = s->linesize * 2;
2455         uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2456         block_offset = &h->block_offset[24];
2457         if(mb_y&1){ //FIXME move out of this function?
2458             dest_y -= s->linesize*15;
2459             dest_cb-= s->uvlinesize*7;
2460             dest_cr-= s->uvlinesize*7;
2461         }
2462         if(FRAME_MBAFF) {
2463             int list;
2464             for(list=0; list<h->list_count; list++){
2465                 if(!USES_LIST(mb_type, list))
2466                     continue;
2467                 if(IS_16X16(mb_type)){
2468                     int8_t *ref = &h->ref_cache[list][scan8[0]];
2469                     fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
2470                 }else{
2471                     for(i=0; i<16; i+=4){
2472                         //FIXME can refs be smaller than 8x8 when !direct_8x8_inference ?
2473                         int ref = h->ref_cache[list][scan8[i]];
2474                         if(ref >= 0)
2475                             fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
2476                     }
2477                 }
2478             }
2479         }
2480     } else {
2481         linesize   = h->mb_linesize   = s->linesize;
2482         uvlinesize = h->mb_uvlinesize = s->uvlinesize;
2483 //        dct_offset = s->linesize * 16;
2484     }
2485
2486     if(transform_bypass){
2487         idct_dc_add =
2488         idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
2489     }else if(IS_8x8DCT(mb_type)){
2490         idct_dc_add = s->dsp.h264_idct8_dc_add;
2491         idct_add = s->dsp.h264_idct8_add;
2492     }else{
2493         idct_dc_add = s->dsp.h264_idct_dc_add;
2494         idct_add = s->dsp.h264_idct_add;
2495     }
2496
2497     if(!simple && FRAME_MBAFF && h->deblocking_filter && IS_INTRA(mb_type)
2498        && (!bottom || !IS_INTRA(s->current_picture.mb_type[mb_xy-s->mb_stride]))){
2499         int mbt_y = mb_y&~1;
2500         uint8_t *top_y  = s->current_picture.data[0] + (mbt_y * 16* s->linesize  ) + mb_x * 16;
2501         uint8_t *top_cb = s->current_picture.data[1] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;
2502         uint8_t *top_cr = s->current_picture.data[2] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;
2503         xchg_pair_border(h, top_y, top_cb, top_cr, s->linesize, s->uvlinesize, 1);
2504     }
2505
2506     if (!simple && IS_INTRA_PCM(mb_type)) {
2507         for (i=0; i<16; i++) {
2508             memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
2509         }
2510         for (i=0; i<8; i++) {
2511             memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4,  8);
2512             memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4,  8);
2513         }
2514     } else {
2515         if(IS_INTRA(mb_type)){
2516             if(h->deblocking_filter && (simple || !FRAME_MBAFF))
2517                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
2518
2519             if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2520                 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
2521                 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
2522             }
2523
2524             if(IS_INTRA4x4(mb_type)){
2525                 if(simple || !s->encoding){
2526                     if(IS_8x8DCT(mb_type)){
2527                         for(i=0; i<16; i+=4){
2528                             uint8_t * const ptr= dest_y + block_offset[i];
2529                             const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
2530                             const int nnz = h->non_zero_count_cache[ scan8[i] ];
2531                             h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
2532                                                    (h->topright_samples_available<<i)&0x4000, linesize);
2533                             if(nnz){
2534                                 if(nnz == 1 && h->mb[i*16])
2535                                     idct_dc_add(ptr, h->mb + i*16, linesize);
2536                                 else
2537                                     idct_add(ptr, h->mb + i*16, linesize);
2538                             }
2539                         }
2540                     }else
2541                     for(i=0; i<16; i++){
2542                         uint8_t * const ptr= dest_y + block_offset[i];
2543                         uint8_t *topright;
2544                         const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
2545                         int nnz, tr;
2546
2547                         if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
2548                             const int topright_avail= (h->topright_samples_available<<i)&0x8000;
2549                             assert(mb_y || linesize <= block_offset[i]);
2550                             if(!topright_avail){
2551                                 tr= ptr[3 - linesize]*0x01010101;
2552                                 topright= (uint8_t*) &tr;
2553                             }else
2554                                 topright= ptr + 4 - linesize;
2555                         }else
2556                             topright= NULL;
2557
2558                         h->hpc.pred4x4[ dir ](ptr, topright, linesize);
2559                         nnz = h->non_zero_count_cache[ scan8[i] ];
2560                         if(nnz){
2561                             if(is_h264){
2562                                 if(nnz == 1 && h->mb[i*16])
2563                                     idct_dc_add(ptr, h->mb + i*16, linesize);
2564                                 else
2565                                     idct_add(ptr, h->mb + i*16, linesize);
2566                             }else
2567                                 svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
2568                         }
2569                     }
2570                 }
2571             }else{
2572                 h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
2573                 if(is_h264){
2574                     if(!transform_bypass)
2575                         h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[0][s->qscale][0]);
2576                 }else
2577                     svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
2578             }
2579             if(h->deblocking_filter && (simple || !FRAME_MBAFF))
2580                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
2581         }else if(is_h264){
2582             hl_motion(h, dest_y, dest_cb, dest_cr,
2583                       s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2584                       s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2585                       s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);
2586         }
2587
2588
2589         if(!IS_INTRA4x4(mb_type)){
2590             if(is_h264){
2591                 if(IS_INTRA16x16(mb_type)){
2592                     for(i=0; i<16; i++){
2593                         if(h->non_zero_count_cache[ scan8[i] ])
2594                             idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2595                         else if(h->mb[i*16])
2596                             idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2597                     }
2598                 }else{
2599                     const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2600                     for(i=0; i<16; i+=di){
2601                         int nnz = h->non_zero_count_cache[ scan8[i] ];
2602                         if(nnz){
2603                             if(nnz==1 && h->mb[i*16])
2604                                 idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2605                             else
2606                                 idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2607                         }
2608                     }
2609                 }
2610             }else{
2611                 for(i=0; i<16; i++){
2612                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
2613                         uint8_t * const ptr= dest_y + block_offset[i];
2614                         svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
2615                     }
2616                 }
2617             }
2618         }
2619
2620         if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2621             uint8_t *dest[2] = {dest_cb, dest_cr};
2622             if(transform_bypass){
2623                 idct_add = idct_dc_add = s->dsp.add_pixels4;
2624             }else{
2625                 idct_add = s->dsp.h264_idct_add;
2626                 idct_dc_add = s->dsp.h264_idct_dc_add;
2627                 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]);
2628                 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]);
2629             }
2630             if(is_h264){
2631                 for(i=16; i<16+8; i++){
2632                     if(h->non_zero_count_cache[ scan8[i] ])
2633                         idct_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2634                     else if(h->mb[i*16])
2635                         idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2636                 }
2637             }else{
2638                 for(i=16; i<16+8; i++){
2639                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2640                         uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
2641                         svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
2642                     }
2643                 }
2644             }
2645         }
2646     }
2647     if(h->deblocking_filter) {
2648         if (!simple && FRAME_MBAFF) {
2649             //FIXME try deblocking one mb at a time?
2650             // the reduction in load/storing mvs and such might outweigh the extra backup/xchg_border
2651             const int mb_y = s->mb_y - 1;
2652             uint8_t  *pair_dest_y, *pair_dest_cb, *pair_dest_cr;
2653             const int mb_xy= mb_x + mb_y*s->mb_stride;
2654             const int mb_type_top   = s->current_picture.mb_type[mb_xy];
2655             const int mb_type_bottom= s->current_picture.mb_type[mb_xy+s->mb_stride];
2656             if (!bottom) return;
2657             pair_dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
2658             pair_dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2659             pair_dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2660
2661             if(IS_INTRA(mb_type_top | mb_type_bottom))
2662                 xchg_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize, 0);
2663
2664             backup_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize);
2665             // deblock a pair
2666             // top
2667             s->mb_y--; h->mb_xy -= s->mb_stride;
2668             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);
2669             fill_caches(h, mb_type_top, 1); //FIXME don't fill stuff which isn't used by filter_mb
2670             h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2671             h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2672             filter_mb(h, mb_x, mb_y, pair_dest_y, pair_dest_cb, pair_dest_cr, linesize, uvlinesize);
2673             // bottom
2674             s->mb_y++; h->mb_xy += s->mb_stride;
2675             tprintf(h->s.avctx, "call mbaff filter_mb\n");
2676             fill_caches(h, mb_type_bottom, 1); //FIXME don't fill stuff which isn't used by filter_mb
2677             h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
2678             h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
2679             filter_mb(h, mb_x, mb_y+1, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2680         } else {
2681             tprintf(h->s.avctx, "call filter_mb\n");
2682             backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, simple);
2683             fill_caches(h, mb_type, 1); //FIXME don't fill stuff which isn't used by filter_mb
2684             h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2685             h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2686             filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2687         }
2688     }
2689 }
2690
2691 /**
2692  * Process a macroblock; this case avoids checks for expensive uncommon cases.
2693  */
2694 static void hl_decode_mb_simple(H264Context *h){
2695     hl_decode_mb_internal(h, 1);
2696 }
2697
2698 /**
2699  * Process a macroblock; this handles edge cases, such as interlacing.
2700  */
2701 static void av_noinline hl_decode_mb_complex(H264Context *h){
2702     hl_decode_mb_internal(h, 0);
2703 }
2704
2705 static void hl_decode_mb(H264Context *h){
2706     MpegEncContext * const s = &h->s;
2707     const int mb_xy= h->mb_xy;
2708     const int mb_type= s->current_picture.mb_type[mb_xy];
2709     int is_complex = FRAME_MBAFF || MB_FIELD || IS_INTRA_PCM(mb_type) || s->codec_id != CODEC_ID_H264 ||
2710                     (ENABLE_GRAY && (s->flags&CODEC_FLAG_GRAY)) || (ENABLE_H264_ENCODER && s->encoding) || ENABLE_SMALL;
2711
2712     if(ENABLE_H264_ENCODER && !s->decode)
2713         return;
2714
2715     if (is_complex)
2716         hl_decode_mb_complex(h);
2717     else hl_decode_mb_simple(h);
2718 }
2719
2720 static void pic_as_field(Picture *pic, const int parity){
2721     int i;
2722     for (i = 0; i < 4; ++i) {
2723         if (parity == PICT_BOTTOM_FIELD)
2724             pic->data[i] += pic->linesize[i];
2725         pic->reference = parity;
2726         pic->linesize[i] *= 2;
2727     }
2728     pic->poc= pic->field_poc[parity == PICT_BOTTOM_FIELD];
2729 }
2730
2731 static int split_field_copy(Picture *dest, Picture *src,
2732                             int parity, int id_add){
2733     int match = !!(src->reference & parity);
2734
2735     if (match) {
2736         *dest = *src;
2737         if(parity != PICT_FRAME){
2738             pic_as_field(dest, parity);
2739             dest->pic_id *= 2;
2740             dest->pic_id += id_add;
2741         }
2742     }
2743
2744     return match;
2745 }
2746
2747 static int build_def_list(Picture *def, Picture **in, int len, int is_long, int sel){
2748     int i[2]={0};
2749     int index=0;
2750
2751     while(i[0]<len || i[1]<len){
2752         while(i[0]<len && !(in[ i[0] ] && (in[ i[0] ]->reference & sel)))
2753             i[0]++;
2754         while(i[1]<len && !(in[ i[1] ] && (in[ i[1] ]->reference & (sel^3))))
2755             i[1]++;
2756         if(i[0] < len){
2757             in[ i[0] ]->pic_id= is_long ? i[0] : in[ i[0] ]->frame_num;
2758             split_field_copy(&def[index++], in[ i[0]++ ], sel  , 1);
2759         }
2760         if(i[1] < len){
2761             in[ i[1] ]->pic_id= is_long ? i[1] : in[ i[1] ]->frame_num;
2762             split_field_copy(&def[index++], in[ i[1]++ ], sel^3, 0);
2763         }
2764     }
2765
2766     return index;
2767 }
2768
2769 static int add_sorted(Picture **sorted, Picture **src, int len, int limit, int dir){
2770     int i, best_poc;
2771     int out_i= 0;
2772
2773     for(;;){
2774         best_poc= dir ? INT_MIN : INT_MAX;
2775
2776         for(i=0; i<len; i++){
2777             const int poc= src[i]->poc;
2778             if(((poc > limit) ^ dir) && ((poc < best_poc) ^ dir)){
2779                 best_poc= poc;
2780                 sorted[out_i]= src[i];
2781             }
2782         }
2783         if(best_poc == (dir ? INT_MIN : INT_MAX))
2784             break;
2785         limit= sorted[out_i++]->poc - dir;
2786     }
2787     return out_i;
2788 }
2789
2790 /**
2791  * fills the default_ref_list.
2792  */
2793 static int fill_default_ref_list(H264Context *h){
2794     MpegEncContext * const s = &h->s;
2795     int i, len;
2796
2797     if(h->slice_type_nos==FF_B_TYPE){
2798         Picture *sorted[32];
2799         int cur_poc, list;
2800         int lens[2];
2801
2802         if(FIELD_PICTURE)
2803             cur_poc= s->current_picture_ptr->field_poc[ s->picture_structure == PICT_BOTTOM_FIELD ];
2804         else
2805             cur_poc= s->current_picture_ptr->poc;
2806
2807         for(list= 0; list<2; list++){
2808             len= add_sorted(sorted    , h->short_ref, h->short_ref_count, cur_poc, 1^list);
2809             len+=add_sorted(sorted+len, h->short_ref, h->short_ref_count, cur_poc, 0^list);
2810             assert(len<=32);
2811             len= build_def_list(h->default_ref_list[list]    , sorted     , len, 0, s->picture_structure);
2812             len+=build_def_list(h->default_ref_list[list]+len, h->long_ref, 16 , 1, s->picture_structure);
2813             assert(len<=32);
2814
2815             if(len < h->ref_count[list])
2816                 memset(&h->default_ref_list[list][len], 0, sizeof(Picture)*(h->ref_count[list] - len));
2817             lens[list]= len;
2818         }
2819
2820         if(lens[0] == lens[1] && lens[1] > 1){
2821             for(i=0; h->default_ref_list[0][i].data[0] == h->default_ref_list[1][i].data[0] && i<lens[0]; i++);
2822             if(i == lens[0])
2823                 FFSWAP(Picture, h->default_ref_list[1][0], h->default_ref_list[1][1]);
2824         }
2825     }else{
2826         len = build_def_list(h->default_ref_list[0]    , h->short_ref, h->short_ref_count, 0, s->picture_structure);
2827         len+= build_def_list(h->default_ref_list[0]+len, h-> long_ref, 16                , 1, s->picture_structure);
2828         assert(len <= 32);
2829         if(len < h->ref_count[0])
2830             memset(&h->default_ref_list[0][len], 0, sizeof(Picture)*(h->ref_count[0] - len));
2831     }
2832 #ifdef TRACE
2833     for (i=0; i<h->ref_count[0]; i++) {
2834         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]);
2835     }
2836     if(h->slice_type_nos==FF_B_TYPE){
2837         for (i=0; i<h->ref_count[1]; i++) {
2838             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]);
2839         }
2840     }
2841 #endif
2842     return 0;
2843 }
2844
2845 static void print_short_term(H264Context *h);
2846 static void print_long_term(H264Context *h);
2847
2848 /**
2849  * Extract structure information about the picture described by pic_num in
2850  * the current decoding context (frame or field). Note that pic_num is
2851  * picture number without wrapping (so, 0<=pic_num<max_pic_num).
2852  * @param pic_num picture number for which to extract structure information
2853  * @param structure one of PICT_XXX describing structure of picture
2854  *                      with pic_num
2855  * @return frame number (short term) or long term index of picture
2856  *         described by pic_num
2857  */
2858 static int pic_num_extract(H264Context *h, int pic_num, int *structure){
2859     MpegEncContext * const s = &h->s;
2860
2861     *structure = s->picture_structure;
2862     if(FIELD_PICTURE){
2863         if (!(pic_num & 1))
2864             /* opposite field */
2865             *structure ^= PICT_FRAME;
2866         pic_num >>= 1;
2867     }
2868
2869     return pic_num;
2870 }
2871
2872 static int decode_ref_pic_list_reordering(H264Context *h){
2873     MpegEncContext * const s = &h->s;
2874     int list, index, pic_structure;
2875
2876     print_short_term(h);
2877     print_long_term(h);
2878
2879     for(list=0; list<h->list_count; list++){
2880         memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);
2881
2882         if(get_bits1(&s->gb)){
2883             int pred= h->curr_pic_num;
2884
2885             for(index=0; ; index++){
2886                 unsigned int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
2887                 unsigned int pic_id;
2888                 int i;
2889                 Picture *ref = NULL;
2890
2891                 if(reordering_of_pic_nums_idc==3)
2892                     break;
2893
2894                 if(index >= h->ref_count[list]){
2895                     av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
2896                     return -1;
2897                 }
2898
2899                 if(reordering_of_pic_nums_idc<3){
2900                     if(reordering_of_pic_nums_idc<2){
2901                         const unsigned int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
2902                         int frame_num;
2903
2904                         if(abs_diff_pic_num > h->max_pic_num){
2905                             av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
2906                             return -1;
2907                         }
2908
2909                         if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
2910                         else                                pred+= abs_diff_pic_num;
2911                         pred &= h->max_pic_num - 1;
2912
2913                         frame_num = pic_num_extract(h, pred, &pic_structure);
2914
2915                         for(i= h->short_ref_count-1; i>=0; i--){
2916                             ref = h->short_ref[i];
2917                             assert(ref->reference);
2918                             assert(!ref->long_ref);
2919                             if(
2920                                    ref->frame_num == frame_num &&
2921                                    (ref->reference & pic_structure)
2922                               )
2923                                 break;
2924                         }
2925                         if(i>=0)
2926                             ref->pic_id= pred;
2927                     }else{
2928                         int long_idx;
2929                         pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
2930
2931                         long_idx= pic_num_extract(h, pic_id, &pic_structure);
2932
2933                         if(long_idx>31){
2934                             av_log(h->s.avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
2935                             return -1;
2936                         }
2937                         ref = h->long_ref[long_idx];
2938                         assert(!(ref && !ref->reference));
2939                         if(ref && (ref->reference & pic_structure)){
2940                             ref->pic_id= pic_id;
2941                             assert(ref->long_ref);
2942                             i=0;
2943                         }else{
2944                             i=-1;
2945                         }
2946                     }
2947
2948                     if (i < 0) {
2949                         av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
2950                         memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
2951                     } else {
2952                         for(i=index; i+1<h->ref_count[list]; i++){
2953                             if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)
2954                                 break;
2955                         }
2956                         for(; i > index; i--){
2957                             h->ref_list[list][i]= h->ref_list[list][i-1];
2958                         }
2959                         h->ref_list[list][index]= *ref;
2960                         if (FIELD_PICTURE){
2961                             pic_as_field(&h->ref_list[list][index], pic_structure);
2962                         }
2963                     }
2964                 }else{
2965                     av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
2966                     return -1;
2967                 }
2968             }
2969         }
2970     }
2971     for(list=0; list<h->list_count; list++){
2972         for(index= 0; index < h->ref_count[list]; index++){
2973             if(!h->ref_list[list][index].data[0]){
2974                 av_log(h->s.avctx, AV_LOG_ERROR, "Missing reference picture\n");
2975                 h->ref_list[list][index]= s->current_picture; //FIXME this is not a sensible solution
2976             }
2977         }
2978     }
2979
2980     if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2981         direct_dist_scale_factor(h);
2982     direct_ref_list_init(h);
2983     return 0;
2984 }
2985
2986 static void fill_mbaff_ref_list(H264Context *h){
2987     int list, i, j;
2988     for(list=0; list<2; list++){ //FIXME try list_count
2989         for(i=0; i<h->ref_count[list]; i++){
2990             Picture *frame = &h->ref_list[list][i];
2991             Picture *field = &h->ref_list[list][16+2*i];
2992             field[0] = *frame;
2993             for(j=0; j<3; j++)
2994                 field[0].linesize[j] <<= 1;
2995             field[0].reference = PICT_TOP_FIELD;
2996             field[1] = field[0];
2997             for(j=0; j<3; j++)
2998                 field[1].data[j] += frame->linesize[j];
2999             field[1].reference = PICT_BOTTOM_FIELD;
3000
3001             h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i];
3002             h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i];
3003             for(j=0; j<2; j++){
3004                 h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j];
3005                 h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j];
3006             }
3007         }
3008     }
3009     for(j=0; j<h->ref_count[1]; j++){
3010         for(i=0; i<h->ref_count[0]; i++)
3011             h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i];
3012         memcpy(h->implicit_weight[16+2*j],   h->implicit_weight[j], sizeof(*h->implicit_weight));
3013         memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight));
3014     }
3015 }
3016
3017 static int pred_weight_table(H264Context *h){
3018     MpegEncContext * const s = &h->s;
3019     int list, i;
3020     int luma_def, chroma_def;
3021
3022     h->use_weight= 0;
3023     h->use_weight_chroma= 0;
3024     h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
3025     h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
3026     luma_def = 1<<h->luma_log2_weight_denom;
3027     chroma_def = 1<<h->chroma_log2_weight_denom;
3028
3029     for(list=0; list<2; list++){
3030         for(i=0; i<h->ref_count[list]; i++){
3031             int luma_weight_flag, chroma_weight_flag;
3032
3033             luma_weight_flag= get_bits1(&s->gb);
3034             if(luma_weight_flag){
3035                 h->luma_weight[list][i]= get_se_golomb(&s->gb);
3036                 h->luma_offset[list][i]= get_se_golomb(&s->gb);
3037                 if(   h->luma_weight[list][i] != luma_def
3038                    || h->luma_offset[list][i] != 0)
3039                     h->use_weight= 1;
3040             }else{
3041                 h->luma_weight[list][i]= luma_def;
3042                 h->luma_offset[list][i]= 0;
3043             }
3044
3045             if(CHROMA){
3046                 chroma_weight_flag= get_bits1(&s->gb);
3047                 if(chroma_weight_flag){
3048                     int j;
3049                     for(j=0; j<2; j++){
3050                         h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
3051                         h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
3052                         if(   h->chroma_weight[list][i][j] != chroma_def
3053                         || h->chroma_offset[list][i][j] != 0)
3054                             h->use_weight_chroma= 1;
3055                     }
3056                 }else{
3057                     int j;
3058                     for(j=0; j<2; j++){
3059                         h->chroma_weight[list][i][j]= chroma_def;
3060                         h->chroma_offset[list][i][j]= 0;
3061                     }
3062                 }
3063             }
3064         }
3065         if(h->slice_type_nos != FF_B_TYPE) break;
3066     }
3067     h->use_weight= h->use_weight || h->use_weight_chroma;
3068     return 0;
3069 }
3070
3071 static void implicit_weight_table(H264Context *h){
3072     MpegEncContext * const s = &h->s;
3073     int ref0, ref1;
3074     int cur_poc = s->current_picture_ptr->poc;
3075
3076     if(   h->ref_count[0] == 1 && h->ref_count[1] == 1
3077        && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
3078         h->use_weight= 0;
3079         h->use_weight_chroma= 0;
3080         return;
3081     }
3082
3083     h->use_weight= 2;
3084     h->use_weight_chroma= 2;
3085     h->luma_log2_weight_denom= 5;
3086     h->chroma_log2_weight_denom= 5;
3087
3088     for(ref0=0; ref0 < h->ref_count[0]; ref0++){
3089         int poc0 = h->ref_list[0][ref0].poc;
3090         for(ref1=0; ref1 < h->ref_count[1]; ref1++){
3091             int poc1 = h->ref_list[1][ref1].poc;
3092             int td = av_clip(poc1 - poc0, -128, 127);
3093             if(td){
3094                 int tb = av_clip(cur_poc - poc0, -128, 127);
3095                 int tx = (16384 + (FFABS(td) >> 1)) / td;
3096                 int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
3097                 if(dist_scale_factor < -64 || dist_scale_factor > 128)
3098                     h->implicit_weight[ref0][ref1] = 32;
3099                 else
3100                     h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
3101             }else
3102                 h->implicit_weight[ref0][ref1] = 32;
3103         }
3104     }
3105 }
3106
3107 /**
3108  * Mark a picture as no longer needed for reference. The refmask
3109  * argument allows unreferencing of individual fields or the whole frame.
3110  * If the picture becomes entirely unreferenced, but is being held for
3111  * display purposes, it is marked as such.
3112  * @param refmask mask of fields to unreference; the mask is bitwise
3113  *                anded with the reference marking of pic
3114  * @return non-zero if pic becomes entirely unreferenced (except possibly
3115  *         for display purposes) zero if one of the fields remains in
3116  *         reference
3117  */
3118 static inline int unreference_pic(H264Context *h, Picture *pic, int refmask){
3119     int i;
3120     if (pic->reference &= refmask) {
3121         return 0;
3122     } else {
3123         for(i = 0; h->delayed_pic[i]; i++)
3124             if(pic == h->delayed_pic[i]){
3125                 pic->reference=DELAYED_PIC_REF;
3126                 break;
3127             }
3128         return 1;
3129     }
3130 }
3131
3132 /**
3133  * instantaneous decoder refresh.
3134  */
3135 static void idr(H264Context *h){
3136     int i;
3137
3138     for(i=0; i<16; i++){
3139         remove_long(h, i, 0);
3140     }
3141     assert(h->long_ref_count==0);
3142
3143     for(i=0; i<h->short_ref_count; i++){
3144         unreference_pic(h, h->short_ref[i], 0);
3145         h->short_ref[i]= NULL;
3146     }
3147     h->short_ref_count=0;
3148     h->prev_frame_num= 0;
3149     h->prev_frame_num_offset= 0;
3150     h->prev_poc_msb=
3151     h->prev_poc_lsb= 0;
3152 }
3153
3154 /* forget old pics after a seek */
3155 static void flush_dpb(AVCodecContext *avctx){
3156     H264Context *h= avctx->priv_data;
3157     int i;
3158     for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
3159         if(h->delayed_pic[i])
3160             h->delayed_pic[i]->reference= 0;
3161         h->delayed_pic[i]= NULL;
3162     }
3163     h->outputed_poc= INT_MIN;
3164     idr(h);
3165     if(h->s.current_picture_ptr)
3166         h->s.current_picture_ptr->reference= 0;
3167     h->s.first_field= 0;
3168     ff_mpeg_flush(avctx);
3169 }
3170
3171 /**
3172  * Find a Picture in the short term reference list by frame number.
3173  * @param frame_num frame number to search for
3174  * @param idx the index into h->short_ref where returned picture is found
3175  *            undefined if no picture found.
3176  * @return pointer to the found picture, or NULL if no pic with the provided
3177  *                 frame number is found
3178  */
3179 static Picture * find_short(H264Context *h, int frame_num, int *idx){
3180     MpegEncContext * const s = &h->s;
3181     int i;
3182
3183     for(i=0; i<h->short_ref_count; i++){
3184         Picture *pic= h->short_ref[i];
3185         if(s->avctx->debug&FF_DEBUG_MMCO)
3186             av_log(h->s.avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
3187         if(pic->frame_num == frame_num) {
3188             *idx = i;
3189             return pic;
3190         }
3191     }
3192     return NULL;
3193 }
3194
3195 /**
3196  * Remove a picture from the short term reference list by its index in
3197  * that list.  This does no checking on the provided index; it is assumed
3198  * to be valid. Other list entries are shifted down.
3199  * @param i index into h->short_ref of picture to remove.
3200  */
3201 static void remove_short_at_index(H264Context *h, int i){
3202     assert(i >= 0 && i < h->short_ref_count);
3203     h->short_ref[i]= NULL;
3204     if (--h->short_ref_count)
3205         memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i)*sizeof(Picture*));
3206 }
3207
3208 /**
3209  *
3210  * @return the removed picture or NULL if an error occurs
3211  */
3212 static Picture * remove_short(H264Context *h, int frame_num, int ref_mask){
3213     MpegEncContext * const s = &h->s;
3214     Picture *pic;
3215     int i;
3216
3217     if(s->avctx->debug&FF_DEBUG_MMCO)
3218         av_log(h->s.avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
3219
3220     pic = find_short(h, frame_num, &i);
3221     if (pic){
3222         if(unreference_pic(h, pic, ref_mask))
3223         remove_short_at_index(h, i);
3224     }
3225
3226     return pic;
3227 }
3228
3229 /**
3230  * Remove a picture from the long term reference list by its index in
3231  * that list.
3232  * @return the removed picture or NULL if an error occurs
3233  */
3234 static Picture * remove_long(H264Context *h, int i, int ref_mask){
3235     Picture *pic;
3236
3237     pic= h->long_ref[i];
3238     if (pic){
3239         if(unreference_pic(h, pic, ref_mask)){
3240             assert(h->long_ref[i]->long_ref == 1);
3241             h->long_ref[i]->long_ref= 0;
3242             h->long_ref[i]= NULL;
3243             h->long_ref_count--;
3244         }
3245     }
3246
3247     return pic;
3248 }
3249
3250 /**
3251  * print short term list
3252  */
3253 static void print_short_term(H264Context *h) {
3254     uint32_t i;
3255     if(h->s.avctx->debug&FF_DEBUG_MMCO) {
3256         av_log(h->s.avctx, AV_LOG_DEBUG, "short term list:\n");
3257         for(i=0; i<h->short_ref_count; i++){
3258             Picture *pic= h->short_ref[i];
3259             av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
3260         }
3261     }
3262 }
3263
3264 /**
3265  * print long term list
3266  */
3267 static void print_long_term(H264Context *h) {
3268     uint32_t i;
3269     if(h->s.avctx->debug&FF_DEBUG_MMCO) {
3270         av_log(h->s.avctx, AV_LOG_DEBUG, "long term list:\n");
3271         for(i = 0; i < 16; i++){
3272             Picture *pic= h->long_ref[i];
3273             if (pic) {
3274                 av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
3275             }
3276         }
3277     }
3278 }
3279
3280 /**
3281  * Executes the reference picture marking (memory management control operations).
3282  */
3283 static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
3284     MpegEncContext * const s = &h->s;
3285     int i, j;
3286     int current_ref_assigned=0;
3287     Picture *pic;
3288
3289     if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)
3290         av_log(h->s.avctx, AV_LOG_DEBUG, "no mmco here\n");
3291
3292     for(i=0; i<mmco_count; i++){
3293         int structure, frame_num;
3294         if(s->avctx->debug&FF_DEBUG_MMCO)
3295             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);
3296
3297         if(   mmco[i].opcode == MMCO_SHORT2UNUSED
3298            || mmco[i].opcode == MMCO_SHORT2LONG){
3299             frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
3300             pic = find_short(h, frame_num, &j);
3301             if(!pic){
3302                 if(mmco[i].opcode != MMCO_SHORT2LONG || !h->long_ref[mmco[i].long_arg]
3303                    || h->long_ref[mmco[i].long_arg]->frame_num != frame_num)
3304                 av_log(h->s.avctx, AV_LOG_ERROR, "mmco: unref short failure\n");
3305                 continue;
3306             }
3307         }
3308
3309         switch(mmco[i].opcode){
3310         case MMCO_SHORT2UNUSED:
3311             if(s->avctx->debug&FF_DEBUG_MMCO)
3312                 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);
3313             remove_short(h, frame_num, structure ^ PICT_FRAME);
3314             break;
3315         case MMCO_SHORT2LONG:
3316                 if (h->long_ref[mmco[i].long_arg] != pic)
3317                     remove_long(h, mmco[i].long_arg, 0);
3318
3319                 remove_short_at_index(h, j);
3320                 h->long_ref[ mmco[i].long_arg ]= pic;
3321                 if (h->long_ref[ mmco[i].long_arg ]){
3322                     h->long_ref[ mmco[i].long_arg ]->long_ref=1;
3323                     h->long_ref_count++;
3324                 }
3325             break;
3326         case MMCO_LONG2UNUSED:
3327             j = pic_num_extract(h, mmco[i].long_arg, &structure);
3328             pic = h->long_ref[j];
3329             if (pic) {
3330                 remove_long(h, j, structure ^ PICT_FRAME);
3331             } else if(s->avctx->debug&FF_DEBUG_MMCO)
3332                 av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
3333             break;
3334         case MMCO_LONG:
3335                     // Comment below left from previous code as it is an interresting note.
3336                     /* First field in pair is in short term list or
3337                      * at a different long term index.
3338                      * This is not allowed; see 7.4.3.3, notes 2 and 3.
3339                      * Report the problem and keep the pair where it is,
3340                      * and mark this field valid.
3341                      */
3342
3343             if (h->long_ref[mmco[i].long_arg] != s->current_picture_ptr) {
3344                 remove_long(h, mmco[i].long_arg, 0);
3345
3346                 h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;
3347                 h->long_ref[ mmco[i].long_arg ]->long_ref=1;
3348                 h->long_ref_count++;
3349             }
3350
3351             s->current_picture_ptr->reference |= s->picture_structure;
3352             current_ref_assigned=1;
3353             break;
3354         case MMCO_SET_MAX_LONG:
3355             assert(mmco[i].long_arg <= 16);
3356             // just remove the long term which index is greater than new max
3357             for(j = mmco[i].long_arg; j<16; j++){
3358                 remove_long(h, j, 0);
3359             }
3360             break;
3361         case MMCO_RESET:
3362             while(h->short_ref_count){
3363                 remove_short(h, h->short_ref[0]->frame_num, 0);
3364             }
3365             for(j = 0; j < 16; j++) {
3366                 remove_long(h, j, 0);
3367             }
3368             s->current_picture_ptr->poc=
3369             s->current_picture_ptr->field_poc[0]=
3370             s->current_picture_ptr->field_poc[1]=
3371             h->poc_lsb=
3372             h->poc_msb=
3373             h->frame_num=
3374             s->current_picture_ptr->frame_num= 0;
3375             break;
3376         default: assert(0);
3377         }
3378     }
3379
3380     if (!current_ref_assigned) {
3381         /* Second field of complementary field pair; the first field of
3382          * which is already referenced. If short referenced, it
3383          * should be first entry in short_ref. If not, it must exist
3384          * in long_ref; trying to put it on the short list here is an
3385          * error in the encoded bit stream (ref: 7.4.3.3, NOTE 2 and 3).
3386          */
3387         if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {
3388             /* Just mark the second field valid */
3389             s->current_picture_ptr->reference = PICT_FRAME;
3390         } else if (s->current_picture_ptr->long_ref) {
3391             av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "
3392                                              "assignment for second field "
3393                                              "in complementary field pair "
3394                                              "(first field is long term)\n");
3395         } else {
3396             pic= remove_short(h, s->current_picture_ptr->frame_num, 0);
3397             if(pic){
3398                 av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
3399             }
3400
3401             if(h->short_ref_count)
3402                 memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
3403
3404             h->short_ref[0]= s->current_picture_ptr;
3405             h->short_ref_count++;
3406             s->current_picture_ptr->reference |= s->picture_structure;
3407         }
3408     }
3409
3410     if (h->long_ref_count + h->short_ref_count > h->sps.ref_frame_count){
3411
3412         /* We have too many reference frames, probably due to corrupted
3413          * stream. Need to discard one frame. Prevents overrun of the
3414          * short_ref and long_ref buffers.
3415          */
3416         av_log(h->s.avctx, AV_LOG_ERROR,
3417                "number of reference frames exceeds max (probably "
3418                "corrupt input), discarding one\n");
3419
3420         if (h->long_ref_count && !h->short_ref_count) {
3421             for (i = 0; i < 16; ++i)
3422                 if (h->long_ref[i])
3423                     break;
3424
3425             assert(i < 16);
3426             remove_long(h, i, 0);
3427         } else {