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