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