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