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