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