h264: add an assert that copied pictures are valid picture pointers
[ffmpeg:ffmpeg-mt.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     av_freep(&h->intra4x4_pred_mode);
768     av_freep(&h->chroma_pred_mode_table);
769     av_freep(&h->cbp_table);
770     av_freep(&h->mvd_table[0]);
771     av_freep(&h->mvd_table[1]);
772     av_freep(&h->direct_table);
773     av_freep(&h->non_zero_count);
774     av_freep(&h->slice_table_base);
775     h->slice_table= NULL;
776     av_freep(&h->list_counts);
777
778     av_freep(&h->mb2b_xy);
779     av_freep(&h->mb2br_xy);
780
781     for(i = 0; i < MAX_THREADS; i++) {
782         hx = h->thread_context[i];
783         if(!hx) continue;
784         av_freep(&hx->top_borders[1]);
785         av_freep(&hx->top_borders[0]);
786         av_freep(&hx->s.obmc_scratchpad);
787         if (free_rbsp){
788             av_freep(&hx->rbsp_buffer[1]);
789             av_freep(&hx->rbsp_buffer[0]);
790             hx->rbsp_buffer_size[0] = 0;
791             hx->rbsp_buffer_size[1] = 0;
792         }
793         if (i) av_freep(&h->thread_context[i]);
794     }
795 }
796
797 static void init_dequant8_coeff_table(H264Context *h){
798     int i,q,x;
799     const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
800     h->dequant8_coeff[0] = h->dequant8_buffer[0];
801     h->dequant8_coeff[1] = h->dequant8_buffer[1];
802
803     for(i=0; i<2; i++ ){
804         if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
805             h->dequant8_coeff[1] = h->dequant8_buffer[0];
806             break;
807         }
808
809         for(q=0; q<max_qp+1; q++){
810             int shift = div6[q];
811             int idx = rem6[q];
812             for(x=0; x<64; x++)
813                 h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
814                     ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
815                     h->pps.scaling_matrix8[i][x]) << shift;
816         }
817     }
818 }
819
820 static void init_dequant4_coeff_table(H264Context *h){
821     int i,j,q,x;
822     const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
823     for(i=0; i<6; i++ ){
824         h->dequant4_coeff[i] = h->dequant4_buffer[i];
825         for(j=0; j<i; j++){
826             if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
827                 h->dequant4_coeff[i] = h->dequant4_buffer[j];
828                 break;
829             }
830         }
831         if(j<i)
832             continue;
833
834         for(q=0; q<max_qp+1; q++){
835             int shift = div6[q] + 2;
836             int idx = rem6[q];
837             for(x=0; x<16; x++)
838                 h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
839                     ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
840                     h->pps.scaling_matrix4[i][x]) << shift;
841         }
842     }
843 }
844
845 static void init_dequant_tables(H264Context *h){
846     int i,x;
847     init_dequant4_coeff_table(h);
848     if(h->pps.transform_8x8_mode)
849         init_dequant8_coeff_table(h);
850     if(h->sps.transform_bypass){
851         for(i=0; i<6; i++)
852             for(x=0; x<16; x++)
853                 h->dequant4_coeff[i][0][x] = 1<<6;
854         if(h->pps.transform_8x8_mode)
855             for(i=0; i<2; i++)
856                 for(x=0; x<64; x++)
857                     h->dequant8_coeff[i][0][x] = 1<<6;
858     }
859 }
860
861
862 int ff_h264_alloc_tables(H264Context *h){
863     MpegEncContext * const s = &h->s;
864     const int big_mb_num= s->mb_stride * (s->mb_height+1);
865     const int row_mb_num= 2*s->mb_stride*s->avctx->thread_count;
866     int x,y;
867
868     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode, row_mb_num * 8  * sizeof(uint8_t), fail)
869
870     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count    , big_mb_num * 32 * sizeof(uint8_t), fail)
871     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
872     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
873
874     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
875     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
876     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
877     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
878     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
879
880     memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(*h->slice_table_base));
881     h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
882
883     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy  , big_mb_num * sizeof(uint32_t), fail);
884     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy , big_mb_num * sizeof(uint32_t), fail);
885     for(y=0; y<s->mb_height; y++){
886         for(x=0; x<s->mb_width; x++){
887             const int mb_xy= x + y*s->mb_stride;
888             const int b_xy = 4*x + 4*y*h->b_stride;
889
890             h->mb2b_xy [mb_xy]= b_xy;
891             h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
892         }
893     }
894
895     s->obmc_scratchpad = NULL;
896
897     if(!h->dequant4_coeff[0])
898         init_dequant_tables(h);
899
900     return 0;
901 fail:
902     free_tables(h, 1);
903     return -1;
904 }
905
906 /**
907  * Mimic alloc_tables(), but for every context thread.
908  */
909 static void clone_tables(H264Context *dst, H264Context *src, int i){
910     MpegEncContext * const s = &src->s;
911     dst->intra4x4_pred_mode       = src->intra4x4_pred_mode + i*8*2*s->mb_stride;
912     dst->non_zero_count           = src->non_zero_count;
913     dst->slice_table              = src->slice_table;
914     dst->cbp_table                = src->cbp_table;
915     dst->mb2b_xy                  = src->mb2b_xy;
916     dst->mb2br_xy                 = src->mb2br_xy;
917     dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;
918     dst->mvd_table[0]             = src->mvd_table[0] + i*8*2*s->mb_stride;
919     dst->mvd_table[1]             = src->mvd_table[1] + i*8*2*s->mb_stride;
920     dst->direct_table             = src->direct_table;
921     dst->list_counts              = src->list_counts;
922
923     dst->s.obmc_scratchpad = NULL;
924     ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma);
925 }
926
927 /**
928  * Init context
929  * Allocate buffers which are not shared amongst multiple threads.
930  */
931 static int context_init(H264Context *h){
932     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t)*2, fail)
933     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t)*2, fail)
934
935     h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
936     h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
937
938     return 0;
939 fail:
940     return -1; // free_tables will clean up for us
941 }
942
943 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
944
945 static av_cold void common_init(H264Context *h){
946     MpegEncContext * const s = &h->s;
947
948     s->width = s->avctx->width;
949     s->height = s->avctx->height;
950     s->codec_id= s->avctx->codec->id;
951
952     ff_h264dsp_init(&h->h264dsp, 8);
953     ff_h264_pred_init(&h->hpc, s->codec_id, 8);
954
955     h->dequant_coeff_pps= -1;
956     s->unrestricted_mv=1;
957     s->decode=1; //FIXME
958
959     dsputil_init(&s->dsp, s->avctx); // needed so that idct permutation is known early
960
961     memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
962     memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
963 }
964
965 int ff_h264_decode_extradata(H264Context *h)
966 {
967     AVCodecContext *avctx = h->s.avctx;
968
969     if(*(char *)avctx->extradata == 1){
970         int i, cnt, nalsize;
971         unsigned char *p = avctx->extradata;
972
973         h->is_avc = 1;
974
975         if(avctx->extradata_size < 7) {
976             av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
977             return -1;
978         }
979         /* sps and pps in the avcC always have length coded with 2 bytes,
980            so put a fake nal_length_size = 2 while parsing them */
981         h->nal_length_size = 2;
982         // Decode sps from avcC
983         cnt = *(p+5) & 0x1f; // Number of sps
984         p += 6;
985         for (i = 0; i < cnt; i++) {
986             nalsize = AV_RB16(p) + 2;
987             if(decode_nal_units(h, p, nalsize) < 0) {
988                 av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
989                 return -1;
990             }
991             p += nalsize;
992         }
993         // Decode pps from avcC
994         cnt = *(p++); // Number of pps
995         for (i = 0; i < cnt; i++) {
996             nalsize = AV_RB16(p) + 2;
997             if(decode_nal_units(h, p, nalsize)  != nalsize) {
998                 av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
999                 return -1;
1000             }
1001             p += nalsize;
1002         }
1003         // Now store right nal length size, that will be use to parse all other nals
1004         h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
1005     } else {
1006         h->is_avc = 0;
1007         if(decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
1008             return -1;
1009     }
1010     return 0;
1011 }
1012
1013 av_cold int ff_h264_decode_init(AVCodecContext *avctx){
1014     H264Context *h= avctx->priv_data;
1015     MpegEncContext * const s = &h->s;
1016
1017     MPV_decode_defaults(s);
1018
1019     s->avctx = avctx;
1020     common_init(h);
1021
1022     s->out_format = FMT_H264;
1023     s->workaround_bugs= avctx->workaround_bugs;
1024
1025     // set defaults
1026 //    s->decode_mb= ff_h263_decode_mb;
1027     s->quarter_sample = 1;
1028     if(!avctx->has_b_frames)
1029     s->low_delay= 1;
1030
1031     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1032
1033     ff_h264_decode_init_vlc();
1034
1035     h->pixel_shift = 0;
1036     h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1037
1038     h->thread_context[0] = h;
1039     h->outputed_poc = h->next_outputed_poc = INT_MIN;
1040     h->prev_poc_msb= 1<<16;
1041     h->x264_build = -1;
1042     ff_h264_reset_sei(h);
1043     if(avctx->codec_id == CODEC_ID_H264){
1044         if(avctx->ticks_per_frame == 1){
1045             s->avctx->time_base.den *=2;
1046         }
1047         avctx->ticks_per_frame = 2;
1048     }
1049
1050     if(avctx->extradata_size > 0 && avctx->extradata &&
1051         ff_h264_decode_extradata(h))
1052         return -1;
1053
1054     if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1055         s->avctx->has_b_frames = h->sps.num_reorder_frames;
1056         s->low_delay = 0;
1057     }
1058
1059     return 0;
1060 }
1061
1062 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b)+(size))))
1063 static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
1064 {
1065     int i;
1066
1067     for (i=0; i<count; i++){
1068         assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1069                 IN_RANGE(from[i], old_base->picture, sizeof(Picture) * old_base->picture_count) ||
1070                 !from[i]));
1071         to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1072     }
1073 }
1074
1075 static void copy_parameter_set(void **to, void **from, int count, int size)
1076 {
1077     int i;
1078
1079     for (i=0; i<count; i++){
1080         if (to[i] && !from[i]) av_freep(&to[i]);
1081         else if (from[i] && !to[i]) to[i] = av_malloc(size);
1082
1083         if (from[i]) memcpy(to[i], from[i], size);
1084     }
1085 }
1086
1087 static int decode_init_thread_copy(AVCodecContext *avctx){
1088     H264Context *h= avctx->priv_data;
1089
1090     if (!avctx->is_copy) return 0;
1091     memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1092     memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1093
1094     return 0;
1095 }
1096
1097 #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
1098 static int decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src){
1099     H264Context *h= dst->priv_data, *h1= src->priv_data;
1100     MpegEncContext * const s = &h->s, * const s1 = &h1->s;
1101     int inited = s->context_initialized, err;
1102     int i;
1103
1104     if(dst == src || !s1->context_initialized) return 0;
1105
1106     err = ff_mpeg_update_thread_context(dst, src);
1107     if(err) return err;
1108
1109     //FIXME handle width/height changing
1110     if(!inited){
1111         for(i = 0; i < MAX_SPS_COUNT; i++)
1112             av_freep(h->sps_buffers + i);
1113
1114         for(i = 0; i < MAX_PPS_COUNT; i++)
1115             av_freep(h->pps_buffers + i);
1116
1117         memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
1118         memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1119         memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1120         ff_h264_alloc_tables(h);
1121         context_init(h);
1122
1123         for(i=0; i<2; i++){
1124             h->rbsp_buffer[i] = NULL;
1125             h->rbsp_buffer_size[i] = 0;
1126         }
1127
1128         h->thread_context[0] = h;
1129
1130         // frame_start may not be called for the next thread (if it's decoding a bottom field)
1131         // so this has to be allocated here
1132         h->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
1133
1134         s->dsp.clear_blocks(h->mb);
1135     }
1136
1137     //extradata/NAL handling
1138     h->is_avc          = h1->is_avc;
1139
1140     //SPS/PPS
1141     copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
1142     h->sps             = h1->sps;
1143     copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
1144     h->pps             = h1->pps;
1145
1146     //Dequantization matrices
1147     //FIXME these are big - can they be only copied when PPS changes?
1148     copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1149
1150     for(i=0; i<6; i++)
1151         h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1152
1153     for(i=0; i<2; i++)
1154         h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1155
1156     h->dequant_coeff_pps = h1->dequant_coeff_pps;
1157
1158     //POC timing
1159     copy_fields(h, h1, poc_lsb, redundant_pic_count);
1160
1161     //reference lists
1162     copy_fields(h, h1, ref_count, intra_gb);
1163     copy_fields(h, h1, short_ref, cabac_init_idc);
1164
1165     copy_picture_range(h->short_ref,   h1->short_ref,   32, s, s1);
1166     copy_picture_range(h->long_ref,    h1->long_ref,    32, s, s1);
1167     copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
1168
1169     h->last_slice_type = h1->last_slice_type;
1170
1171     if(!s->current_picture_ptr) return 0;
1172
1173     if(!s->dropable) {
1174         ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1175         h->prev_poc_msb     = h->poc_msb;
1176         h->prev_poc_lsb     = h->poc_lsb;
1177     }
1178     h->prev_frame_num_offset= h->frame_num_offset;
1179     h->prev_frame_num       = h->frame_num;
1180     h->outputed_poc         = h->next_outputed_poc;
1181
1182     return 0;
1183 }
1184
1185 int ff_h264_frame_start(H264Context *h){
1186     MpegEncContext * const s = &h->s;
1187     int i;
1188     const int pixel_shift = h->pixel_shift;
1189
1190     if(MPV_frame_start(s, s->avctx) < 0)
1191         return -1;
1192     ff_er_frame_start(s);
1193     /*
1194      * MPV_frame_start uses pict_type to derive key_frame.
1195      * This is incorrect for H.264; IDR markings must be used.
1196      * Zero here; IDR markings per slice in frame or fields are ORed in later.
1197      * See decode_nal_units().
1198      */
1199     s->current_picture_ptr->key_frame= 0;
1200     s->current_picture_ptr->mmco_reset= 0;
1201
1202     assert(s->linesize && s->uvlinesize);
1203
1204     for(i=0; i<16; i++){
1205         h->block_offset[i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
1206         h->block_offset[24+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
1207     }
1208     for(i=0; i<4; i++){
1209         h->block_offset[16+i]=
1210         h->block_offset[20+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1211         h->block_offset[24+16+i]=
1212         h->block_offset[24+20+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1213     }
1214
1215     /* can't be in alloc_tables because linesize isn't known there.
1216      * FIXME: redo bipred weight to not require extra buffer? */
1217     for(i = 0; i < s->avctx->thread_count; i++)
1218         if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
1219             h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
1220
1221     /* some macroblocks can be accessed before they're available in case of lost slices, mbaff or threading*/
1222     memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(*h->slice_table));
1223
1224 //    s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
1225
1226     // We mark the current picture as non-reference after allocating it, so
1227     // that if we break out due to an error it can be released automatically
1228     // in the next MPV_frame_start().
1229     // SVQ3 as well as most other codecs have only last/next/current and thus
1230     // get released even with set reference, besides SVQ3 and others do not
1231     // mark frames as reference later "naturally".
1232     if(s->codec_id != CODEC_ID_SVQ3)
1233         s->current_picture_ptr->reference= 0;
1234
1235     s->current_picture_ptr->field_poc[0]=
1236     s->current_picture_ptr->field_poc[1]= INT_MAX;
1237
1238     h->next_output_pic = NULL;
1239
1240     assert(s->current_picture_ptr->long_ref==0);
1241
1242     return 0;
1243 }
1244
1245 /**
1246   * Run setup operations that must be run after slice header decoding.
1247   * This includes finding the next displayed frame.
1248   *
1249   * @param h h264 master context
1250   * @param setup_finished enough NALs have been read that we can call
1251   * ff_thread_finish_setup()
1252   */
1253 static void decode_postinit(H264Context *h, int setup_finished){
1254     MpegEncContext * const s = &h->s;
1255     Picture *out = s->current_picture_ptr;
1256     Picture *cur = s->current_picture_ptr;
1257     int i, pics, out_of_order, out_idx;
1258
1259     s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
1260     s->current_picture_ptr->pict_type= s->pict_type;
1261
1262     if (h->next_output_pic) return;
1263
1264     if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
1265         //FIXME: if we have two PAFF fields in one packet, we can't start the next thread here.
1266         //If we have one field per packet, we can. The check in decode_nal_units() is not good enough
1267         //to find this yet, so we assume the worst for now.
1268         //if (setup_finished)
1269         //    ff_thread_finish_setup(s->avctx);
1270         return;
1271     }
1272
1273     cur->interlaced_frame = 0;
1274     cur->repeat_pict = 0;
1275
1276     /* Signal interlacing information externally. */
1277     /* Prioritize picture timing SEI information over used decoding process if it exists. */
1278
1279     if(h->sps.pic_struct_present_flag){
1280         switch (h->sei_pic_struct)
1281         {
1282         case SEI_PIC_STRUCT_FRAME:
1283             break;
1284         case SEI_PIC_STRUCT_TOP_FIELD:
1285         case SEI_PIC_STRUCT_BOTTOM_FIELD:
1286             cur->interlaced_frame = 1;
1287             break;
1288         case SEI_PIC_STRUCT_TOP_BOTTOM:
1289         case SEI_PIC_STRUCT_BOTTOM_TOP:
1290             if (FIELD_OR_MBAFF_PICTURE)
1291                 cur->interlaced_frame = 1;
1292             else
1293                 // try to flag soft telecine progressive
1294                 cur->interlaced_frame = h->prev_interlaced_frame;
1295             break;
1296         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1297         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1298             // Signal the possibility of telecined film externally (pic_struct 5,6)
1299             // From these hints, let the applications decide if they apply deinterlacing.
1300             cur->repeat_pict = 1;
1301             break;
1302         case SEI_PIC_STRUCT_FRAME_DOUBLING:
1303             // Force progressive here, as doubling interlaced frame is a bad idea.
1304             cur->repeat_pict = 2;
1305             break;
1306         case SEI_PIC_STRUCT_FRAME_TRIPLING:
1307             cur->repeat_pict = 4;
1308             break;
1309         }
1310
1311         if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1312             cur->interlaced_frame = (h->sei_ct_type & (1<<1)) != 0;
1313     }else{
1314         /* Derive interlacing flag from used decoding process. */
1315         cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1316     }
1317     h->prev_interlaced_frame = cur->interlaced_frame;
1318
1319     if (cur->field_poc[0] != cur->field_poc[1]){
1320         /* Derive top_field_first from field pocs. */
1321         cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
1322     }else{
1323         if(cur->interlaced_frame || h->sps.pic_struct_present_flag){
1324             /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
1325             if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
1326               || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1327                 cur->top_field_first = 1;
1328             else
1329                 cur->top_field_first = 0;
1330         }else{
1331             /* Most likely progressive */
1332             cur->top_field_first = 0;
1333         }
1334     }
1335
1336     //FIXME do something with unavailable reference frames
1337
1338     /* Sort B-frames into display order */
1339
1340     if(h->sps.bitstream_restriction_flag
1341        && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1342         s->avctx->has_b_frames = h->sps.num_reorder_frames;
1343         s->low_delay = 0;
1344     }
1345
1346     if(   s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
1347        && !h->sps.bitstream_restriction_flag){
1348         s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;
1349         s->low_delay= 0;
1350     }
1351
1352     pics = 0;
1353     while(h->delayed_pic[pics]) pics++;
1354
1355     assert(pics <= MAX_DELAYED_PIC_COUNT);
1356
1357     h->delayed_pic[pics++] = cur;
1358     if(cur->reference == 0)
1359         cur->reference = DELAYED_PIC_REF;
1360
1361     out = h->delayed_pic[0];
1362     out_idx = 0;
1363     for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
1364         if(h->delayed_pic[i]->poc < out->poc){
1365             out = h->delayed_pic[i];
1366             out_idx = i;
1367         }
1368     if(s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset))
1369         h->next_outputed_poc= INT_MIN;
1370     out_of_order = out->poc < h->next_outputed_poc;
1371
1372     if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
1373         { }
1374     else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)
1375        || (s->low_delay &&
1376         ((h->next_outputed_poc != INT_MIN && out->poc > h->next_outputed_poc + 2)
1377          || cur->pict_type == AV_PICTURE_TYPE_B)))
1378     {
1379         s->low_delay = 0;
1380         s->avctx->has_b_frames++;
1381     }
1382
1383     if(out_of_order || pics > s->avctx->has_b_frames){
1384         out->reference &= ~DELAYED_PIC_REF;
1385         out->owner2 = s; // for frame threading, the owner must be the second field's thread
1386                          // or else the first thread can release the picture and reuse it unsafely
1387         for(i=out_idx; h->delayed_pic[i]; i++)
1388             h->delayed_pic[i] = h->delayed_pic[i+1];
1389     }
1390     if(!out_of_order && pics > s->avctx->has_b_frames){
1391         h->next_output_pic = out;
1392         if(out_idx==0 && h->delayed_pic[0] && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset)) {
1393             h->next_outputed_poc = INT_MIN;
1394         } else
1395             h->next_outputed_poc = out->poc;
1396     }else{
1397         av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
1398     }
1399
1400     if (setup_finished)
1401         ff_thread_finish_setup(s->avctx);
1402 }
1403
1404 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){
1405     MpegEncContext * const s = &h->s;
1406     uint8_t *top_border;
1407     int top_idx = 1;
1408     const int pixel_shift = h->pixel_shift;
1409
1410     src_y  -=   linesize;
1411     src_cb -= uvlinesize;
1412     src_cr -= uvlinesize;
1413
1414     if(!simple && FRAME_MBAFF){
1415         if(s->mb_y&1){
1416             if(!MB_MBAFF){
1417                 top_border = h->top_borders[0][s->mb_x];
1418                 AV_COPY128(top_border, src_y + 15*linesize);
1419                 if (pixel_shift)
1420                     AV_COPY128(top_border+16, src_y+15*linesize+16);
1421                 if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1422                     if (pixel_shift) {
1423                         AV_COPY128(top_border+32, src_cb+7*uvlinesize);
1424                         AV_COPY128(top_border+48, src_cr+7*uvlinesize);
1425                     } else {
1426                     AV_COPY64(top_border+16, src_cb+7*uvlinesize);
1427                     AV_COPY64(top_border+24, src_cr+7*uvlinesize);
1428                     }
1429                 }
1430             }
1431         }else if(MB_MBAFF){
1432             top_idx = 0;
1433         }else
1434             return;
1435     }
1436
1437     top_border = h->top_borders[top_idx][s->mb_x];
1438     // There are two lines saved, the line above the the top macroblock of a pair,
1439     // and the line above the bottom macroblock
1440     AV_COPY128(top_border, src_y + 16*linesize);
1441     if (pixel_shift)
1442         AV_COPY128(top_border+16, src_y+16*linesize+16);
1443
1444     if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1445         if (pixel_shift) {
1446             AV_COPY128(top_border+32, src_cb+8*uvlinesize);
1447             AV_COPY128(top_border+48, src_cr+8*uvlinesize);
1448         } else {
1449         AV_COPY64(top_border+16, src_cb+8*uvlinesize);
1450         AV_COPY64(top_border+24, src_cr+8*uvlinesize);
1451         }
1452     }
1453 }
1454
1455 static inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1456                                   uint8_t *src_cb, uint8_t *src_cr,
1457                                   int linesize, int uvlinesize,
1458                                   int xchg, int simple, int pixel_shift){
1459     MpegEncContext * const s = &h->s;
1460     int deblock_left;
1461     int deblock_top;
1462     int top_idx = 1;
1463     uint8_t *top_border_m1;
1464     uint8_t *top_border;
1465
1466     if(!simple && FRAME_MBAFF){
1467         if(s->mb_y&1){
1468             if(!MB_MBAFF)
1469                 return;
1470         }else{
1471             top_idx = MB_MBAFF ? 0 : 1;
1472         }
1473     }
1474
1475     if(h->deblocking_filter == 2) {
1476         deblock_left = h->left_type[0];
1477         deblock_top  = h->top_type;
1478     } else {
1479         deblock_left = (s->mb_x > 0);
1480         deblock_top =  (s->mb_y > !!MB_FIELD);
1481     }
1482
1483     src_y  -=   linesize + 1 + pixel_shift;
1484     src_cb -= uvlinesize + 1 + pixel_shift;
1485     src_cr -= uvlinesize + 1 + pixel_shift;
1486
1487     top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1488     top_border    = h->top_borders[top_idx][s->mb_x];
1489
1490 #define XCHG(a,b,xchg)\
1491     if (pixel_shift) {\
1492         if (xchg) {\
1493             AV_SWAP64(b+0,a+0);\
1494             AV_SWAP64(b+8,a+8);\
1495         } else {\
1496             AV_COPY128(b,a); \
1497         }\
1498     } else \
1499 if (xchg) AV_SWAP64(b,a);\
1500 else      AV_COPY64(b,a);
1501
1502     if(deblock_top){
1503         if(deblock_left){
1504             XCHG(top_border_m1 + (8 << pixel_shift), src_y - (7 << pixel_shift), 1);
1505         }
1506         XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1507         XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1508         if(s->mb_x+1 < s->mb_width){
1509             XCHG(h->top_borders[top_idx][s->mb_x+1], src_y + (17 << pixel_shift), 1);
1510         }
1511     }
1512     if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1513         if(deblock_top){
1514             if(deblock_left){
1515                 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1516                 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1517             }
1518             XCHG(top_border + (16 << pixel_shift), src_cb+1+pixel_shift, 1);
1519             XCHG(top_border + (24 << pixel_shift), src_cr+1+pixel_shift, 1);
1520         }
1521     }
1522 }
1523
1524 static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth, int index) {
1525     if (high_bit_depth) {
1526         return AV_RN32A(((int32_t*)mb) + index);
1527     } else
1528         return AV_RN16A(mb + index);
1529 }
1530
1531 static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth, int index, int value) {
1532     if (high_bit_depth) {
1533         AV_WN32A(((int32_t*)mb) + index, value);
1534     } else
1535         AV_WN16A(mb + index, value);
1536 }
1537
1538 static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple, int pixel_shift){
1539     MpegEncContext * const s = &h->s;
1540     const int mb_x= s->mb_x;
1541     const int mb_y= s->mb_y;
1542     const int mb_xy= h->mb_xy;
1543     const int mb_type= s->current_picture.mb_type[mb_xy];
1544     uint8_t  *dest_y, *dest_cb, *dest_cr;
1545     int linesize, uvlinesize /*dct_offset*/;
1546     int i;
1547     int *block_offset = &h->block_offset[0];
1548     const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
1549     /* is_h264 should always be true if SVQ3 is disabled. */
1550     const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
1551     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1552     void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1553
1554     dest_y  = s->current_picture.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize  ) * 16;
1555     dest_cb = s->current_picture.data[1] + ((mb_x << pixel_shift) + mb_y * s->uvlinesize) * 8;
1556     dest_cr = s->current_picture.data[2] + ((mb_x << pixel_shift) + mb_y * s->uvlinesize) * 8;
1557
1558     s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
1559     s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + (64 << pixel_shift), dest_cr - dest_cb, 2);
1560
1561     h->list_counts[mb_xy]= h->list_count;
1562
1563     if (!simple && MB_FIELD) {
1564         linesize   = h->mb_linesize   = s->linesize * 2;
1565         uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
1566         block_offset = &h->block_offset[24];
1567         if(mb_y&1){ //FIXME move out of this function?
1568             dest_y -= s->linesize*15;
1569             dest_cb-= s->uvlinesize*7;
1570             dest_cr-= s->uvlinesize*7;
1571         }
1572         if(FRAME_MBAFF) {
1573             int list;
1574             for(list=0; list<h->list_count; list++){
1575                 if(!USES_LIST(mb_type, list))
1576                     continue;
1577                 if(IS_16X16(mb_type)){
1578                     int8_t *ref = &h->ref_cache[list][scan8[0]];
1579                     fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
1580                 }else{
1581                     for(i=0; i<16; i+=4){
1582                         int ref = h->ref_cache[list][scan8[i]];
1583                         if(ref >= 0)
1584                             fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
1585                     }
1586                 }
1587             }
1588         }
1589     } else {
1590         linesize   = h->mb_linesize   = s->linesize;
1591         uvlinesize = h->mb_uvlinesize = s->uvlinesize;
1592 //        dct_offset = s->linesize * 16;
1593     }
1594
1595     if (!simple && IS_INTRA_PCM(mb_type)) {
1596         if (pixel_shift) {
1597             const int bit_depth = h->sps.bit_depth_luma;
1598             int j;
1599             GetBitContext gb;
1600             init_get_bits(&gb, (uint8_t*)h->mb, 384*bit_depth);
1601
1602             for (i = 0; i < 16; i++) {
1603                 uint16_t *tmp_y  = (uint16_t*)(dest_y  + i*linesize);
1604                 for (j = 0; j < 16; j++)
1605                     tmp_y[j] = get_bits(&gb, bit_depth);
1606             }
1607             for (i = 0; i < 8; i++) {
1608                 uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
1609                 for (j = 0; j < 8; j++)
1610                     tmp_cb[j] = get_bits(&gb, bit_depth);
1611             }
1612             for (i = 0; i < 8; i++) {
1613                 uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
1614                 for (j = 0; j < 8; j++)
1615                     tmp_cr[j] = get_bits(&gb, bit_depth);
1616             }
1617         } else {
1618         for (i=0; i<16; i++) {
1619             memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
1620         }
1621         for (i=0; i<8; i++) {
1622             memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4,  8);
1623             memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4,  8);
1624         }
1625         }
1626     } else {
1627         if(IS_INTRA(mb_type)){
1628             if(h->deblocking_filter)
1629                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple, pixel_shift);
1630
1631             if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1632                 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
1633                 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
1634             }
1635
1636             if(IS_INTRA4x4(mb_type)){
1637                 if(simple || !s->encoding){
1638                     if(IS_8x8DCT(mb_type)){
1639                         if(transform_bypass){
1640                             idct_dc_add =
1641                             idct_add    = s->dsp.add_pixels8;
1642                         }else{
1643                             idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1644                             idct_add    = h->h264dsp.h264_idct8_add;
1645                         }
1646                         for(i=0; i<16; i+=4){
1647                             uint8_t * const ptr= dest_y + block_offset[i];
1648                             const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1649                             if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1650                                 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i*16 << pixel_shift), linesize);
1651                             }else{
1652                                 const int nnz = h->non_zero_count_cache[ scan8[i] ];
1653                                 h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
1654                                                             (h->topright_samples_available<<i)&0x4000, linesize);
1655                                 if(nnz){
1656                                     if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16))
1657                                         idct_dc_add(ptr, h->mb + (i*16 << pixel_shift), linesize);
1658                                     else
1659                                         idct_add   (ptr, h->mb + (i*16 << pixel_shift), linesize);
1660                                 }
1661                             }
1662                         }
1663                     }else{
1664                         if(transform_bypass){
1665                             idct_dc_add =
1666                             idct_add    = s->dsp.add_pixels4;
1667                         }else{
1668                             idct_dc_add = h->h264dsp.h264_idct_dc_add;
1669                             idct_add    = h->h264dsp.h264_idct_add;
1670                         }
1671                         for(i=0; i<16; i++){
1672                             uint8_t * const ptr= dest_y + block_offset[i];
1673                             const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1674
1675                             if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1676                                 h->hpc.pred4x4_add[dir](ptr, h->mb + (i*16 << pixel_shift), linesize);
1677                             }else{
1678                                 uint8_t *topright;
1679                                 int nnz, tr;
1680                                 uint64_t tr_high;
1681                                 if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
1682                                     const int topright_avail= (h->topright_samples_available<<i)&0x8000;
1683                                     assert(mb_y || linesize <= block_offset[i]);
1684                                     if(!topright_avail){
1685                                         if (pixel_shift) {
1686                                             tr_high= ((uint16_t*)ptr)[3 - linesize/2]*0x0001000100010001ULL;
1687                                             topright= (uint8_t*) &tr_high;
1688                                         } else {
1689                                         tr= ptr[3 - linesize]*0x01010101;
1690                                         topright= (uint8_t*) &tr;
1691                                         }
1692                                     }else
1693                                         topright= ptr + (4 << pixel_shift) - linesize;
1694                                 }else
1695                                     topright= NULL;
1696
1697                                 h->hpc.pred4x4[ dir ](ptr, topright, linesize);
1698                                 nnz = h->non_zero_count_cache[ scan8[i] ];
1699                                 if(nnz){
1700                                     if(is_h264){
1701                                         if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16))
1702                                             idct_dc_add(ptr, h->mb + (i*16 << pixel_shift), linesize);
1703                                         else
1704                                             idct_add   (ptr, h->mb + (i*16 << pixel_shift), linesize);
1705                                     }else
1706                                         ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
1707                                 }
1708                             }
1709                         }
1710                     }
1711                 }
1712             }else{
1713                 h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
1714                 if(is_h264){
1715                     if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX] ]){
1716                         if(!transform_bypass)
1717                             h->h264dsp.h264_luma_dc_dequant_idct(h->mb, h->mb_luma_dc, h->dequant4_coeff[0][s->qscale][0]);
1718                         else{
1719                             static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
1720                                                                     8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
1721                             for(i = 0; i < 16; i++)
1722                                 dctcoef_set(h->mb, pixel_shift, dc_mapping[i], dctcoef_get(h->mb_luma_dc, pixel_shift, i));
1723                         }
1724                     }
1725                 }else
1726                     ff_svq3_luma_dc_dequant_idct_c(h->mb, h->mb_luma_dc, s->qscale);
1727             }
1728             if(h->deblocking_filter)
1729                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple, pixel_shift);
1730         }else if(is_h264){
1731             if (pixel_shift) {
1732                 hl_motion_16(h, dest_y, dest_cb, dest_cr,
1733                              s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
1734                              s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
1735                              h->h264dsp.weight_h264_pixels_tab,
1736                              h->h264dsp.biweight_h264_pixels_tab);
1737             } else
1738                 hl_motion_8(h, dest_y, dest_cb, dest_cr,
1739                             s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
1740                             s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
1741                             h->h264dsp.weight_h264_pixels_tab,
1742                             h->h264dsp.biweight_h264_pixels_tab);
1743         }
1744
1745
1746         if(!IS_INTRA4x4(mb_type)){
1747             if(is_h264){
1748                 if(IS_INTRA16x16(mb_type)){
1749                     if(transform_bypass){
1750                         if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
1751                             h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb, linesize);
1752                         }else{
1753                             for(i=0; i<16; i++){
1754                                 if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h->mb, pixel_shift, i*16))
1755                                     s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + (i*16 << pixel_shift), linesize);
1756                             }
1757                         }
1758                     }else{
1759                          h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1760                     }
1761                 }else if(h->cbp&15){
1762                     if(transform_bypass){
1763                         const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1764                         idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
1765                         for(i=0; i<16; i+=di){
1766                             if(h->non_zero_count_cache[ scan8[i] ]){
1767                                 idct_add(dest_y + block_offset[i], h->mb + (i*16 << pixel_shift), linesize);
1768                             }
1769                         }
1770                     }else{
1771                         if(IS_8x8DCT(mb_type)){
1772                             h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1773                         }else{
1774                             h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1775                         }
1776                     }
1777                 }
1778             }else{
1779                 for(i=0; i<16; i++){
1780                     if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
1781                         uint8_t * const ptr= dest_y + block_offset[i];
1782                         ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1783                     }
1784                 }
1785             }
1786         }
1787
1788         if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
1789             uint8_t *dest[2] = {dest_cb, dest_cr};
1790             if(transform_bypass){
1791                 if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
1792                     h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + (16*16 << pixel_shift), uvlinesize);
1793                     h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 20, h->mb + (20*16 << pixel_shift), uvlinesize);
1794                 }else{
1795                     idct_add = s->dsp.add_pixels4;
1796                     for(i=16; i<16+8; i++){
1797                         if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h->mb, pixel_shift, i*16))
1798                             idct_add   (dest[(i&4)>>2] + block_offset[i], h->mb + (i*16 << pixel_shift), uvlinesize);
1799                     }
1800                 }
1801             }else{
1802                 if(is_h264){
1803                     if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
1804                         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]);
1805                     if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
1806                         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]);
1807                     h->h264dsp.h264_idct_add8(dest, block_offset,
1808                                               h->mb, uvlinesize,
1809                                               h->non_zero_count_cache);
1810                 }else{
1811                     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]);
1812                     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]);
1813                     for(i=16; i<16+8; i++){
1814                         if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
1815                             uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
1816                             ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
1817                         }
1818                     }
1819                 }
1820             }
1821         }
1822     }
1823     if(h->cbp || IS_INTRA(mb_type))
1824         s->dsp.clear_blocks(h->mb);
1825 }
1826
1827 /**
1828  * Process a macroblock; this case avoids checks for expensive uncommon cases.
1829  */
1830 #define hl_decode_mb_simple(sh, bits) \
1831 static void hl_decode_mb_simple_ ## bits(H264Context *h){ \
1832     hl_decode_mb_internal(h, 1, sh); \
1833 }
1834 hl_decode_mb_simple(0, 8);
1835 hl_decode_mb_simple(1, 16);
1836
1837 /**
1838  * Process a macroblock; this handles edge cases, such as interlacing.
1839  */
1840 static void av_noinline hl_decode_mb_complex(H264Context *h){
1841     hl_decode_mb_internal(h, 0, h->pixel_shift);
1842 }
1843
1844 void ff_h264_hl_decode_mb(H264Context *h){
1845     MpegEncContext * const s = &h->s;
1846     const int mb_xy= h->mb_xy;
1847     const int mb_type= s->current_picture.mb_type[mb_xy];
1848     int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
1849
1850     if (is_complex) {
1851         hl_decode_mb_complex(h);
1852     } else if (h->pixel_shift) {
1853         hl_decode_mb_simple_16(h);
1854     } else
1855         hl_decode_mb_simple_8(h);
1856 }
1857
1858 static int pred_weight_table(H264Context *h){
1859     MpegEncContext * const s = &h->s;
1860     int list, i;
1861     int luma_def, chroma_def;
1862
1863     h->use_weight= 0;
1864     h->use_weight_chroma= 0;
1865     h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
1866     if(CHROMA)
1867         h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
1868     luma_def = 1<<h->luma_log2_weight_denom;
1869     chroma_def = 1<<h->chroma_log2_weight_denom;
1870
1871     for(list=0; list<2; list++){
1872         h->luma_weight_flag[list]   = 0;
1873         h->chroma_weight_flag[list] = 0;
1874         for(i=0; i<h->ref_count[list]; i++){
1875             int luma_weight_flag, chroma_weight_flag;
1876
1877             luma_weight_flag= get_bits1(&s->gb);
1878             if(luma_weight_flag){
1879                 h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
1880                 h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
1881                 if(   h->luma_weight[i][list][0] != luma_def
1882                    || h->luma_weight[i][list][1] != 0) {
1883                     h->use_weight= 1;
1884                     h->luma_weight_flag[list]= 1;
1885                 }
1886             }else{
1887                 h->luma_weight[i][list][0]= luma_def;
1888                 h->luma_weight[i][list][1]= 0;
1889             }
1890
1891             if(CHROMA){
1892                 chroma_weight_flag= get_bits1(&s->gb);
1893                 if(chroma_weight_flag){
1894                     int j;
1895                     for(j=0; j<2; j++){
1896                         h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
1897                         h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
1898                         if(   h->chroma_weight[i][list][j][0] != chroma_def
1899                            || h->chroma_weight[i][list][j][1] != 0) {
1900                             h->use_weight_chroma= 1;
1901                             h->chroma_weight_flag[list]= 1;
1902                         }
1903                     }
1904                 }else{
1905                     int j;
1906                     for(j=0; j<2; j++){
1907                         h->chroma_weight[i][list][j][0]= chroma_def;
1908                         h->chroma_weight[i][list][j][1]= 0;
1909                     }
1910                 }
1911             }
1912         }
1913         if(h->slice_type_nos != AV_PICTURE_TYPE_B) break;
1914     }
1915     h->use_weight= h->use_weight || h->use_weight_chroma;
1916     return 0;
1917 }
1918
1919 /**
1920  * Initialize implicit_weight table.
1921  * @param field  0/1 initialize the weight for interlaced MBAFF
1922  *                -1 initializes the rest
1923  */
1924 static void implicit_weight_table(H264Context *h, int field){
1925     MpegEncContext * const s = &h->s;
1926     int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
1927
1928     for (i = 0; i < 2; i++) {
1929         h->luma_weight_flag[i]   = 0;
1930         h->chroma_weight_flag[i] = 0;
1931     }
1932
1933     if(field < 0){
1934         cur_poc = s->current_picture_ptr->poc;
1935     if(   h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
1936        && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
1937         h->use_weight= 0;
1938         h->use_weight_chroma= 0;
1939         return;
1940     }
1941         ref_start= 0;
1942         ref_count0= h->ref_count[0];
1943         ref_count1= h->ref_count[1];
1944     }else{
1945         cur_poc = s->current_picture_ptr->field_poc[field];
1946         ref_start= 16;
1947         ref_count0= 16+2*h->ref_count[0];
1948         ref_count1= 16+2*h->ref_count[1];
1949     }
1950
1951     h->use_weight= 2;
1952     h->use_weight_chroma= 2;
1953     h->luma_log2_weight_denom= 5;
1954     h->chroma_log2_weight_denom= 5;
1955
1956     for(ref0=ref_start; ref0 < ref_count0; ref0++){
1957         int poc0 = h->ref_list[0][ref0].poc;
1958         for(ref1=ref_start; ref1 < ref_count1; ref1++){
1959             int poc1 = h->ref_list[1][ref1].poc;
1960             int td = av_clip(poc1 - poc0, -128, 127);
1961             int w= 32;
1962             if(td){
1963                 int tb = av_clip(cur_poc - poc0, -128, 127);
1964                 int tx = (16384 + (FFABS(td) >> 1)) / td;
1965                 int dist_scale_factor = (tb*tx + 32) >> 8;
1966                 if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
1967                     w = 64 - dist_scale_factor;
1968             }
1969             if(field<0){
1970                 h->implicit_weight[ref0][ref1][0]=
1971                 h->implicit_weight[ref0][ref1][1]= w;
1972             }else{
1973                 h->implicit_weight[ref0][ref1][field]=w;
1974             }
1975         }
1976     }
1977 }
1978
1979 /**
1980  * instantaneous decoder refresh.
1981  */
1982 static void idr(H264Context *h){
1983     ff_h264_remove_all_refs(h);
1984     h->prev_frame_num= 0;
1985     h->prev_frame_num_offset= 0;
1986     h->prev_poc_msb=
1987     h->prev_poc_lsb= 0;
1988 }
1989
1990 /* forget old pics after a seek */
1991 static void flush_dpb(AVCodecContext *avctx){
1992     H264Context *h= avctx->priv_data;
1993     int i;
1994     for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
1995         if(h->delayed_pic[i])
1996             h->delayed_pic[i]->reference= 0;
1997         h->delayed_pic[i]= NULL;
1998     }
1999     h->outputed_poc=h->next_outputed_poc= INT_MIN;
2000     h->prev_interlaced_frame = 1;
2001     idr(h);
2002     if(h->s.current_picture_ptr)
2003         h->s.current_picture_ptr->reference= 0;
2004     h->s.first_field= 0;
2005     ff_h264_reset_sei(h);
2006     ff_mpeg_flush(avctx);
2007 }
2008
2009 static int init_poc(H264Context *h){
2010     MpegEncContext * const s = &h->s;
2011     const int max_frame_num= 1<<h->sps.log2_max_frame_num;
2012     int field_poc[2];
2013     Picture *cur = s->current_picture_ptr;
2014
2015     h->frame_num_offset= h->prev_frame_num_offset;
2016     if(h->frame_num < h->prev_frame_num)
2017         h->frame_num_offset += max_frame_num;
2018
2019     if(h->sps.poc_type==0){
2020         const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
2021
2022         if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
2023             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2024         else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
2025             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2026         else
2027             h->poc_msb = h->prev_poc_msb;
2028 //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2029         field_poc[0] =
2030         field_poc[1] = h->poc_msb + h->poc_lsb;
2031         if(s->picture_structure == PICT_FRAME)
2032             field_poc[1] += h->delta_poc_bottom;
2033     }else if(h->sps.poc_type==1){
2034         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2035         int i;
2036
2037         if(h->sps.poc_cycle_length != 0)
2038             abs_frame_num = h->frame_num_offset + h->frame_num;
2039         else
2040             abs_frame_num = 0;
2041
2042         if(h->nal_ref_idc==0 && abs_frame_num > 0)
2043             abs_frame_num--;
2044
2045         expected_delta_per_poc_cycle = 0;
2046         for(i=0; i < h->sps.poc_cycle_length; i++)
2047             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
2048
2049         if(abs_frame_num > 0){
2050             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2051             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2052
2053             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2054             for(i = 0; i <= frame_num_in_poc_cycle; i++)
2055                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
2056         } else
2057             expectedpoc = 0;
2058
2059         if(h->nal_ref_idc == 0)
2060             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2061
2062         field_poc[0] = expectedpoc + h->delta_poc[0];
2063         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2064
2065         if(s->picture_structure == PICT_FRAME)
2066             field_poc[1] += h->delta_poc[1];
2067     }else{
2068         int poc= 2*(h->frame_num_offset + h->frame_num);
2069
2070         if(!h->nal_ref_idc)
2071             poc--;
2072
2073         field_poc[0]= poc;
2074         field_poc[1]= poc;
2075     }
2076
2077     if(s->picture_structure != PICT_BOTTOM_FIELD)
2078         s->current_picture_ptr->field_poc[0]= field_poc[0];
2079     if(s->picture_structure != PICT_TOP_FIELD)
2080         s->current_picture_ptr->field_poc[1]= field_poc[1];
2081     cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
2082
2083     return 0;
2084 }
2085
2086
2087 /**
2088  * initialize scan tables
2089  */
2090 static void init_scan_tables(H264Context *h){
2091     int i;
2092     for(i=0; i<16; i++){
2093 #define T(x) (x>>2) | ((x<<2) & 0xF)
2094         h->zigzag_scan[i] = T(zigzag_scan[i]);
2095         h-> field_scan[i] = T( field_scan[i]);
2096 #undef T
2097     }
2098     for(i=0; i<64; i++){
2099 #define T(x) (x>>3) | ((x&7)<<3)
2100         h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
2101         h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2102         h->field_scan8x8[i]        = T(field_scan8x8[i]);
2103         h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
2104 #undef T
2105     }
2106     if(h->sps.transform_bypass){ //FIXME same ugly
2107         h->zigzag_scan_q0          = zigzag_scan;
2108         h->zigzag_scan8x8_q0       = ff_zigzag_direct;
2109         h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2110         h->field_scan_q0           = field_scan;
2111         h->field_scan8x8_q0        = field_scan8x8;
2112         h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
2113     }else{
2114         h->zigzag_scan_q0          = h->zigzag_scan;
2115         h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
2116         h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2117         h->field_scan_q0           = h->field_scan;
2118         h->field_scan8x8_q0        = h->field_scan8x8;
2119         h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
2120     }
2121 }
2122
2123 static void field_end(H264Context *h, int in_setup){
2124     MpegEncContext * const s = &h->s;
2125     AVCodecContext * const avctx= s->avctx;
2126     s->mb_y= 0;
2127
2128     if (!in_setup && !s->dropable)
2129         ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
2130                                  s->picture_structure==PICT_BOTTOM_FIELD);
2131
2132     if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2133         ff_vdpau_h264_set_reference_frames(s);
2134
2135     if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
2136         if(!s->dropable) {
2137             ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2138             h->prev_poc_msb= h->poc_msb;
2139             h->prev_poc_lsb= h->poc_lsb;
2140         }
2141         h->prev_frame_num_offset= h->frame_num_offset;
2142         h->prev_frame_num= h->frame_num;
2143         h->outputed_poc = h->next_outputed_poc;
2144     }
2145
2146     if (avctx->hwaccel) {
2147         if (avctx->hwaccel->end_frame(avctx) < 0)
2148             av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
2149     }
2150
2151     if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2152         ff_vdpau_h264_picture_complete(s);
2153
2154     /*
2155      * FIXME: Error handling code does not seem to support interlaced
2156      * when slices span multiple rows
2157      * The ff_er_add_slice calls don't work right for bottom
2158      * fields; they cause massive erroneous error concealing
2159      * Error marking covers both fields (top and bottom).
2160      * This causes a mismatched s->error_count
2161      * and a bad error table. Further, the error count goes to
2162      * INT_MAX when called for bottom field, because mb_y is
2163      * past end by one (callers fault) and resync_mb_y != 0
2164      * causes problems for the first MB line, too.
2165      */
2166     if (!FIELD_PICTURE)
2167         ff_er_frame_end(s);
2168
2169     MPV_frame_end(s);
2170
2171     h->current_slice=0;
2172 }
2173
2174 /**
2175  * Replicate H264 "master" context to thread contexts.
2176  */
2177 static void clone_slice(H264Context *dst, H264Context *src)
2178 {
2179     memcpy(dst->block_offset,     src->block_offset, sizeof(dst->block_offset));
2180     dst->s.current_picture_ptr  = src->s.current_picture_ptr;
2181     dst->s.current_picture      = src->s.current_picture;
2182     dst->s.linesize             = src->s.linesize;
2183     dst->s.uvlinesize           = src->s.uvlinesize;
2184     dst->s.first_field          = src->s.first_field;
2185
2186     dst->prev_poc_msb           = src->prev_poc_msb;
2187     dst->prev_poc_lsb           = src->prev_poc_lsb;
2188     dst->prev_frame_num_offset  = src->prev_frame_num_offset;
2189     dst->prev_frame_num         = src->prev_frame_num;
2190     dst->short_ref_count        = src->short_ref_count;
2191
2192     memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
2193     memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
2194     memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2195     memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
2196
2197     memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
2198     memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
2199 }
2200
2201 /**
2202  * computes profile from profile_idc and constraint_set?_flags
2203  *
2204  * @param sps SPS
2205  *
2206  * @return profile as defined by FF_PROFILE_H264_*
2207  */
2208 int ff_h264_get_profile(SPS *sps)
2209 {
2210     int profile = sps->profile_idc;
2211
2212     switch(sps->profile_idc) {
2213     case FF_PROFILE_H264_BASELINE:
2214         // constraint_set1_flag set to 1
2215         profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2216         break;
2217     case FF_PROFILE_H264_HIGH_10:
2218     case FF_PROFILE_H264_HIGH_422:
2219     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2220         // constraint_set3_flag set to 1
2221         profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
2222         break;
2223     }
2224
2225     return profile;
2226 }
2227
2228 /**
2229  * decodes a slice header.
2230  * This will also call MPV_common_init() and frame_start() as needed.
2231  *
2232  * @param h h264context
2233  * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
2234  *
2235  * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2236  */
2237 static int decode_slice_header(H264Context *h, H264Context *h0){
2238     MpegEncContext * const s = &h->s;
2239     MpegEncContext * const s0 = &h0->s;
2240     unsigned int first_mb_in_slice;
2241     unsigned int pps_id;
2242     int num_ref_idx_active_override_flag;
2243     unsigned int slice_type, tmp, i, j;
2244     int default_ref_list_done = 0;
2245     int last_pic_structure;
2246
2247     s->dropable= h->nal_ref_idc == 0;
2248
2249     if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
2250         s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
2251         s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
2252     }else{
2253         s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
2254         s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
2255     }
2256
2257     first_mb_in_slice= get_ue_golomb(&s->gb);
2258
2259     if(first_mb_in_slice == 0){ //FIXME better field boundary detection
2260         if(h0->current_slice && FIELD_PICTURE){
2261             field_end(h, 1);
2262         }
2263
2264         h0->current_slice = 0;
2265         if (!s0->first_field)
2266             s->current_picture_ptr= NULL;
2267     }
2268
2269     slice_type= get_ue_golomb_31(&s->gb);
2270     if(slice_type > 9){
2271         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);
2272         return -1;
2273     }
2274     if(slice_type > 4){
2275         slice_type -= 5;
2276         h->slice_type_fixed=1;
2277     }else
2278         h->slice_type_fixed=0;
2279
2280     slice_type= golomb_to_pict_type[ slice_type ];
2281     if (slice_type == AV_PICTURE_TYPE_I
2282         || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
2283         default_ref_list_done = 1;
2284     }
2285     h->slice_type= slice_type;
2286     h->slice_type_nos= slice_type & 3;
2287
2288     s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
2289
2290     pps_id= get_ue_golomb(&s->gb);
2291     if(pps_id>=MAX_PPS_COUNT){
2292         av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2293         return -1;
2294     }
2295     if(!h0->pps_buffers[pps_id]) {
2296         av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
2297         return -1;
2298     }
2299     h->pps= *h0->pps_buffers[pps_id];
2300
2301     if(!h0->sps_buffers[h->pps.sps_id]) {
2302         av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
2303         return -1;
2304     }
2305     h->sps = *h0->sps_buffers[h->pps.sps_id];
2306
2307     s->avctx->profile = ff_h264_get_profile(&h->sps);
2308     s->avctx->level   = h->sps.level_idc;
2309     s->avctx->refs    = h->sps.ref_frame_count;
2310
2311     if(h == h0 && h->dequant_coeff_pps != pps_id){
2312         h->dequant_coeff_pps = pps_id;
2313         init_dequant_tables(h);
2314     }
2315
2316     s->mb_width= h->sps.mb_width;
2317     s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2318
2319     h->b_stride=  s->mb_width*4;
2320
2321     s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
2322     if(h->sps.frame_mbs_only_flag)
2323         s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
2324     else
2325         s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 7);
2326
2327     if (s->context_initialized
2328         && (   s->width != s->avctx->width || s->height != s->avctx->height
2329             || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2330         if(h != h0) {
2331             av_log_missing_feature(s->avctx, "Width/height changing with threads is", 0);
2332             return -1;   // width / height changed during parallelized decoding
2333         }
2334         free_tables(h, 0);
2335         flush_dpb(s->avctx);
2336         MPV_common_end(s);
2337     }
2338     if (!s->context_initialized) {
2339         if(h != h0)
2340             return -1;  // we cant (re-)initialize context during parallel decoding
2341
2342         avcodec_set_dimensions(s->avctx, s->width, s->height);
2343         s->avctx->sample_aspect_ratio= h->sps.sar;
2344         av_assert0(s->avctx->sample_aspect_ratio.den);
2345
2346         if(h->sps.video_signal_type_present_flag){
2347             s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2348             if(h->sps.colour_description_present_flag){
2349                 s->avctx->color_primaries = h->sps.color_primaries;
2350                 s->avctx->color_trc       = h->sps.color_trc;
2351                 s->avctx->colorspace      = h->sps.colorspace;
2352             }
2353         }
2354
2355         if(h->sps.timing_info_present_flag){
2356             int64_t den= h->sps.time_scale;
2357             if(h->x264_build < 44U)
2358                 den *= 2;
2359             av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2360                       h->sps.num_units_in_tick, den, 1<<30);
2361         }
2362
2363         switch (h->sps.bit_depth_luma) {
2364             case 9 :
2365                 s->avctx->pix_fmt = PIX_FMT_YUV420P9;
2366                 break;
2367             case 10 :
2368                 s->avctx->pix_fmt = PIX_FMT_YUV420P10;
2369                 break;
2370             default:
2371         s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2372                                                  s->avctx->codec->pix_fmts ?
2373                                                  s->avctx->codec->pix_fmts :
2374                                                  s->avctx->color_range == AVCOL_RANGE_JPEG ?
2375                                                  hwaccel_pixfmt_list_h264_jpeg_420 :
2376                                                  ff_hwaccel_pixfmt_list_420);
2377         }
2378
2379         s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2380
2381         if (MPV_common_init(s) < 0)
2382             return -1;
2383         s->first_field = 0;
2384         h->prev_interlaced_frame = 1;
2385
2386         init_scan_tables(h);
2387         ff_h264_alloc_tables(h);
2388
2389         if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
2390             if (context_init(h) < 0)
2391                 return -1;
2392         } else {
2393             for(i = 1; i < s->avctx->thread_count; i++) {
2394                 H264Context *c;
2395                 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2396                 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2397                 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2398                 c->h264dsp = h->h264dsp;
2399                 c->sps = h->sps;
2400                 c->pps = h->pps;
2401                 init_scan_tables(c);
2402                 clone_tables(c, h, i);
2403             }
2404
2405             for(i = 0; i < s->avctx->thread_count; i++)
2406                 if(context_init(h->thread_context[i]) < 0)
2407                     return -1;
2408         }
2409     }
2410
2411     h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
2412
2413     h->mb_mbaff = 0;
2414     h->mb_aff_frame = 0;
2415     last_pic_structure = s0->picture_structure;
2416     if(h->sps.frame_mbs_only_flag){
2417         s->picture_structure= PICT_FRAME;
2418     }else{
2419         if(get_bits1(&s->gb)) { //field_pic_flag
2420             s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
2421         } else {
2422             s->picture_structure= PICT_FRAME;
2423             h->mb_aff_frame = h->sps.mb_aff;
2424         }
2425     }
2426     h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
2427
2428     if(h0->current_slice == 0){
2429         if(h->frame_num != h->prev_frame_num &&
2430           (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num) < (h->frame_num - h->sps.ref_frame_count))
2431             h->prev_frame_num = h->frame_num - h->sps.ref_frame_count - 1;
2432
2433         while(h->frame_num !=  h->prev_frame_num &&
2434               h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
2435             Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2436             av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
2437             if (ff_h264_frame_start(h) < 0)
2438                 return -1;
2439             h->prev_frame_num++;
2440             h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
2441             s->current_picture_ptr->frame_num= h->prev_frame_num;
2442             ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
2443             ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
2444             ff_generate_sliding_window_mmcos(h);
2445             ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2446             /* Error concealment: if a ref is missing, copy the previous ref in its place.
2447              * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2448              * about there being no actual duplicates.
2449              * FIXME: this doesn't copy padding for out-of-frame motion vectors.  Given we're
2450              * concealing a lost frame, this probably isn't noticable by comparison, but it should
2451              * be fixed. */
2452             if (h->short_ref_count) {
2453                 if (prev) {
2454                     av_image_copy(h->short_ref[0]->data, h->short_ref[0]->linesize,
2455                                   (const uint8_t**)prev->data, prev->linesize,
2456                                   s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
2457                     h->short_ref[0]->poc = prev->poc+2;
2458                 }
2459                 h->short_ref[0]->frame_num = h->prev_frame_num;
2460             }
2461         }
2462
2463         /* See if we have a decoded first field looking for a pair... */
2464         if (s0->first_field) {
2465             assert(s0->current_picture_ptr);
2466             assert(s0->current_picture_ptr->data[0]);
2467             assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
2468
2469             /* figure out if we have a complementary field pair */
2470             if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2471                 /*
2472                  * Previous field is unmatched. Don't display it, but let it
2473                  * remain for reference if marked as such.
2474                  */
2475                 s0->current_picture_ptr = NULL;
2476                 s0->first_field = FIELD_PICTURE;
2477
2478             } else {
2479                 if (h->nal_ref_idc &&
2480                         s0->current_picture_ptr->reference &&
2481                         s0->current_picture_ptr->frame_num != h->frame_num) {
2482                     /*
2483                      * This and previous field were reference, but had
2484                      * different frame_nums. Consider this field first in
2485                      * pair. Throw away previous field except for reference
2486                      * purposes.
2487                      */
2488                     s0->first_field = 1;
2489                     s0->current_picture_ptr = NULL;
2490
2491                 } else {
2492                     /* Second field in complementary pair */
2493                     s0->first_field = 0;
2494                 }
2495             }
2496
2497         } else {
2498             /* Frame or first field in a potentially complementary pair */
2499             assert(!s0->current_picture_ptr);
2500             s0->first_field = FIELD_PICTURE;
2501         }
2502
2503         if(!FIELD_PICTURE || s0->first_field) {
2504             if (ff_h264_frame_start(h) < 0) {
2505                 s0->first_field = 0;
2506                 return -1;
2507             }
2508         } else {
2509             ff_release_unused_pictures(s, 0);
2510         }
2511     }
2512     if(h != h0)
2513         clone_slice(h, h0);
2514
2515     s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2516
2517     assert(s->mb_num == s->mb_width * s->mb_height);
2518     if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2519        first_mb_in_slice                    >= s->mb_num){
2520         av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2521         return -1;
2522     }
2523     s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2524     s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2525     if (s->picture_structure == PICT_BOTTOM_FIELD)
2526         s->resync_mb_y = s->mb_y = s->mb_y + 1;
2527     assert(s->mb_y < s->mb_height);
2528
2529     if(s->picture_structure==PICT_FRAME){
2530         h->curr_pic_num=   h->frame_num;
2531         h->max_pic_num= 1<< h->sps.log2_max_frame_num;
2532     }else{
2533         h->curr_pic_num= 2*h->frame_num + 1;
2534         h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
2535     }
2536
2537     if(h->nal_unit_type == NAL_IDR_SLICE){
2538         get_ue_golomb(&s->gb); /* idr_pic_id */
2539     }
2540
2541     if(h->sps.poc_type==0){
2542         h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2543
2544         if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
2545             h->delta_poc_bottom= get_se_golomb(&s->gb);
2546         }
2547     }
2548
2549     if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
2550         h->delta_poc[0]= get_se_golomb(&s->gb);
2551
2552         if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
2553             h->delta_poc[1]= get_se_golomb(&s->gb);
2554     }
2555
2556     init_poc(h);
2557
2558     if(h->pps.redundant_pic_cnt_present){
2559         h->redundant_pic_count= get_ue_golomb(&s->gb);
2560     }
2561
2562     //set defaults, might be overridden a few lines later
2563     h->ref_count[0]= h->pps.ref_count[0];
2564     h->ref_count[1]= h->pps.ref_count[1];
2565
2566     if(h->slice_type_nos != AV_PICTURE_TYPE_I){
2567         if(h->slice_type_nos == AV_PICTURE_TYPE_B){
2568             h->direct_spatial_mv_pred= get_bits1(&s->gb);
2569         }
2570         num_ref_idx_active_override_flag= get_bits1(&s->gb);
2571
2572         if(num_ref_idx_active_override_flag){
2573             h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
2574             if(h->slice_type_nos==AV_PICTURE_TYPE_B)
2575                 h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
2576
2577             if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
2578                 av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
2579                 h->ref_count[0]= h->ref_count[1]= 1;
2580                 return -1;
2581             }
2582         }
2583         if(h->slice_type_nos == AV_PICTURE_TYPE_B)
2584             h->list_count= 2;
2585         else
2586             h->list_count= 1;
2587     }else
2588         h->list_count= 0;
2589
2590     if(!default_ref_list_done){
2591         ff_h264_fill_default_ref_list(h);
2592     }
2593
2594     if(h->slice_type_nos!=AV_PICTURE_TYPE_I && ff_h264_decode_ref_pic_list_reordering(h) < 0)
2595         return -1;
2596
2597     if(h->slice_type_nos!=AV_PICTURE_TYPE_I){
2598         s->last_picture_ptr= &h->ref_list[0][0];
2599         ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2600     }
2601     if(h->slice_type_nos==AV_PICTURE_TYPE_B){
2602         s->next_picture_ptr= &h->ref_list[1][0];
2603         ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2604     }
2605
2606     if(   (h->pps.weighted_pred          && h->slice_type_nos == AV_PICTURE_TYPE_P )
2607        ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== AV_PICTURE_TYPE_B ) )
2608         pred_weight_table(h);
2609     else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
2610         implicit_weight_table(h, -1);
2611     }else {
2612         h->use_weight = 0;
2613         for (i = 0; i < 2; i++) {
2614             h->luma_weight_flag[i]   = 0;
2615             h->chroma_weight_flag[i] = 0;
2616         }
2617     }
2618
2619     if(h->nal_ref_idc)
2620         ff_h264_decode_ref_pic_marking(h0, &s->gb);
2621
2622     if(FRAME_MBAFF){
2623         ff_h264_fill_mbaff_ref_list(h);
2624
2625         if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
2626             implicit_weight_table(h, 0);
2627             implicit_weight_table(h, 1);
2628         }
2629     }
2630
2631     if(h->slice_type_nos==AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
2632         ff_h264_direct_dist_scale_factor(h);
2633     ff_h264_direct_ref_list_init(h);
2634
2635     if( h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac ){
2636         tmp = get_ue_golomb_31(&s->gb);
2637         if(tmp > 2){
2638             av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2639             return -1;
2640         }
2641         h->cabac_init_idc= tmp;
2642     }
2643
2644     h->last_qscale_diff = 0;
2645     tmp = h->pps.init_qp + get_se_golomb(&s->gb);
2646     if(tmp>51+6*(h->sps.bit_depth_luma-8)){
2647         av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
2648         return -1;
2649     }
2650     s->qscale= tmp;
2651     h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2652     h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2653     //FIXME qscale / qp ... stuff
2654     if(h->slice_type == AV_PICTURE_TYPE_SP){
2655         get_bits1(&s->gb); /* sp_for_switch_flag */
2656     }
2657     if(h->slice_type==AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI){
2658         get_se_golomb(&s->gb); /* slice_qs_delta */
2659     }
2660
2661     h->deblocking_filter = 1;
2662     h->slice_alpha_c0_offset = 52;
2663     h->slice_beta_offset = 52;
2664     if( h->pps.deblocking_filter_parameters_present ) {
2665         tmp= get_ue_golomb_31(&s->gb);
2666         if(tmp > 2){
2667             av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
2668             return -1;
2669         }
2670         h->deblocking_filter= tmp;
2671         if(h->deblocking_filter < 2)
2672             h->deblocking_filter^= 1; // 1<->0
2673
2674         if( h->deblocking_filter ) {
2675             h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
2676             h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
2677             if(   h->slice_alpha_c0_offset > 104U
2678                || h->slice_beta_offset     > 104U){
2679                 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);
2680                 return -1;
2681             }
2682         }
2683     }
2684
2685     if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
2686        ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I)
2687        ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == AV_PICTURE_TYPE_B)
2688        ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
2689         h->deblocking_filter= 0;
2690
2691     if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
2692         if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
2693             /* Cheat slightly for speed:
2694                Do not bother to deblock across slices. */
2695             h->deblocking_filter = 2;
2696         } else {
2697             h0->max_contexts = 1;
2698             if(!h0->single_decode_warning) {
2699                 av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
2700                 h0->single_decode_warning = 1;
2701             }
2702             if(h != h0)
2703                 return 1; // deblocking switched inside frame
2704         }
2705     }
2706     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]);
2707
2708 #if 0 //FMO
2709     if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
2710         slice_group_change_cycle= get_bits(&s->gb, ?);
2711 #endif
2712
2713     h0->last_slice_type = slice_type;
2714     h->slice_num = ++h0->current_slice;
2715     if(h->slice_num >= MAX_SLICES){
2716         av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
2717     }
2718
2719     for(j=0; j<2; j++){
2720         int id_list[16];
2721         int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
2722         for(i=0; i<16; i++){
2723             id_list[i]= 60;
2724             if(h->ref_list[j][i].data[0]){
2725                 int k;
2726                 uint8_t *base= h->ref_list[j][i].base[0];
2727                 for(k=0; k<h->short_ref_count; k++)
2728                     if(h->short_ref[k]->base[0] == base){
2729                         id_list[i]= k;
2730                         break;
2731                     }
2732                 for(k=0; k<h->long_ref_count; k++)
2733                     if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
2734                         id_list[i]= h->short_ref_count + k;
2735                         break;
2736                     }
2737             }
2738         }
2739
2740         ref2frm[0]=
2741         ref2frm[1]= -1;
2742         for(i=0; i<16; i++)
2743             ref2frm[i+2]= 4*id_list[i]
2744                           +(h->ref_list[j][i].reference&3);
2745         ref2frm[18+0]=
2746         ref2frm[18+1]= -1;
2747         for(i=16; i<48; i++)
2748             ref2frm[i+4]= 4*id_list[(i-16)>>1]
2749                           +(h->ref_list[j][i].reference&3);
2750     }
2751
2752     //FIXME: fix draw_edges+PAFF+frame threads
2753     h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE || (!h->sps.frame_mbs_only_flag && s->avctx->active_thread_type)) ? 0 : 16;
2754     h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
2755
2756     if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2757         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",
2758                h->slice_num,
2759                (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
2760                first_mb_in_slice,
2761                av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
2762                pps_id, h->frame_num,
2763                s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
2764                h->ref_count[0], h->ref_count[1],
2765                s->qscale,
2766                h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
2767                h->use_weight,
2768                h->use_weight==1 && h->use_weight_chroma ? "c" : "",
2769                h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
2770                );
2771     }
2772
2773     return 0;
2774 }
2775
2776 int ff_h264_get_slice_type(const H264Context *h)
2777 {
2778     switch (h->slice_type) {
2779     case AV_PICTURE_TYPE_P:  return 0;
2780     case AV_PICTURE_TYPE_B:  return 1;
2781     case AV_PICTURE_TYPE_I:  return 2;
2782     case AV_PICTURE_TYPE_SP: return 3;
2783     case AV_PICTURE_TYPE_SI: return 4;
2784     default:         return -1;
2785     }
2786 }
2787
2788 /**
2789  *
2790  * @return non zero if the loop filter can be skiped
2791  */
2792 static int fill_filter_caches(H264Context *h, int mb_type){
2793     MpegEncContext * const s = &h->s;