Merge remote-tracking branch 'qatar/master'
[ffmpeg.git] / libavcodec / h264.c
1 /*
2  * H.26L/H.264/AVC/JVT/14496-10/... 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
24  * H.264 / AVC / MPEG4 part10 codec.
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #define UNCHECKED_BITSTREAM_READER 1
29
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
32 #include "internal.h"
33 #include "cabac.h"
34 #include "cabac_functions.h"
35 #include "dsputil.h"
36 #include "avcodec.h"
37 #include "mpegvideo.h"
38 #include "h264.h"
39 #include "h264data.h"
40 #include "h264_mvpred.h"
41 #include "golomb.h"
42 #include "mathops.h"
43 #include "rectangle.h"
44 #include "thread.h"
45 #include "vdpau_internal.h"
46 #include "libavutil/avassert.h"
47
48 //#undef NDEBUG
49 #include <assert.h>
50
51 static const uint8_t rem6[QP_MAX_NUM+1]={
52 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, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
53 };
54
55 static const uint8_t div6[QP_MAX_NUM+1]={
56 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, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,
57 };
58
59 static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
60     PIX_FMT_DXVA2_VLD,
61     PIX_FMT_VAAPI_VLD,
62     PIX_FMT_VDA_VLD,
63     PIX_FMT_YUVJ420P,
64     PIX_FMT_NONE
65 };
66
67 /**
68  * Check if the top & left blocks are available if needed and
69  * change the dc mode so it only uses the available blocks.
70  */
71 int ff_h264_check_intra4x4_pred_mode(H264Context *h){
72     MpegEncContext * const s = &h->s;
73     static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
74     static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
75     int i;
76
77     if(!(h->top_samples_available&0x8000)){
78         for(i=0; i<4; i++){
79             int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
80             if(status<0){
81                 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);
82                 return -1;
83             } else if(status){
84                 h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
85             }
86         }
87     }
88
89     if((h->left_samples_available&0x8888)!=0x8888){
90         static const int mask[4]={0x8000,0x2000,0x80,0x20};
91         for(i=0; i<4; i++){
92             if(!(h->left_samples_available&mask[i])){
93                 int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
94                 if(status<0){
95                     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);
96                     return -1;
97                 } else if(status){
98                     h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
99                 }
100             }
101         }
102     }
103
104     return 0;
105 } //FIXME cleanup like check_intra_pred_mode
106
107 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma){
108     MpegEncContext * const s = &h->s;
109     static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
110     static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
111
112     if(mode > 6U) {
113         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);
114         return -1;
115     }
116
117     if(!(h->top_samples_available&0x8000)){
118         mode= top[ mode ];
119         if(mode<0){
120             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);
121             return -1;
122         }
123     }
124
125     if((h->left_samples_available&0x8080) != 0x8080){
126         mode= left[ mode ];
127         if(is_chroma && (h->left_samples_available&0x8080)){ //mad cow disease mode, aka MBAFF + constrained_intra_pred
128             mode= ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available&0x8000)) + 2*(mode == DC_128_PRED8x8);
129         }
130         if(mode<0){
131             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);
132             return -1;
133         }
134     }
135
136     return mode;
137 }
138
139
140 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
141     int i, si, di;
142     uint8_t *dst;
143     int bufidx;
144
145 //    src[0]&0x80;                //forbidden bit
146     h->nal_ref_idc= src[0]>>5;
147     h->nal_unit_type= src[0]&0x1F;
148
149     src++; length--;
150
151 #if HAVE_FAST_UNALIGNED
152 # if HAVE_FAST_64BIT
153 #   define RS 7
154     for(i=0; i+1<length; i+=9){
155         if(!((~AV_RN64A(src+i) & (AV_RN64A(src+i) - 0x0100010001000101ULL)) & 0x8000800080008080ULL))
156 # else
157 #   define RS 3
158     for(i=0; i+1<length; i+=5){
159         if(!((~AV_RN32A(src+i) & (AV_RN32A(src+i) - 0x01000101U)) & 0x80008080U))
160 # endif
161             continue;
162         if(i>0 && !src[i]) i--;
163         while(src[i]) i++;
164 #else
165 #   define RS 0
166     for(i=0; i+1<length; i+=2){
167         if(src[i]) continue;
168         if(i>0 && src[i-1]==0) i--;
169 #endif
170         if(i+2<length && src[i+1]==0 && src[i+2]<=3){
171             if(src[i+2]!=3){
172                 /* startcode, so we must be past the end */
173                 length=i;
174             }
175             break;
176         }
177         i-= RS;
178     }
179
180     bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
181     si=h->rbsp_buffer_size[bufidx];
182     av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+FF_INPUT_BUFFER_PADDING_SIZE+MAX_MBPAIR_SIZE);
183     dst= h->rbsp_buffer[bufidx];
184     if(si != h->rbsp_buffer_size[bufidx])
185         memset(dst + length, 0, FF_INPUT_BUFFER_PADDING_SIZE+MAX_MBPAIR_SIZE);
186
187     if (dst == NULL){
188         return NULL;
189     }
190
191     if(i>=length-1){ //no escaped 0
192         *dst_length= length;
193         *consumed= length+1; //+1 for the header
194         if(h->s.avctx->flags2 & CODEC_FLAG2_FAST){
195             return src;
196         }else{
197             memcpy(dst, src, length);
198             return dst;
199         }
200     }
201
202 //printf("decoding esc\n");
203     memcpy(dst, src, i);
204     si=di=i;
205     while(si+2<length){
206         //remove escapes (very rare 1:2^22)
207         if(src[si+2]>3){
208             dst[di++]= src[si++];
209             dst[di++]= src[si++];
210         }else if(src[si]==0 && src[si+1]==0){
211             if(src[si+2]==3){ //escape
212                 dst[di++]= 0;
213                 dst[di++]= 0;
214                 si+=3;
215                 continue;
216             }else //next start code
217                 goto nsc;
218         }
219
220         dst[di++]= src[si++];
221     }
222     while(si<length)
223         dst[di++]= src[si++];
224 nsc:
225
226     memset(dst+di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
227
228     *dst_length= di;
229     *consumed= si + 1;//+1 for the header
230 //FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
231     return dst;
232 }
233
234 /**
235  * Identify the exact end of the bitstream
236  * @return the length of the trailing, or 0 if damaged
237  */
238 static int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
239     int v= *src;
240     int r;
241
242     tprintf(h->s.avctx, "rbsp trailing %X\n", v);
243
244     for(r=1; r<9; r++){
245         if(v&1) return r;
246         v>>=1;
247     }
248     return 0;
249 }
250
251 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n, int height,
252                                  int y_offset, int list){
253     int raw_my= h->mv_cache[list][ scan8[n] ][1];
254     int filter_height= (raw_my&3) ? 2 : 0;
255     int full_my= (raw_my>>2) + y_offset;
256     int top = full_my - filter_height, bottom = full_my + height + filter_height;
257
258     return FFMAX(abs(top), bottom);
259 }
260
261 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n, int height,
262                                int y_offset, int list0, int list1, int *nrefs){
263     MpegEncContext * const s = &h->s;
264     int my;
265
266     y_offset += 16*(s->mb_y >> MB_FIELD);
267
268     if(list0){
269         int ref_n = h->ref_cache[0][ scan8[n] ];
270         Picture *ref= &h->ref_list[0][ref_n];
271
272         // Error resilience puts the current picture in the ref list.
273         // Don't try to wait on these as it will cause a deadlock.
274         // Fields can wait on each other, though.
275         if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
276            (ref->f.reference & 3) != s->picture_structure) {
277             my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
278             if (refs[0][ref_n] < 0) nrefs[0] += 1;
279             refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
280         }
281     }
282
283     if(list1){
284         int ref_n = h->ref_cache[1][ scan8[n] ];
285         Picture *ref= &h->ref_list[1][ref_n];
286
287         if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
288            (ref->f.reference & 3) != s->picture_structure) {
289             my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
290             if (refs[1][ref_n] < 0) nrefs[1] += 1;
291             refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
292         }
293     }
294 }
295
296 /**
297  * Wait until all reference frames are available for MC operations.
298  *
299  * @param h the H264 context
300  */
301 static void await_references(H264Context *h){
302     MpegEncContext * const s = &h->s;
303     const int mb_xy= h->mb_xy;
304     const int mb_type = s->current_picture.f.mb_type[mb_xy];
305     int refs[2][48];
306     int nrefs[2] = {0};
307     int ref, list;
308
309     memset(refs, -1, sizeof(refs));
310
311     if(IS_16X16(mb_type)){
312         get_lowest_part_y(h, refs, 0, 16, 0,
313                   IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
314     }else if(IS_16X8(mb_type)){
315         get_lowest_part_y(h, refs, 0, 8, 0,
316                   IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
317         get_lowest_part_y(h, refs, 8, 8, 8,
318                   IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
319     }else if(IS_8X16(mb_type)){
320         get_lowest_part_y(h, refs, 0, 16, 0,
321                   IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
322         get_lowest_part_y(h, refs, 4, 16, 0,
323                   IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
324     }else{
325         int i;
326
327         assert(IS_8X8(mb_type));
328
329         for(i=0; i<4; i++){
330             const int sub_mb_type= h->sub_mb_type[i];
331             const int n= 4*i;
332             int y_offset= (i&2)<<2;
333
334             if(IS_SUB_8X8(sub_mb_type)){
335                 get_lowest_part_y(h, refs, n  , 8, y_offset,
336                           IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
337             }else if(IS_SUB_8X4(sub_mb_type)){
338                 get_lowest_part_y(h, refs, n  , 4, y_offset,
339                           IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
340                 get_lowest_part_y(h, refs, n+2, 4, y_offset+4,
341                           IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
342             }else if(IS_SUB_4X8(sub_mb_type)){
343                 get_lowest_part_y(h, refs, n  , 8, y_offset,
344                           IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
345                 get_lowest_part_y(h, refs, n+1, 8, y_offset,
346                           IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
347             }else{
348                 int j;
349                 assert(IS_SUB_4X4(sub_mb_type));
350                 for(j=0; j<4; j++){
351                     int sub_y_offset= y_offset + 2*(j&2);
352                     get_lowest_part_y(h, refs, n+j, 4, sub_y_offset,
353                               IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
354                 }
355             }
356         }
357     }
358
359     for(list=h->list_count-1; list>=0; list--){
360         for(ref=0; ref<48 && nrefs[list]; ref++){
361             int row = refs[list][ref];
362             if(row >= 0){
363                 Picture *ref_pic = &h->ref_list[list][ref];
364                 int ref_field = ref_pic->f.reference - 1;
365                 int ref_field_picture = ref_pic->field_picture;
366                 int pic_height = 16*s->mb_height >> ref_field_picture;
367
368                 row <<= MB_MBAFF;
369                 nrefs[list]--;
370
371                 if(!FIELD_PICTURE && ref_field_picture){ // frame referencing two fields
372                     ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) - !(row&1), pic_height-1), 1);
373                     ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1)           , pic_height-1), 0);
374                 }else if(FIELD_PICTURE && !ref_field_picture){ // field referencing one field of a frame
375                     ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row*2 + ref_field    , pic_height-1), 0);
376                 }else if(FIELD_PICTURE){
377                     ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), ref_field);
378                 }else{
379                     ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), 0);
380                 }
381             }
382         }
383     }
384 }
385
386 #if 0
387 /**
388  * DCT transforms the 16 dc values.
389  * @param qp quantization parameter ??? FIXME
390  */
391 static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
392 //    const int qmul= dequant_coeff[qp][0];
393     int i;
394     int temp[16]; //FIXME check if this is a good idea
395     static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
396     static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
397
398     for(i=0; i<4; i++){
399         const int offset= y_offset[i];
400         const int z0= block[offset+stride*0] + block[offset+stride*4];
401         const int z1= block[offset+stride*0] - block[offset+stride*4];
402         const int z2= block[offset+stride*1] - block[offset+stride*5];
403         const int z3= block[offset+stride*1] + block[offset+stride*5];
404
405         temp[4*i+0]= z0+z3;
406         temp[4*i+1]= z1+z2;
407         temp[4*i+2]= z1-z2;
408         temp[4*i+3]= z0-z3;
409     }
410
411     for(i=0; i<4; i++){
412         const int offset= x_offset[i];
413         const int z0= temp[4*0+i] + temp[4*2+i];
414         const int z1= temp[4*0+i] - temp[4*2+i];
415         const int z2= temp[4*1+i] - temp[4*3+i];
416         const int z3= temp[4*1+i] + temp[4*3+i];
417
418         block[stride*0 +offset]= (z0 + z3)>>1;
419         block[stride*2 +offset]= (z1 + z2)>>1;
420         block[stride*8 +offset]= (z1 - z2)>>1;
421         block[stride*10+offset]= (z0 - z3)>>1;
422     }
423 }
424 #endif
425
426 #undef xStride
427 #undef stride
428
429 #if 0
430 static void chroma_dc_dct_c(DCTELEM *block){
431     const int stride= 16*2;
432     const int xStride= 16;
433     int a,b,c,d,e;
434
435     a= block[stride*0 + xStride*0];
436     b= block[stride*0 + xStride*1];
437     c= block[stride*1 + xStride*0];
438     d= block[stride*1 + xStride*1];
439
440     e= a-b;
441     a= a+b;
442     b= c-d;
443     c= c+d;
444
445     block[stride*0 + xStride*0]= (a+c);
446     block[stride*0 + xStride*1]= (e+b);
447     block[stride*1 + xStride*0]= (a-c);
448     block[stride*1 + xStride*1]= (e-b);
449 }
450 #endif
451
452 static av_always_inline void
453 mc_dir_part(H264Context *h, Picture *pic, int n, int square,
454             int height, int delta, int list,
455             uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
456             int src_x_offset, int src_y_offset,
457             qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op,
458             int pixel_shift, int chroma_idc)
459 {
460     MpegEncContext * const s = &h->s;
461     const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
462     int my=       h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
463     const int luma_xy= (mx&3) + ((my&3)<<2);
464     int offset = ((mx>>2) << pixel_shift) + (my>>2)*h->mb_linesize;
465     uint8_t * src_y = pic->f.data[0] + offset;
466     uint8_t * src_cb, * src_cr;
467     int extra_width= h->emu_edge_width;
468     int extra_height= h->emu_edge_height;
469     int emu=0;
470     const int full_mx= mx>>2;
471     const int full_my= my>>2;
472     const int pic_width  = 16*s->mb_width;
473     const int pic_height = 16*s->mb_height >> MB_FIELD;
474     int ysh;
475
476     if(mx&7) extra_width -= 3;
477     if(my&7) extra_height -= 3;
478
479     if(   full_mx < 0-extra_width
480        || full_my < 0-extra_height
481        || full_mx + 16/*FIXME*/ > pic_width + extra_width
482        || full_my + 16/*FIXME*/ > pic_height + extra_height){
483         s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_y - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
484                                 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
485             src_y= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
486         emu=1;
487     }
488
489     qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
490     if(!square){
491         qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
492     }
493
494     if(CONFIG_GRAY && s->flags&CODEC_FLAG_GRAY) return;
495
496     if(chroma_idc == 3 /* yuv444 */){
497         src_cb = pic->f.data[1] + offset;
498         if(emu){
499             s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
500                                     16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
501             src_cb= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
502         }
503         qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); //FIXME try variable height perhaps?
504         if(!square){
505             qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
506         }
507
508         src_cr = pic->f.data[2] + offset;
509         if(emu){
510             s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
511                                     16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
512             src_cr= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
513         }
514         qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); //FIXME try variable height perhaps?
515         if(!square){
516             qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
517         }
518         return;
519     }
520
521     ysh = 3 - (chroma_idc == 2 /* yuv422 */);
522     if(chroma_idc == 1 /* yuv420 */ && MB_FIELD){
523         // chroma offset when predicting from a field of opposite parity
524         my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
525         emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
526     }
527
528     src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) + (my >> ysh) * h->mb_uvlinesize;
529     src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) + (my >> ysh) * h->mb_uvlinesize;
530
531     if(emu){
532         s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
533                                 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
534                                 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
535             src_cb= s->edge_emu_buffer;
536     }
537     chroma_op(dest_cb, src_cb, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
538               mx&7, (my << (chroma_idc == 2 /* yuv422 */)) &7);
539
540     if(emu){
541         s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
542                                 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
543                                 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
544             src_cr= s->edge_emu_buffer;
545     }
546     chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
547               mx&7, (my << (chroma_idc == 2 /* yuv422 */)) &7);
548 }
549
550 static av_always_inline void
551 mc_part_std(H264Context *h, int n, int square, int height, int delta,
552             uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
553             int x_offset, int y_offset,
554             qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
555             qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
556             int list0, int list1, int pixel_shift, int chroma_idc)
557 {
558     MpegEncContext * const s = &h->s;
559     qpel_mc_func *qpix_op=  qpix_put;
560     h264_chroma_mc_func chroma_op= chroma_put;
561
562     dest_y  += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
563     if (chroma_idc == 3 /* yuv444 */) {
564         dest_cb += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
565         dest_cr += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
566     } else if (chroma_idc == 2 /* yuv422 */) {
567         dest_cb += (  x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
568         dest_cr += (  x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
569     } else /* yuv420 */ {
570         dest_cb += (  x_offset << pixel_shift) +   y_offset*h->mb_uvlinesize;
571         dest_cr += (  x_offset << pixel_shift) +   y_offset*h->mb_uvlinesize;
572     }
573     x_offset += 8*s->mb_x;
574     y_offset += 8*(s->mb_y >> MB_FIELD);
575
576     if(list0){
577         Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
578         mc_dir_part(h, ref, n, square, height, delta, 0,
579                            dest_y, dest_cb, dest_cr, x_offset, y_offset,
580                            qpix_op, chroma_op, pixel_shift, chroma_idc);
581
582         qpix_op=  qpix_avg;
583         chroma_op= chroma_avg;
584     }
585
586     if(list1){
587         Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
588         mc_dir_part(h, ref, n, square, height, delta, 1,
589                            dest_y, dest_cb, dest_cr, x_offset, y_offset,
590                            qpix_op, chroma_op, pixel_shift, chroma_idc);
591     }
592 }
593
594 static av_always_inline void
595 mc_part_weighted(H264Context *h, int n, int square, int height, int delta,
596                  uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
597                  int x_offset, int y_offset,
598                  qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
599                  h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
600                  h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
601                  int list0, int list1, int pixel_shift, int chroma_idc){
602     MpegEncContext * const s = &h->s;
603     int chroma_height;
604
605     dest_y += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
606     if (chroma_idc == 3 /* yuv444 */) {
607         chroma_height = height;
608         chroma_weight_avg = luma_weight_avg;
609         chroma_weight_op = luma_weight_op;
610         dest_cb += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
611         dest_cr += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
612     } else if (chroma_idc == 2 /* yuv422 */) {
613         chroma_height = height;
614         dest_cb += (  x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
615         dest_cr += (  x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
616     } else /* yuv420 */ {
617         chroma_height = height >> 1;
618         dest_cb += (  x_offset << pixel_shift) +   y_offset*h->mb_uvlinesize;
619         dest_cr += (  x_offset << pixel_shift) +   y_offset*h->mb_uvlinesize;
620     }
621     x_offset += 8*s->mb_x;
622     y_offset += 8*(s->mb_y >> MB_FIELD);
623
624     if(list0 && list1){
625         /* don't optimize for luma-only case, since B-frames usually
626          * use implicit weights => chroma too. */
627         uint8_t *tmp_cb = s->obmc_scratchpad;
628         uint8_t *tmp_cr = s->obmc_scratchpad + (16 << pixel_shift);
629         uint8_t *tmp_y  = s->obmc_scratchpad + 16*h->mb_uvlinesize;
630         int refn0 = h->ref_cache[0][ scan8[n] ];
631         int refn1 = h->ref_cache[1][ scan8[n] ];
632
633         mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
634                     dest_y, dest_cb, dest_cr,
635                     x_offset, y_offset, qpix_put, chroma_put,
636                     pixel_shift, chroma_idc);
637         mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
638                     tmp_y, tmp_cb, tmp_cr,
639                     x_offset, y_offset, qpix_put, chroma_put,
640                     pixel_shift, chroma_idc);
641
642         if(h->use_weight == 2){
643             int weight0 = h->implicit_weight[refn0][refn1][s->mb_y&1];
644             int weight1 = 64 - weight0;
645             luma_weight_avg(  dest_y,  tmp_y,  h->  mb_linesize,
646                               height,        5, weight0, weight1, 0);
647             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
648                               chroma_height, 5, weight0, weight1, 0);
649             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
650                               chroma_height, 5, weight0, weight1, 0);
651         }else{
652             luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height, h->luma_log2_weight_denom,
653                             h->luma_weight[refn0][0][0] , h->luma_weight[refn1][1][0],
654                             h->luma_weight[refn0][0][1] + h->luma_weight[refn1][1][1]);
655             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
656                             h->chroma_weight[refn0][0][0][0] , h->chroma_weight[refn1][1][0][0],
657                             h->chroma_weight[refn0][0][0][1] + h->chroma_weight[refn1][1][0][1]);
658             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
659                             h->chroma_weight[refn0][0][1][0] , h->chroma_weight[refn1][1][1][0],
660                             h->chroma_weight[refn0][0][1][1] + h->chroma_weight[refn1][1][1][1]);
661         }
662     }else{
663         int list = list1 ? 1 : 0;
664         int refn = h->ref_cache[list][ scan8[n] ];
665         Picture *ref= &h->ref_list[list][refn];
666         mc_dir_part(h, ref, n, square, height, delta, list,
667                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
668                     qpix_put, chroma_put, pixel_shift, chroma_idc);
669
670         luma_weight_op(dest_y, h->mb_linesize, height, h->luma_log2_weight_denom,
671                        h->luma_weight[refn][list][0], h->luma_weight[refn][list][1]);
672         if(h->use_weight_chroma){
673             chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
674                              h->chroma_weight[refn][list][0][0], h->chroma_weight[refn][list][0][1]);
675             chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
676                              h->chroma_weight[refn][list][1][0], h->chroma_weight[refn][list][1][1]);
677         }
678     }
679 }
680
681 static av_always_inline void
682 mc_part(H264Context *h, int n, int square, int height, int delta,
683         uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
684         int x_offset, int y_offset,
685         qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
686         qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
687         h264_weight_func *weight_op, h264_biweight_func *weight_avg,
688         int list0, int list1, int pixel_shift, int chroma_idc)
689 {
690     if((h->use_weight==2 && list0 && list1
691         && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ][h->s.mb_y&1] != 32))
692        || h->use_weight==1)
693         mc_part_weighted(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
694                          x_offset, y_offset, qpix_put, chroma_put,
695                          weight_op[0], weight_op[1], weight_avg[0],
696                          weight_avg[1], list0, list1, pixel_shift, chroma_idc);
697     else
698         mc_part_std(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
699                     x_offset, y_offset, qpix_put, chroma_put, qpix_avg,
700                     chroma_avg, list0, list1, pixel_shift, chroma_idc);
701 }
702
703 static av_always_inline void
704 prefetch_motion(H264Context *h, int list, int pixel_shift, int chroma_idc)
705 {
706     /* fetch pixels for estimated mv 4 macroblocks ahead
707      * optimized for 64byte cache lines */
708     MpegEncContext * const s = &h->s;
709     const int refn = h->ref_cache[list][scan8[0]];
710     if(refn >= 0){
711         const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
712         const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
713         uint8_t **src = h->ref_list[list][refn].f.data;
714         int off= (mx << pixel_shift) + (my + (s->mb_x&3)*4)*h->mb_linesize + (64 << pixel_shift);
715         s->dsp.prefetch(src[0]+off, s->linesize, 4);
716         if (chroma_idc == 3 /* yuv444 */) {
717             s->dsp.prefetch(src[1]+off, s->linesize, 4);
718             s->dsp.prefetch(src[2]+off, s->linesize, 4);
719         }else{
720             off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
721             s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
722         }
723     }
724 }
725
726 static av_always_inline void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
727                       qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
728                       qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
729                       h264_weight_func *weight_op, h264_biweight_func *weight_avg,
730                       int pixel_shift, int chroma_idc)
731 {
732     MpegEncContext * const s = &h->s;
733     const int mb_xy= h->mb_xy;
734     const int mb_type = s->current_picture.f.mb_type[mb_xy];
735
736     assert(IS_INTER(mb_type));
737
738     if(HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
739         await_references(h);
740     prefetch_motion(h, 0, pixel_shift, chroma_idc);
741
742     if(IS_16X16(mb_type)){
743         mc_part(h, 0, 1, 16, 0, dest_y, dest_cb, dest_cr, 0, 0,
744                 qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
745                 weight_op, weight_avg,
746                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
747                 pixel_shift, chroma_idc);
748     }else if(IS_16X8(mb_type)){
749         mc_part(h, 0, 0, 8, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 0,
750                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
751                 weight_op, weight_avg,
752                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
753                 pixel_shift, chroma_idc);
754         mc_part(h, 8, 0, 8, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 4,
755                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
756                 weight_op, weight_avg,
757                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
758                 pixel_shift, chroma_idc);
759     }else if(IS_8X16(mb_type)){
760         mc_part(h, 0, 0, 16, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
761                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
762                 &weight_op[1], &weight_avg[1],
763                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
764                 pixel_shift, chroma_idc);
765         mc_part(h, 4, 0, 16, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
766                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
767                 &weight_op[1], &weight_avg[1],
768                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
769                 pixel_shift, chroma_idc);
770     }else{
771         int i;
772
773         assert(IS_8X8(mb_type));
774
775         for(i=0; i<4; i++){
776             const int sub_mb_type= h->sub_mb_type[i];
777             const int n= 4*i;
778             int x_offset= (i&1)<<2;
779             int y_offset= (i&2)<<1;
780
781             if(IS_SUB_8X8(sub_mb_type)){
782                 mc_part(h, n, 1, 8, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
783                     qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
784                     &weight_op[1], &weight_avg[1],
785                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
786                     pixel_shift, chroma_idc);
787             }else if(IS_SUB_8X4(sub_mb_type)){
788                 mc_part(h, n  , 0, 4, 4 << pixel_shift, dest_y, dest_cb, dest_cr, x_offset, y_offset,
789                     qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
790                     &weight_op[1], &weight_avg[1],
791                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
792                     pixel_shift, chroma_idc);
793                 mc_part(h, n+2, 0, 4, 4 << pixel_shift, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
794                     qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
795                     &weight_op[1], &weight_avg[1],
796                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
797                     pixel_shift, chroma_idc);
798             }else if(IS_SUB_4X8(sub_mb_type)){
799                 mc_part(h, n  , 0, 8, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
800                     qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
801                     &weight_op[2], &weight_avg[2],
802                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
803                     pixel_shift, chroma_idc);
804                 mc_part(h, n+1, 0, 8, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
805                     qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
806                     &weight_op[2], &weight_avg[2],
807                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
808                     pixel_shift, chroma_idc);
809             }else{
810                 int j;
811                 assert(IS_SUB_4X4(sub_mb_type));
812                 for(j=0; j<4; j++){
813                     int sub_x_offset= x_offset + 2*(j&1);
814                     int sub_y_offset= y_offset +   (j&2);
815                     mc_part(h, n+j, 1, 4, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
816                         qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
817                         &weight_op[2], &weight_avg[2],
818                         IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
819                         pixel_shift, chroma_idc);
820                 }
821             }
822         }
823     }
824
825     prefetch_motion(h, 1, pixel_shift, chroma_idc);
826 }
827
828 static av_always_inline void
829 hl_motion_420(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
830               qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
831               qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
832               h264_weight_func *weight_op, h264_biweight_func *weight_avg,
833               int pixel_shift)
834 {
835     hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put,
836               qpix_avg, chroma_avg, weight_op, weight_avg, pixel_shift, 1);
837 }
838
839 static av_always_inline void
840 hl_motion_422(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
841               qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
842               qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
843               h264_weight_func *weight_op, h264_biweight_func *weight_avg,
844               int pixel_shift)
845 {
846     hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put,
847               qpix_avg, chroma_avg, weight_op, weight_avg, pixel_shift, 2);
848 }
849
850 static void free_tables(H264Context *h, int free_rbsp){
851     int i;
852     H264Context *hx;
853
854     av_freep(&h->intra4x4_pred_mode);
855     av_freep(&h->chroma_pred_mode_table);
856     av_freep(&h->cbp_table);
857     av_freep(&h->mvd_table[0]);
858     av_freep(&h->mvd_table[1]);
859     av_freep(&h->direct_table);
860     av_freep(&h->non_zero_count);
861     av_freep(&h->slice_table_base);
862     h->slice_table= NULL;
863     av_freep(&h->list_counts);
864
865     av_freep(&h->mb2b_xy);
866     av_freep(&h->mb2br_xy);
867
868     for(i = 0; i < MAX_THREADS; i++) {
869         hx = h->thread_context[i];
870         if(!hx) continue;
871         av_freep(&hx->top_borders[1]);
872         av_freep(&hx->top_borders[0]);
873         av_freep(&hx->s.obmc_scratchpad);
874         if (free_rbsp){
875             av_freep(&hx->rbsp_buffer[1]);
876             av_freep(&hx->rbsp_buffer[0]);
877             hx->rbsp_buffer_size[0] = 0;
878             hx->rbsp_buffer_size[1] = 0;
879         }
880         if (i) av_freep(&h->thread_context[i]);
881     }
882 }
883
884 static void init_dequant8_coeff_table(H264Context *h){
885     int i,j,q,x;
886     const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
887
888     for(i=0; i<6; i++ ){
889         h->dequant8_coeff[i] = h->dequant8_buffer[i];
890         for(j=0; j<i; j++){
891             if(!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i], 64*sizeof(uint8_t))){
892                 h->dequant8_coeff[i] = h->dequant8_buffer[j];
893                 break;
894             }
895         }
896         if(j<i)
897             continue;
898
899         for(q=0; q<max_qp+1; q++){
900             int shift = div6[q];
901             int idx = rem6[q];
902             for(x=0; x<64; x++)
903                 h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
904                     ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
905                     h->pps.scaling_matrix8[i][x]) << shift;
906         }
907     }
908 }
909
910 static void init_dequant4_coeff_table(H264Context *h){
911     int i,j,q,x;
912     const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
913     for(i=0; i<6; i++ ){
914         h->dequant4_coeff[i] = h->dequant4_buffer[i];
915         for(j=0; j<i; j++){
916             if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
917                 h->dequant4_coeff[i] = h->dequant4_buffer[j];
918                 break;
919             }
920         }
921         if(j<i)
922             continue;
923
924         for(q=0; q<max_qp+1; q++){
925             int shift = div6[q] + 2;
926             int idx = rem6[q];
927             for(x=0; x<16; x++)
928                 h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
929                     ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
930                     h->pps.scaling_matrix4[i][x]) << shift;
931         }
932     }
933 }
934
935 static void init_dequant_tables(H264Context *h){
936     int i,x;
937     init_dequant4_coeff_table(h);
938     if(h->pps.transform_8x8_mode)
939         init_dequant8_coeff_table(h);
940     if(h->sps.transform_bypass){
941         for(i=0; i<6; i++)
942             for(x=0; x<16; x++)
943                 h->dequant4_coeff[i][0][x] = 1<<6;
944         if(h->pps.transform_8x8_mode)
945             for(i=0; i<6; i++)
946                 for(x=0; x<64; x++)
947                     h->dequant8_coeff[i][0][x] = 1<<6;
948     }
949 }
950
951
952 int ff_h264_alloc_tables(H264Context *h){
953     MpegEncContext * const s = &h->s;
954     const int big_mb_num= s->mb_stride * (s->mb_height+1);
955     const int row_mb_num= 2*s->mb_stride*FFMAX(s->avctx->thread_count, 1);
956     int x,y;
957
958     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode, row_mb_num * 8  * sizeof(uint8_t), fail)
959
960     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count    , big_mb_num * 48 * sizeof(uint8_t), fail)
961     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
962     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
963
964     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
965     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
966     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
967     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
968     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
969
970     memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(*h->slice_table_base));
971     h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
972
973     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy  , big_mb_num * sizeof(uint32_t), fail);
974     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy , big_mb_num * sizeof(uint32_t), fail);
975     for(y=0; y<s->mb_height; y++){
976         for(x=0; x<s->mb_width; x++){
977             const int mb_xy= x + y*s->mb_stride;
978             const int b_xy = 4*x + 4*y*h->b_stride;
979
980             h->mb2b_xy [mb_xy]= b_xy;
981             h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
982         }
983     }
984
985     s->obmc_scratchpad = NULL;
986
987     if(!h->dequant4_coeff[0])
988         init_dequant_tables(h);
989
990     return 0;
991 fail:
992     free_tables(h, 1);
993     return -1;
994 }
995
996 /**
997  * Mimic alloc_tables(), but for every context thread.
998  */
999 static void clone_tables(H264Context *dst, H264Context *src, int i){
1000     MpegEncContext * const s = &src->s;
1001     dst->intra4x4_pred_mode       = src->intra4x4_pred_mode + i*8*2*s->mb_stride;
1002     dst->non_zero_count           = src->non_zero_count;
1003     dst->slice_table              = src->slice_table;
1004     dst->cbp_table                = src->cbp_table;
1005     dst->mb2b_xy                  = src->mb2b_xy;
1006     dst->mb2br_xy                 = src->mb2br_xy;
1007     dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;
1008     dst->mvd_table[0]             = src->mvd_table[0] + i*8*2*s->mb_stride;
1009     dst->mvd_table[1]             = src->mvd_table[1] + i*8*2*s->mb_stride;
1010     dst->direct_table             = src->direct_table;
1011     dst->list_counts              = src->list_counts;
1012
1013     dst->s.obmc_scratchpad = NULL;
1014     ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma, src->sps.chroma_format_idc);
1015 }
1016
1017 /**
1018  * Init context
1019  * Allocate buffers which are not shared amongst multiple threads.
1020  */
1021 static int context_init(H264Context *h){
1022     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * 16*3 * sizeof(uint8_t)*2, fail)
1023     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * 16*3 * sizeof(uint8_t)*2, fail)
1024
1025     h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
1026     h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
1027
1028     return 0;
1029 fail:
1030     return -1; // free_tables will clean up for us
1031 }
1032
1033 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
1034
1035 static av_cold void common_init(H264Context *h){
1036     MpegEncContext * const s = &h->s;
1037
1038     s->width = s->avctx->width;
1039     s->height = s->avctx->height;
1040     s->codec_id= s->avctx->codec->id;
1041
1042     s->avctx->bits_per_raw_sample = 8;
1043     h->cur_chroma_format_idc = 1;
1044
1045     ff_h264dsp_init(&h->h264dsp,
1046                     s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
1047     ff_h264_pred_init(&h->hpc, s->codec_id,
1048                       s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
1049
1050     h->dequant_coeff_pps= -1;
1051     s->unrestricted_mv=1;
1052
1053     s->dsp.dct_bits = 16;
1054     ff_dsputil_init(&s->dsp, s->avctx); // needed so that idct permutation is known early
1055
1056     memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
1057     memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
1058 }
1059
1060 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1061 {
1062     AVCodecContext *avctx = h->s.avctx;
1063
1064     if(!buf || size <= 0)
1065         return -1;
1066
1067     if(buf[0] == 1){
1068         int i, cnt, nalsize;
1069         const unsigned char *p = buf;
1070
1071         h->is_avc = 1;
1072
1073         if(size < 7) {
1074             av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1075             return -1;
1076         }
1077         /* sps and pps in the avcC always have length coded with 2 bytes,
1078            so put a fake nal_length_size = 2 while parsing them */
1079         h->nal_length_size = 2;
1080         // Decode sps from avcC
1081         cnt = *(p+5) & 0x1f; // Number of sps
1082         p += 6;
1083         for (i = 0; i < cnt; i++) {
1084             nalsize = AV_RB16(p) + 2;
1085             if(nalsize > size - (p-buf))
1086                 return -1;
1087             if(decode_nal_units(h, p, nalsize) < 0) {
1088                 av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
1089                 return -1;
1090             }
1091             p += nalsize;
1092         }
1093         // Decode pps from avcC
1094         cnt = *(p++); // Number of pps
1095         for (i = 0; i < cnt; i++) {
1096             nalsize = AV_RB16(p) + 2;
1097             if(nalsize > size - (p-buf))
1098                 return -1;
1099             if (decode_nal_units(h, p, nalsize) < 0) {
1100                 av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
1101                 return -1;
1102             }
1103             p += nalsize;
1104         }
1105         // Now store right nal length size, that will be use to parse all other nals
1106         h->nal_length_size = (buf[4] & 0x03) + 1;
1107     } else {
1108         h->is_avc = 0;
1109         if(decode_nal_units(h, buf, size) < 0)
1110             return -1;
1111     }
1112     return size;
1113 }
1114
1115 av_cold int ff_h264_decode_init(AVCodecContext *avctx){
1116     H264Context *h= avctx->priv_data;
1117     MpegEncContext * const s = &h->s;
1118     int i;
1119
1120     ff_MPV_decode_defaults(s);
1121
1122     s->avctx = avctx;
1123     common_init(h);
1124
1125     s->out_format = FMT_H264;
1126     s->workaround_bugs= avctx->workaround_bugs;
1127
1128     // set defaults
1129 //    s->decode_mb= ff_h263_decode_mb;
1130     s->quarter_sample = 1;
1131     if(!avctx->has_b_frames)
1132     s->low_delay= 1;
1133
1134     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1135
1136     ff_h264_decode_init_vlc();
1137
1138     h->pixel_shift = 0;
1139     h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1140
1141     h->thread_context[0] = h;
1142     h->outputed_poc = h->next_outputed_poc = INT_MIN;
1143     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1144         h->last_pocs[i] = INT_MIN;
1145     h->prev_poc_msb= 1<<16;
1146     h->prev_frame_num= -1;
1147     h->x264_build = -1;
1148     ff_h264_reset_sei(h);
1149     if(avctx->codec_id == CODEC_ID_H264){
1150         if(avctx->ticks_per_frame == 1){
1151             s->avctx->time_base.den *=2;
1152         }
1153         avctx->ticks_per_frame = 2;
1154     }
1155
1156     if(avctx->extradata_size > 0 && avctx->extradata &&
1157         ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size)<0)
1158         return -1;
1159
1160     if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1161         s->avctx->has_b_frames = h->sps.num_reorder_frames;
1162         s->low_delay = 0;
1163     }
1164
1165     return 0;
1166 }
1167
1168 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b)+(size))))
1169 static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
1170 {
1171     int i;
1172
1173     for (i=0; i<count; i++){
1174         assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1175                 IN_RANGE(from[i], old_base->picture, sizeof(Picture) * old_base->picture_count) ||
1176                 !from[i]));
1177         to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1178     }
1179 }
1180
1181 static void copy_parameter_set(void **to, void **from, int count, int size)
1182 {
1183     int i;
1184
1185     for (i=0; i<count; i++){
1186         if (to[i] && !from[i]) av_freep(&to[i]);
1187         else if (from[i] && !to[i]) to[i] = av_malloc(size);
1188
1189         if (from[i]) memcpy(to[i], from[i], size);
1190     }
1191 }
1192
1193 static int decode_init_thread_copy(AVCodecContext *avctx){
1194     H264Context *h= avctx->priv_data;
1195
1196     if (!avctx->internal->is_copy)
1197         return 0;
1198     memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1199     memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1200
1201     return 0;
1202 }
1203
1204 #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
1205 static int decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src){
1206     H264Context *h= dst->priv_data, *h1= src->priv_data;
1207     MpegEncContext * const s = &h->s, * const s1 = &h1->s;
1208     int inited = s->context_initialized, err;
1209     int i;
1210
1211     if(dst == src) return 0;
1212
1213     err = ff_mpeg_update_thread_context(dst, src);
1214     if(err) return err;
1215
1216     //FIXME handle width/height changing
1217     if(!inited){
1218         for(i = 0; i < MAX_SPS_COUNT; i++)
1219             av_freep(h->sps_buffers + i);
1220
1221         for(i = 0; i < MAX_PPS_COUNT; i++)
1222             av_freep(h->pps_buffers + i);
1223
1224         memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
1225         memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1226         memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1227
1228         if (s1->context_initialized) {
1229         if (ff_h264_alloc_tables(h) < 0) {
1230             av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1231             return AVERROR(ENOMEM);
1232         }
1233         context_init(h);
1234
1235         // frame_start may not be called for the next thread (if it's decoding a bottom field)
1236         // so this has to be allocated here
1237         h->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
1238         }
1239
1240         for(i=0; i<2; i++){
1241             h->rbsp_buffer[i] = NULL;
1242             h->rbsp_buffer_size[i] = 0;
1243         }
1244
1245         h->thread_context[0] = h;
1246
1247         s->dsp.clear_blocks(h->mb);
1248         s->dsp.clear_blocks(h->mb+(24*16<<h->pixel_shift));
1249     }
1250
1251     //extradata/NAL handling
1252     h->is_avc          = h1->is_avc;
1253
1254     //SPS/PPS
1255     copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
1256     h->sps             = h1->sps;
1257     copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
1258     h->pps             = h1->pps;
1259
1260     //Dequantization matrices
1261     //FIXME these are big - can they be only copied when PPS changes?
1262     copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1263
1264     for(i=0; i<6; i++)
1265         h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1266
1267     for(i=0; i<6; i++)
1268         h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1269
1270     h->dequant_coeff_pps = h1->dequant_coeff_pps;
1271
1272     //POC timing
1273     copy_fields(h, h1, poc_lsb, redundant_pic_count);
1274
1275     //reference lists
1276     copy_fields(h, h1, ref_count, list_count);
1277     copy_fields(h, h1, ref_list,  intra_gb);
1278     copy_fields(h, h1, short_ref, cabac_init_idc);
1279
1280     copy_picture_range(h->short_ref,   h1->short_ref,   32, s, s1);
1281     copy_picture_range(h->long_ref,    h1->long_ref,    32, s, s1);
1282     copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
1283
1284     h->last_slice_type = h1->last_slice_type;
1285     h->sync            = h1->sync;
1286
1287     if(!s->current_picture_ptr) return 0;
1288
1289     if(!s->dropable) {
1290         err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1291         h->prev_poc_msb     = h->poc_msb;
1292         h->prev_poc_lsb     = h->poc_lsb;
1293     }
1294     h->prev_frame_num_offset= h->frame_num_offset;
1295     h->prev_frame_num       = h->frame_num;
1296     h->outputed_poc         = h->next_outputed_poc;
1297
1298     return err;
1299 }
1300
1301 int ff_h264_frame_start(H264Context *h){
1302     MpegEncContext * const s = &h->s;
1303     int i;
1304     const int pixel_shift = h->pixel_shift;
1305
1306     if(ff_MPV_frame_start(s, s->avctx) < 0)
1307         return -1;
1308     ff_er_frame_start(s);
1309     /*
1310      * ff_MPV_frame_start uses pict_type to derive key_frame.
1311      * This is incorrect for H.264; IDR markings must be used.
1312      * Zero here; IDR markings per slice in frame or fields are ORed in later.
1313      * See decode_nal_units().
1314      */
1315     s->current_picture_ptr->f.key_frame = 0;
1316     s->current_picture_ptr->sync = 0;
1317     s->current_picture_ptr->mmco_reset= 0;
1318
1319     assert(s->linesize && s->uvlinesize);
1320
1321     for(i=0; i<16; i++){
1322         h->block_offset[i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
1323         h->block_offset[48+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
1324     }
1325     for(i=0; i<16; i++){
1326         h->block_offset[16+i]=
1327         h->block_offset[32+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1328         h->block_offset[48+16+i]=
1329         h->block_offset[48+32+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1330     }
1331
1332     /* can't be in alloc_tables because linesize isn't known there.
1333      * FIXME: redo bipred weight to not require extra buffer? */
1334     for(i = 0; i < s->slice_context_count; i++)
1335         if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
1336             h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
1337
1338     /* some macroblocks can be accessed before they're available in case of lost slices, mbaff or threading*/
1339     memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(*h->slice_table));
1340
1341 //    s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.f.reference /*|| h->contains_intra*/ || 1;
1342
1343     // We mark the current picture as non-reference after allocating it, so
1344     // that if we break out due to an error it can be released automatically
1345     // in the next ff_MPV_frame_start().
1346     // SVQ3 as well as most other codecs have only last/next/current and thus
1347     // get released even with set reference, besides SVQ3 and others do not
1348     // mark frames as reference later "naturally".
1349     if(s->codec_id != CODEC_ID_SVQ3)
1350         s->current_picture_ptr->f.reference = 0;
1351
1352     s->current_picture_ptr->field_poc[0]=
1353     s->current_picture_ptr->field_poc[1]= INT_MAX;
1354
1355     h->next_output_pic = NULL;
1356
1357     assert(s->current_picture_ptr->long_ref==0);
1358
1359     return 0;
1360 }
1361
1362 /**
1363   * Run setup operations that must be run after slice header decoding.
1364   * This includes finding the next displayed frame.
1365   *
1366   * @param h h264 master context
1367   * @param setup_finished enough NALs have been read that we can call
1368   * ff_thread_finish_setup()
1369   */
1370 static void decode_postinit(H264Context *h, int setup_finished){
1371     MpegEncContext * const s = &h->s;
1372     Picture *out = s->current_picture_ptr;
1373     Picture *cur = s->current_picture_ptr;
1374     int i, pics, out_of_order, out_idx;
1375
1376     s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1377     s->current_picture_ptr->f.pict_type   = s->pict_type;
1378
1379     if (h->next_output_pic) return;
1380
1381     if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
1382         //FIXME: if we have two PAFF fields in one packet, we can't start the next thread here.
1383         //If we have one field per packet, we can. The check in decode_nal_units() is not good enough
1384         //to find this yet, so we assume the worst for now.
1385         //if (setup_finished)
1386         //    ff_thread_finish_setup(s->avctx);
1387         return;
1388     }
1389
1390     cur->f.interlaced_frame = 0;
1391     cur->f.repeat_pict      = 0;
1392
1393     /* Signal interlacing information externally. */
1394     /* Prioritize picture timing SEI information over used decoding process if it exists. */
1395
1396     if(h->sps.pic_struct_present_flag){
1397         switch (h->sei_pic_struct)
1398         {
1399         case SEI_PIC_STRUCT_FRAME:
1400             break;
1401         case SEI_PIC_STRUCT_TOP_FIELD:
1402         case SEI_PIC_STRUCT_BOTTOM_FIELD:
1403             cur->f.interlaced_frame = 1;
1404             break;
1405         case SEI_PIC_STRUCT_TOP_BOTTOM:
1406         case SEI_PIC_STRUCT_BOTTOM_TOP:
1407             if (FIELD_OR_MBAFF_PICTURE)
1408                 cur->f.interlaced_frame = 1;
1409             else
1410                 // try to flag soft telecine progressive
1411                 cur->f.interlaced_frame = h->prev_interlaced_frame;
1412             break;
1413         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1414         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1415             // Signal the possibility of telecined film externally (pic_struct 5,6)
1416             // From these hints, let the applications decide if they apply deinterlacing.
1417             cur->f.repeat_pict = 1;
1418             break;
1419         case SEI_PIC_STRUCT_FRAME_DOUBLING:
1420             // Force progressive here, as doubling interlaced frame is a bad idea.
1421             cur->f.repeat_pict = 2;
1422             break;
1423         case SEI_PIC_STRUCT_FRAME_TRIPLING:
1424             cur->f.repeat_pict = 4;
1425             break;
1426         }
1427
1428         if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1429             cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1430     }else{
1431         /* Derive interlacing flag from used decoding process. */
1432         cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1433     }
1434     h->prev_interlaced_frame = cur->f.interlaced_frame;
1435
1436     if (cur->field_poc[0] != cur->field_poc[1]){
1437         /* Derive top_field_first from field pocs. */
1438         cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1439     }else{
1440         if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1441             /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
1442             if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
1443               || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1444                 cur->f.top_field_first = 1;
1445             else
1446                 cur->f.top_field_first = 0;
1447         }else{
1448             /* Most likely progressive */
1449             cur->f.top_field_first = 0;
1450         }
1451     }
1452
1453     cur->mmco_reset = h->mmco_reset;
1454     h->mmco_reset = 0;
1455     //FIXME do something with unavailable reference frames
1456
1457     /* Sort B-frames into display order */
1458
1459     if(h->sps.bitstream_restriction_flag
1460        && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1461         s->avctx->has_b_frames = h->sps.num_reorder_frames;
1462         s->low_delay = 0;
1463     }
1464
1465     if(   s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
1466        && !h->sps.bitstream_restriction_flag){
1467         s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1468         s->low_delay= 0;
1469     }
1470
1471     for (i = 0; 1; i++) {
1472         if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
1473             if(i)
1474                 h->last_pocs[i-1] = cur->poc;
1475             break;
1476         } else if(i) {
1477             h->last_pocs[i-1]= h->last_pocs[i];
1478         }
1479     }
1480     out_of_order = MAX_DELAYED_PIC_COUNT - i;
1481     if(   cur->f.pict_type == AV_PICTURE_TYPE_B
1482        || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
1483         out_of_order = FFMAX(out_of_order, 1);
1484     if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
1485         av_log(s->avctx, AV_LOG_WARNING, "Increasing reorder buffer to %d\n", out_of_order);
1486         s->avctx->has_b_frames = out_of_order;
1487         s->low_delay = 0;
1488     }
1489
1490     pics = 0;
1491     while(h->delayed_pic[pics]) pics++;
1492
1493     av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
1494
1495     h->delayed_pic[pics++] = cur;
1496     if (cur->f.reference == 0)
1497         cur->f.reference = DELAYED_PIC_REF;
1498
1499     out = h->delayed_pic[0];
1500     out_idx = 0;
1501     for (i = 1; h->delayed_pic[i] && !h->delayed_pic[i]->f.key_frame && !h->delayed_pic[i]->mmco_reset; i++)
1502         if(h->delayed_pic[i]->poc < out->poc){
1503             out = h->delayed_pic[i];
1504             out_idx = i;
1505         }
1506     if (s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
1507         h->next_outputed_poc= INT_MIN;
1508     out_of_order = out->poc < h->next_outputed_poc;
1509
1510     if(out_of_order || pics > s->avctx->has_b_frames){
1511         out->f.reference &= ~DELAYED_PIC_REF;
1512         out->owner2 = s; // for frame threading, the owner must be the second field's thread
1513                          // or else the first thread can release the picture and reuse it unsafely
1514         for(i=out_idx; h->delayed_pic[i]; i++)
1515             h->delayed_pic[i] = h->delayed_pic[i+1];
1516     }
1517     if(!out_of_order && pics > s->avctx->has_b_frames){
1518         h->next_output_pic = out;
1519         if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
1520             h->next_outputed_poc = INT_MIN;
1521         } else
1522             h->next_outputed_poc = out->poc;
1523     }else{
1524         av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
1525     }
1526
1527     if (h->next_output_pic && h->next_output_pic->sync) {
1528         h->sync |= 2;
1529     }
1530
1531     if (setup_finished)
1532         ff_thread_finish_setup(s->avctx);
1533 }
1534
1535 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1536                                               uint8_t *src_cb, uint8_t *src_cr,
1537                                               int linesize, int uvlinesize, int simple)
1538 {
1539     MpegEncContext * const s = &h->s;
1540     uint8_t *top_border;
1541     int top_idx = 1;
1542     const int pixel_shift = h->pixel_shift;
1543     int chroma444 = CHROMA444;
1544     int chroma422 = CHROMA422;
1545
1546     src_y  -=   linesize;
1547     src_cb -= uvlinesize;
1548     src_cr -= uvlinesize;
1549
1550     if(!simple && FRAME_MBAFF){
1551         if(s->mb_y&1){
1552             if(!MB_MBAFF){
1553                 top_border = h->top_borders[0][s->mb_x];
1554                 AV_COPY128(top_border, src_y + 15*linesize);
1555                 if (pixel_shift)
1556                     AV_COPY128(top_border+16, src_y+15*linesize+16);
1557                 if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1558                     if(chroma444){
1559                         if (pixel_shift){
1560                             AV_COPY128(top_border+32, src_cb + 15*uvlinesize);
1561                             AV_COPY128(top_border+48, src_cb + 15*uvlinesize+16);
1562                             AV_COPY128(top_border+64, src_cr + 15*uvlinesize);
1563                             AV_COPY128(top_border+80, src_cr + 15*uvlinesize+16);
1564                         } else {
1565                             AV_COPY128(top_border+16, src_cb + 15*uvlinesize);
1566                             AV_COPY128(top_border+32, src_cr + 15*uvlinesize);
1567                         }
1568                     } else if(chroma422){
1569                         if (pixel_shift) {
1570                             AV_COPY128(top_border+32, src_cb + 15*uvlinesize);
1571                             AV_COPY128(top_border+48, src_cr + 15*uvlinesize);
1572                         } else {
1573                             AV_COPY64(top_border+16, src_cb +  15*uvlinesize);
1574                             AV_COPY64(top_border+24, src_cr +  15*uvlinesize);
1575                         }
1576                     } else {
1577                         if (pixel_shift) {
1578                             AV_COPY128(top_border+32, src_cb+7*uvlinesize);
1579                             AV_COPY128(top_border+48, src_cr+7*uvlinesize);
1580                         } else {
1581                             AV_COPY64(top_border+16, src_cb+7*uvlinesize);
1582                             AV_COPY64(top_border+24, src_cr+7*uvlinesize);
1583                         }
1584                     }
1585                 }
1586             }
1587         }else if(MB_MBAFF){
1588             top_idx = 0;
1589         }else
1590             return;
1591     }
1592
1593     top_border = h->top_borders[top_idx][s->mb_x];
1594     // There are two lines saved, the line above the the top macroblock of a pair,
1595     // and the line above the bottom macroblock
1596     AV_COPY128(top_border, src_y + 16*linesize);
1597     if (pixel_shift)
1598         AV_COPY128(top_border+16, src_y+16*linesize+16);
1599
1600     if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1601         if(chroma444){
1602             if (pixel_shift){
1603                 AV_COPY128(top_border+32, src_cb + 16*linesize);
1604                 AV_COPY128(top_border+48, src_cb + 16*linesize+16);
1605                 AV_COPY128(top_border+64, src_cr + 16*linesize);
1606                 AV_COPY128(top_border+80, src_cr + 16*linesize+16);
1607             } else {
1608                 AV_COPY128(top_border+16, src_cb + 16*linesize);
1609                 AV_COPY128(top_border+32, src_cr + 16*linesize);
1610             }
1611         } else if(chroma422) {
1612             if (pixel_shift) {
1613                 AV_COPY128(top_border+32, src_cb+16*uvlinesize);
1614                 AV_COPY128(top_border+48, src_cr+16*uvlinesize);
1615             } else {
1616                 AV_COPY64(top_border+16, src_cb+16*uvlinesize);
1617                 AV_COPY64(top_border+24, src_cr+16*uvlinesize);
1618             }
1619         } else {
1620             if (pixel_shift) {
1621                 AV_COPY128(top_border+32, src_cb+8*uvlinesize);
1622                 AV_COPY128(top_border+48, src_cr+8*uvlinesize);
1623             } else {
1624                 AV_COPY64(top_border+16, src_cb+8*uvlinesize);
1625                 AV_COPY64(top_border+24, src_cr+8*uvlinesize);
1626             }
1627         }
1628     }
1629 }
1630
1631 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1632                                   uint8_t *src_cb, uint8_t *src_cr,
1633                                   int linesize, int uvlinesize,
1634                                   int xchg, int chroma444,
1635                                   int simple, int pixel_shift){
1636     MpegEncContext * const s = &h->s;
1637     int deblock_topleft;
1638     int deblock_top;
1639     int top_idx = 1;
1640     uint8_t *top_border_m1;
1641     uint8_t *top_border;
1642
1643     if(!simple && FRAME_MBAFF){
1644         if(s->mb_y&1){
1645             if(!MB_MBAFF)
1646                 return;
1647         }else{
1648             top_idx = MB_MBAFF ? 0 : 1;
1649         }
1650     }
1651
1652     if(h->deblocking_filter == 2) {
1653         deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1654         deblock_top     = h->top_type;
1655     } else {
1656         deblock_topleft = (s->mb_x > 0);
1657         deblock_top     = (s->mb_y > !!MB_FIELD);
1658     }
1659
1660     src_y  -=   linesize + 1 + pixel_shift;
1661     src_cb -= uvlinesize + 1 + pixel_shift;
1662     src_cr -= uvlinesize + 1 + pixel_shift;
1663
1664     top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1665     top_border    = h->top_borders[top_idx][s->mb_x];
1666
1667 #define XCHG(a,b,xchg)\
1668     if (pixel_shift) {\
1669         if (xchg) {\
1670             AV_SWAP64(b+0,a+0);\
1671             AV_SWAP64(b+8,a+8);\
1672         } else {\
1673             AV_COPY128(b,a); \
1674         }\
1675     } else \
1676 if (xchg) AV_SWAP64(b,a);\
1677 else      AV_COPY64(b,a);
1678
1679     if(deblock_top){
1680         if(deblock_topleft){
1681             XCHG(top_border_m1 + (8 << pixel_shift), src_y - (7 << pixel_shift), 1);
1682         }
1683         XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1684         XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1685         if(s->mb_x+1 < s->mb_width){
1686             XCHG(h->top_borders[top_idx][s->mb_x+1], src_y + (17 << pixel_shift), 1);
1687         }
1688     }
1689     if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1690         if(chroma444){
1691             if(deblock_topleft){
1692                 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1693                 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1694             }
1695             XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1696             XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1697             XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1698             XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1699             if(s->mb_x+1 < s->mb_width){
1700                 XCHG(h->top_borders[top_idx][s->mb_x+1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1701                 XCHG(h->top_borders[top_idx][s->mb_x+1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1702             }
1703         } else {
1704             if(deblock_top){
1705                 if(deblock_topleft){
1706                     XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1707                     XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1708                 }
1709                 XCHG(top_border + (16 << pixel_shift), src_cb+1+pixel_shift, 1);
1710                 XCHG(top_border + (24 << pixel_shift), src_cr+1+pixel_shift, 1);
1711             }
1712         }
1713     }
1714 }
1715
1716 static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth, int index) {
1717     if (high_bit_depth) {
1718         return AV_RN32A(((int32_t*)mb) + index);
1719     } else
1720         return AV_RN16A(mb + index);
1721 }
1722
1723 static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth, int index, int value) {
1724     if (high_bit_depth) {
1725         AV_WN32A(((int32_t*)mb) + index, value);
1726     } else
1727         AV_WN16A(mb + index, value);
1728 }
1729
1730 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,
1731                                                        int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)
1732 {
1733     MpegEncContext * const s = &h->s;
1734     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1735     void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1736     int i;
1737     int qscale = p == 0 ? s->qscale : h->chroma_qp[p-1];
1738     block_offset += 16*p;
1739     if(IS_INTRA4x4(mb_type)){
1740         if(simple || !s->encoding){
1741             if(IS_8x8DCT(mb_type)){
1742                 if(transform_bypass){
1743                     idct_dc_add =
1744                     idct_add    = s->dsp.add_pixels8;
1745                 }else{
1746                     idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1747                     idct_add    = h->h264dsp.h264_idct8_add;
1748                 }
1749                 for(i=0; i<16; i+=4){
1750                     uint8_t * const ptr= dest_y + block_offset[i];
1751                     const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1752                     if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1753                         h->hpc.pred8x8l_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1754                     }else{
1755                         const int nnz = h->non_zero_count_cache[ scan8[i+p*16] ];
1756                         h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
1757                                                     (h->topright_samples_available<<i)&0x4000, linesize);
1758                         if(nnz){
1759                             if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))
1760                                 idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1761                             else
1762                                 idct_add   (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1763                         }
1764                     }
1765                 }
1766             }else{
1767                 if(transform_bypass){
1768                     idct_dc_add =
1769                     idct_add    = s->dsp.add_pixels4;
1770                 }else{
1771                     idct_dc_add = h->h264dsp.h264_idct_dc_add;
1772                     idct_add    = h->h264dsp.h264_idct_add;
1773                 }
1774                 for(i=0; i<16; i++){
1775                     uint8_t * const ptr= dest_y + block_offset[i];
1776                     const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1777
1778                     if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1779                         h->hpc.pred4x4_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1780                     }else{
1781                         uint8_t *topright;
1782                         int nnz, tr;
1783                         uint64_t tr_high;
1784                         if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
1785                             const int topright_avail= (h->topright_samples_available<<i)&0x8000;
1786                             assert(s->mb_y || linesize <= block_offset[i]);
1787                             if(!topright_avail){
1788                                 if (pixel_shift) {
1789                                     tr_high= ((uint16_t*)ptr)[3 - linesize/2]*0x0001000100010001ULL;
1790                                     topright= (uint8_t*) &tr_high;
1791                                 } else {
1792                                     tr= ptr[3 - linesize]*0x01010101u;
1793                                     topright= (uint8_t*) &tr;
1794                                 }
1795                             }else
1796                                 topright= ptr + (4 << pixel_shift) - linesize;
1797                         }else
1798                             topright= NULL;
1799
1800                         h->hpc.pred4x4[ dir ](ptr, topright, linesize);
1801                         nnz = h->non_zero_count_cache[ scan8[i+p*16] ];
1802                         if(nnz){
1803                             if(is_h264){
1804                                 if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))
1805                                     idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1806                                 else
1807                                     idct_add   (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1808                             } else if (CONFIG_SVQ3_DECODER)
1809                                 ff_svq3_add_idct_c(ptr, h->mb + i*16+p*256, linesize, qscale, 0);
1810                         }
1811                     }
1812                 }
1813             }
1814         }
1815     }else{
1816         h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
1817         if(is_h264){
1818             if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX+p] ]){
1819                 if(!transform_bypass)
1820                     h->h264dsp.h264_luma_dc_dequant_idct(h->mb+(p*256 << pixel_shift), h->mb_luma_dc[p], h->dequant4_coeff[p][qscale][0]);
1821                 else{
1822                     static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
1823                                                             8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
1824                     for(i = 0; i < 16; i++)
1825                         dctcoef_set(h->mb+(p*256 << pixel_shift), pixel_shift, dc_mapping[i], dctcoef_get(h->mb_luma_dc[p], pixel_shift, i));
1826                 }
1827             }
1828         } else if (CONFIG_SVQ3_DECODER)
1829             ff_svq3_luma_dc_dequant_idct_c(h->mb+p*256, h->mb_luma_dc[p], qscale);
1830     }
1831 }
1832
1833 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,
1834                                                     int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)
1835 {
1836     MpegEncContext * const s = &h->s;
1837     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1838     int i;
1839     block_offset += 16*p;
1840     if(!IS_INTRA4x4(mb_type)){
1841         if(is_h264){
1842             if(IS_INTRA16x16(mb_type)){
1843                 if(transform_bypass){
1844                     if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
1845                         h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize);
1846                     }else{
1847                         for(i=0; i<16; i++){
1848                             if(h->non_zero_count_cache[ scan8[i+p*16] ] || dctcoef_get(h->mb, pixel_shift, i*16+p*256))
1849                                 s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + (i*16+p*256 << pixel_shift), linesize);
1850                         }
1851                     }
1852                 }else{
1853                     h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
1854                 }
1855             }else if(h->cbp&15){
1856                 if(transform_bypass){
1857                     const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1858                     idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
1859                     for(i=0; i<16; i+=di){
1860                         if(h->non_zero_count_cache[ scan8[i+p*16] ]){
1861                             idct_add(dest_y + block_offset[i], h->mb + (i*16+p*256 << pixel_shift), linesize);
1862                         }
1863                     }
1864                 }else{
1865                     if(IS_8x8DCT(mb_type)){
1866                         h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
1867                     }else{
1868                         h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
1869                     }
1870                 }
1871             }
1872         } else if (CONFIG_SVQ3_DECODER) {
1873             for(i=0; i<16; i++){
1874                 if(h->non_zero_count_cache[ scan8[i+p*16] ] || h->mb[i*16+p*256]){ //FIXME benchmark weird rule, & below
1875                     uint8_t * const ptr= dest_y + block_offset[i];
1876                     ff_svq3_add_idct_c(ptr, h->mb + i*16 + p*256, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1877                 }
1878             }
1879         }
1880     }
1881 }
1882
1883 static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple, int pixel_shift)
1884 {
1885     MpegEncContext * const s = &h->s;
1886     const int mb_x= s->mb_x;
1887     const int mb_y= s->mb_y;
1888     const int mb_xy= h->mb_xy;
1889     const int mb_type = s->current_picture.f.mb_type[mb_xy];
1890     uint8_t  *dest_y, *dest_cb, *dest_cr;
1891     int linesize, uvlinesize /*dct_offset*/;
1892     int i, j;
1893     int *block_offset = &h->block_offset[0];
1894     const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
1895     /* is_h264 should always be true if SVQ3 is disabled. */
1896     const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
1897     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1898     const int block_h = 16 >> s->chroma_y_shift;
1899     const int chroma422 = CHROMA422;
1900
1901     dest_y  = s->current_picture.f.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize  ) * 16;
1902     dest_cb = s->current_picture.f.data[1] + (mb_x << pixel_shift)*8 + mb_y * s->uvlinesize * block_h;
1903     dest_cr = s->current_picture.f.data[2] + (mb_x << pixel_shift)*8 + mb_y * s->uvlinesize * block_h;
1904
1905     s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
1906     s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + (64 << pixel_shift), dest_cr - dest_cb, 2);
1907
1908     h->list_counts[mb_xy]= h->list_count;
1909
1910     if (!simple && MB_FIELD) {
1911         linesize   = h->mb_linesize   = s->linesize * 2;
1912         uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
1913         block_offset = &h->block_offset[48];
1914         if(mb_y&1){ //FIXME move out of this function?
1915             dest_y -= s->linesize*15;
1916             dest_cb-= s->uvlinesize * (block_h - 1);
1917             dest_cr-= s->uvlinesize * (block_h - 1);
1918         }
1919         if(FRAME_MBAFF) {
1920             int list;
1921             for(list=0; list<h->list_count; list++){
1922                 if(!USES_LIST(mb_type, list))
1923                     continue;
1924                 if(IS_16X16(mb_type)){
1925                     int8_t *ref = &h->ref_cache[list][scan8[0]];
1926                     fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
1927                 }else{
1928                     for(i=0; i<16; i+=4){
1929                         int ref = h->ref_cache[list][scan8[i]];
1930                         if(ref >= 0)
1931                             fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
1932                     }
1933                 }
1934             }
1935         }
1936     } else {
1937         linesize   = h->mb_linesize   = s->linesize;
1938         uvlinesize = h->mb_uvlinesize = s->uvlinesize;
1939 //        dct_offset = s->linesize * 16;
1940     }
1941
1942     if (!simple && IS_INTRA_PCM(mb_type)) {
1943         const int bit_depth = h->sps.bit_depth_luma;
1944         if (pixel_shift) {
1945             int j;
1946             GetBitContext gb;
1947             init_get_bits(&gb, (uint8_t*)h->mb, 384*bit_depth);
1948
1949             for (i = 0; i < 16; i++) {
1950                 uint16_t *tmp_y  = (uint16_t*)(dest_y  + i*linesize);
1951                 for (j = 0; j < 16; j++)
1952                     tmp_y[j] = get_bits(&gb, bit_depth);
1953             }
1954             if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1955                 if (!h->sps.chroma_format_idc) {
1956                     for (i = 0; i < block_h; i++) {
1957                         uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
1958                         uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
1959                         for (j = 0; j < 8; j++) {
1960                             tmp_cb[j] = tmp_cr[j] = 1 << (bit_depth - 1);
1961                         }
1962                     }
1963                 } else {
1964                     for (i = 0; i < block_h; i++) {
1965                         uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
1966                         for (j = 0; j < 8; j++)
1967                             tmp_cb[j] = get_bits(&gb, bit_depth);
1968                     }
1969                     for (i = 0; i < block_h; i++) {
1970                         uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
1971                         for (j = 0; j < 8; j++)
1972                             tmp_cr[j] = get_bits(&gb, bit_depth);
1973                     }
1974                 }
1975             }
1976         } else {
1977             for (i=0; i<16; i++) {
1978                 memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
1979             }
1980             if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1981                 if (!h->sps.chroma_format_idc) {
1982                     for (i=0; i<8; i++) {
1983                         memset(dest_cb + i*uvlinesize, 1 << (bit_depth - 1), 8);
1984                         memset(dest_cr + i*uvlinesize, 1 << (bit_depth - 1), 8);
1985                     }
1986                 } else {
1987                     for (i=0; i<block_h; i++) {
1988                         memcpy(dest_cb + i*uvlinesize, h->mb + 128 + i*4,  8);
1989                         memcpy(dest_cr + i*uvlinesize, h->mb + 160 + i*4,  8);
1990                     }
1991                 }
1992             }
1993         }
1994     } else {
1995         if(IS_INTRA(mb_type)){
1996             if(h->deblocking_filter)
1997                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, 0, simple, pixel_shift);
1998
1999             if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2000                 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
2001                 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
2002             }
2003
2004             hl_decode_mb_predict_luma(h, mb_type, is_h264, simple, transform_bypass, pixel_shift, block_offset, linesize, dest_y, 0);
2005
2006             if(h->deblocking_filter)
2007                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, 0, simple, pixel_shift);
2008         }else if(is_h264){
2009             if (chroma422) {
2010                 hl_motion_422(h, dest_y, dest_cb, dest_cr,
2011                               s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2012                               s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2013                               h->h264dsp.weight_h264_pixels_tab,
2014                               h->h264dsp.biweight_h264_pixels_tab,
2015                               pixel_shift);
2016             } else {
2017                 hl_motion_420(h, dest_y, dest_cb, dest_cr,
2018                               s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2019                               s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2020                               h->h264dsp.weight_h264_pixels_tab,
2021                               h->h264dsp.biweight_h264_pixels_tab,
2022                               pixel_shift);
2023             }
2024         }
2025
2026         hl_decode_mb_idct_luma(h, mb_type, is_h264, simple, transform_bypass, pixel_shift, block_offset, linesize, dest_y, 0);
2027
2028         if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
2029             uint8_t *dest[2] = {dest_cb, dest_cr};
2030             if(transform_bypass){
2031                 if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
2032                     h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + (16*16*1 << pixel_shift), uvlinesize);
2033                     h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 32, h->mb + (16*16*2 << pixel_shift), uvlinesize);
2034                 }else{
2035                     idct_add = s->dsp.add_pixels4;
2036                     for(j=1; j<3; j++){
2037                         for(i=j*16; i<j*16+4; i++){
2038                             if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h->mb, pixel_shift, i*16))
2039                                 idct_add   (dest[j-1] + block_offset[i], h->mb + (i*16 << pixel_shift), uvlinesize);
2040                         }
2041                         if (chroma422) {
2042                             for(i=j*16+4; i<j*16+8; i++){
2043                                 if(h->non_zero_count_cache[ scan8[i+4] ] || dctcoef_get(h->mb, pixel_shift, i*16))
2044                                     idct_add   (dest[j-1] + block_offset[i+4], h->mb + (i*16 << pixel_shift), uvlinesize);
2045                             }
2046                         }
2047                     }
2048                 }
2049             }else{
2050                 if(is_h264){
2051                     int qp[2];
2052                     if (chroma422) {
2053                         qp[0] = h->chroma_qp[0] + 3;
2054                         qp[1] = h->chroma_qp[1] + 3;
2055                     } else {
2056                         qp[0] = h->chroma_qp[0];
2057                         qp[1] = h->chroma_qp[1];
2058                     }
2059                     if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
2060                         h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16*16*1 << pixel_shift), h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][qp[0]][0]);
2061                     if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
2062                         h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16*16*2 << pixel_shift), h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][qp[1]][0]);
2063                     h->h264dsp.h264_idct_add8(dest, block_offset,
2064                                               h->mb, uvlinesize,
2065                                               h->non_zero_count_cache);
2066                 } else if (CONFIG_SVQ3_DECODER) {
2067                     h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16*1, h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
2068                     h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16*2, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
2069                     for(j=1; j<3; j++){
2070                         for(i=j*16; i<j*16+4; i++){
2071                             if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2072                                 uint8_t * const ptr= dest[j-1] + block_offset[i];
2073                                 ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
2074                             }
2075                         }
2076                     }
2077                 }
2078             }
2079         }
2080     }
2081     if(h->cbp || IS_INTRA(mb_type))
2082     {
2083         s->dsp.clear_blocks(h->mb);
2084         s->dsp.clear_blocks(h->mb+(24*16<<pixel_shift));
2085     }
2086 }
2087
2088 static av_always_inline void hl_decode_mb_444_internal(H264Context *h, int simple, int pixel_shift){
2089     MpegEncContext * const s = &h->s;
2090     const int mb_x= s->mb_x;
2091     const int mb_y= s->mb_y;
2092     const int mb_xy= h->mb_xy;
2093     const int mb_type = s->current_picture.f.mb_type[mb_xy];
2094     uint8_t  *dest[3];
2095     int linesize;
2096     int i, j, p;
2097     int *block_offset = &h->block_offset[0];
2098     const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
2099     const int plane_count = (simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) ? 3 : 1;
2100
2101     for (p = 0; p < plane_count; p++)
2102     {
2103         dest[p] = s->current_picture.f.data[p] + ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
2104         s->dsp.prefetch(dest[p] + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
2105     }
2106
2107     h->list_counts[mb_xy]= h->list_count;
2108
2109     if (!simple && MB_FIELD) {
2110         linesize   = h->mb_linesize = h->mb_uvlinesize = s->linesize * 2;
2111         block_offset = &h->block_offset[48];
2112         if(mb_y&1) //FIXME move out of this function?
2113             for (p = 0; p < 3; p++)
2114                 dest[p] -= s->linesize*15;
2115         if(FRAME_MBAFF) {
2116             int list;
2117             for(list=0; list<h->list_count; list++){
2118                 if(!USES_LIST(mb_type, list))
2119                     continue;
2120                 if(IS_16X16(mb_type)){
2121                     int8_t *ref = &h->ref_cache[list][scan8[0]];
2122                     fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
2123                 }else{
2124                     for(i=0; i<16; i+=4){
2125                         int ref = h->ref_cache[list][scan8[i]];
2126                         if(ref >= 0)
2127                             fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
2128                     }
2129                 }
2130             }
2131         }
2132     } else {
2133         linesize   = h->mb_linesize = h->mb_uvlinesize = s->linesize;
2134     }
2135
2136     if (!simple && IS_INTRA_PCM(mb_type)) {
2137         if (pixel_shift) {
2138             const int bit_depth = h->sps.bit_depth_luma;
2139             GetBitContext gb;
2140             init_get_bits(&gb, (uint8_t*)h->mb, 768*bit_depth);
2141
2142             for (p = 0; p < plane_count; p++) {
2143                 for (i = 0; i < 16; i++) {
2144                     uint16_t *tmp = (uint16_t*)(dest[p] + i*linesize);
2145                     for (j = 0; j < 16; j++)
2146                         tmp[j] = get_bits(&gb, bit_depth);
2147                 }
2148             }
2149         } else {
2150             for (p = 0; p < plane_count; p++) {
2151                 for (i = 0; i < 16; i++) {
2152                     memcpy(dest[p] + i*linesize, h->mb + p*128 + i*8, 16);
2153                 }
2154             }
2155         }
2156     } else {
2157         if(IS_INTRA(mb_type)){
2158             if(h->deblocking_filter)
2159                 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize, linesize, 1, 1, simple, pixel_shift);
2160
2161             for (p = 0; p < plane_count; p++)
2162                 hl_decode_mb_predict_luma(h, mb_type, 1, simple, transform_bypass, pixel_shift, block_offset, linesize, dest[p], p);
2163
2164             if(h->deblocking_filter)
2165                 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize, linesize, 0, 1, simple, pixel_shift);
2166         }else{
2167             hl_motion(h, dest[0], dest[1], dest[2],
2168                       s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2169                       s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2170                       h->h264dsp.weight_h264_pixels_tab,
2171                       h->h264dsp.biweight_h264_pixels_tab, pixel_shift, 3);
2172         }
2173
2174         for (p = 0; p < plane_count; p++)
2175             hl_decode_mb_idct_luma(h, mb_type, 1, simple, transform_bypass, pixel_shift, block_offset, linesize, dest[p], p);
2176     }
2177     if(h->cbp || IS_INTRA(mb_type))
2178     {
2179         s->dsp.clear_blocks(h->mb);
2180         s->dsp.clear_blocks(h->mb+(24*16<<pixel_shift));
2181     }
2182 }
2183
2184 /**
2185  * Process a macroblock; this case avoids checks for expensive uncommon cases.
2186  */
2187 #define hl_decode_mb_simple(sh, bits) \
2188 static void hl_decode_mb_simple_ ## bits(H264Context *h){ \
2189     hl_decode_mb_internal(h, 1, sh); \
2190 }
2191 hl_decode_mb_simple(0, 8)
2192 hl_decode_mb_simple(1, 16)
2193
2194 /**
2195  * Process a macroblock; this handles edge cases, such as interlacing.
2196  */
2197 static void av_noinline hl_decode_mb_complex(H264Context *h){
2198     hl_decode_mb_internal(h, 0, h->pixel_shift);
2199 }
2200
2201 static void av_noinline hl_decode_mb_444_complex(H264Context *h){
2202     hl_decode_mb_444_internal(h, 0, h->pixel_shift);
2203 }
2204
2205 static void av_noinline hl_decode_mb_444_simple(H264Context *h){
2206     hl_decode_mb_444_internal(h, 1, 0);
2207 }
2208
2209 void ff_h264_hl_decode_mb(H264Context *h){
2210     MpegEncContext * const s = &h->s;
2211     const int mb_xy= h->mb_xy;
2212     const int mb_type = s->current_picture.f.mb_type[mb_xy];
2213     int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
2214
2215     if (CHROMA444) {
2216         if(is_complex || h->pixel_shift)
2217             hl_decode_mb_444_complex(h);
2218         else
2219             hl_decode_mb_444_simple(h);
2220     } else if (is_complex) {
2221         hl_decode_mb_complex(h);
2222     } else if (h->pixel_shift) {
2223         hl_decode_mb_simple_16(h);
2224     } else
2225         hl_decode_mb_simple_8(h);
2226 }
2227
2228 static int pred_weight_table(H264Context *h){
2229     MpegEncContext * const s = &h->s;
2230     int list, i;
2231     int luma_def, chroma_def;
2232
2233     h->use_weight= 0;
2234     h->use_weight_chroma= 0;
2235     h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
2236     if(h->sps.chroma_format_idc)
2237         h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
2238     luma_def = 1<<h->luma_log2_weight_denom;
2239     chroma_def = 1<<h->chroma_log2_weight_denom;
2240
2241     for(list=0; list<2; list++){
2242         h->luma_weight_flag[list]   = 0;
2243         h->chroma_weight_flag[list] = 0;
2244         for(i=0; i<h->ref_count[list]; i++){
2245             int luma_weight_flag, chroma_weight_flag;
2246
2247             luma_weight_flag= get_bits1(&s->gb);
2248             if(luma_weight_flag){
2249                 h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
2250                 h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
2251                 if(   h->luma_weight[i][list][0] != luma_def
2252                    || h->luma_weight[i][list][1] != 0) {
2253                     h->use_weight= 1;
2254                     h->luma_weight_flag[list]= 1;
2255                 }
2256             }else{
2257                 h->luma_weight[i][list][0]= luma_def;
2258                 h->luma_weight[i][list][1]= 0;
2259             }
2260
2261             if(h->sps.chroma_format_idc){
2262                 chroma_weight_flag= get_bits1(&s->gb);
2263                 if(chroma_weight_flag){
2264                     int j;
2265                     for(j=0; j<2; j++){
2266                         h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
2267                         h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
2268                         if(   h->chroma_weight[i][list][j][0] != chroma_def
2269                            || h->chroma_weight[i][list][j][1] != 0) {
2270                             h->use_weight_chroma= 1;
2271                             h->chroma_weight_flag[list]= 1;
2272                         }
2273                     }
2274                 }else{
2275                     int j;
2276                     for(j=0; j<2; j++){
2277                         h->chroma_weight[i][list][j][0]= chroma_def;
2278                         h->chroma_weight[i][list][j][1]= 0;
2279                     }
2280                 }
2281             }
2282         }
2283         if(h->slice_type_nos != AV_PICTURE_TYPE_B) break;
2284     }
2285     h->use_weight= h->use_weight || h->use_weight_chroma;
2286     return 0;
2287 }
2288
2289 /**
2290  * Initialize implicit_weight table.
2291  * @param field  0/1 initialize the weight for interlaced MBAFF
2292  *                -1 initializes the rest
2293  */
2294 static void implicit_weight_table(H264Context *h, int field){
2295     MpegEncContext * const s = &h->s;
2296     int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2297
2298     for (i = 0; i < 2; i++) {
2299         h->luma_weight_flag[i]   = 0;
2300         h->chroma_weight_flag[i] = 0;
2301     }
2302
2303     if(field < 0){
2304         if (s->picture_structure == PICT_FRAME) {
2305             cur_poc = s->current_picture_ptr->poc;
2306         } else {
2307             cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2308         }
2309     if(   h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
2310        && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
2311         h->use_weight= 0;
2312         h->use_weight_chroma= 0;
2313         return;
2314     }
2315         ref_start= 0;
2316         ref_count0= h->ref_count[0];
2317         ref_count1= h->ref_count[1];
2318     }else{
2319         cur_poc = s->current_picture_ptr->field_poc[field];
2320         ref_start= 16;
2321         ref_count0= 16+2*h->ref_count[0];
2322         ref_count1= 16+2*h->ref_count[1];
2323     }
2324
2325     h->use_weight= 2;
2326     h->use_weight_chroma= 2;
2327     h->luma_log2_weight_denom= 5;
2328     h->chroma_log2_weight_denom= 5;
2329
2330     for(ref0=ref_start; ref0 < ref_count0; ref0++){
2331         int poc0 = h->ref_list[0][ref0].poc;
2332         for(ref1=ref_start; ref1 < ref_count1; ref1++){
2333             int w = 32;
2334             if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2335                 int poc1 = h->ref_list[1][ref1].poc;
2336                 int td = av_clip(poc1 - poc0, -128, 127);
2337                 if(td){
2338                     int tb = av_clip(cur_poc - poc0, -128, 127);
2339                     int tx = (16384 + (FFABS(td) >> 1)) / td;
2340                     int dist_scale_factor = (tb*tx + 32) >> 8;
2341                     if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
2342                         w = 64 - dist_scale_factor;
2343                 }
2344             }
2345             if(field<0){
2346                 h->implicit_weight[ref0][ref1][0]=
2347                 h->implicit_weight[ref0][ref1][1]= w;
2348             }else{
2349                 h->implicit_weight[ref0][ref1][field]=w;
2350             }
2351         }
2352     }
2353 }
2354
2355 /**
2356  * instantaneous decoder refresh.
2357  */
2358 static void idr(H264Context *h){
2359     int i;
2360     ff_h264_remove_all_refs(h);
2361     h->prev_frame_num= 0;
2362     h->prev_frame_num_offset= 0;
2363     h->prev_poc_msb= 1<<16;
2364     h->prev_poc_lsb= 0;
2365     for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2366         h->last_pocs[i] = INT_MIN;
2367 }
2368
2369 /* forget old pics after a seek */
2370 static void flush_dpb(AVCodecContext *avctx){
2371     H264Context *h= avctx->priv_data;
2372     int i;
2373     for(i=0; i<=MAX_DELAYED_PIC_COUNT; i++) {
2374         if(h->delayed_pic[i])
2375             h->delayed_pic[i]->f.reference = 0;
2376         h->delayed_pic[i]= NULL;
2377     }
2378     h->outputed_poc=h->next_outputed_poc= INT_MIN;
2379     h->prev_interlaced_frame = 1;
2380     idr(h);
2381     h->prev_frame_num= -1;
2382     if(h->s.current_picture_ptr)
2383         h->s.current_picture_ptr->f.reference = 0;
2384     h->s.first_field= 0;
2385     ff_h264_reset_sei(h);
2386     ff_mpeg_flush(avctx);
2387     h->recovery_frame= -1;
2388     h->sync= 0;
2389 }
2390
2391 static int init_poc(H264Context *h){
2392     MpegEncContext * const s = &h->s;
2393     const int max_frame_num= 1<<h->sps.log2_max_frame_num;
2394     int field_poc[2];
2395     Picture *cur = s->current_picture_ptr;
2396
2397     h->frame_num_offset= h->prev_frame_num_offset;
2398     if(h->frame_num < h->prev_frame_num)
2399         h->frame_num_offset += max_frame_num;
2400
2401     if(h->sps.poc_type==0){
2402         const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
2403
2404         if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
2405             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2406         else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
2407             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2408         else
2409             h->poc_msb = h->prev_poc_msb;
2410 //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2411         field_poc[0] =
2412         field_poc[1] = h->poc_msb + h->poc_lsb;
2413         if(s->picture_structure == PICT_FRAME)
2414             field_poc[1] += h->delta_poc_bottom;
2415     }else if(h->sps.poc_type==1){
2416         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2417         int i;
2418
2419         if(h->sps.poc_cycle_length != 0)
2420             abs_frame_num = h->frame_num_offset + h->frame_num;
2421         else
2422             abs_frame_num = 0;
2423
2424         if(h->nal_ref_idc==0 && abs_frame_num > 0)
2425             abs_frame_num--;
2426
2427         expected_delta_per_poc_cycle = 0;
2428         for(i=0; i < h->sps.poc_cycle_length; i++)
2429             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
2430
2431         if(abs_frame_num > 0){
2432             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2433             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2434
2435             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2436             for(i = 0; i <= frame_num_in_poc_cycle; i++)
2437                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
2438         } else
2439             expectedpoc = 0;
2440
2441         if(h->nal_ref_idc == 0)
2442             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2443
2444         field_poc[0] = expectedpoc + h->delta_poc[0];
2445         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2446
2447         if(s->picture_structure == PICT_FRAME)
2448             field_poc[1] += h->delta_poc[1];
2449     }else{
2450         int poc= 2*(h->frame_num_offset + h->frame_num);
2451
2452         if(!h->nal_ref_idc)
2453             poc--;
2454
2455         field_poc[0]= poc;
2456         field_poc[1]= poc;
2457     }
2458
2459     if(s->picture_structure != PICT_BOTTOM_FIELD)
2460         s->current_picture_ptr->field_poc[0]= field_poc[0];
2461     if(s->picture_structure != PICT_TOP_FIELD)
2462         s->current_picture_ptr->field_poc[1]= field_poc[1];
2463     cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
2464
2465     return 0;
2466 }
2467
2468
2469 /**
2470  * initialize scan tables
2471  */
2472 static void init_scan_tables(H264Context *h){
2473     int i;
2474     for(i=0; i<16; i++){
2475 #define T(x) (x>>2) | ((x<<2) & 0xF)
2476         h->zigzag_scan[i] = T(zigzag_scan[i]);
2477         h-> field_scan[i] = T( field_scan[i]);
2478 #undef T
2479     }
2480     for(i=0; i<64; i++){
2481 #define T(x) (x>>3) | ((x&7)<<3)
2482         h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
2483         h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2484         h->field_scan8x8[i]        = T(field_scan8x8[i]);
2485         h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
2486 #undef T
2487     }
2488     if(h->sps.transform_bypass){ //FIXME same ugly
2489         h->zigzag_scan_q0          = zigzag_scan;
2490         h->zigzag_scan8x8_q0       = ff_zigzag_direct;
2491         h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2492         h->field_scan_q0           = field_scan;
2493         h->field_scan8x8_q0        = field_scan8x8;
2494         h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
2495     }else{
2496         h->zigzag_scan_q0          = h->zigzag_scan;
2497         h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
2498         h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2499         h->field_scan_q0           = h->field_scan;
2500         h->field_scan8x8_q0        = h->field_scan8x8;
2501         h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
2502     }
2503 }
2504
2505 static int field_end(H264Context *h, int in_setup){
2506     MpegEncContext * const s = &h->s;
2507     AVCodecContext * const avctx= s->avctx;
2508     int err = 0;
2509     s->mb_y= 0;
2510
2511     if (!in_setup && !s->dropable)
2512         ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
2513                                  s->picture_structure==PICT_BOTTOM_FIELD);
2514
2515     if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2516         ff_vdpau_h264_set_reference_frames(s);
2517
2518     if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
2519         if(!s->dropable) {
2520             err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2521             h->prev_poc_msb= h->poc_msb;
2522             h->prev_poc_lsb= h->poc_lsb;
2523         }
2524         h->prev_frame_num_offset= h->frame_num_offset;
2525         h->prev_frame_num= h->frame_num;
2526         h->outputed_poc = h->next_outputed_poc;
2527     }
2528
2529     if (avctx->hwaccel) {
2530         if (avctx->hwaccel->end_frame(avctx) < 0)
2531             av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
2532     }
2533
2534     if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2535         ff_vdpau_h264_picture_complete(s);
2536
2537     /*
2538      * FIXME: Error handling code does not seem to support interlaced
2539      * when slices span multiple rows
2540      * The ff_er_add_slice calls don't work right for bottom
2541      * fields; they cause massive erroneous error concealing
2542      * Error marking covers both fields (top and bottom).
2543      * This causes a mismatched s->error_count
2544      * and a bad error table. Further, the error count goes to
2545      * INT_MAX when called for bottom field, because mb_y is
2546      * past end by one (callers fault) and resync_mb_y != 0
2547      * causes problems for the first MB line, too.
2548      */
2549     if (!FIELD_PICTURE)
2550         ff_er_frame_end(s);
2551
2552     ff_MPV_frame_end(s);
2553
2554     h->current_slice=0;
2555
2556     return err;
2557 }
2558
2559 /**
2560  * Replicate H264 "master" context to thread contexts.
2561  */
2562 static void clone_slice(H264Context *dst, H264Context *src)
2563 {
2564     memcpy(dst->block_offset,     src->block_offset, sizeof(dst->block_offset));
2565     dst->s.current_picture_ptr  = src->s.current_picture_ptr;
2566     dst->s.current_picture      = src->s.current_picture;
2567     dst->s.linesize             = src->s.linesize;
2568     dst->s.uvlinesize           = src->s.uvlinesize;
2569     dst->s.first_field          = src->s.first_field;
2570
2571     dst->prev_poc_msb           = src->prev_poc_msb;
2572     dst->prev_poc_lsb           = src->prev_poc_lsb;
2573     dst->prev_frame_num_offset  = src->prev_frame_num_offset;
2574     dst->prev_frame_num         = src->prev_frame_num;
2575     dst->short_ref_count        = src->short_ref_count;
2576
2577     memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
2578     memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
2579     memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2580     memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
2581
2582     memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
2583     memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
2584 }
2585
2586 /**
2587  * Compute profile from profile_idc and constraint_set?_flags.
2588  *
2589  * @param sps SPS
2590  *
2591  * @return profile as defined by FF_PROFILE_H264_*
2592  */
2593 int ff_h264_get_profile(SPS *sps)
2594 {
2595     int profile = sps->profile_idc;
2596
2597     switch(sps->profile_idc) {
2598     case FF_PROFILE_H264_BASELINE:
2599         // constraint_set1_flag set to 1
2600         profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2601         break;
2602     case FF_PROFILE_H264_HIGH_10:
2603     case FF_PROFILE_H264_HIGH_422:
2604     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2605         // constraint_set3_flag set to 1
2606         profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
2607         break;
2608     }
2609
2610     return profile;
2611 }
2612
2613 /**
2614  * Decode a slice header.
2615  * This will also call ff_MPV_common_init() and frame_start() as needed.
2616  *
2617  * @param h h264context
2618  * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
2619  *
2620  * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2621  */
2622 static int decode_slice_header(H264Context *h, H264Context *h0){
2623     MpegEncContext * const s = &h->s;
2624     MpegEncContext * const s0 = &h0->s;
2625     unsigned int first_mb_in_slice;
2626     unsigned int pps_id;
2627     int num_ref_idx_active_override_flag;
2628     unsigned int slice_type, tmp, i, j;
2629     int default_ref_list_done = 0;
2630     int last_pic_structure;
2631
2632     s->dropable= h->nal_ref_idc == 0;
2633
2634     /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2635     if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc && !h->pixel_shift){
2636         s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
2637         s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
2638     }else{
2639         s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
2640         s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
2641     }
2642
2643     first_mb_in_slice= get_ue_golomb_long(&s->gb);
2644
2645     if(first_mb_in_slice == 0){ //FIXME better field boundary detection
2646         if(h0->current_slice && FIELD_PICTURE){
2647             field_end(h, 1);
2648         }
2649
2650         h0->current_slice = 0;
2651         if (!s0->first_field)
2652             s->current_picture_ptr= NULL;
2653     }
2654
2655     slice_type= get_ue_golomb_31(&s->gb);
2656     if(slice_type > 9){
2657         av_log(h->s.avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", h->slice_type, s->mb_x, s->mb_y);
2658         return -1;
2659     }
2660     if(slice_type > 4){
2661         slice_type -= 5;
2662         h->slice_type_fixed=1;
2663     }else
2664         h->slice_type_fixed=0;
2665
2666     slice_type= golomb_to_pict_type[ slice_type ];
2667     if (slice_type == AV_PICTURE_TYPE_I
2668         || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
2669         default_ref_list_done = 1;
2670     }
2671     h->slice_type= slice_type;
2672     h->slice_type_nos= slice_type & 3;
2673
2674     s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
2675
2676     pps_id= get_ue_golomb(&s->gb);
2677     if(pps_id>=MAX_PPS_COUNT){
2678         av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2679         return -1;
2680     }
2681     if(!h0->pps_buffers[pps_id]) {
2682         av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
2683         return -1;
2684     }
2685     h->pps= *h0->pps_buffers[pps_id];
2686
2687     if(!h0->sps_buffers[h->pps.sps_id]) {
2688         av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
2689         return -1;
2690     }
2691     h->sps = *h0->sps_buffers[h->pps.sps_id];
2692
2693     s->avctx->profile = ff_h264_get_profile(&h->sps);
2694     s->avctx->level   = h->sps.level_idc;
2695     s->avctx->refs    = h->sps.ref_frame_count;
2696
2697     if(h == h0 && h->dequant_coeff_pps != pps_id){
2698         h->dequant_coeff_pps = pps_id;
2699         init_dequant_tables(h);
2700     }
2701
2702     s->mb_width= h->sps.mb_width;
2703     s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2704
2705     h->b_stride=  s->mb_width*4;
2706
2707     s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
2708
2709     s->width = 16*s->mb_width;
2710     s->height= 16*s->mb_height;
2711
2712     if (s->context_initialized
2713         && (   s->width != s->avctx->coded_width || s->height != s->avctx->coded_height
2714             || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
2715             || h->cur_chroma_format_idc != h->sps.chroma_format_idc
2716             || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2717         if(h != h0 || (s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2718             av_log_missing_feature(s->avctx, "Width/height/bit depth/chroma idc changing with threads is", 0);
2719             return -1;   // width / height changed during parallelized decoding
2720         }
2721         free_tables(h, 0);
2722         flush_dpb(s->avctx);
2723         ff_MPV_common_end(s);
2724         h->list_count = 0;
2725     }
2726     if (!s->context_initialized) {
2727         if (h != h0) {
2728             av_log(h->s.avctx, AV_LOG_ERROR, "Cannot (re-)initialize context during parallel decoding.\n");
2729             return -1;
2730         }
2731         avcodec_set_dimensions(s->avctx, s->width, s->height);
2732         s->avctx->width  -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
2733         s->avctx->height -= (1<<s->chroma_y_shift)*FFMIN(h->sps.crop_bottom, (16>>s->chroma_y_shift)-1) * (2 - h->sps.frame_mbs_only_flag);
2734         s->avctx->sample_aspect_ratio= h->sps.sar;
2735         av_assert0(s->avctx->sample_aspect_ratio.den);
2736
2737         if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2738             h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2739             if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10 &&
2740                 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2741                 s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2742                 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2743                 h->pixel_shift = h->sps.bit_depth_luma > 8;
2744
2745                 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2746                 ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2747                 s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2748                 ff_dsputil_init(&s->dsp, s->avctx);
2749             } else {
2750                 av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d chroma_idc: %d\n",
2751                        h->sps.bit_depth_luma, h->sps.chroma_format_idc);
2752                 return -1;
2753             }
2754         }
2755
2756         if(h->sps.video_signal_type_present_flag){
2757             s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2758             if(h->sps.colour_description_present_flag){
2759                 s->avctx->color_primaries = h->sps.color_primaries;
2760                 s->avctx->color_trc       = h->sps.color_trc;
2761                 s->avctx->colorspace      = h->sps.colorspace;
2762             }
2763         }
2764
2765         if(h->sps.timing_info_present_flag){
2766             int64_t den= h->sps.time_scale;
2767             if(h->x264_build < 44U)
2768                 den *= 2;
2769             av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2770                       h->sps.num_units_in_tick, den, 1<<30);
2771         }
2772
2773         switch (h->sps.bit_depth_luma) {
2774             case 9 :
2775                 if (CHROMA444) {
2776                     if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2777                         s->avctx->pix_fmt = PIX_FMT_GBRP9;
2778                     } else
2779                         s->avctx->pix_fmt = PIX_FMT_YUV444P9;
2780                 } else if (CHROMA422)
2781                     s->avctx->pix_fmt = PIX_FMT_YUV422P9;
2782                 else
2783                     s->avctx->pix_fmt = PIX_FMT_YUV420P9;
2784                 break;
2785             case 10 :
2786                 if (CHROMA444) {
2787                     if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2788                         s->avctx->pix_fmt = PIX_FMT_GBRP10;
2789                     } else
2790                         s->avctx->pix_fmt = PIX_FMT_YUV444P10;
2791                 } else if (CHROMA422)
2792                     s->avctx->pix_fmt = PIX_FMT_YUV422P10;
2793                 else
2794                     s->avctx->pix_fmt = PIX_FMT_YUV420P10;
2795                 break;
2796             default:
2797                 if (CHROMA444){
2798                     s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P : PIX_FMT_YUV444P;
2799                     if (s->avctx->colorspace == AVCOL_SPC_RGB) {
2800                        s->avctx->pix_fmt = PIX_FMT_GBR24P;
2801                        av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
2802                     } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
2803                         av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
2804                     }
2805                 } else if (CHROMA422) {
2806                     s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ422P : PIX_FMT_YUV422P;
2807                 }else{
2808                     s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2809                                                              s->avctx->codec->pix_fmts ?
2810                                                              s->avctx->codec->pix_fmts :
2811                                                              s->avctx->color_range == AVCOL_RANGE_JPEG ?
2812                                                              hwaccel_pixfmt_list_h264_jpeg_420 :
2813                                                              ff_hwaccel_pixfmt_list_420);
2814                 }
2815         }
2816
2817         s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2818
2819         if (ff_MPV_common_init(s) < 0) {
2820             av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
2821             return -1;
2822         }
2823         s->first_field = 0;
2824         h->prev_interlaced_frame = 1;
2825
2826         init_scan_tables(h);
2827         if (ff_h264_alloc_tables(h) < 0) {
2828             av_log(h->s.avctx, AV_LOG_ERROR, "Could not allocate memory for h264\n");
2829             return AVERROR(ENOMEM);
2830         }
2831
2832         if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
2833             if (context_init(h) < 0) {
2834                 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2835                 return -1;
2836             }
2837         } else {
2838             for(i = 1; i < s->slice_context_count; i++) {
2839                 H264Context *c;
2840                 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2841                 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2842                 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2843                 c->h264dsp = h->h264dsp;
2844                 c->sps = h->sps;
2845                 c->pps = h->pps;
2846                 c->pixel_shift = h->pixel_shift;
2847                 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
2848                 init_scan_tables(c);
2849                 clone_tables(c, h, i);
2850             }
2851
2852             for(i = 0; i < s->slice_context_count; i++)
2853                 if (context_init(h->thread_context[i]) < 0) {
2854                     av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2855                     return -1;
2856                 }
2857         }
2858     }
2859
2860     h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
2861
2862     h->mb_mbaff = 0;
2863     h->mb_aff_frame = 0;
2864     last_pic_structure = s0->picture_structure;
2865     if(h->sps.frame_mbs_only_flag){
2866         s->picture_structure= PICT_FRAME;
2867     }else{
2868         if(!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B){
2869             av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
2870             return -1;
2871         }
2872         if(get_bits1(&s->gb)) { //field_pic_flag
2873             s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
2874         } else {
2875             s->picture_structure= PICT_FRAME;
2876             h->mb_aff_frame = h->sps.mb_aff;
2877         }
2878     }
2879     h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
2880
2881     if(h0->current_slice == 0){
2882         // Shorten frame num gaps so we don't have to allocate reference frames just to throw them away
2883         if(h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
2884             int unwrap_prev_frame_num = h->prev_frame_num, max_frame_num = 1<<h->sps.log2_max_frame_num;
2885
2886             if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num;
2887
2888             if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
2889                 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
2890                 if (unwrap_prev_frame_num < 0)
2891                     unwrap_prev_frame_num += max_frame_num;
2892
2893                 h->prev_frame_num = unwrap_prev_frame_num;
2894             }
2895         }
2896
2897         while(h->frame_num !=  h->prev_frame_num && h->prev_frame_num >= 0 &&
2898               h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
2899             Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2900             av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
2901             if (ff_h264_frame_start(h) < 0)
2902                 return -1;
2903             h->prev_frame_num++;
2904             h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
2905             s->current_picture_ptr->frame_num= h->prev_frame_num;
2906             ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
2907             ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
2908             ff_generate_sliding_window_mmcos(h);
2909             if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
2910                 (s->avctx->err_recognition & AV_EF_EXPLODE))
2911                 return AVERROR_INVALIDDATA;
2912             /* Error concealment: if a ref is missing, copy the previous ref in its place.
2913              * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2914              * about there being no actual duplicates.
2915              * FIXME: this doesn't copy padding for out-of-frame motion vectors.  Given we're
2916              * concealing a lost frame, this probably isn't noticeable by comparison, but it should
2917              * be fixed. */
2918             if (h->short_ref_count) {
2919                 if (prev) {
2920                     av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
2921                                   (const uint8_t**)prev->f.data, prev->f.linesize,
2922                                   s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
2923                     h->short_ref[0]->poc = prev->poc+2;
2924                 }
2925                 h->short_ref[0]->frame_num = h->prev_frame_num;
2926             }
2927         }
2928
2929         /* See if we have a decoded first field looking for a pair... */
2930         if (s0->first_field) {
2931             assert(s0->current_picture_ptr);
2932             assert(s0->current_picture_ptr->f.data[0]);
2933             assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
2934
2935             /* figure out if we have a complementary field pair */
2936             if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2937                 /*
2938                  * Previous field is unmatched. Don't display it, but let it
2939                  * remain for reference if marked as such.
2940                  */
2941                 s0->current_picture_ptr = NULL;
2942                 s0->first_field = FIELD_PICTURE;
2943
2944             } else {
2945                 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2946                     ff_thread_report_progress((AVFrame*)s0->current_picture_ptr, INT_MAX,
2947                                               s0->picture_structure==PICT_BOTTOM_FIELD);
2948                     /*
2949                      * This and previous field had
2950                      * different frame_nums. Consider this field first in
2951                      * pair. Throw away previous field except for reference
2952                      * purposes.
2953                      */
2954                     s0->first_field = 1;
2955                     s0->current_picture_ptr = NULL;
2956
2957                 } else {
2958                     /* Second field in complementary pair */
2959                     s0->first_field = 0;
2960                 }
2961             }
2962
2963         } else {
2964             /* Frame or first field in a potentially complementary pair */
2965             assert(!s0->current_picture_ptr);
2966             s0->first_field = FIELD_PICTURE;
2967         }
2968
2969         if(!FIELD_PICTURE || s0->first_field) {
2970             if (ff_h264_frame_start(h) < 0) {
2971                 s0->first_field = 0;
2972                 return -1;
2973             }
2974         } else {
2975             ff_release_unused_pictures(s, 0);
2976         }
2977     }
2978     if(h != h0)
2979         clone_slice(h, h0);
2980
2981     s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2982
2983     assert(s->mb_num == s->mb_width * s->mb_height);
2984     if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2985        first_mb_in_slice                    >= s->mb_num){
2986         av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2987         return -1;
2988     }
2989     s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2990     s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2991     if (s->picture_structure == PICT_BOTTOM_FIELD)
2992         s->resync_mb_y = s->mb_y = s->mb_y + 1;
2993     assert(s->mb_y < s->mb_height);
2994
2995     if(s->picture_structure==PICT_FRAME){
2996         h->curr_pic_num=   h->frame_num;
2997         h->max_pic_num= 1<< h->sps.log2_max_frame_num;
2998     }else{
2999         h->curr_pic_num= 2*h->frame_num + 1;
3000         h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
3001     }
3002
3003     if(h->nal_unit_type == NAL_IDR_SLICE){
3004         get_ue_golomb(&s->gb); /* idr_pic_id */
3005     }
3006
3007     if(h->sps.poc_type==0){
3008         h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3009
3010         if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
3011             h->delta_poc_bottom= get_se_golomb(&s->gb);
3012         }
3013     }
3014
3015     if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
3016         h->delta_poc[0]= get_se_golomb(&s->gb);
3017
3018         if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
3019             h->delta_poc[1]= get_se_golomb(&s->gb);
3020     }
3021
3022     init_poc(h);
3023
3024     if(h->pps.redundant_pic_cnt_present){
3025         h->redundant_pic_count= get_ue_golomb(&s->gb);
3026     }
3027
3028     //set defaults, might be overridden a few lines later
3029     h->ref_count[0]= h->pps.ref_count[0];
3030     h->ref_count[1]= h->pps.ref_count[1];
3031
3032     if(h->slice_type_nos != AV_PICTURE_TYPE_I){
3033         unsigned max= (16<<(s->picture_structure != PICT_FRAME))-1;
3034         if(h->slice_type_nos == AV_PICTURE_TYPE_B){
3035             h->direct_spatial_mv_pred= get_bits1(&s->gb);
3036         }
3037         num_ref_idx_active_override_flag= get_bits1(&s->gb);
3038
3039         if(num_ref_idx_active_override_flag){
3040             h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
3041             if(h->slice_type_nos==AV_PICTURE_TYPE_B)
3042                 h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
3043
3044         }
3045         if(h->ref_count[0]-1 > max || h->ref_count[1]-1 > max){
3046             av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3047             h->ref_count[0]= h->ref_count[1]= 1;
3048             return -1;
3049         }
3050         if(h->slice_type_nos == AV_PICTURE_TYPE_B)
3051             h->list_count= 2;
3052         else
3053             h->list_count= 1;
3054     }else
3055         h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
3056
3057     if(!default_ref_list_done){
3058         ff_h264_fill_default_ref_list(h);
3059     }
3060
3061     if(h->slice_type_nos!=AV_PICTURE_TYPE_I && ff_h264_decode_ref_pic_list_reordering(h) < 0) {
3062         h->ref_count[1]= h->ref_count[0]= 0;
3063         return -1;
3064     }
3065
3066     if(h->slice_type_nos!=AV_PICTURE_TYPE_I){
3067         s->last_picture_ptr= &h->ref_list[0][0];
3068         ff_copy_picture(&s->last_picture, s->last_picture_ptr);
3069     }
3070     if(h->slice_type_nos==AV_PICTURE_TYPE_B){
3071         s->next_picture_ptr= &h->ref_list[1][0];
3072         ff_copy_picture(&s->next_picture, s->next_picture_ptr);
3073     }
3074
3075     if(   (h->pps.weighted_pred          && h->slice_type_nos == AV_PICTURE_TYPE_P )
3076        ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== AV_PICTURE_TYPE_B ) )
3077         pred_weight_table(h);
3078     else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
3079         implicit_weight_table(h, -1);
3080     }else {
3081         h->use_weight = 0;
3082         for (i = 0; i < 2; i++) {
3083             h->luma_weight_flag[i]   = 0;
3084             h->chroma_weight_flag[i] = 0;
3085         }
3086     }
3087
3088     if(h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
3089        (s->avctx->err_recognition & AV_EF_EXPLODE))
3090         return AVERROR_INVALIDDATA;
3091
3092     if(FRAME_MBAFF){
3093         ff_h264_fill_mbaff_ref_list(h);
3094
3095         if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
3096             implicit_weight_table(h, 0);
3097             implicit_weight_table(h, 1);
3098         }
3099     }
3100
3101     if(h->slice_type_nos==AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3102         ff_h264_direct_dist_scale_factor(h);
3103     ff_h264_direct_ref_list_init(h);
3104
3105     if( h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac ){
3106         tmp = get_ue_golomb_31(&s->gb);
3107         if(tmp > 2){
3108             av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3109             return -1;
3110         }
3111         h->cabac_init_idc= tmp;
3112     }
3113
3114     h->last_qscale_diff = 0;
3115     tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3116     if(tmp>51+6*(h->sps.bit_depth_luma-8)){
3117         av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3118         return -1;
3119     }
3120     s->qscale= tmp;
3121     h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3122     h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3123     //FIXME qscale / qp ... stuff
3124     if(h->slice_type == AV_PICTURE_TYPE_SP){
3125         get_bits1(&s->gb); /* sp_for_switch_flag */
3126     }
3127     if(h->slice_type==AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI){
3128         get_se_golomb(&s->gb); /* slice_qs_delta */
3129     }
3130
3131     h->deblocking_filter = 1;
3132     h->slice_alpha_c0_offset = 52;
3133     h->slice_beta_offset = 52;
3134     if( h->pps.deblocking_filter_parameters_present ) {
3135         tmp= get_ue_golomb_31(&s->gb);
3136         if(tmp > 2){
3137             av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
3138             return -1;
3139         }
3140         h->deblocking_filter= tmp;
3141         if(h->deblocking_filter < 2)
3142             h->deblocking_filter^= 1; // 1<->0
3143
3144         if( h->deblocking_filter ) {
3145             h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
3146             h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
3147             if(   h->slice_alpha_c0_offset > 104U
3148                || h->slice_beta_offset     > 104U){
3149                 av_log(s->avctx, AV_LOG_ERROR, "deblocking filter parameters %d %d out of range\n", h->slice_alpha_c0_offset, h->slice_beta_offset);
3150                 return -1;
3151             }
3152         }
3153     }
3154
3155     if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
3156        ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I)
3157        ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == AV_PICTURE_TYPE_B)
3158        ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
3159         h->deblocking_filter= 0;
3160
3161     if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
3162         if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
3163             /* Cheat slightly for speed:
3164                Do not bother to deblock across slices. */
3165             h->deblocking_filter = 2;
3166         } else {
3167             h0->max_contexts = 1;
3168             if(!h0->single_decode_warning) {
3169                 av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3170                 h0->single_decode_warning = 1;
3171             }
3172             if (h != h0) {
3173                 av_log(h->s.avctx, AV_LOG_ERROR, "Deblocking switched inside frame.\n");
3174                 return 1;
3175             }
3176         }
3177     }
3178     h->qp_thresh = 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset)
3179                  - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1])
3180                  + 6 * (h->sps.bit_depth_luma - 8);
3181
3182 #if 0 //FMO
3183     if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
3184         slice_group_change_cycle= get_bits(&s->gb, ?);
3185 #endif
3186
3187     h0->last_slice_type = slice_type;
3188     h->slice_num = ++h0->current_slice;
3189
3190     if(h->slice_num)
3191         h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
3192     if (   h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
3193         && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
3194         && h->slice_num >= MAX_SLICES) {
3195         //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3196         av_log(s->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
3197     }
3198
3199     for(j=0; j<2; j++){
3200         int id_list[16];
3201         int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
3202         for(i=0; i<16; i++){
3203             id_list[i]= 60;
3204             if (h->ref_list[j][i].f.data[0]) {
3205                 int k;
3206                 uint8_t *base = h->ref_list[j][i].f.base[0];
3207                 for(k=0; k<h->short_ref_count; k++)
3208                     if (h->short_ref[k]->f.base[0] == base) {
3209                         id_list[i]= k;
3210                         break;
3211                     }
3212                 for(k=0; k<h->long_ref_count; k++)
3213                     if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3214                         id_list[i]= h->short_ref_count + k;
3215                         break;
3216                     }
3217             }
3218         }
3219
3220         ref2frm[0]=
3221         ref2frm[1]= -1;
3222         for(i=0; i<16; i++)
3223             ref2frm[i+2]= 4*id_list[i]
3224                           + (h->ref_list[j][i].f.reference & 3);
3225         ref2frm[18+0]=
3226         ref2frm[18+1]= -1;
3227         for(i=16; i<48; i++)
3228             ref2frm[i+4]= 4*id_list[(i-16)>>1]
3229                           + (h->ref_list[j][i].f.reference & 3);
3230     }
3231
3232     //FIXME: fix draw_edges+PAFF+frame threads
3233     h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE || (!h->sps.frame_mbs_only_flag && s->avctx->active_thread_type)) ? 0 : 16;
3234     h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3235
3236     if(s->avctx->debug&FF_DEBUG_PICT_INFO){
3237         av_log(h->s.avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
3238                h->slice_num,
3239                (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
3240                first_mb_in_slice,
3241                av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3242                pps_id, h->frame_num,
3243                s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
3244                h->ref_count[0], h->ref_count[1],
3245                s->qscale,
3246                h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
3247                h->use_weight,
3248                h->use_weight==1 && h->use_weight_chroma ? "c" : "",
3249                h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
3250                );
3251     }
3252
3253     return 0;
3254 }
3255
3256 int ff_h264_get_slice_type(const H264Context *h)
3257 {
3258     switch (h->slice_type) {
3259     case AV_PICTURE_TYPE_P:  return 0;
3260     case AV_PICTURE_TYPE_B:  return 1;
3261     case AV_PICTURE_TYPE_I:  return 2;
3262     case AV_PICTURE_TYPE_SP: return 3;
3263     case AV_PICTURE_TYPE_SI: return 4;
3264     default:         return -1;
3265     }
3266 }
3267
3268 static av_always_inline void fill_filter_caches_inter(H264Context *h, MpegEncContext * const s, int mb_type, int top_xy,
3269                                                       int left_xy[LEFT_MBS], int top_type, int left_type[LEFT_MBS], int mb_xy, int list)
3270 {
3271     int b_stride = h->b_stride;
3272     int16_t (*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3273     int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3274     if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
3275         if(USES_LIST(top_type, list)){
3276             const int b_xy= h->mb2b_xy[top_xy] + 3*b_stride;
3277             const int b8_xy= 4*top_xy + 2;
3278             int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
3279             AV_COPY128(mv_dst - 1*8, s->current_picture.f.motion_val[list][b_xy + 0]);
3280             ref_cache[0 - 1*8]=
3281             ref_cache[1 - 1*8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
3282             ref_cache[2 - 1*8]=
3283             ref_cache[3 - 1*8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
3284         }else{
3285             AV_ZERO128(mv_dst - 1*8);
3286             AV_WN32A(&ref_cache[0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3287         }
3288
3289         if(!IS_INTERLACED(mb_type^left_type[LTOP])){
3290             if(USES_LIST(left_type[LTOP], list)){
3291                 const int b_xy= h->mb2b_xy[left_xy[LTOP]] + 3;
3292                 const int b8_xy= 4*left_xy[LTOP] + 1;
3293                 int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[LTOP]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
3294                 AV_COPY32(mv_dst - 1 +  0, s->current_picture.f.motion_val[list][b_xy + b_stride*0]);
3295                 AV_COPY32(mv_dst - 1 +  8, s->current_picture.f.motion_val[list][b_xy + b_stride*1]);
3296                 AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride*2]);
3297                 AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride*3]);
3298                 ref_cache[-1 +  0]=
3299                 ref_cache[-1 +  8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2*0]];
3300                 ref_cache[-1 + 16]=
3301                 ref_cache[-1 + 24]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2*1]];
3302             }else{
3303                 AV_ZERO32(mv_dst - 1 + 0);
3304                 AV_ZERO32(mv_dst - 1 + 8);
3305                 AV_ZERO32(mv_dst - 1 +16);
3306                 AV_ZERO32(mv_dst - 1 +24);
3307                 ref_cache[-1 +  0]=
3308                 ref_cache[-1 +  8]=
3309                 ref_cache[-1 + 16]=
3310                 ref_cache[-1 + 24]= LIST_NOT_USED;
3311             }
3312         }
3313     }
3314
3315     if(!USES_LIST(mb_type, list)){
3316         fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0,0), 4);
3317         AV_WN32A(&ref_cache[0*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3318         AV_WN32A(&ref_cache[1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3319         AV_WN32A(&ref_cache[2*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3320         AV_WN32A(&ref_cache[3*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
3321         return;
3322     }
3323
3324     {
3325         int8_t *ref = &s->current_picture.f.ref_index[list][4*mb_xy];
3326         int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
3327         uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101;
3328         uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]],ref2frm[list][ref[3]])&0x00FF00FF)*0x0101;
3329         AV_WN32A(&ref_cache[0*8], ref01);
3330         AV_WN32A(&ref_cache[1*8], ref01);
3331         AV_WN32A(&ref_cache[2*8], ref23);
3332         AV_WN32A(&ref_cache[3*8], ref23);
3333     }
3334
3335     {
3336         int16_t (*mv_src)[2] = &s->current_picture.f.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
3337         AV_COPY128(mv_dst + 8*0, mv_src + 0*b_stride);
3338         AV_COPY128(mv_dst + 8*1, mv_src + 1*b_stride);
3339         AV_COPY128(mv_dst + 8*2, mv_src + 2*b_stride);
3340         AV_COPY128(mv_dst + 8*3, mv_src + 3*b_stride);
3341     }
3342 }
3343
3344 /**
3345  *
3346  * @return non zero if the loop filter can be skipped
3347  */
3348 static int fill_filter_caches(H264Context *h, int mb_type){
3349     MpegEncContext * const s = &h->s;
3350     const int mb_xy= h->mb_xy;
3351     int top_xy, left_xy[LEFT_MBS];
3352     int top_type, left_type[LEFT_MBS];
3353     uint8_t *nnz;
3354     uint8_t *nnz_cache;
3355
3356     top_xy     = mb_xy  - (s->mb_stride << MB_FIELD);
3357
3358     /* Wow, what a mess, why didn't they simplify the interlacing & intra
3359      * stuff, I can't imagine that these complex rules are worth it. */
3360
3361     left_xy[LBOT] = left_xy[LTOP] = mb_xy-1;
3362     if(FRAME_MBAFF){
3363         const int left_mb_field_flag     = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
3364         const int curr_mb_field_flag     = IS_INTERLACED(mb_type);
3365         if(s->mb_y&1){
3366             if (left_mb_field_flag != curr_mb_field_flag) {
3367                 left_xy[LTOP] -= s->mb_stride;
3368             }
3369         }else{
3370             if(curr_mb_field_flag){
3371                 top_xy += s->mb_stride & (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
3372             }
3373             if (left_mb_field_flag != curr_mb_field_flag) {
3374                 left_xy[LBOT] += s->mb_stride;
3375             }
3376         }
3377     }
3378
3379     h->top_mb_xy = top_xy;
3380     h->left_mb_xy[LTOP] = left_xy[LTOP];
3381     h->left_mb_xy[LBOT] = left_xy[LBOT];
3382     {
3383         //for sufficiently low qp, filtering wouldn't do anything
3384         //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
3385         int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
3386         int qp = s->current_picture.f.qscale_table[mb_xy];
3387         if(qp <= qp_thresh
3388            && (left_xy[LTOP] < 0 || ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh)
3389            && (top_xy        < 0 || ((qp + s->current_picture.f.qscale_table[top_xy       ] + 1) >> 1) <= qp_thresh)) {
3390             if(!FRAME_MBAFF)
3391                 return 1;
3392             if ((left_xy[LTOP] < 0            || ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]        ] + 1) >> 1) <= qp_thresh) &&
3393                 (top_xy        < s->mb_stride || ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
3394                 return 1;
3395         }
3396     }
3397
3398     top_type        = s->current_picture.f.mb_type[top_xy];
3399     left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
3400     left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
3401     if(h->deblocking_filter == 2){
3402         if(h->slice_table[top_xy       ] != h->slice_num) top_type= 0;
3403         if(h->slice_table[left_xy[LBOT]] != h->slice_num) left_type[LTOP]= left_type[LBOT]= 0;
3404     }else{
3405         if(h->slice_table[top_xy       ] == 0xFFFF) top_type= 0;
3406         if(h->slice_table[left_xy[LBOT]] == 0xFFFF) left_type[LTOP]= left_type[LBOT] =0;
3407     }
3408     h->top_type       = top_type;
3409     h->left_type[LTOP]= left_type[LTOP];
3410     h->left_type[LBOT]= left_type[LBOT];
3411
3412     if(IS_INTRA(mb_type))
3413         return 0;
3414
3415     fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 0);
3416     if(h->list_count == 2)
3417         fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 1);
3418
3419     nnz = h->non_zero_count[mb_xy];
3420     nnz_cache = h->non_zero_count_cache;
3421     AV_COPY32(&nnz_cache[4+8*1], &nnz[ 0]);
3422     AV_COPY32(&nnz_cache[4+8*2], &nnz[ 4]);
3423     AV_COPY32(&nnz_cache[4+8*3], &nnz[ 8]);
3424     AV_COPY32(&nnz_cache[4+8*4], &nnz[12]);
3425     h->cbp= h->cbp_table[mb_xy];
3426
3427     if(top_type){
3428         nnz = h->non_zero_count[top_xy];
3429         AV_COPY32(&nnz_cache[4+8*0], &nnz[3*4]);
3430     }
3431
3432     if(left_type[LTOP]){
3433         nnz = h->non_zero_count[left_xy[LTOP]];
3434         nnz_cache[3+8*1]= nnz[3+0*4];
3435         nnz_cache[3+8*2]= nnz[3+1*4];
3436         nnz_cache[3+8*3]= nnz[3+2*4];
3437         nnz_cache[3+8*4]= nnz[3+3*4];
3438     }
3439
3440     // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
3441     if(!CABAC && h->pps.transform_8x8_mode){
3442         if(IS_8x8DCT(top_type)){
3443             nnz_cache[4+8*0]=
3444             nnz_cache[5+8*0]= (h->cbp_table[top_xy] & 0x4000) >> 12;
3445             nnz_cache[6+8*0]=
3446             nnz_cache[7+8*0]= (h->cbp_table[top_xy] & 0x8000) >> 12;
3447         }
3448         if(IS_8x8DCT(left_type[LTOP])){
3449             nnz_cache[3+8*1]=
3450             nnz_cache[3+8*2]= (h->cbp_table[left_xy[LTOP]]&0x2000) >> 12; //FIXME check MBAFF
3451         }
3452         if(IS_8x8DCT(left_type[LBOT])){
3453             nnz_cache[3+8*3]=
3454             nnz_cache[3+8*4