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