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