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