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