Merge commit 'aa45b90804ab21175b8c116bd8e5eb4b4e85fbcb' into release/0.8
[ffmpeg:ffmpeg.git] / libavcodec / h264.c
1 /*
2  * H.26L/H.264/AVC/JVT/14496-10/... decoder
3  * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * H.264 / AVC / MPEG4 part10 codec.
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #include "libavutil/imgutils.h"
29 #include "internal.h"
30 #include "dsputil.h"
31 #include "avcodec.h"
32 #include "mpegvideo.h"
33 #include "h264.h"
34 #include "h264data.h"
35 #include "h264_mvpred.h"
36 #include "golomb.h"
37 #include "mathops.h"
38 #include "rectangle.h"
39 #include "thread.h"
40 #include "vdpau_internal.h"
41 #include "libavutil/avassert.h"
42
43 #include "cabac.h"
44
45 //#undef NDEBUG
46 #include <assert.h>
47
48 static const uint8_t rem6[QP_MAX_NUM+1]={
49 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
50 };
51
52 static const uint8_t div6[QP_MAX_NUM+1]={
53 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,
54 };
55
56 static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
57     PIX_FMT_DXVA2_VLD,
58     PIX_FMT_VAAPI_VLD,
59     PIX_FMT_YUVJ420P,
60     PIX_FMT_NONE
61 };
62
63 void ff_h264_write_back_intra_pred_mode(H264Context *h){
64     int8_t *mode= h->intra4x4_pred_mode + h->mb2br_xy[h->mb_xy];
65
66     AV_COPY32(mode, h->intra4x4_pred_mode_cache + 4 + 8*4);
67     mode[4]= h->intra4x4_pred_mode_cache[7+8*3];
68     mode[5]= h->intra4x4_pred_mode_cache[7+8*2];
69     mode[6]= h->intra4x4_pred_mode_cache[7+8*1];
70 }
71
72 /**
73  * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
74  */
75 int ff_h264_check_intra4x4_pred_mode(H264Context *h){
76     MpegEncContext * const s = &h->s;
77     static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
78     static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
79     int i;
80
81     if(!(h->top_samples_available&0x8000)){
82         for(i=0; i<4; i++){
83             int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
84             if(status<0){
85                 av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
86                 return -1;
87             } else if(status){
88                 h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
89             }
90         }
91     }
92
93     if((h->left_samples_available&0x8888)!=0x8888){
94         static const int mask[4]={0x8000,0x2000,0x80,0x20};
95         for(i=0; i<4; i++){
96             if(!(h->left_samples_available&mask[i])){
97                 int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
98                 if(status<0){
99                     av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
100                     return -1;
101                 } else if(status){
102                     h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
103                 }
104             }
105         }
106     }
107
108     return 0;
109 } //FIXME cleanup like check_intra_pred_mode
110
111 /**
112  * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
113  */
114 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma){
115     MpegEncContext * const s = &h->s;
116     static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
117     static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
118
119     if(mode > 6U) {
120         av_log(h->s.avctx, AV_LOG_ERROR, "out of range intra chroma pred mode at %d %d\n", s->mb_x, s->mb_y);
121         return -1;
122     }
123
124     if(!(h->top_samples_available&0x8000)){
125         mode= top[ mode ];
126         if(mode<0){
127             av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
128             return -1;
129         }
130     }
131
132     if((h->left_samples_available&0x8080) != 0x8080){
133         mode= left[ mode ];
134         if(is_chroma && (h->left_samples_available&0x8080)){ //mad cow disease mode, aka MBAFF + constrained_intra_pred
135             mode= ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available&0x8000)) + 2*(mode == DC_128_PRED8x8);
136         }
137         if(mode<0){
138             av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
139             return -1;
140         }
141     }
142
143     return mode;
144 }
145
146 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
147     int i, si, di;
148     uint8_t *dst;
149     int bufidx;
150
151 //    src[0]&0x80;                //forbidden bit
152     h->nal_ref_idc= src[0]>>5;
153     h->nal_unit_type= src[0]&0x1F;
154
155     src++; length--;
156
157 #if HAVE_FAST_UNALIGNED
158 # if HAVE_FAST_64BIT
159 #   define RS 7
160     for(i=0; i+1<length; i+=9){
161         if(!((~AV_RN64A(src+i) & (AV_RN64A(src+i) - 0x0100010001000101ULL)) & 0x8000800080008080ULL))
162 # else
163 #   define RS 3
164     for(i=0; i+1<length; i+=5){
165         if(!((~AV_RN32A(src+i) & (AV_RN32A(src+i) - 0x01000101U)) & 0x80008080U))
166 # endif
167             continue;
168         if(i>0 && !src[i]) i--;
169         while(src[i]) i++;
170 #else
171 #   define RS 0
172     for(i=0; i+1<length; i+=2){
173         if(src[i]) continue;
174         if(i>0 && src[i-1]==0) i--;
175 #endif
176         if(i+2<length && src[i+1]==0 && src[i+2]<=3){
177             if(src[i+2]!=3){
178                 /* startcode, so we must be past the end */
179                 length=i;
180             }
181             break;
182         }
183         i-= RS;
184     }
185
186     bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
187     si=h->rbsp_buffer_size[bufidx];
188     av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+FF_INPUT_BUFFER_PADDING_SIZE+MAX_MBPAIR_SIZE);
189     dst= h->rbsp_buffer[bufidx];
190     if(si != h->rbsp_buffer_size[bufidx])
191         memset(dst + length, 0, FF_INPUT_BUFFER_PADDING_SIZE+MAX_MBPAIR_SIZE);
192
193     if (dst == NULL){
194         return NULL;
195     }
196
197     if(i>=length-1){ //no escaped 0
198         *dst_length= length;
199         *consumed= length+1; //+1 for the header
200         if(h->s.avctx->flags2 & CODEC_FLAG2_FAST){
201             return src;
202         }else{
203             memcpy(dst, src, length);
204             return dst;
205         }
206     }
207
208 //printf("decoding esc\n");
209     memcpy(dst, src, i);
210     si=di=i;
211     while(si+2<length){
212         //remove escapes (very rare 1:2^22)
213         if(src[si+2]>3){
214             dst[di++]= src[si++];
215             dst[di++]= src[si++];
216         }else if(src[si]==0 && src[si+1]==0){
217             if(src[si+2]==3){ //escape
218                 dst[di++]= 0;
219                 dst[di++]= 0;
220                 si+=3;
221                 continue;
222             }else //next start code
223                 goto nsc;
224         }
225
226         dst[di++]= src[si++];
227     }
228     while(si<length)
229         dst[di++]= src[si++];
230 nsc:
231
232     memset(dst+di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
233
234     *dst_length= di;
235     *consumed= si + 1;//+1 for the header
236 //FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
237     return dst;
238 }
239
240 /**
241  * Identify the exact end of the bitstream
242  * @return the length of the trailing, or 0 if damaged
243  */
244 static int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
245     int v= *src;
246     int r;
247
248     tprintf(h->s.avctx, "rbsp trailing %X\n", v);
249
250     for(r=1; r<9; r++){
251         if(v&1) return r;
252         v>>=1;
253     }
254     return 0;
255 }
256
257 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n, int height,
258                                  int y_offset, int list){
259     int raw_my= h->mv_cache[list][ scan8[n] ][1];
260     int filter_height= (raw_my&3) ? 2 : 0;
261     int full_my= (raw_my>>2) + y_offset;
262     int top = full_my - filter_height, bottom = full_my + height + filter_height;
263
264     return FFMAX(abs(top), bottom);
265 }
266
267 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n, int height,
268                                int y_offset, int list0, int list1, int *nrefs){
269     MpegEncContext * const s = &h->s;
270     int my;
271
272     y_offset += 16*(s->mb_y >> MB_FIELD);
273
274     if(list0){
275         int ref_n = h->ref_cache[0][ scan8[n] ];
276         Picture *ref= &h->ref_list[0][ref_n];
277
278         // Error resilience puts the current picture in the ref list.
279         // Don't try to wait on these as it will cause a deadlock.
280         // Fields can wait on each other, though.
281         if(ref->thread_opaque != s->current_picture.thread_opaque ||
282            (ref->reference&3) != s->picture_structure) {
283             my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
284             if (refs[0][ref_n] < 0) nrefs[0] += 1;
285             refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
286         }
287     }
288
289     if(list1){
290         int ref_n = h->ref_cache[1][ scan8[n] ];
291         Picture *ref= &h->ref_list[1][ref_n];
292
293         if(ref->thread_opaque != s->current_picture.thread_opaque ||
294            (ref->reference&3) != s->picture_structure) {
295             my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
296             if (refs[1][ref_n] < 0) nrefs[1] += 1;
297             refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
298         }
299     }
300 }
301
302 /**
303  * Wait until all reference frames are available for MC operations.
304  *
305  * @param h the H264 context
306  */
307 static void await_references(H264Context *h){
308     MpegEncContext * const s = &h->s;
309     const int mb_xy= h->mb_xy;
310     const int mb_type= s->current_picture.mb_type[mb_xy];
311     int refs[2][48];
312     int nrefs[2] = {0};
313     int ref, list;
314
315     memset(refs, -1, sizeof(refs));
316
317     if(IS_16X16(mb_type)){
318         get_lowest_part_y(h, refs, 0, 16, 0,
319                   IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
320     }else if(IS_16X8(mb_type)){
321         get_lowest_part_y(h, refs, 0, 8, 0,
322                   IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
323         get_lowest_part_y(h, refs, 8, 8, 8,
324                   IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
325     }else if(IS_8X16(mb_type)){
326         get_lowest_part_y(h, refs, 0, 16, 0,
327                   IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
328         get_lowest_part_y(h, refs, 4, 16, 0,
329                   IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
330     }else{
331         int i;
332
333         assert(IS_8X8(mb_type));
334
335         for(i=0; i<4; i++){
336             const int sub_mb_type= h->sub_mb_type[i];
337             const int n= 4*i;
338             int y_offset= (i&2)<<2;
339
340             if(IS_SUB_8X8(sub_mb_type)){
341                 get_lowest_part_y(h, refs, n  , 8, y_offset,
342                           IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
343             }else if(IS_SUB_8X4(sub_mb_type)){
344                 get_lowest_part_y(h, refs, n  , 4, y_offset,
345                           IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
346                 get_lowest_part_y(h, refs, n+2, 4, y_offset+4,
347                           IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
348             }else if(IS_SUB_4X8(sub_mb_type)){
349                 get_lowest_part_y(h, refs, n  , 8, y_offset,
350                           IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
351                 get_lowest_part_y(h, refs, n+1, 8, y_offset,
352                           IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
353             }else{
354                 int j;
355                 assert(IS_SUB_4X4(sub_mb_type));
356                 for(j=0; j<4; j++){
357                     int sub_y_offset= y_offset + 2*(j&2);
358                     get_lowest_part_y(h, refs, n+j, 4, sub_y_offset,
359                               IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
360                 }
361             }
362         }
363     }
364
365     for(list=h->list_count-1; list>=0; list--){
366         for(ref=0; ref<48 && nrefs[list]; ref++){
367             int row = refs[list][ref];
368             if(row >= 0){
369                 Picture *ref_pic = &h->ref_list[list][ref];
370                 int ref_field = ref_pic->reference - 1;
371                 int ref_field_picture = ref_pic->field_picture;
372                 int pic_height = 16*s->mb_height >> ref_field_picture;
373
374                 row <<= MB_MBAFF;
375                 nrefs[list]--;
376
377                 if(!FIELD_PICTURE && ref_field_picture){ // frame referencing two fields
378                     ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) - !(row&1), pic_height-1), 1);
379                     ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1)           , pic_height-1), 0);
380                 }else if(FIELD_PICTURE && !ref_field_picture){ // field referencing one field of a frame
381                     ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row*2 + ref_field    , pic_height-1), 0);
382                 }else if(FIELD_PICTURE){
383                     ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), ref_field);
384                 }else{
385                     ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), 0);
386                 }
387             }
388         }
389     }
390 }
391
392 #if 0
393 /**
394  * DCT transforms the 16 dc values.
395  * @param qp quantization parameter ??? FIXME
396  */
397 static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
398 //    const int qmul= dequant_coeff[qp][0];
399     int i;
400     int temp[16]; //FIXME check if this is a good idea
401     static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
402     static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
403
404     for(i=0; i<4; i++){
405         const int offset= y_offset[i];
406         const int z0= block[offset+stride*0] + block[offset+stride*4];
407         const int z1= block[offset+stride*0] - block[offset+stride*4];
408         const int z2= block[offset+stride*1] - block[offset+stride*5];
409         const int z3= block[offset+stride*1] + block[offset+stride*5];
410
411         temp[4*i+0]= z0+z3;
412         temp[4*i+1]= z1+z2;
413         temp[4*i+2]= z1-z2;
414         temp[4*i+3]= z0-z3;
415     }
416
417     for(i=0; i<4; i++){
418         const int offset= x_offset[i];
419         const int z0= temp[4*0+i] + temp[4*2+i];
420         const int z1= temp[4*0+i] - temp[4*2+i];
421         const int z2= temp[4*1+i] - temp[4*3+i];
422         const int z3= temp[4*1+i] + temp[4*3+i];
423
424         block[stride*0 +offset]= (z0 + z3)>>1;
425         block[stride*2 +offset]= (z1 + z2)>>1;
426         block[stride*8 +offset]= (z1 - z2)>>1;
427         block[stride*10+offset]= (z0 - z3)>>1;
428     }
429 }
430 #endif
431
432 #undef xStride
433 #undef stride
434
435 #if 0
436 static void chroma_dc_dct_c(DCTELEM *block){
437     const int stride= 16*2;
438     const int xStride= 16;
439     int a,b,c,d,e;
440
441     a= block[stride*0 + xStride*0];
442     b= block[stride*0 + xStride*1];
443     c= block[stride*1 + xStride*0];
444     d= block[stride*1 + xStride*1];
445
446     e= a-b;
447     a= a+b;
448     b= c-d;
449     c= c+d;
450
451     block[stride*0 + xStride*0]= (a+c);
452     block[stride*0 + xStride*1]= (e+b);
453     block[stride*1 + xStride*0]= (a-c);
454     block[stride*1 + xStride*1]= (e-b);
455 }
456 #endif
457
458 static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
459                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
460                            int src_x_offset, int src_y_offset,
461                            qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op,
462                            int pixel_shift, int chroma444){
463     MpegEncContext * const s = &h->s;
464     const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
465     int my=       h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
466     const int luma_xy= (mx&3) + ((my&3)<<2);
467     int offset = ((mx>>2) << pixel_shift) + (my>>2)*h->mb_linesize;
468     uint8_t * src_y = pic->data[0] + offset;
469     uint8_t * src_cb, * src_cr;
470     int extra_width= h->emu_edge_width;
471     int extra_height= h->emu_edge_height;
472     int emu=0;
473     const int full_mx= mx>>2;
474     const int full_my= my>>2;
475     const int pic_width  = 16*s->mb_width;
476     const int pic_height = 16*s->mb_height >> MB_FIELD;
477
478     if(mx&7) extra_width -= 3;
479     if(my&7) extra_height -= 3;
480
481     if(   full_mx < 0-extra_width
482        || full_my < 0-extra_height
483        || full_mx + 16/*FIXME*/ > pic_width + extra_width
484        || full_my + 16/*FIXME*/ > pic_height + extra_height){
485         s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_y - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
486             src_y= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
487         emu=1;
488     }
489
490     qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
491     if(!square){
492         qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
493     }
494
495     if(CONFIG_GRAY && s->flags&CODEC_FLAG_GRAY) return;
496
497     if(chroma444){
498         src_cb = pic->data[1] + offset;
499         if(emu){
500             s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
501                                     16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
502             src_cb= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
503         }
504         qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); //FIXME try variable height perhaps?
505         if(!square){
506             qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
507         }
508
509         src_cr = pic->data[2] + offset;
510         if(emu){
511             s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
512                                     16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
513             src_cr= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
514         }
515         qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); //FIXME try variable height perhaps?
516         if(!square){
517             qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
518         }
519         return;
520     }
521
522     if(MB_FIELD){
523         // chroma offset when predicting from a field of opposite parity
524         my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
525         emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
526     }
527     src_cb= pic->data[1] + ((mx>>3) << pixel_shift) + (my>>3)*h->mb_uvlinesize;
528     src_cr= pic->data[2] + ((mx>>3) << pixel_shift) + (my>>3)*h->mb_uvlinesize;
529
530     if(emu){
531         s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
532             src_cb= s->edge_emu_buffer;
533     }
534     chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
535
536     if(emu){
537         s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
538             src_cr= s->edge_emu_buffer;
539     }
540     chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
541 }
542
543 static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
544                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
545                            int x_offset, int y_offset,
546                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
547                            qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
548                            int list0, int list1, int pixel_shift, int chroma444){
549     MpegEncContext * const s = &h->s;
550     qpel_mc_func *qpix_op=  qpix_put;
551     h264_chroma_mc_func chroma_op= chroma_put;
552
553     dest_y  += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
554     if(chroma444){
555         dest_cb += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
556         dest_cr += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
557     }else{
558         dest_cb += (  x_offset << pixel_shift) +   y_offset*h->mb_uvlinesize;
559         dest_cr += (  x_offset << pixel_shift) +   y_offset*h->mb_uvlinesize;
560     }
561     x_offset += 8*s->mb_x;
562     y_offset += 8*(s->mb_y >> MB_FIELD);
563
564     if(list0){
565         Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
566         mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
567                            dest_y, dest_cb, dest_cr, x_offset, y_offset,
568                            qpix_op, chroma_op, pixel_shift, chroma444);
569
570         qpix_op=  qpix_avg;
571         chroma_op= chroma_avg;
572     }
573
574     if(list1){
575         Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
576         mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
577                            dest_y, dest_cb, dest_cr, x_offset, y_offset,
578                            qpix_op, chroma_op, pixel_shift, chroma444);
579     }
580 }
581
582 static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
583                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
584                            int x_offset, int y_offset,
585                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
586                            h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
587                            h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
588                            int list0, int list1, int pixel_shift, int chroma444){
589     MpegEncContext * const s = &h->s;
590
591     dest_y += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
592     if(chroma444){
593         chroma_weight_avg = luma_weight_avg;
594         chroma_weight_op = luma_weight_op;
595         dest_cb += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
596         dest_cr += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
597     }else{
598         dest_cb += (  x_offset << pixel_shift) +   y_offset*h->mb_uvlinesize;
599         dest_cr += (  x_offset << pixel_shift) +   y_offset*h->mb_uvlinesize;
600     }
601     x_offset += 8*s->mb_x;
602     y_offset += 8*(s->mb_y >> MB_FIELD);
603
604     if(list0 && list1){
605         /* don't optimize for luma-only case, since B-frames usually
606          * use implicit weights => chroma too. */
607         uint8_t *tmp_cb = s->obmc_scratchpad;
608         uint8_t *tmp_cr = s->obmc_scratchpad + (16 << pixel_shift);
609         uint8_t *tmp_y  = s->obmc_scratchpad + 16*h->mb_uvlinesize;
610         int refn0 = h->ref_cache[0][ scan8[n] ];
611         int refn1 = h->ref_cache[1][ scan8[n] ];
612
613         mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
614                     dest_y, dest_cb, dest_cr,
615                     x_offset, y_offset, qpix_put, chroma_put, pixel_shift, chroma444);
616         mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
617                     tmp_y, tmp_cb, tmp_cr,
618                     x_offset, y_offset, qpix_put, chroma_put, pixel_shift, chroma444);
619
620         if(h->use_weight == 2){
621             int weight0 = h->implicit_weight[refn0][refn1][s->mb_y&1];
622             int weight1 = 64 - weight0;
623             luma_weight_avg(  dest_y,  tmp_y,  h->  mb_linesize, 5, weight0, weight1, 0);
624             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
625             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
626         }else{
627             luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
628                             h->luma_weight[refn0][0][0] , h->luma_weight[refn1][1][0],
629                             h->luma_weight[refn0][0][1] + h->luma_weight[refn1][1][1]);
630             chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
631                             h->chroma_weight[refn0][0][0][0] , h->chroma_weight[refn1][1][0][0],
632                             h->chroma_weight[refn0][0][0][1] + h->chroma_weight[refn1][1][0][1]);
633             chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
634                             h->chroma_weight[refn0][0][1][0] , h->chroma_weight[refn1][1][1][0],
635                             h->chroma_weight[refn0][0][1][1] + h->chroma_weight[refn1][1][1][1]);
636         }
637     }else{
638         int list = list1 ? 1 : 0;
639         int refn = h->ref_cache[list][ scan8[n] ];
640         Picture *ref= &h->ref_list[list][refn];
641         mc_dir_part(h, ref, n, square, chroma_height, delta, list,
642                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
643                     qpix_put, chroma_put, pixel_shift, chroma444);
644
645         luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
646                        h->luma_weight[refn][list][0], h->luma_weight[refn][list][1]);
647         if(h->use_weight_chroma){
648             chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
649                              h->chroma_weight[refn][list][0][0], h->chroma_weight[refn][list][0][1]);
650             chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
651                              h->chroma_weight[refn][list][1][0], h->chroma_weight[refn][list][1][1]);
652         }
653     }
654 }
655
656 static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
657                            uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
658                            int x_offset, int y_offset,
659                            qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
660                            qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
661                            h264_weight_func *weight_op, h264_biweight_func *weight_avg,
662                            int list0, int list1, int pixel_shift, int chroma444){
663     if((h->use_weight==2 && list0 && list1
664         && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ][h->s.mb_y&1] != 32))
665        || h->use_weight==1)
666         mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
667                          x_offset, y_offset, qpix_put, chroma_put,
668                          weight_op[0], weight_op[3], weight_avg[0],
669                          weight_avg[3], list0, list1, pixel_shift, chroma444);
670     else
671         mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
672                     x_offset, y_offset, qpix_put, chroma_put, qpix_avg,
673                     chroma_avg, list0, list1, pixel_shift, chroma444);
674 }
675
676 static inline void prefetch_motion(H264Context *h, int list, int pixel_shift, int chroma444){
677     /* fetch pixels for estimated mv 4 macroblocks ahead
678      * optimized for 64byte cache lines */
679     MpegEncContext * const s = &h->s;
680     const int refn = h->ref_cache[list][scan8[0]];
681     if(refn >= 0){
682         const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
683         const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
684         uint8_t **src= h->ref_list[list][refn].data;
685         int off= ((mx+64)<<h->pixel_shift) + (my + (s->mb_x&3)*4)*h->mb_linesize;
686         s->dsp.prefetch(src[0]+off, s->linesize, 4);
687         if(chroma444){
688             s->dsp.prefetch(src[1]+off, s->linesize, 4);
689             s->dsp.prefetch(src[2]+off, s->linesize, 4);
690         }else{
691             off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
692             s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
693         }
694     }
695 }
696
697 static av_always_inline void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
698                       qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
699                       qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
700                       h264_weight_func *weight_op, h264_biweight_func *weight_avg,
701                       int pixel_shift, int chroma444){
702     MpegEncContext * const s = &h->s;
703     const int mb_xy= h->mb_xy;
704     const int mb_type= s->current_picture.mb_type[mb_xy];
705
706     assert(IS_INTER(mb_type));
707
708     if(HAVE_PTHREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
709         await_references(h);
710     prefetch_motion(h, 0, pixel_shift, chroma444);
711
712     if(IS_16X16(mb_type)){
713         mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
714                 qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
715                 weight_op, weight_avg,
716                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
717                 pixel_shift, chroma444);
718     }else if(IS_16X8(mb_type)){
719         mc_part(h, 0, 0, 4, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 0,
720                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
721                 &weight_op[1], &weight_avg[1],
722                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
723                 pixel_shift, chroma444);
724         mc_part(h, 8, 0, 4, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 4,
725                 qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
726                 &weight_op[1], &weight_avg[1],
727                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
728                 pixel_shift, chroma444);
729     }else if(IS_8X16(mb_type)){
730         mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
731                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
732                 &weight_op[2], &weight_avg[2],
733                 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
734                 pixel_shift, chroma444);
735         mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
736                 qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
737                 &weight_op[2], &weight_avg[2],
738                 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
739                 pixel_shift, chroma444);
740     }else{
741         int i;
742
743         assert(IS_8X8(mb_type));
744
745         for(i=0; i<4; i++){
746             const int sub_mb_type= h->sub_mb_type[i];
747             const int n= 4*i;
748             int x_offset= (i&1)<<2;
749             int y_offset= (i&2)<<1;
750
751             if(IS_SUB_8X8(sub_mb_type)){
752                 mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
753                     qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
754                     &weight_op[3], &weight_avg[3],
755                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
756                     pixel_shift, chroma444);
757             }else if(IS_SUB_8X4(sub_mb_type)){
758                 mc_part(h, n  , 0, 2, 4 << pixel_shift, dest_y, dest_cb, dest_cr, x_offset, y_offset,
759                     qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
760                     &weight_op[4], &weight_avg[4],
761                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
762                     pixel_shift, chroma444);
763                 mc_part(h, n+2, 0, 2, 4 << pixel_shift, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
764                     qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
765                     &weight_op[4], &weight_avg[4],
766                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
767                     pixel_shift, chroma444);
768             }else if(IS_SUB_4X8(sub_mb_type)){
769                 mc_part(h, n  , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
770                     qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
771                     &weight_op[5], &weight_avg[5],
772                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
773                     pixel_shift, chroma444);
774                 mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
775                     qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
776                     &weight_op[5], &weight_avg[5],
777                     IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
778                     pixel_shift, chroma444);
779             }else{
780                 int j;
781                 assert(IS_SUB_4X4(sub_mb_type));
782                 for(j=0; j<4; j++){
783                     int sub_x_offset= x_offset + 2*(j&1);
784                     int sub_y_offset= y_offset +   (j&2);
785                     mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
786                         qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
787                         &weight_op[6], &weight_avg[6],
788                         IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
789                         pixel_shift, chroma444);
790                 }
791             }
792         }
793     }
794
795     prefetch_motion(h, 1, pixel_shift, chroma444);
796 }
797
798 #define hl_motion_fn(sh, bits) \
799 static av_always_inline void hl_motion_ ## bits(H264Context *h, \
800                                        uint8_t *dest_y, \
801                                        uint8_t *dest_cb, uint8_t *dest_cr, \
802                                        qpel_mc_func (*qpix_put)[16], \
803                                        h264_chroma_mc_func (*chroma_put), \
804                                        qpel_mc_func (*qpix_avg)[16], \
805                                        h264_chroma_mc_func (*chroma_avg), \
806                                        h264_weight_func *weight_op, \
807                                        h264_biweight_func *weight_avg, \
808                                        int chroma444) \
809 { \
810     hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put, \
811               qpix_avg, chroma_avg, weight_op, weight_avg, sh, chroma444); \
812 }
813 hl_motion_fn(0, 8);
814 hl_motion_fn(1, 16);
815
816 static void free_tables(H264Context *h, int free_rbsp){
817     int i;
818     H264Context *hx;
819
820     av_freep(&h->intra4x4_pred_mode);
821     av_freep(&h->chroma_pred_mode_table);
822     av_freep(&h->cbp_table);
823     av_freep(&h->mvd_table[0]);
824     av_freep(&h->mvd_table[1]);
825     av_freep(&h->direct_table);
826     av_freep(&h->non_zero_count);
827     av_freep(&h->slice_table_base);
828     h->slice_table= NULL;
829     av_freep(&h->list_counts);
830
831     av_freep(&h->mb2b_xy);
832     av_freep(&h->mb2br_xy);
833
834     for(i = 0; i < MAX_THREADS; i++) {
835         hx = h->thread_context[i];
836         if(!hx) continue;
837         av_freep(&hx->top_borders[1]);
838         av_freep(&hx->top_borders[0]);
839         av_freep(&hx->s.obmc_scratchpad);
840         if (free_rbsp){
841             av_freep(&hx->rbsp_buffer[1]);
842             av_freep(&hx->rbsp_buffer[0]);
843             hx->rbsp_buffer_size[0] = 0;
844             hx->rbsp_buffer_size[1] = 0;
845         }
846         if (i) av_freep(&h->thread_context[i]);
847     }
848 }
849
850 static void init_dequant8_coeff_table(H264Context *h){
851     int i,j,q,x;
852     const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
853
854     for(i=0; i<6; i++ ){
855         h->dequant8_coeff[i] = h->dequant8_buffer[i];
856         for(j=0; j<i; j++){
857             if(!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i], 64*sizeof(uint8_t))){
858                 h->dequant8_coeff[i] = h->dequant8_buffer[j];
859                 break;
860             }
861         }
862         if(j<i)
863             continue;
864
865         for(q=0; q<max_qp+1; q++){
866             int shift = div6[q];
867             int idx = rem6[q];
868             for(x=0; x<64; x++)
869                 h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
870                     ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
871                     h->pps.scaling_matrix8[i][x]) << shift;
872         }
873     }
874 }
875
876 static void init_dequant4_coeff_table(H264Context *h){
877     int i,j,q,x;
878     const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
879     for(i=0; i<6; i++ ){
880         h->dequant4_coeff[i] = h->dequant4_buffer[i];
881         for(j=0; j<i; j++){
882             if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
883                 h->dequant4_coeff[i] = h->dequant4_buffer[j];
884                 break;
885             }
886         }
887         if(j<i)
888             continue;
889
890         for(q=0; q<max_qp+1; q++){
891             int shift = div6[q] + 2;
892             int idx = rem6[q];
893             for(x=0; x<16; x++)
894                 h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
895                     ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
896                     h->pps.scaling_matrix4[i][x]) << shift;
897         }
898     }
899 }
900
901 static void init_dequant_tables(H264Context *h){
902     int i,x;
903     init_dequant4_coeff_table(h);
904     if(h->pps.transform_8x8_mode)
905         init_dequant8_coeff_table(h);
906     if(h->sps.transform_bypass){
907         for(i=0; i<6; i++)
908             for(x=0; x<16; x++)
909                 h->dequant4_coeff[i][0][x] = 1<<6;
910         if(h->pps.transform_8x8_mode)
911             for(i=0; i<6; i++)
912                 for(x=0; x<64; x++)
913                     h->dequant8_coeff[i][0][x] = 1<<6;
914     }
915 }
916
917
918 int ff_h264_alloc_tables(H264Context *h){
919     MpegEncContext * const s = &h->s;
920     const int big_mb_num= s->mb_stride * (s->mb_height+1);
921     const int row_mb_num= 2*s->mb_stride*s->avctx->thread_count;
922     int x,y;
923
924     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode, row_mb_num * 8  * sizeof(uint8_t), fail)
925
926     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count    , big_mb_num * 48 * sizeof(uint8_t), fail)
927     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
928     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
929
930     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
931     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
932     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
933     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
934     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
935
936     memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(*h->slice_table_base));
937     h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
938
939     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy  , big_mb_num * sizeof(uint32_t), fail);
940     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy , big_mb_num * sizeof(uint32_t), fail);
941     for(y=0; y<s->mb_height; y++){
942         for(x=0; x<s->mb_width; x++){
943             const int mb_xy= x + y*s->mb_stride;
944             const int b_xy = 4*x + 4*y*h->b_stride;
945
946             h->mb2b_xy [mb_xy]= b_xy;
947             h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
948         }
949     }
950
951     s->obmc_scratchpad = NULL;
952
953     if(!h->dequant4_coeff[0])
954         init_dequant_tables(h);
955
956     return 0;
957 fail:
958     free_tables(h, 1);
959     return -1;
960 }
961
962 /**
963  * Mimic alloc_tables(), but for every context thread.
964  */
965 static void clone_tables(H264Context *dst, H264Context *src, int i){
966     MpegEncContext * const s = &src->s;
967     dst->intra4x4_pred_mode       = src->intra4x4_pred_mode + i*8*2*s->mb_stride;
968     dst->non_zero_count           = src->non_zero_count;
969     dst->slice_table              = src->slice_table;
970     dst->cbp_table                = src->cbp_table;
971     dst->mb2b_xy                  = src->mb2b_xy;
972     dst->mb2br_xy                 = src->mb2br_xy;
973     dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;
974     dst->mvd_table[0]             = src->mvd_table[0] + i*8*2*s->mb_stride;
975     dst->mvd_table[1]             = src->mvd_table[1] + i*8*2*s->mb_stride;
976     dst->direct_table             = src->direct_table;
977     dst->list_counts              = src->list_counts;
978
979     dst->s.obmc_scratchpad = NULL;
980     ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma);
981 }
982
983 /**
984  * Init context
985  * Allocate buffers which are not shared amongst multiple threads.
986  */
987 static int context_init(H264Context *h){
988     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * 16*3 * sizeof(uint8_t)*2, fail)
989     FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * 16*3 * sizeof(uint8_t)*2, fail)
990
991     h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
992     h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
993
994     return 0;
995 fail:
996     return -1; // free_tables will clean up for us
997 }
998
999 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
1000
1001 static av_cold void common_init(H264Context *h){
1002     MpegEncContext * const s = &h->s;
1003
1004     s->width = s->avctx->width;
1005     s->height = s->avctx->height;
1006     s->codec_id= s->avctx->codec->id;
1007
1008     s->avctx->bits_per_raw_sample = 8;
1009
1010     ff_h264dsp_init(&h->h264dsp,
1011                     s->avctx->bits_per_raw_sample);
1012     ff_h264_pred_init(&h->hpc, s->codec_id,
1013                       s->avctx->bits_per_raw_sample);
1014
1015     h->dequant_coeff_pps= -1;
1016     s->unrestricted_mv=1;
1017     s->decode=1; //FIXME
1018
1019     dsputil_init(&s->dsp, s->avctx); // needed so that idct permutation is known early
1020
1021     memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
1022     memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
1023 }
1024
1025 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1026 {
1027     AVCodecContext *avctx = h->s.avctx;
1028
1029     if(!buf || size <= 0)
1030         return -1;
1031
1032     if(buf[0] == 1){
1033         int i, cnt, nalsize;
1034         const unsigned char *p = buf;
1035
1036         h->is_avc = 1;
1037
1038         if(size < 7) {
1039             av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1040             return -1;
1041         }
1042         /* sps and pps in the avcC always have length coded with 2 bytes,
1043            so put a fake nal_length_size = 2 while parsing them */
1044         h->nal_length_size = 2;
1045         // Decode sps from avcC
1046         cnt = *(p+5) & 0x1f; // Number of sps
1047         p += 6;
1048         for (i = 0; i < cnt; i++) {
1049             nalsize = AV_RB16(p) + 2;
1050             if(nalsize > size - (p-buf))
1051                 return -1;
1052             if(decode_nal_units(h, p, nalsize) < 0) {
1053                 av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
1054                 return -1;
1055             }
1056             p += nalsize;
1057         }
1058         // Decode pps from avcC
1059         cnt = *(p++); // Number of pps
1060         for (i = 0; i < cnt; i++) {
1061             nalsize = AV_RB16(p) + 2;
1062             if(nalsize > size - (p-buf))
1063                 return -1;
1064             if (decode_nal_units(h, p, nalsize) < 0) {
1065                 av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
1066                 return -1;
1067             }
1068             p += nalsize;
1069         }
1070         // Now store right nal length size, that will be use to parse all other nals
1071         h->nal_length_size = (buf[4] & 0x03) + 1;
1072     } else {
1073         h->is_avc = 0;
1074         if(decode_nal_units(h, buf, size) < 0)
1075             return -1;
1076     }
1077     return 0;
1078 }
1079
1080 av_cold int ff_h264_decode_init(AVCodecContext *avctx){
1081     H264Context *h= avctx->priv_data;
1082     MpegEncContext * const s = &h->s;
1083
1084     MPV_decode_defaults(s);
1085
1086     s->avctx = avctx;
1087     common_init(h);
1088
1089     s->out_format = FMT_H264;
1090     s->workaround_bugs= avctx->workaround_bugs;
1091
1092     // set defaults
1093 //    s->decode_mb= ff_h263_decode_mb;
1094     s->quarter_sample = 1;
1095     if(!avctx->has_b_frames)
1096     s->low_delay= 1;
1097
1098     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1099
1100     ff_h264_decode_init_vlc();
1101
1102     h->pixel_shift = 0;
1103     h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1104
1105     h->thread_context[0] = h;
1106     h->outputed_poc = h->next_outputed_poc = INT_MIN;
1107     h->prev_poc_msb= 1<<16;
1108     h->x264_build = -1;
1109     ff_h264_reset_sei(h);
1110     if(avctx->codec_id == CODEC_ID_H264){
1111         if(avctx->ticks_per_frame == 1){
1112             s->avctx->time_base.den *=2;
1113         }
1114         avctx->ticks_per_frame = 2;
1115     }
1116
1117     if(avctx->extradata_size > 0 && avctx->extradata &&
1118         ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size))
1119         return -1;
1120
1121     if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1122         s->avctx->has_b_frames = h->sps.num_reorder_frames;
1123         s->low_delay = 0;
1124     }
1125
1126     return 0;
1127 }
1128
1129 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b)+(size))))
1130 static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
1131 {
1132     int i;
1133
1134     for (i=0; i<count; i++){
1135         assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1136                 IN_RANGE(from[i], old_base->picture, sizeof(Picture) * old_base->picture_count) ||
1137                 !from[i]));
1138         to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1139     }
1140 }
1141
1142 static void copy_parameter_set(void **to, void **from, int count, int size)
1143 {
1144     int i;
1145
1146     for (i=0; i<count; i++){
1147         if (to[i] && !from[i]) av_freep(&to[i]);
1148         else if (from[i] && !to[i]) to[i] = av_malloc(size);
1149
1150         if (from[i]) memcpy(to[i], from[i], size);
1151     }
1152 }
1153
1154 static int decode_init_thread_copy(AVCodecContext *avctx){
1155     H264Context *h= avctx->priv_data;
1156
1157     if (!avctx->is_copy) return 0;
1158     memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1159     memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1160
1161     return 0;
1162 }
1163
1164 #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
1165 static int decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src){
1166     H264Context *h= dst->priv_data, *h1= src->priv_data;
1167     MpegEncContext * const s = &h->s, * const s1 = &h1->s;
1168     int inited = s->context_initialized, err;
1169     int i;
1170
1171     if(dst == src || !s1->context_initialized) return 0;
1172
1173     err = ff_mpeg_update_thread_context(dst, src);
1174     if(err) return err;
1175
1176     //FIXME handle width/height changing
1177     if(!inited){
1178         for(i = 0; i < MAX_SPS_COUNT; i++)
1179             av_freep(h->sps_buffers + i);
1180
1181         for(i = 0; i < MAX_PPS_COUNT; i++)
1182             av_freep(h->pps_buffers + i);
1183
1184         memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
1185         memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1186         memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1187         if (ff_h264_alloc_tables(h) < 0) {
1188             av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1189             return AVERROR(ENOMEM);
1190         }
1191         context_init(h);
1192
1193         for(i=0; i<2; i++){
1194             h->rbsp_buffer[i] = NULL;
1195             h->rbsp_buffer_size[i] = 0;
1196         }
1197
1198         h->thread_context[0] = h;
1199
1200         // frame_start may not be called for the next thread (if it's decoding a bottom field)
1201         // so this has to be allocated here
1202         h->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
1203
1204         s->dsp.clear_blocks(h->mb);
1205         s->dsp.clear_blocks(h->mb+(24*16<<h->pixel_shift));
1206     }
1207
1208     //extradata/NAL handling
1209     h->is_avc          = h1->is_avc;
1210
1211     //SPS/PPS
1212     copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
1213     h->sps             = h1->sps;
1214     copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
1215     h->pps             = h1->pps;
1216
1217     //Dequantization matrices
1218     //FIXME these are big - can they be only copied when PPS changes?
1219     copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1220
1221     for(i=0; i<6; i++)
1222         h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1223
1224     for(i=0; i<6; i++)
1225         h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1226
1227     h->dequant_coeff_pps = h1->dequant_coeff_pps;
1228
1229     //POC timing
1230     copy_fields(h, h1, poc_lsb, redundant_pic_count);
1231
1232     //reference lists
1233     copy_fields(h, h1, ref_count, list_count);
1234     copy_fields(h, h1, ref_list,  intra_gb);
1235     copy_fields(h, h1, short_ref, cabac_init_idc);
1236
1237     copy_picture_range(h->short_ref,   h1->short_ref,   32, s, s1);
1238     copy_picture_range(h->long_ref,    h1->long_ref,    32, s, s1);
1239     copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
1240
1241     h->last_slice_type = h1->last_slice_type;
1242
1243     if(!s->current_picture_ptr) return 0;
1244
1245     if(!s->dropable) {
1246         ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1247         h->prev_poc_msb     = h->poc_msb;
1248         h->prev_poc_lsb     = h->poc_lsb;
1249     }
1250     h->prev_frame_num_offset= h->frame_num_offset;
1251     h->prev_frame_num       = h->frame_num;
1252     h->outputed_poc         = h->next_outputed_poc;
1253
1254     return 0;
1255 }
1256
1257 int ff_h264_frame_start(H264Context *h){
1258     MpegEncContext * const s = &h->s;
1259     int i;
1260     const int pixel_shift = h->pixel_shift;
1261     int thread_count = (s->avctx->active_thread_type & FF_THREAD_SLICE) ? s->avctx->thread_count : 1;
1262
1263     if(MPV_frame_start(s, s->avctx) < 0)
1264         return -1;
1265     ff_er_frame_start(s);
1266     /*
1267      * MPV_frame_start uses pict_type to derive key_frame.
1268      * This is incorrect for H.264; IDR markings must be used.
1269      * Zero here; IDR markings per slice in frame or fields are ORed in later.
1270      * See decode_nal_units().
1271      */
1272     s->current_picture_ptr->key_frame= 0;
1273     s->current_picture_ptr->mmco_reset= 0;
1274
1275     assert(s->linesize && s->uvlinesize);
1276
1277     for(i=0; i<16; i++){
1278         h->block_offset[i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
1279         h->block_offset[48+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
1280     }
1281     for(i=0; i<16; i++){
1282         h->block_offset[16+i]=
1283         h->block_offset[32+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1284         h->block_offset[48+16+i]=
1285         h->block_offset[48+32+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1286     }
1287
1288     /* can't be in alloc_tables because linesize isn't known there.
1289      * FIXME: redo bipred weight to not require extra buffer? */
1290     for(i = 0; i < thread_count; i++)
1291         if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
1292             h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
1293
1294     /* some macroblocks can be accessed before they're available in case of lost slices, mbaff or threading*/
1295     memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(*h->slice_table));
1296
1297 //    s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
1298
1299     // We mark the current picture as non-reference after allocating it, so
1300     // that if we break out due to an error it can be released automatically
1301     // in the next MPV_frame_start().
1302     // SVQ3 as well as most other codecs have only last/next/current and thus
1303     // get released even with set reference, besides SVQ3 and others do not
1304     // mark frames as reference later "naturally".
1305     if(s->codec_id != CODEC_ID_SVQ3)
1306         s->current_picture_ptr->reference= 0;
1307
1308     s->current_picture_ptr->field_poc[0]=
1309     s->current_picture_ptr->field_poc[1]= INT_MAX;
1310
1311     h->next_output_pic = NULL;
1312
1313     assert(s->current_picture_ptr->long_ref==0);
1314
1315     return 0;
1316 }
1317
1318 /**
1319   * Run setup operations that must be run after slice header decoding.
1320   * This includes finding the next displayed frame.
1321   *
1322   * @param h h264 master context
1323   * @param setup_finished enough NALs have been read that we can call
1324   * ff_thread_finish_setup()
1325   */
1326 static void decode_postinit(H264Context *h, int setup_finished){
1327     MpegEncContext * const s = &h->s;
1328     Picture *out = s->current_picture_ptr;
1329     Picture *cur = s->current_picture_ptr;
1330     int i, pics, out_of_order, out_idx;
1331
1332     s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
1333     s->current_picture_ptr->pict_type= s->pict_type;
1334
1335     if (h->next_output_pic) return;
1336
1337     if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
1338         //FIXME: if we have two PAFF fields in one packet, we can't start the next thread here.
1339         //If we have one field per packet, we can. The check in decode_nal_units() is not good enough
1340         //to find this yet, so we assume the worst for now.
1341         //if (setup_finished)
1342         //    ff_thread_finish_setup(s->avctx);
1343         return;
1344     }
1345
1346     cur->interlaced_frame = 0;
1347     cur->repeat_pict = 0;
1348
1349     /* Signal interlacing information externally. */
1350     /* Prioritize picture timing SEI information over used decoding process if it exists. */
1351
1352     if(h->sps.pic_struct_present_flag){
1353         switch (h->sei_pic_struct)
1354         {
1355         case SEI_PIC_STRUCT_FRAME:
1356             break;
1357         case SEI_PIC_STRUCT_TOP_FIELD:
1358         case SEI_PIC_STRUCT_BOTTOM_FIELD:
1359             cur->interlaced_frame = 1;
1360             break;
1361         case SEI_PIC_STRUCT_TOP_BOTTOM:
1362         case SEI_PIC_STRUCT_BOTTOM_TOP:
1363             if (FIELD_OR_MBAFF_PICTURE)
1364                 cur->interlaced_frame = 1;
1365             else
1366                 // try to flag soft telecine progressive
1367                 cur->interlaced_frame = h->prev_interlaced_frame;
1368             break;
1369         case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1370         case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1371             // Signal the possibility of telecined film externally (pic_struct 5,6)
1372             // From these hints, let the applications decide if they apply deinterlacing.
1373             cur->repeat_pict = 1;
1374             break;
1375         case SEI_PIC_STRUCT_FRAME_DOUBLING:
1376             // Force progressive here, as doubling interlaced frame is a bad idea.
1377             cur->repeat_pict = 2;
1378             break;
1379         case SEI_PIC_STRUCT_FRAME_TRIPLING:
1380             cur->repeat_pict = 4;
1381             break;
1382         }
1383
1384         if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1385             cur->interlaced_frame = (h->sei_ct_type & (1<<1)) != 0;
1386     }else{
1387         /* Derive interlacing flag from used decoding process. */
1388         cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1389     }
1390     h->prev_interlaced_frame = cur->interlaced_frame;
1391
1392     if (cur->field_poc[0] != cur->field_poc[1]){
1393         /* Derive top_field_first from field pocs. */
1394         cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
1395     }else{
1396         if(cur->interlaced_frame || h->sps.pic_struct_present_flag){
1397             /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
1398             if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
1399               || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1400                 cur->top_field_first = 1;
1401             else
1402                 cur->top_field_first = 0;
1403         }else{
1404             /* Most likely progressive */
1405             cur->top_field_first = 0;
1406         }
1407     }
1408
1409     //FIXME do something with unavailable reference frames
1410
1411     /* Sort B-frames into display order */
1412
1413     if(h->sps.bitstream_restriction_flag
1414        && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1415         s->avctx->has_b_frames = h->sps.num_reorder_frames;
1416         s->low_delay = 0;
1417     }
1418
1419     if(   s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
1420        && !h->sps.bitstream_restriction_flag){
1421         s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;
1422         s->low_delay= 0;
1423     }
1424
1425     pics = 0;
1426     while(h->delayed_pic[pics]) pics++;
1427
1428     av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
1429
1430     h->delayed_pic[pics++] = cur;
1431     if(cur->reference == 0)
1432         cur->reference = DELAYED_PIC_REF;
1433
1434     out = h->delayed_pic[0];
1435     out_idx = 0;
1436     for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
1437         if(h->delayed_pic[i]->poc < out->poc){
1438             out = h->delayed_pic[i];
1439             out_idx = i;
1440         }
1441     if(s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset))
1442         h->next_outputed_poc= INT_MIN;
1443     out_of_order = out->poc < h->next_outputed_poc;
1444
1445     if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
1446         { }
1447     else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)
1448        || (s->low_delay &&
1449         ((h->next_outputed_poc != INT_MIN && out->poc > h->next_outputed_poc + 2)
1450          || cur->pict_type == AV_PICTURE_TYPE_B)))
1451     {
1452         s->low_delay = 0;
1453         s->avctx->has_b_frames++;
1454     }
1455
1456     if(out_of_order || pics > s->avctx->has_b_frames){
1457         out->reference &= ~DELAYED_PIC_REF;
1458         out->owner2 = s; // for frame threading, the owner must be the second field's thread
1459                          // or else the first thread can release the picture and reuse it unsafely
1460         for(i=out_idx; h->delayed_pic[i]; i++)
1461             h->delayed_pic[i] = h->delayed_pic[i+1];
1462     }
1463     if(!out_of_order && pics > s->avctx->has_b_frames){
1464         h->next_output_pic = out;
1465         if(out_idx==0 && h->delayed_pic[0] && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset)) {
1466             h->next_outputed_poc = INT_MIN;
1467         } else
1468             h->next_outputed_poc = out->poc;
1469     }else{
1470         av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
1471     }
1472
1473     if (setup_finished)
1474         ff_thread_finish_setup(s->avctx);
1475 }
1476
1477 static inline void backup_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int chroma444, int simple){
1478     MpegEncContext * const s = &h->s;
1479     uint8_t *top_border;
1480     int top_idx = 1;
1481     const int pixel_shift = h->pixel_shift;
1482
1483     src_y  -=   linesize;
1484     src_cb -= uvlinesize;
1485     src_cr -= uvlinesize;
1486
1487     if(!simple && FRAME_MBAFF){
1488         if(s->mb_y&1){
1489             if(!MB_MBAFF){
1490                 top_border = h->top_borders[0][s->mb_x];
1491                 AV_COPY128(top_border, src_y + 15*linesize);
1492                 if (pixel_shift)
1493                     AV_COPY128(top_border+16, src_y+15*linesize+16);
1494                 if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1495                     if(chroma444){
1496                         if (pixel_shift){
1497                             AV_COPY128(top_border+32, src_cb + 15*uvlinesize);
1498                             AV_COPY128(top_border+48, src_cb + 15*uvlinesize+16);
1499                             AV_COPY128(top_border+64, src_cr + 15*uvlinesize);
1500                             AV_COPY128(top_border+80, src_cr + 15*uvlinesize+16);
1501                         } else {
1502                             AV_COPY128(top_border+16, src_cb + 15*uvlinesize);
1503                             AV_COPY128(top_border+32, src_cr + 15*uvlinesize);
1504                         }
1505                     } else {
1506                         if (pixel_shift) {
1507                             AV_COPY128(top_border+32, src_cb+7*uvlinesize);
1508                             AV_COPY128(top_border+48, src_cr+7*uvlinesize);
1509                         } else {
1510                             AV_COPY64(top_border+16, src_cb+7*uvlinesize);
1511                             AV_COPY64(top_border+24, src_cr+7*uvlinesize);
1512                         }
1513                     }
1514                 }
1515             }
1516         }else if(MB_MBAFF){
1517             top_idx = 0;
1518         }else
1519             return;
1520     }
1521
1522     top_border = h->top_borders[top_idx][s->mb_x];
1523     // There are two lines saved, the line above the the top macroblock of a pair,
1524     // and the line above the bottom macroblock
1525     AV_COPY128(top_border, src_y + 16*linesize);
1526     if (pixel_shift)
1527         AV_COPY128(top_border+16, src_y+16*linesize+16);
1528
1529     if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1530         if(chroma444){
1531             if (pixel_shift){
1532                 AV_COPY128(top_border+32, src_cb + 16*linesize);
1533                 AV_COPY128(top_border+48, src_cb + 16*linesize+16);
1534                 AV_COPY128(top_border+64, src_cr + 16*linesize);
1535                 AV_COPY128(top_border+80, src_cr + 16*linesize+16);
1536             } else {
1537                 AV_COPY128(top_border+16, src_cb + 16*linesize);
1538                 AV_COPY128(top_border+32, src_cr + 16*linesize);
1539             }
1540         } else {
1541             if (pixel_shift) {
1542                 AV_COPY128(top_border+32, src_cb+8*uvlinesize);
1543                 AV_COPY128(top_border+48, src_cr+8*uvlinesize);
1544             } else {
1545                 AV_COPY64(top_border+16, src_cb+8*uvlinesize);
1546                 AV_COPY64(top_border+24, src_cr+8*uvlinesize);
1547             }
1548         }
1549     }
1550 }
1551
1552 static inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1553                                   uint8_t *src_cb, uint8_t *src_cr,
1554                                   int linesize, int uvlinesize,
1555                                   int xchg, int chroma444,
1556                                   int simple, int pixel_shift){
1557     MpegEncContext * const s = &h->s;
1558     int deblock_topleft;
1559     int deblock_top;
1560     int top_idx = 1;
1561     uint8_t *top_border_m1;
1562     uint8_t *top_border;
1563
1564     if(!simple && FRAME_MBAFF){
1565         if(s->mb_y&1){
1566             if(!MB_MBAFF)
1567                 return;
1568         }else{
1569             top_idx = MB_MBAFF ? 0 : 1;
1570         }
1571     }
1572
1573     if(h->deblocking_filter == 2) {
1574         deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
1575         deblock_top     = h->top_type;
1576     } else {
1577         deblock_topleft = (s->mb_x > 0);
1578         deblock_top     = (s->mb_y > !!MB_FIELD);
1579     }
1580
1581     src_y  -=   linesize + 1 + pixel_shift;
1582     src_cb -= uvlinesize + 1 + pixel_shift;
1583     src_cr -= uvlinesize + 1 + pixel_shift;
1584
1585     top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1586     top_border    = h->top_borders[top_idx][s->mb_x];
1587
1588 #define XCHG(a,b,xchg)\
1589     if (pixel_shift) {\
1590         if (xchg) {\
1591             AV_SWAP64(b+0,a+0);\
1592             AV_SWAP64(b+8,a+8);\
1593         } else {\
1594             AV_COPY128(b,a); \
1595         }\
1596     } else \
1597 if (xchg) AV_SWAP64(b,a);\
1598 else      AV_COPY64(b,a);
1599
1600     if(deblock_top){
1601         if(deblock_topleft){
1602             XCHG(top_border_m1 + (8 << pixel_shift), src_y - (7 << pixel_shift), 1);
1603         }
1604         XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
1605         XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
1606         if(s->mb_x+1 < s->mb_width){
1607             XCHG(h->top_borders[top_idx][s->mb_x+1], src_y + (17 << pixel_shift), 1);
1608         }
1609     }
1610     if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1611         if(chroma444){
1612             if(deblock_topleft){
1613                 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1614                 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1615             }
1616             XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
1617             XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
1618             XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
1619             XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
1620             if(s->mb_x+1 < s->mb_width){
1621                 XCHG(h->top_borders[top_idx][s->mb_x+1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
1622                 XCHG(h->top_borders[top_idx][s->mb_x+1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
1623             }
1624         } else {
1625             if(deblock_top){
1626                 if(deblock_topleft){
1627                     XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
1628                     XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
1629                 }
1630                 XCHG(top_border + (16 << pixel_shift), src_cb+1+pixel_shift, 1);
1631                 XCHG(top_border + (24 << pixel_shift), src_cr+1+pixel_shift, 1);
1632             }
1633         }
1634     }
1635 }
1636
1637 static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth, int index) {
1638     if (high_bit_depth) {
1639         return AV_RN32A(((int32_t*)mb) + index);
1640     } else
1641         return AV_RN16A(mb + index);
1642 }
1643
1644 static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth, int index, int value) {
1645     if (high_bit_depth) {
1646         AV_WN32A(((int32_t*)mb) + index, value);
1647     } else
1648         AV_WN16A(mb + index, value);
1649 }
1650
1651 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,
1652                                                        int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)
1653 {
1654     MpegEncContext * const s = &h->s;
1655     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1656     void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1657     int i;
1658     int qscale = p == 0 ? s->qscale : h->chroma_qp[p-1];
1659     block_offset += 16*p;
1660     if(IS_INTRA4x4(mb_type)){
1661         if(simple || !s->encoding){
1662             if(IS_8x8DCT(mb_type)){
1663                 if(transform_bypass){
1664                     idct_dc_add =
1665                     idct_add    = s->dsp.add_pixels8;
1666                 }else{
1667                     idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1668                     idct_add    = h->h264dsp.h264_idct8_add;
1669                 }
1670                 for(i=0; i<16; i+=4){
1671                     uint8_t * const ptr= dest_y + block_offset[i];
1672                     const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1673                     if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1674                         h->hpc.pred8x8l_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1675                     }else{
1676                         const int nnz = h->non_zero_count_cache[ scan8[i+p*16] ];
1677                         h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
1678                                                     (h->topright_samples_available<<i)&0x4000, linesize);
1679                         if(nnz){
1680                             if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))
1681                                 idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1682                             else
1683                                 idct_add   (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1684                         }
1685                     }
1686                 }
1687             }else{
1688                 if(transform_bypass){
1689                     idct_dc_add =
1690                     idct_add    = s->dsp.add_pixels4;
1691                 }else{
1692                     idct_dc_add = h->h264dsp.h264_idct_dc_add;
1693                     idct_add    = h->h264dsp.h264_idct_add;
1694                 }
1695                 for(i=0; i<16; i++){
1696                     uint8_t * const ptr= dest_y + block_offset[i];
1697                     const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1698
1699                     if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1700                         h->hpc.pred4x4_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1701                     }else{
1702                         uint8_t *topright;
1703                         int nnz, tr;
1704                         uint64_t tr_high;
1705                         if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
1706                             const int topright_avail= (h->topright_samples_available<<i)&0x8000;
1707                             assert(s->mb_y || linesize <= block_offset[i]);
1708                             if(!topright_avail){
1709                                 if (pixel_shift) {
1710                                     tr_high= ((uint16_t*)ptr)[3 - linesize/2]*0x0001000100010001ULL;
1711                                     topright= (uint8_t*) &tr_high;
1712                                 } else {
1713                                     tr= ptr[3 - linesize]*0x01010101;
1714                                     topright= (uint8_t*) &tr;
1715                                 }
1716                             }else
1717                                 topright= ptr + (4 << pixel_shift) - linesize;
1718                         }else
1719                             topright= NULL;
1720
1721                         h->hpc.pred4x4[ dir ](ptr, topright, linesize);
1722                         nnz = h->non_zero_count_cache[ scan8[i+p*16] ];
1723                         if(nnz){
1724                             if(is_h264){
1725                                 if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))
1726                                     idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1727                                 else
1728                                     idct_add   (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
1729                             }else
1730                                 ff_svq3_add_idct_c(ptr, h->mb + i*16+p*256, linesize, qscale, 0);
1731                         }
1732                     }
1733                 }
1734             }
1735         }
1736     }else{
1737         h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
1738         if(is_h264){
1739             if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX+p] ]){
1740                 if(!transform_bypass)
1741                     h->h264dsp.h264_luma_dc_dequant_idct(h->mb+(p*256 << pixel_shift), h->mb_luma_dc[p], h->dequant4_coeff[p][qscale][0]);
1742                 else{
1743                     static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
1744                                                             8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
1745                     for(i = 0; i < 16; i++)
1746                         dctcoef_set(h->mb+p*256, pixel_shift, dc_mapping[i], dctcoef_get(h->mb_luma_dc[p], pixel_shift, i));
1747                 }
1748             }
1749         }else
1750             ff_svq3_luma_dc_dequant_idct_c(h->mb+p*256, h->mb_luma_dc[p], qscale);
1751     }
1752 }
1753
1754 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,
1755                                                     int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)
1756 {
1757     MpegEncContext * const s = &h->s;
1758     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1759     int i;
1760     block_offset += 16*p;
1761     if(!IS_INTRA4x4(mb_type)){
1762         if(is_h264){
1763             if(IS_INTRA16x16(mb_type)){
1764                 if(transform_bypass){
1765                     if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
1766                         h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize);
1767                     }else{
1768                         for(i=0; i<16; i++){
1769                             if(h->non_zero_count_cache[ scan8[i+p*16] ] || dctcoef_get(h->mb, pixel_shift, i*16+p*256))
1770                                 s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + (i*16+p*256 << pixel_shift), linesize);
1771                         }
1772                     }
1773                 }else{
1774                     h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
1775                 }
1776             }else if(h->cbp&15){
1777                 if(transform_bypass){
1778                     const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1779                     idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
1780                     for(i=0; i<16; i+=di){
1781                         if(h->non_zero_count_cache[ scan8[i+p*16] ]){
1782                             idct_add(dest_y + block_offset[i], h->mb + (i*16+p*256 << pixel_shift), linesize);
1783                         }
1784                     }
1785                 }else{
1786                     if(IS_8x8DCT(mb_type)){
1787                         h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
1788                     }else{
1789                         h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
1790                     }
1791                 }
1792             }
1793         }else{
1794             for(i=0; i<16; i++){
1795                 if(h->non_zero_count_cache[ scan8[i+p*16] ] || h->mb[i*16+p*256]){ //FIXME benchmark weird rule, & below
1796                     uint8_t * const ptr= dest_y + block_offset[i];
1797                     ff_svq3_add_idct_c(ptr, h->mb + i*16 + p*256, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1798                 }
1799             }
1800         }
1801     }
1802 }
1803
1804 static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple, int pixel_shift){
1805     MpegEncContext * const s = &h->s;
1806     const int mb_x= s->mb_x;
1807     const int mb_y= s->mb_y;
1808     const int mb_xy= h->mb_xy;
1809     const int mb_type= s->current_picture.mb_type[mb_xy];
1810     uint8_t  *dest_y, *dest_cb, *dest_cr;
1811     int linesize, uvlinesize /*dct_offset*/;
1812     int i, j;
1813     int *block_offset = &h->block_offset[0];
1814     const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
1815     /* is_h264 should always be true if SVQ3 is disabled. */
1816     const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
1817     void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1818
1819     dest_y  = s->current_picture.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize  ) * 16;
1820     dest_cb = s->current_picture.data[1] + ((mb_x << pixel_shift) + mb_y * s->uvlinesize) * 8;
1821     dest_cr = s->current_picture.data[2] + ((mb_x << pixel_shift) + mb_y * s->uvlinesize) * 8;
1822
1823     s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
1824     s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + (64 << pixel_shift), dest_cr - dest_cb, 2);
1825
1826     h->list_counts[mb_xy]= h->list_count;
1827
1828     if (!simple && MB_FIELD) {
1829         linesize   = h->mb_linesize   = s->linesize * 2;
1830         uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
1831         block_offset = &h->block_offset[48];
1832         if(mb_y&1){ //FIXME move out of this function?
1833             dest_y -= s->linesize*15;
1834             dest_cb-= s->uvlinesize*7;
1835             dest_cr-= s->uvlinesize*7;
1836         }
1837         if(FRAME_MBAFF) {
1838             int list;
1839             for(list=0; list<h->list_count; list++){
1840                 if(!USES_LIST(mb_type, list))
1841                     continue;
1842                 if(IS_16X16(mb_type)){
1843                     int8_t *ref = &h->ref_cache[list][scan8[0]];
1844                     fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
1845                 }else{
1846                     for(i=0; i<16; i+=4){
1847                         int ref = h->ref_cache[list][scan8[i]];
1848                         if(ref >= 0)
1849                             fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
1850                     }
1851                 }
1852             }
1853         }
1854     } else {
1855         linesize   = h->mb_linesize   = s->linesize;
1856         uvlinesize = h->mb_uvlinesize = s->uvlinesize;
1857 //        dct_offset = s->linesize * 16;
1858     }
1859
1860     if (!simple && IS_INTRA_PCM(mb_type)) {
1861         if (pixel_shift) {
1862             const int bit_depth = h->sps.bit_depth_luma;
1863             int j;
1864             GetBitContext gb;
1865             init_get_bits(&gb, (uint8_t*)h->mb, 384*bit_depth);
1866
1867             for (i = 0; i < 16; i++) {
1868                 uint16_t *tmp_y  = (uint16_t*)(dest_y  + i*linesize);
1869                 for (j = 0; j < 16; j++)
1870                     tmp_y[j] = get_bits(&gb, bit_depth);
1871             }
1872             if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1873                 if (!h->sps.chroma_format_idc) {
1874                     for (i = 0; i < 8; i++) {
1875                         uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
1876                         for (j = 0; j < 8; j++) {
1877                             tmp_cb[j] = 1 << (bit_depth - 1);
1878                         }
1879                     }
1880                     for (i = 0; i < 8; i++) {
1881                         uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
1882                         for (j = 0; j < 8; j++) {
1883                             tmp_cr[j] = 1 << (bit_depth - 1);
1884                         }
1885                     }
1886                 } else {
1887                     for (i = 0; i < 8; i++) {
1888                         uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
1889                         for (j = 0; j < 8; j++)
1890                             tmp_cb[j] = get_bits(&gb, bit_depth);
1891                     }
1892                     for (i = 0; i < 8; i++) {
1893                         uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
1894                         for (j = 0; j < 8; j++)
1895                             tmp_cr[j] = get_bits(&gb, bit_depth);
1896                     }
1897                 }
1898             }
1899         } else {
1900             for (i=0; i<16; i++) {
1901                 memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
1902             }
1903             if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1904                 if (!h->sps.chroma_format_idc) {
1905                     for (i = 0; i < 8; i++) {
1906                         memset(dest_cb + i*uvlinesize, 128, 8);
1907                         memset(dest_cr + i*uvlinesize, 128, 8);
1908                     }
1909                 } else {
1910                     for (i = 0; i < 8; i++) {
1911                         memcpy(dest_cb + i*uvlinesize, h->mb + 128 + i*4,  8);
1912                         memcpy(dest_cr + i*uvlinesize, h->mb + 160 + i*4,  8);
1913                     }
1914                 }
1915             }
1916         }
1917     } else {
1918         if(IS_INTRA(mb_type)){
1919             if(h->deblocking_filter)
1920                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, 0, simple, pixel_shift);
1921
1922             if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1923                 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
1924                 h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
1925             }
1926
1927             hl_decode_mb_predict_luma(h, mb_type, is_h264, simple, transform_bypass, pixel_shift, block_offset, linesize, dest_y, 0);
1928
1929             if(h->deblocking_filter)
1930                 xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, 0, simple, pixel_shift);
1931         }else if(is_h264){
1932             if (pixel_shift) {
1933                 hl_motion_16(h, dest_y, dest_cb, dest_cr,
1934                              s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
1935                              s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
1936                              h->h264dsp.weight_h264_pixels_tab,
1937                              h->h264dsp.biweight_h264_pixels_tab, 0);
1938             } else
1939                 hl_motion_8(h, dest_y, dest_cb, dest_cr,
1940                             s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
1941                             s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
1942                             h->h264dsp.weight_h264_pixels_tab,
1943                             h->h264dsp.biweight_h264_pixels_tab, 0);
1944         }
1945
1946         hl_decode_mb_idct_luma(h, mb_type, is_h264, simple, transform_bypass, pixel_shift, block_offset, linesize, dest_y, 0);
1947
1948         if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
1949             uint8_t *dest[2] = {dest_cb, dest_cr};
1950             if(transform_bypass){
1951                 if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
1952                     h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + (16*16*1 << pixel_shift), uvlinesize);
1953                     h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 32, h->mb + (16*16*2 << pixel_shift), uvlinesize);
1954                 }else{
1955                     idct_add = s->dsp.add_pixels4;
1956                     for(j=1; j<3; j++){
1957                         for(i=j*16; i<j*16+4; i++){
1958                             if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h->mb, pixel_shift, i*16))
1959                                 idct_add   (dest[j-1] + block_offset[i], h->mb + (i*16 << pixel_shift), uvlinesize);
1960                         }
1961                     }
1962                 }
1963             }else{
1964                 if(is_h264){
1965                     if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
1966                         h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16*16*1 << pixel_shift), h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
1967                     if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
1968                         h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16*16*2 << pixel_shift), h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
1969                     h->h264dsp.h264_idct_add8(dest, block_offset,
1970                                               h->mb, uvlinesize,
1971                                               h->non_zero_count_cache);
1972                 }
1973 #if CONFIG_SVQ3_DECODER
1974                 else{
1975                     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]);
1976                     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]);
1977                     for(j=1; j<3; j++){
1978                         for(i=j*16; i<j*16+4; i++){
1979                             if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
1980                                 uint8_t * const ptr= dest[j-1] + block_offset[i];
1981                                 ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
1982                             }
1983                         }
1984                     }
1985                 }
1986 #endif
1987             }
1988         }
1989     }
1990     if(h->cbp || IS_INTRA(mb_type))
1991     {
1992         s->dsp.clear_blocks(h->mb);
1993         s->dsp.clear_blocks(h->mb+(24*16<<pixel_shift));
1994     }
1995 }
1996
1997 static av_always_inline void hl_decode_mb_444_internal(H264Context *h, int simple, int pixel_shift){
1998     MpegEncContext * const s = &h->s;
1999     const int mb_x= s->mb_x;
2000     const int mb_y= s->mb_y;
2001     const int mb_xy= h->mb_xy;
2002     const int mb_type= s->current_picture.mb_type[mb_xy];
2003     uint8_t  *dest[3];
2004     int linesize;
2005     int i, j, p;
2006     int *block_offset = &h->block_offset[0];
2007     const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
2008     const int plane_count = (simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) ? 3 : 1;
2009
2010     for (p = 0; p < plane_count; p++)
2011     {
2012         dest[p] = s->current_picture.data[p] + ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
2013         s->dsp.prefetch(dest[p] + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
2014     }
2015
2016     h->list_counts[mb_xy]= h->list_count;
2017
2018     if (!simple && MB_FIELD) {
2019         linesize   = h->mb_linesize = h->mb_uvlinesize = s->linesize * 2;
2020         block_offset = &h->block_offset[48];
2021         if(mb_y&1) //FIXME move out of this function?
2022             for (p = 0; p < 3; p++)
2023                 dest[p] -= s->linesize*15;
2024         if(FRAME_MBAFF) {
2025             int list;
2026             for(list=0; list<h->list_count; list++){
2027                 if(!USES_LIST(mb_type, list))
2028                     continue;
2029                 if(IS_16X16(mb_type)){
2030                     int8_t *ref = &h->ref_cache[list][scan8[0]];
2031                     fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
2032                 }else{
2033                     for(i=0; i<16; i+=4){
2034                         int ref = h->ref_cache[list][scan8[i]];
2035                         if(ref >= 0)
2036                             fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
2037                     }
2038                 }
2039             }
2040         }
2041     } else {
2042         linesize   = h->mb_linesize = h->mb_uvlinesize = s->linesize;
2043     }
2044
2045     if (!simple && IS_INTRA_PCM(mb_type)) {
2046         if (pixel_shift) {
2047             const int bit_depth = h->sps.bit_depth_luma;
2048             GetBitContext gb;
2049             init_get_bits(&gb, (uint8_t*)h->mb, 768*bit_depth);
2050
2051             for (p = 0; p < plane_count; p++) {
2052                 for (i = 0; i < 16; i++) {
2053                     uint16_t *tmp = (uint16_t*)(dest[p] + i*linesize);
2054                     for (j = 0; j < 16; j++)
2055                         tmp[j] = get_bits(&gb, bit_depth);
2056                 }
2057             }
2058         } else {
2059             for (p = 0; p < plane_count; p++) {
2060                 for (i = 0; i < 16; i++) {
2061                     memcpy(dest[p] + i*linesize, h->mb + p*128 + i*8, 16);
2062                 }
2063             }
2064         }
2065     } else {
2066         if(IS_INTRA(mb_type)){
2067             if(h->deblocking_filter)
2068                 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize, linesize, 1, 1, simple, pixel_shift);
2069
2070             for (p = 0; p < plane_count; p++)
2071                 hl_decode_mb_predict_luma(h, mb_type, 1, simple, transform_bypass, pixel_shift, block_offset, linesize, dest[p], p);
2072
2073             if(h->deblocking_filter)
2074                 xchg_mb_border(h, dest[0], dest[1], dest[2], linesize, linesize, 0, 1, simple, pixel_shift);
2075         }else{
2076             if (pixel_shift) {
2077                 hl_motion_16(h, dest[0], dest[1], dest[2],
2078                              s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2079                              s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2080                              h->h264dsp.weight_h264_pixels_tab,
2081                              h->h264dsp.biweight_h264_pixels_tab, 1);
2082             } else
2083                 hl_motion_8(h, dest[0], dest[1], dest[2],
2084                             s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2085                             s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2086                             h->h264dsp.weight_h264_pixels_tab,
2087                             h->h264dsp.biweight_h264_pixels_tab, 1);
2088         }
2089
2090         for (p = 0; p < plane_count; p++)
2091             hl_decode_mb_idct_luma(h, mb_type, 1, simple, transform_bypass, pixel_shift, block_offset, linesize, dest[p], p);
2092     }
2093     if(h->cbp || IS_INTRA(mb_type))
2094     {
2095         s->dsp.clear_blocks(h->mb);
2096         s->dsp.clear_blocks(h->mb+(24*16<<pixel_shift));
2097     }
2098 }
2099
2100 /**
2101  * Process a macroblock; this case avoids checks for expensive uncommon cases.
2102  */
2103 #define hl_decode_mb_simple(sh, bits) \
2104 static void hl_decode_mb_simple_ ## bits(H264Context *h){ \
2105     hl_decode_mb_internal(h, 1, sh); \
2106 }
2107 hl_decode_mb_simple(0, 8);
2108 hl_decode_mb_simple(1, 16);
2109
2110 /**
2111  * Process a macroblock; this handles edge cases, such as interlacing.
2112  */
2113 static void av_noinline hl_decode_mb_complex(H264Context *h){
2114     hl_decode_mb_internal(h, 0, h->pixel_shift);
2115 }
2116
2117 static void av_noinline hl_decode_mb_444_complex(H264Context *h){
2118     hl_decode_mb_444_internal(h, 0, h->pixel_shift);
2119 }
2120
2121 static void av_noinline hl_decode_mb_444_simple(H264Context *h){
2122     hl_decode_mb_444_internal(h, 1, 0);
2123 }
2124
2125 void ff_h264_hl_decode_mb(H264Context *h){
2126     MpegEncContext * const s = &h->s;
2127     const int mb_xy= h->mb_xy;
2128     const int mb_type= s->current_picture.mb_type[mb_xy];
2129     int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
2130
2131     if (CHROMA444) {
2132         if(is_complex || h->pixel_shift)
2133             hl_decode_mb_444_complex(h);
2134         else
2135             hl_decode_mb_444_simple(h);
2136     } else if (is_complex) {
2137         hl_decode_mb_complex(h);
2138     } else if (h->pixel_shift) {
2139         hl_decode_mb_simple_16(h);
2140     } else
2141         hl_decode_mb_simple_8(h);
2142 }
2143
2144 static int pred_weight_table(H264Context *h){
2145     MpegEncContext * const s = &h->s;
2146     int list, i;
2147     int luma_def, chroma_def;
2148
2149     h->use_weight= 0;
2150     h->use_weight_chroma= 0;
2151     h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
2152     if(h->sps.chroma_format_idc)
2153         h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
2154     luma_def = 1<<h->luma_log2_weight_denom;
2155     chroma_def = 1<<h->chroma_log2_weight_denom;
2156
2157     for(list=0; list<2; list++){
2158         h->luma_weight_flag[list]   = 0;
2159         h->chroma_weight_flag[list] = 0;
2160         for(i=0; i<h->ref_count[list]; i++){
2161             int luma_weight_flag, chroma_weight_flag;
2162
2163             luma_weight_flag= get_bits1(&s->gb);
2164             if(luma_weight_flag){
2165                 h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
2166                 h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
2167                 if(   h->luma_weight[i][list][0] != luma_def
2168                    || h->luma_weight[i][list][1] != 0) {
2169                     h->use_weight= 1;
2170                     h->luma_weight_flag[list]= 1;
2171                 }
2172             }else{
2173                 h->luma_weight[i][list][0]= luma_def;
2174                 h->luma_weight[i][list][1]= 0;
2175             }
2176
2177             if(h->sps.chroma_format_idc){
2178                 chroma_weight_flag= get_bits1(&s->gb);
2179                 if(chroma_weight_flag){
2180                     int j;
2181                     for(j=0; j<2; j++){
2182                         h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
2183                         h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
2184                         if(   h->chroma_weight[i][list][j][0] != chroma_def
2185                            || h->chroma_weight[i][list][j][1] != 0) {
2186                             h->use_weight_chroma= 1;
2187                             h->chroma_weight_flag[list]= 1;
2188                         }
2189                     }
2190                 }else{
2191                     int j;
2192                     for(j=0; j<2; j++){
2193                         h->chroma_weight[i][list][j][0]= chroma_def;
2194                         h->chroma_weight[i][list][j][1]= 0;
2195                     }
2196                 }
2197             }
2198         }
2199         if(h->slice_type_nos != AV_PICTURE_TYPE_B) break;
2200     }
2201     h->use_weight= h->use_weight || h->use_weight_chroma;
2202     return 0;
2203 }
2204
2205 /**
2206  * Initialize implicit_weight table.
2207  * @param field  0/1 initialize the weight for interlaced MBAFF
2208  *                -1 initializes the rest
2209  */
2210 static void implicit_weight_table(H264Context *h, int field){
2211     MpegEncContext * const s = &h->s;
2212     int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2213
2214     for (i = 0; i < 2; i++) {
2215         h->luma_weight_flag[i]   = 0;
2216         h->chroma_weight_flag[i] = 0;
2217     }
2218
2219     if(field < 0){
2220         if (s->picture_structure == PICT_FRAME) {
2221             cur_poc = s->current_picture_ptr->poc;
2222         } else {
2223             cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
2224         }
2225     if(   h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
2226        && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
2227         h->use_weight= 0;
2228         h->use_weight_chroma= 0;
2229         return;
2230     }
2231         ref_start= 0;
2232         ref_count0= h->ref_count[0];
2233         ref_count1= h->ref_count[1];
2234     }else{
2235         cur_poc = s->current_picture_ptr->field_poc[field];
2236         ref_start= 16;
2237         ref_count0= 16+2*h->ref_count[0];
2238         ref_count1= 16+2*h->ref_count[1];
2239     }
2240
2241     h->use_weight= 2;
2242     h->use_weight_chroma= 2;
2243     h->luma_log2_weight_denom= 5;
2244     h->chroma_log2_weight_denom= 5;
2245
2246     for(ref0=ref_start; ref0 < ref_count0; ref0++){
2247         int poc0 = h->ref_list[0][ref0].poc;
2248         for(ref1=ref_start; ref1 < ref_count1; ref1++){
2249             int w = 32;
2250             if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2251                 int poc1 = h->ref_list[1][ref1].poc;
2252                 int td = av_clip(poc1 - poc0, -128, 127);
2253                 if(td){
2254                     int tb = av_clip(cur_poc - poc0, -128, 127);
2255                     int tx = (16384 + (FFABS(td) >> 1)) / td;
2256                     int dist_scale_factor = (tb*tx + 32) >> 8;
2257                     if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
2258                         w = 64 - dist_scale_factor;
2259                 }
2260             }
2261             if(field<0){
2262                 h->implicit_weight[ref0][ref1][0]=
2263                 h->implicit_weight[ref0][ref1][1]= w;
2264             }else{
2265                 h->implicit_weight[ref0][ref1][field]=w;
2266             }
2267         }
2268     }
2269 }
2270
2271 /**
2272  * instantaneous decoder refresh.
2273  */
2274 static void idr(H264Context *h){
2275     ff_h264_remove_all_refs(h);
2276     h->prev_frame_num= 0;
2277     h->prev_frame_num_offset= 0;
2278     h->prev_poc_msb=
2279     h->prev_poc_lsb= 0;
2280 }
2281
2282 /* forget old pics after a seek */
2283 static void flush_dpb(AVCodecContext *avctx){
2284     H264Context *h= avctx->priv_data;
2285     int i;
2286     for(i=0; i<=MAX_DELAYED_PIC_COUNT; i++) {
2287         if(h->delayed_pic[i])
2288             h->delayed_pic[i]->reference= 0;
2289         h->delayed_pic[i]= NULL;
2290     }
2291     h->outputed_poc=h->next_outputed_poc= INT_MIN;
2292     h->prev_interlaced_frame = 1;
2293     idr(h);
2294     if(h->s.current_picture_ptr)
2295         h->s.current_picture_ptr->reference= 0;
2296     h->s.first_field= 0;
2297     ff_h264_reset_sei(h);
2298     ff_mpeg_flush(avctx);
2299 }
2300
2301 static int init_poc(H264Context *h){
2302     MpegEncContext * const s = &h->s;
2303     const int max_frame_num= 1<<h->sps.log2_max_frame_num;
2304     int field_poc[2];
2305     Picture *cur = s->current_picture_ptr;
2306
2307     h->frame_num_offset= h->prev_frame_num_offset;
2308     if(h->frame_num < h->prev_frame_num)
2309         h->frame_num_offset += max_frame_num;
2310
2311     if(h->sps.poc_type==0){
2312         const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
2313
2314         if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
2315             h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2316         else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
2317             h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2318         else
2319             h->poc_msb = h->prev_poc_msb;
2320 //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2321         field_poc[0] =
2322         field_poc[1] = h->poc_msb + h->poc_lsb;
2323         if(s->picture_structure == PICT_FRAME)
2324             field_poc[1] += h->delta_poc_bottom;
2325     }else if(h->sps.poc_type==1){
2326         int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2327         int i;
2328
2329         if(h->sps.poc_cycle_length != 0)
2330             abs_frame_num = h->frame_num_offset + h->frame_num;
2331         else
2332             abs_frame_num = 0;
2333
2334         if(h->nal_ref_idc==0 && abs_frame_num > 0)
2335             abs_frame_num--;
2336
2337         expected_delta_per_poc_cycle = 0;
2338         for(i=0; i < h->sps.poc_cycle_length; i++)
2339             expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
2340
2341         if(abs_frame_num > 0){
2342             int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2343             int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2344
2345             expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2346             for(i = 0; i <= frame_num_in_poc_cycle; i++)
2347                 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
2348         } else
2349             expectedpoc = 0;
2350
2351         if(h->nal_ref_idc == 0)
2352             expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2353
2354         field_poc[0] = expectedpoc + h->delta_poc[0];
2355         field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2356
2357         if(s->picture_structure == PICT_FRAME)
2358             field_poc[1] += h->delta_poc[1];
2359     }else{
2360         int poc= 2*(h->frame_num_offset + h->frame_num);
2361
2362         if(!h->nal_ref_idc)
2363             poc--;
2364
2365         field_poc[0]= poc;
2366         field_poc[1]= poc;
2367     }
2368
2369     if(s->picture_structure != PICT_BOTTOM_FIELD)
2370         s->current_picture_ptr->field_poc[0]= field_poc[0];
2371     if(s->picture_structure != PICT_TOP_FIELD)
2372         s->current_picture_ptr->field_poc[1]= field_poc[1];
2373     cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
2374
2375     return 0;
2376 }
2377
2378
2379 /**
2380  * initialize scan tables
2381  */
2382 static void init_scan_tables(H264Context *h){
2383     int i;
2384     for(i=0; i<16; i++){
2385 #define T(x) (x>>2) | ((x<<2) & 0xF)
2386         h->zigzag_scan[i] = T(zigzag_scan[i]);
2387         h-> field_scan[i] = T( field_scan[i]);
2388 #undef T
2389     }
2390     for(i=0; i<64; i++){
2391 #define T(x) (x>>3) | ((x&7)<<3)
2392         h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
2393         h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2394         h->field_scan8x8[i]        = T(field_scan8x8[i]);
2395         h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
2396 #undef T
2397     }
2398     if(h->sps.transform_bypass){ //FIXME same ugly
2399         h->zigzag_scan_q0          = zigzag_scan;
2400         h->zigzag_scan8x8_q0       = ff_zigzag_direct;
2401         h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2402         h->field_scan_q0           = field_scan;
2403         h->field_scan8x8_q0        = field_scan8x8;
2404         h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
2405     }else{
2406         h->zigzag_scan_q0          = h->zigzag_scan;
2407         h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
2408         h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2409         h->field_scan_q0           = h->field_scan;
2410         h->field_scan8x8_q0        = h->field_scan8x8;
2411         h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
2412     }
2413 }
2414
2415 static void field_end(H264Context *h, int in_setup){
2416     MpegEncContext * const s = &h->s;
2417     AVCodecContext * const avctx= s->avctx;
2418     s->mb_y= 0;
2419
2420     if (!in_setup && !s->dropable)
2421         ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
2422                                  s->picture_structure==PICT_BOTTOM_FIELD);
2423
2424     if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2425         ff_vdpau_h264_set_reference_frames(s);
2426
2427     if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
2428         if(!s->dropable) {
2429             ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2430             h->prev_poc_msb= h->poc_msb;
2431             h->prev_poc_lsb= h->poc_lsb;
2432         }
2433         h->prev_frame_num_offset= h->frame_num_offset;
2434         h->prev_frame_num= h->frame_num;
2435         h->outputed_poc = h->next_outputed_poc;
2436     }
2437
2438     if (avctx->hwaccel) {
2439         if (avctx->hwaccel->end_frame(avctx) < 0)
2440             av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
2441     }
2442
2443     if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2444         ff_vdpau_h264_picture_complete(s);
2445
2446     /*
2447      * FIXME: Error handling code does not seem to support interlaced
2448      * when slices span multiple rows
2449      * The ff_er_add_slice calls don't work right for bottom
2450      * fields; they cause massive erroneous error concealing
2451      * Error marking covers both fields (top and bottom).
2452      * This causes a mismatched s->error_count
2453      * and a bad error table. Further, the error count goes to
2454      * INT_MAX when called for bottom field, because mb_y is
2455      * past end by one (callers fault) and resync_mb_y != 0
2456      * causes problems for the first MB line, too.
2457      */
2458     if (!FIELD_PICTURE)
2459         ff_er_frame_end(s);
2460
2461     MPV_frame_end(s);
2462
2463     h->current_slice=0;
2464 }
2465
2466 /**
2467  * Replicate H264 "master" context to thread contexts.
2468  */
2469 static void clone_slice(H264Context *dst, H264Context *src)
2470 {
2471     memcpy(dst->block_offset,     src->block_offset, sizeof(dst->block_offset));
2472     dst->s.current_picture_ptr  = src->s.current_picture_ptr;
2473     dst->s.current_picture      = src->s.current_picture;
2474     dst->s.linesize             = src->s.linesize;
2475     dst->s.uvlinesize           = src->s.uvlinesize;
2476     dst->s.first_field          = src->s.first_field;
2477
2478     dst->prev_poc_msb           = src->prev_poc_msb;
2479     dst->prev_poc_lsb           = src->prev_poc_lsb;
2480     dst->prev_frame_num_offset  = src->prev_frame_num_offset;
2481     dst->prev_frame_num         = src->prev_frame_num;
2482     dst->short_ref_count        = src->short_ref_count;
2483
2484     memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
2485     memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
2486     memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2487     memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
2488
2489     memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
2490     memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
2491 }
2492
2493 /**
2494  * computes profile from profile_idc and constraint_set?_flags
2495  *
2496  * @param sps SPS
2497  *
2498  * @return profile as defined by FF_PROFILE_H264_*
2499  */
2500 int ff_h264_get_profile(SPS *sps)
2501 {
2502     int profile = sps->profile_idc;
2503
2504     switch(sps->profile_idc) {
2505     case FF_PROFILE_H264_BASELINE:
2506         // constraint_set1_flag set to 1
2507         profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2508         break;
2509     case FF_PROFILE_H264_HIGH_10:
2510     case FF_PROFILE_H264_HIGH_422:
2511     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2512         // constraint_set3_flag set to 1
2513         profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
2514         break;
2515     }
2516
2517     return profile;
2518 }
2519
2520 /**
2521  * decodes a slice header.
2522  * This will also call MPV_common_init() and frame_start() as needed.
2523  *
2524  * @param h h264context
2525  * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
2526  *
2527  * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2528  */
2529 static int decode_slice_header(H264Context *h, H264Context *h0){
2530     MpegEncContext * const s = &h->s;
2531     MpegEncContext * const s0 = &h0->s;
2532     unsigned int first_mb_in_slice;
2533     unsigned int pps_id;
2534     int num_ref_idx_active_override_flag;
2535     unsigned int slice_type, tmp, i, j;
2536     int default_ref_list_done = 0;
2537     int last_pic_structure;
2538
2539     s->dropable= h->nal_ref_idc == 0;
2540
2541     /* FIXME: 2tap qpel isn't implemented for high bit depth. */
2542     if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc && !h->pixel_shift){
2543         s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
2544         s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
2545     }else{
2546         s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
2547         s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
2548     }
2549
2550     first_mb_in_slice= get_ue_golomb(&s->gb);
2551
2552     if(first_mb_in_slice == 0){ //FIXME better field boundary detection
2553         if(h0->current_slice && FIELD_PICTURE){
2554             field_end(h, 1);
2555         }
2556
2557         h0->current_slice = 0;
2558         if (!s0->first_field)
2559             s->current_picture_ptr= NULL;
2560     }
2561
2562     slice_type= get_ue_golomb_31(&s->gb);
2563     if(slice_type > 9){
2564         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);
2565         return -1;
2566     }
2567     if(slice_type > 4){
2568         slice_type -= 5;
2569         h->slice_type_fixed=1;
2570     }else
2571         h->slice_type_fixed=0;
2572
2573     slice_type= golomb_to_pict_type[ slice_type ];
2574     if (slice_type == AV_PICTURE_TYPE_I
2575         || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
2576         default_ref_list_done = 1;
2577     }
2578     h->slice_type= slice_type;
2579     h->slice_type_nos= slice_type & 3;
2580
2581     s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
2582
2583     pps_id= get_ue_golomb(&s->gb);
2584     if(pps_id>=MAX_PPS_COUNT){
2585         av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2586         return -1;
2587     }
2588     if(!h0->pps_buffers[pps_id]) {
2589         av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
2590         return -1;
2591     }
2592     h->pps= *h0->pps_buffers[pps_id];
2593
2594     if(!h0->sps_buffers[h->pps.sps_id]) {
2595         av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
2596         return -1;
2597     }
2598     h->sps = *h0->sps_buffers[h->pps.sps_id];
2599
2600     s->avctx->profile = ff_h264_get_profile(&h->sps);
2601     s->avctx->level   = h->sps.level_idc;
2602     s->avctx->refs    = h->sps.ref_frame_count;
2603
2604     if(h == h0 && h->dequant_coeff_pps != pps_id){
2605         h->dequant_coeff_pps = pps_id;
2606         init_dequant_tables(h);
2607     }
2608
2609     s->mb_width= h->sps.mb_width;
2610     s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2611
2612     h->b_stride=  s->mb_width*4;
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 - (2>>CHROMA444)*FFMIN(h->sps.crop_bottom, (8<<CHROMA444)-1);
2617     else
2618         s->height= 16*s->mb_height - (4>>CHROMA444)*FFMIN(h->sps.crop_bottom, (8<<CHROMA444)-1);
2619
2620     if (FFALIGN(s->avctx->width,  16) == s->width &&
2621         FFALIGN(s->avctx->height, 16) == s->height) {
2622         s->width  = s->avctx->width;
2623         s->height = s->avctx->height;
2624     }
2625
2626     if (FFALIGN(s->avctx->width,  16) == s->width &&
2627         FFALIGN(s->avctx->height, 16) == s->height) {
2628         s->width  = s->avctx->width;
2629         s->height = s->avctx->height;
2630     }
2631
2632     if (s->context_initialized
2633         && (   s->width != s->avctx->width || s->height != s->avctx->height
2634             || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2635         if(h != h0 || (HAVE_THREADS && h->s.avctx->active_thread_type & FF_THREAD_FRAME)) {
2636             av_log_missing_feature(s->avctx, "Width/height changing with threads is", 0);
2637             return AVERROR_PATCHWELCOME;   // width / height changed during parallelized decoding
2638         }
2639         free_tables(h, 0);
2640         flush_dpb(s->avctx);
2641         MPV_common_end(s);
2642         h->list_count = 0;
2643     }
2644     if (!s->context_initialized) {
2645         if (h != h0) {
2646             av_log(h->s.avctx, AV_LOG_ERROR, "Cannot (re-)initialize context during parallel decoding.\n");
2647             return -1;
2648         }
2649
2650         avcodec_set_dimensions(s->avctx, s->width, s->height);
2651         s->avctx->sample_aspect_ratio= h->sps.sar;
2652         av_assert0(s->avctx->sample_aspect_ratio.den);
2653
2654         h->s.avctx->coded_width = 16*s->mb_width;
2655         h->s.avctx->coded_height = 16*s->mb_height;
2656
2657         if(h->sps.video_signal_type_present_flag){
2658             s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2659             if(h->sps.colour_description_present_flag){
2660                 s->avctx->color_primaries = h->sps.color_primaries;
2661                 s->avctx->color_trc       = h->sps.color_trc;
2662                 s->avctx->colorspace      = h->sps.colorspace;
2663             }
2664         }
2665
2666         if(h->sps.timing_info_present_flag){
2667             int64_t den= h->sps.time_scale;
2668             if(h->x264_build < 44U)
2669                 den *= 2;
2670             av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2671                       h->sps.num_units_in_tick, den, 1<<30);
2672         }
2673
2674         switch (h->sps.bit_depth_luma) {
2675             case 9 :
2676                 s->avctx->pix_fmt = CHROMA444 ? PIX_FMT_YUV444P9 : PIX_FMT_YUV420P9;
2677                 break;
2678             case 10 :
2679                 s->avctx->pix_fmt = CHROMA444 ? PIX_FMT_YUV444P10 : PIX_FMT_YUV420P10;
2680                 break;
2681             default:
2682                 if (CHROMA444){
2683                     s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P : PIX_FMT_YUV444P;
2684                 }else{
2685                     s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2686                                                              s->avctx->codec->pix_fmts ?
2687                                                              s->avctx->codec->pix_fmts :
2688                                                              s->avctx->color_range == AVCOL_RANGE_JPEG ?
2689                                                              hwaccel_pixfmt_list_h264_jpeg_420 :
2690                                                              ff_hwaccel_pixfmt_list_420);
2691                 }
2692         }
2693
2694         s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2695
2696         if (MPV_common_init(s) < 0) {
2697             av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed.\n");
2698             return -1;
2699         }
2700         s->first_field = 0;
2701         h->prev_interlaced_frame = 1;
2702
2703         init_scan_tables(h);
2704         if (ff_h264_alloc_tables(h) < 0) {
2705             av_log(h->s.avctx, AV_LOG_ERROR, "Could not allocate memory for h264\n");
2706             return AVERROR(ENOMEM);
2707         }
2708
2709         if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
2710             if (context_init(h) < 0) {
2711                 av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2712                 return -1;
2713             }
2714         } else {
2715             for(i = 1; i < s->avctx->thread_count; i++) {
2716                 H264Context *c;
2717                 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2718                 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2719                 memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2720                 c->h264dsp = h->h264dsp;
2721                 c->sps = h->sps;
2722                 c->pps = h->pps;
2723                 c->pixel_shift = h->pixel_shift;
2724                 init_scan_tables(c);
2725                 clone_tables(c, h, i);
2726             }
2727
2728             for(i = 0; i < s->avctx->thread_count; i++)
2729                 if (context_init(h->thread_context[i]) < 0) {
2730                     av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
2731                     return -1;
2732                 }
2733         }
2734     }
2735
2736     h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
2737
2738     h->mb_mbaff = 0;
2739     h->mb_aff_frame = 0;
2740     last_pic_structure = s0->picture_structure;
2741     if(h->sps.frame_mbs_only_flag){
2742         s->picture_structure= PICT_FRAME;
2743     }else{
2744         if(get_bits1(&s->gb)) { //field_pic_flag
2745             s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
2746         } else {
2747             s->picture_structure= PICT_FRAME;
2748             h->mb_aff_frame = h->sps.mb_aff;
2749         }
2750     }
2751     h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
2752
2753     if(h0->current_slice == 0){
2754         // Shorten frame num gaps so we don't have to allocate reference frames just to throw them away
2755         if(h->frame_num != h->prev_frame_num) {
2756             int unwrap_prev_frame_num = h->prev_frame_num, max_frame_num = 1<<h->sps.log2_max_frame_num;
2757
2758             if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num;
2759
2760             if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
2761                 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
2762                 if (unwrap_prev_frame_num < 0)
2763                     unwrap_prev_frame_num += max_frame_num;
2764
2765                 h->prev_frame_num = unwrap_prev_frame_num;
2766             }
2767         }
2768
2769         while(h->frame_num !=  h->prev_frame_num &&
2770               h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
2771             Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2772             av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
2773             if (ff_h264_frame_start(h) < 0)
2774                 return -1;
2775             h->prev_frame_num++;
2776             h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
2777             s->current_picture_ptr->frame_num= h->prev_frame_num;
2778             ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
2779             ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
2780             ff_generate_sliding_window_mmcos(h);
2781             ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2782             /* Error concealment: if a ref is missing, copy the previous ref in its place.
2783              * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2784              * about there being no actual duplicates.
2785              * FIXME: this doesn't copy padding for out-of-frame motion vectors.  Given we're
2786              * concealing a lost frame, this probably isn't noticable by comparison, but it should
2787              * be fixed. */
2788             if (h->short_ref_count) {
2789                 if (prev) {
2790                     av_image_copy(h->short_ref[0]->data, h->short_ref[0]->linesize,
2791                                   (const uint8_t**)prev->data, prev->linesize,
2792                                   s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
2793                     h->short_ref[0]->poc = prev->poc+2;
2794                 }
2795                 h->short_ref[0]->frame_num = h->prev_frame_num;
2796             }
2797         }
2798
2799         /* See if we have a decoded first field looking for a pair... */
2800         if (s0->first_field) {
2801             assert(s0->current_picture_ptr);
2802             assert(s0->current_picture_ptr->data[0]);
2803             assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
2804
2805             /* figure out if we have a complementary field pair */
2806             if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2807                 /*
2808                  * Previous field is unmatched. Don't display it, but let it
2809                  * remain for reference if marked as such.
2810                  */
2811                 s0->current_picture_ptr = NULL;
2812                 s0->first_field = FIELD_PICTURE;
2813
2814             } else {
2815                 if (s0->current_picture_ptr->frame_num != h->frame_num) {
2816                     /*
2817                      * This and previous field had
2818                      * different frame_nums. Consider this field first in
2819                      * pair. Throw away previous field except for reference
<