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