Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ dc172ecc

History | View | Annotate | Download (144 KB)

1
/*
2
 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3
 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
/**
23
 * @file
24
 * H.264 / AVC / MPEG4 part10 codec.
25
 * @author Michael Niedermayer <michaelni@gmx.at>
26
 */
27

    
28
#include "libavutil/imgutils.h"
29
#include "internal.h"
30
#include "dsputil.h"
31
#include "avcodec.h"
32
#include "mpegvideo.h"
33
#include "h264.h"
34
#include "h264data.h"
35
#include "h264_mvpred.h"
36
#include "golomb.h"
37
#include "mathops.h"
38
#include "rectangle.h"
39
#include "thread.h"
40
#include "vdpau_internal.h"
41
#include "libavutil/avassert.h"
42

    
43
#include "cabac.h"
44

    
45
//#undef NDEBUG
46
#include <assert.h>
47

    
48
static const uint8_t rem6[52]={
49
0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
50
};
51

    
52
static const uint8_t div6[52]={
53
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
54
};
55

    
56
static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
57
    PIX_FMT_DXVA2_VLD,
58
    PIX_FMT_VAAPI_VLD,
59
    PIX_FMT_YUVJ420P,
60
    PIX_FMT_NONE
61
};
62

    
63
void ff_h264_write_back_intra_pred_mode(H264Context *h){
64
    int8_t *mode= h->intra4x4_pred_mode + h->mb2br_xy[h->mb_xy];
65

    
66
    AV_COPY32(mode, h->intra4x4_pred_mode_cache + 4 + 8*4);
67
    mode[4]= h->intra4x4_pred_mode_cache[7+8*3];
68
    mode[5]= h->intra4x4_pred_mode_cache[7+8*2];
69
    mode[6]= h->intra4x4_pred_mode_cache[7+8*1];
70
}
71

    
72
/**
73
 * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
74
 */
75
int ff_h264_check_intra4x4_pred_mode(H264Context *h){
76
    MpegEncContext * const s = &h->s;
77
    static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
78
    static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
79
    int i;
80

    
81
    if(!(h->top_samples_available&0x8000)){
82
        for(i=0; i<4; i++){
83
            int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
84
            if(status<0){
85
                av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
86
                return -1;
87
            } else if(status){
88
                h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
89
            }
90
        }
91
    }
92

    
93
    if((h->left_samples_available&0x8888)!=0x8888){
94
        static const int mask[4]={0x8000,0x2000,0x80,0x20};
95
        for(i=0; i<4; i++){
96
            if(!(h->left_samples_available&mask[i])){
97
                int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
98
                if(status<0){
99
                    av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
100
                    return -1;
101
                } else if(status){
102
                    h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
103
                }
104
            }
105
        }
106
    }
107

    
108
    return 0;
109
} //FIXME cleanup like ff_h264_check_intra_pred_mode
110

    
111
/**
112
 * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
113
 */
114
int ff_h264_check_intra_pred_mode(H264Context *h, int mode){
115
    MpegEncContext * const s = &h->s;
116
    static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
117
    static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
118

    
119
    if(mode > 6U) {
120
        av_log(h->s.avctx, AV_LOG_ERROR, "out of range intra chroma pred mode at %d %d\n", s->mb_x, s->mb_y);
121
        return -1;
122
    }
123

    
124
    if(!(h->top_samples_available&0x8000)){
125
        mode= top[ mode ];
126
        if(mode<0){
127
            av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
128
            return -1;
129
        }
130
    }
131

    
132
    if((h->left_samples_available&0x8080) != 0x8080){
133
        mode= left[ mode ];
134
        if(h->left_samples_available&0x8080){ //mad cow disease mode, aka MBAFF + constrained_intra_pred
135
            mode= ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available&0x8000)) + 2*(mode == DC_128_PRED8x8);
136
        }
137
        if(mode<0){
138
            av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
139
            return -1;
140
        }
141
    }
142

    
143
    return mode;
144
}
145

    
146
const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
147
    int i, si, di;
148
    uint8_t *dst;
149
    int bufidx;
150

    
151
//    src[0]&0x80;                //forbidden bit
152
    h->nal_ref_idc= src[0]>>5;
153
    h->nal_unit_type= src[0]&0x1F;
154

    
155
    src++; length--;
156
#if 0
157
    for(i=0; i<length; i++)
158
        printf("%2X ", src[i]);
159
#endif
160

    
161
#if HAVE_FAST_UNALIGNED
162
# if HAVE_FAST_64BIT
163
#   define RS 7
164
    for(i=0; i+1<length; i+=9){
165
        if(!((~AV_RN64A(src+i) & (AV_RN64A(src+i) - 0x0100010001000101ULL)) & 0x8000800080008080ULL))
166
# else
167
#   define RS 3
168
    for(i=0; i+1<length; i+=5){
169
        if(!((~AV_RN32A(src+i) & (AV_RN32A(src+i) - 0x01000101U)) & 0x80008080U))
170
# endif
171
            continue;
172
        if(i>0 && !src[i]) i--;
173
        while(src[i]) i++;
174
#else
175
#   define RS 0
176
    for(i=0; i+1<length; i+=2){
177
        if(src[i]) continue;
178
        if(i>0 && src[i-1]==0) i--;
179
#endif
180
        if(i+2<length && src[i+1]==0 && src[i+2]<=3){
181
            if(src[i+2]!=3){
182
                /* startcode, so we must be past the end */
183
                length=i;
184
            }
185
            break;
186
        }
187
        i-= RS;
188
    }
189

    
190
    if(i>=length-1){ //no escaped 0
191
        *dst_length= length;
192
        *consumed= length+1; //+1 for the header
193
        return src;
194
    }
195

    
196
    bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
197
    av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+FF_INPUT_BUFFER_PADDING_SIZE);
198
    dst= h->rbsp_buffer[bufidx];
199

    
200
    if (dst == NULL){
201
        return NULL;
202
    }
203

    
204
//printf("decoding esc\n");
205
    memcpy(dst, src, i);
206
    si=di=i;
207
    while(si+2<length){
208
        //remove escapes (very rare 1:2^22)
209
        if(src[si+2]>3){
210
            dst[di++]= src[si++];
211
            dst[di++]= src[si++];
212
        }else if(src[si]==0 && src[si+1]==0){
213
            if(src[si+2]==3){ //escape
214
                dst[di++]= 0;
215
                dst[di++]= 0;
216
                si+=3;
217
                continue;
218
            }else //next start code
219
                goto nsc;
220
        }
221

    
222
        dst[di++]= src[si++];
223
    }
224
    while(si<length)
225
        dst[di++]= src[si++];
226
nsc:
227

    
228
    memset(dst+di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
229

    
230
    *dst_length= di;
231
    *consumed= si + 1;//+1 for the header
232
//FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
233
    return dst;
234
}
235

    
236
/**
237
 * Identify the exact end of the bitstream
238
 * @return the length of the trailing, or 0 if damaged
239
 */
240
static int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
241
    int v= *src;
242
    int r;
243

    
244
    tprintf(h->s.avctx, "rbsp trailing %X\n", v);
245

    
246
    for(r=1; r<9; r++){
247
        if(v&1) return r;
248
        v>>=1;
249
    }
250
    return 0;
251
}
252

    
253
static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n, int height,
254
                                 int y_offset, int list){
255
    int raw_my= h->mv_cache[list][ scan8[n] ][1];
256
    int filter_height= (raw_my&3) ? 2 : 0;
257
    int full_my= (raw_my>>2) + y_offset;
258
    int top = full_my - filter_height, bottom = full_my + height + filter_height;
259

    
260
    return FFMAX(abs(top), bottom);
261
}
262

    
263
static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n, int height,
264
                               int y_offset, int list0, int list1, int *nrefs){
265
    MpegEncContext * const s = &h->s;
266
    int my;
267

    
268
    y_offset += 16*(s->mb_y >> MB_FIELD);
269

    
270
    if(list0){
271
        int ref_n = h->ref_cache[0][ scan8[n] ];
272
        Picture *ref= &h->ref_list[0][ref_n];
273

    
274
        // Error resilience puts the current picture in the ref list.
275
        // Don't try to wait on these as it will cause a deadlock.
276
        // Fields can wait on each other, though.
277
        if(ref->thread_opaque != s->current_picture.thread_opaque ||
278
           (ref->reference&3) != s->picture_structure) {
279
            my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
280
            if (refs[0][ref_n] < 0) nrefs[0] += 1;
281
            refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
282
        }
283
    }
284

    
285
    if(list1){
286
        int ref_n = h->ref_cache[1][ scan8[n] ];
287
        Picture *ref= &h->ref_list[1][ref_n];
288

    
289
        if(ref->thread_opaque != s->current_picture.thread_opaque ||
290
           (ref->reference&3) != s->picture_structure) {
291
            my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
292
            if (refs[1][ref_n] < 0) nrefs[1] += 1;
293
            refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
294
        }
295
    }
296
}
297

    
298
/**
299
 * Wait until all reference frames are available for MC operations.
300
 *
301
 * @param h the H264 context
302
 */
303
static void await_references(H264Context *h){
304
    MpegEncContext * const s = &h->s;
305
    const int mb_xy= h->mb_xy;
306
    const int mb_type= s->current_picture.mb_type[mb_xy];
307
    int refs[2][48];
308
    int nrefs[2] = {0};
309
    int ref, list;
310

    
311
    memset(refs, -1, sizeof(refs));
312

    
313
    if(IS_16X16(mb_type)){
314
        get_lowest_part_y(h, refs, 0, 16, 0,
315
                  IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
316
    }else if(IS_16X8(mb_type)){
317
        get_lowest_part_y(h, refs, 0, 8, 0,
318
                  IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
319
        get_lowest_part_y(h, refs, 8, 8, 8,
320
                  IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
321
    }else if(IS_8X16(mb_type)){
322
        get_lowest_part_y(h, refs, 0, 16, 0,
323
                  IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
324
        get_lowest_part_y(h, refs, 4, 16, 0,
325
                  IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
326
    }else{
327
        int i;
328

    
329
        assert(IS_8X8(mb_type));
330

    
331
        for(i=0; i<4; i++){
332
            const int sub_mb_type= h->sub_mb_type[i];
333
            const int n= 4*i;
334
            int y_offset= (i&2)<<2;
335

    
336
            if(IS_SUB_8X8(sub_mb_type)){
337
                get_lowest_part_y(h, refs, n  , 8, y_offset,
338
                          IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
339
            }else if(IS_SUB_8X4(sub_mb_type)){
340
                get_lowest_part_y(h, refs, n  , 4, y_offset,
341
                          IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
342
                get_lowest_part_y(h, refs, n+2, 4, y_offset+4,
343
                          IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
344
            }else if(IS_SUB_4X8(sub_mb_type)){
345
                get_lowest_part_y(h, refs, n  , 8, y_offset,
346
                          IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
347
                get_lowest_part_y(h, refs, n+1, 8, y_offset,
348
                          IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
349
            }else{
350
                int j;
351
                assert(IS_SUB_4X4(sub_mb_type));
352
                for(j=0; j<4; j++){
353
                    int sub_y_offset= y_offset + 2*(j&2);
354
                    get_lowest_part_y(h, refs, n+j, 4, sub_y_offset,
355
                              IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
356
                }
357
            }
358
        }
359
    }
360

    
361
    for(list=h->list_count-1; list>=0; list--){
362
        for(ref=0; ref<48 && nrefs[list]; ref++){
363
            int row = refs[list][ref];
364
            if(row >= 0){
365
                Picture *ref_pic = &h->ref_list[list][ref];
366
                int ref_field = ref_pic->reference - 1;
367
                int ref_field_picture = ref_pic->field_picture;
368
                int pic_height = 16*s->mb_height >> ref_field_picture;
369

    
370
                row <<= MB_MBAFF;
371
                nrefs[list]--;
372

    
373
                if(!FIELD_PICTURE && ref_field_picture){ // frame referencing two fields
374
                    ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) - !(row&1), pic_height-1), 1);
375
                    ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1)           , pic_height-1), 0);
376
                }else if(FIELD_PICTURE && !ref_field_picture){ // field referencing one field of a frame
377
                    ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row*2 + ref_field    , pic_height-1), 0);
378
                }else if(FIELD_PICTURE){
379
                    ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), ref_field);
380
                }else{
381
                    ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), 0);
382
                }
383
            }
384
        }
385
    }
386
}
387

    
388
#if 0
389
/**
390
 * DCT transforms the 16 dc values.
391
 * @param qp quantization parameter ??? FIXME
392
 */
393
static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
394
//    const int qmul= dequant_coeff[qp][0];
395
    int i;
396
    int temp[16]; //FIXME check if this is a good idea
397
    static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
398
    static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
399

400
    for(i=0; i<4; i++){
401
        const int offset= y_offset[i];
402
        const int z0= block[offset+stride*0] + block[offset+stride*4];
403
        const int z1= block[offset+stride*0] - block[offset+stride*4];
404
        const int z2= block[offset+stride*1] - block[offset+stride*5];
405
        const int z3= block[offset+stride*1] + block[offset+stride*5];
406

407
        temp[4*i+0]= z0+z3;
408
        temp[4*i+1]= z1+z2;
409
        temp[4*i+2]= z1-z2;
410
        temp[4*i+3]= z0-z3;
411
    }
412

413
    for(i=0; i<4; i++){
414
        const int offset= x_offset[i];
415
        const int z0= temp[4*0+i] + temp[4*2+i];
416
        const int z1= temp[4*0+i] - temp[4*2+i];
417
        const int z2= temp[4*1+i] - temp[4*3+i];
418
        const int z3= temp[4*1+i] + temp[4*3+i];
419

420
        block[stride*0 +offset]= (z0 + z3)>>1;
421
        block[stride*2 +offset]= (z1 + z2)>>1;
422
        block[stride*8 +offset]= (z1 - z2)>>1;
423
        block[stride*10+offset]= (z0 - z3)>>1;
424
    }
425
}
426
#endif
427

    
428
#undef xStride
429
#undef stride
430

    
431
#if 0
432
static void chroma_dc_dct_c(DCTELEM *block){
433
    const int stride= 16*2;
434
    const int xStride= 16;
435
    int a,b,c,d,e;
436

437
    a= block[stride*0 + xStride*0];
438
    b= block[stride*0 + xStride*1];
439
    c= block[stride*1 + xStride*0];
440
    d= block[stride*1 + xStride*1];
441

442
    e= a-b;
443
    a= a+b;
444
    b= c-d;
445
    c= c+d;
446

447
    block[stride*0 + xStride*0]= (a+c);
448
    block[stride*0 + xStride*1]= (e+b);
449
    block[stride*1 + xStride*0]= (a-c);
450
    block[stride*1 + xStride*1]= (e-b);
451
}
452
#endif
453

    
454
static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
455
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
456
                           int src_x_offset, int src_y_offset,
457
                           qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
458
    MpegEncContext * const s = &h->s;
459
    const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
460
    int my=       h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
461
    const int luma_xy= (mx&3) + ((my&3)<<2);
462
    uint8_t * src_y = pic->data[0] + (mx>>2)*h->pixel_size + (my>>2)*h->mb_linesize;
463
    uint8_t * src_cb, * src_cr;
464
    int extra_width= h->emu_edge_width;
465
    int extra_height= h->emu_edge_height;
466
    int emu=0;
467
    const int full_mx= mx>>2;
468
    const int full_my= my>>2;
469
    const int pic_width  = 16*s->mb_width;
470
    const int pic_height = 16*s->mb_height >> MB_FIELD;
471

    
472
    if(mx&7) extra_width -= 3;
473
    if(my&7) extra_height -= 3;
474

    
475
    if(   full_mx < 0-extra_width
476
       || full_my < 0-extra_height
477
       || full_mx + 16/*FIXME*/ > pic_width + extra_width
478
       || full_my + 16/*FIXME*/ > pic_height + extra_height){
479
        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_y - 2*h->pixel_size - 2*h->mb_linesize, h->mb_linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
480
            src_y= s->edge_emu_buffer + 2*h->pixel_size + 2*h->mb_linesize;
481
        emu=1;
482
    }
483

    
484
    qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
485
    if(!square){
486
        qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
487
    }
488

    
489
    if(CONFIG_GRAY && s->flags&CODEC_FLAG_GRAY) return;
490

    
491
    if(MB_FIELD){
492
        // chroma offset when predicting from a field of opposite parity
493
        my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
494
        emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
495
    }
496
    src_cb= pic->data[1] + (mx>>3)*h->pixel_size + (my>>3)*h->mb_uvlinesize;
497
    src_cr= pic->data[2] + (mx>>3)*h->pixel_size + (my>>3)*h->mb_uvlinesize;
498

    
499
    if(emu){
500
        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);
501
            src_cb= s->edge_emu_buffer;
502
    }
503
    chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
504

    
505
    if(emu){
506
        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);
507
            src_cr= s->edge_emu_buffer;
508
    }
509
    chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
510
}
511

    
512
static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
513
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
514
                           int x_offset, int y_offset,
515
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
516
                           qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
517
                           int list0, int list1){
518
    MpegEncContext * const s = &h->s;
519
    qpel_mc_func *qpix_op=  qpix_put;
520
    h264_chroma_mc_func chroma_op= chroma_put;
521

    
522
    dest_y  += 2*x_offset*h->pixel_size + 2*y_offset*h->  mb_linesize;
523
    dest_cb +=   x_offset*h->pixel_size +   y_offset*h->mb_uvlinesize;
524
    dest_cr +=   x_offset*h->pixel_size +   y_offset*h->mb_uvlinesize;
525
    x_offset += 8*s->mb_x;
526
    y_offset += 8*(s->mb_y >> MB_FIELD);
527

    
528
    if(list0){
529
        Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
530
        mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
531
                           dest_y, dest_cb, dest_cr, x_offset, y_offset,
532
                           qpix_op, chroma_op);
533

    
534
        qpix_op=  qpix_avg;
535
        chroma_op= chroma_avg;
536
    }
537

    
538
    if(list1){
539
        Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
540
        mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
541
                           dest_y, dest_cb, dest_cr, x_offset, y_offset,
542
                           qpix_op, chroma_op);
543
    }
544
}
545

    
546
static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
547
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
548
                           int x_offset, int y_offset,
549
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
550
                           h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
551
                           h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
552
                           int list0, int list1){
553
    MpegEncContext * const s = &h->s;
554

    
555
    dest_y  += 2*x_offset*h->pixel_size + 2*y_offset*h->  mb_linesize;
556
    dest_cb +=   x_offset*h->pixel_size +   y_offset*h->mb_uvlinesize;
557
    dest_cr +=   x_offset*h->pixel_size +   y_offset*h->mb_uvlinesize;
558
    x_offset += 8*s->mb_x;
559
    y_offset += 8*(s->mb_y >> MB_FIELD);
560

    
561
    if(list0 && list1){
562
        /* don't optimize for luma-only case, since B-frames usually
563
         * use implicit weights => chroma too. */
564
        uint8_t *tmp_cb = s->obmc_scratchpad;
565
        uint8_t *tmp_cr = s->obmc_scratchpad + 8*h->pixel_size;
566
        uint8_t *tmp_y  = s->obmc_scratchpad + 8*h->mb_uvlinesize;
567
        int refn0 = h->ref_cache[0][ scan8[n] ];
568
        int refn1 = h->ref_cache[1][ scan8[n] ];
569

    
570
        mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
571
                    dest_y, dest_cb, dest_cr,
572
                    x_offset, y_offset, qpix_put, chroma_put);
573
        mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
574
                    tmp_y, tmp_cb, tmp_cr,
575
                    x_offset, y_offset, qpix_put, chroma_put);
576

    
577
        if(h->use_weight == 2){
578
            int weight0 = h->implicit_weight[refn0][refn1][s->mb_y&1];
579
            int weight1 = 64 - weight0;
580
            luma_weight_avg(  dest_y,  tmp_y,  h->  mb_linesize, 5, weight0, weight1, 0);
581
            chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
582
            chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
583
        }else{
584
            luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
585
                            h->luma_weight[refn0][0][0] , h->luma_weight[refn1][1][0],
586
                            h->luma_weight[refn0][0][1] + h->luma_weight[refn1][1][1]);
587
            chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
588
                            h->chroma_weight[refn0][0][0][0] , h->chroma_weight[refn1][1][0][0],
589
                            h->chroma_weight[refn0][0][0][1] + h->chroma_weight[refn1][1][0][1]);
590
            chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
591
                            h->chroma_weight[refn0][0][1][0] , h->chroma_weight[refn1][1][1][0],
592
                            h->chroma_weight[refn0][0][1][1] + h->chroma_weight[refn1][1][1][1]);
593
        }
594
    }else{
595
        int list = list1 ? 1 : 0;
596
        int refn = h->ref_cache[list][ scan8[n] ];
597
        Picture *ref= &h->ref_list[list][refn];
598
        mc_dir_part(h, ref, n, square, chroma_height, delta, list,
599
                    dest_y, dest_cb, dest_cr, x_offset, y_offset,
600
                    qpix_put, chroma_put);
601

    
602
        luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
603
                       h->luma_weight[refn][list][0], h->luma_weight[refn][list][1]);
604
        if(h->use_weight_chroma){
605
            chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
606
                             h->chroma_weight[refn][list][0][0], h->chroma_weight[refn][list][0][1]);
607
            chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
608
                             h->chroma_weight[refn][list][1][0], h->chroma_weight[refn][list][1][1]);
609
        }
610
    }
611
}
612

    
613
static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
614
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
615
                           int x_offset, int y_offset,
616
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
617
                           qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
618
                           h264_weight_func *weight_op, h264_biweight_func *weight_avg,
619
                           int list0, int list1){
620
    if((h->use_weight==2 && list0 && list1
621
        && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ][h->s.mb_y&1] != 32))
622
       || h->use_weight==1)
623
        mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
624
                         x_offset, y_offset, qpix_put, chroma_put,
625
                         weight_op[0], weight_op[3], weight_avg[0], weight_avg[3], list0, list1);
626
    else
627
        mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
628
                    x_offset, y_offset, qpix_put, chroma_put, qpix_avg, chroma_avg, list0, list1);
629
}
630

    
631
static inline void prefetch_motion(H264Context *h, int list){
632
    /* fetch pixels for estimated mv 4 macroblocks ahead
633
     * optimized for 64byte cache lines */
634
    MpegEncContext * const s = &h->s;
635
    const int refn = h->ref_cache[list][scan8[0]];
636
    if(refn >= 0){
637
        const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
638
        const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
639
        uint8_t **src= h->ref_list[list][refn].data;
640
        int off= mx*h->pixel_size + (my + (s->mb_x&3)*4)*h->mb_linesize + 64*h->pixel_size;
641
        s->dsp.prefetch(src[0]+off, s->linesize, 4);
642
        off= (mx>>1)*h->pixel_size + ((my>>1)*h->pixel_size + (s->mb_x&7))*s->uvlinesize + 64*h->pixel_size;
643
        s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
644
    }
645
}
646

    
647
static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
648
                      qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
649
                      qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
650
                      h264_weight_func *weight_op, h264_biweight_func *weight_avg){
651
    MpegEncContext * const s = &h->s;
652
    const int mb_xy= h->mb_xy;
653
    const int mb_type= s->current_picture.mb_type[mb_xy];
654

    
655
    assert(IS_INTER(mb_type));
656

    
657
    if(HAVE_PTHREADS && s->avctx->active_thread_type&FF_THREAD_FRAME)
658
        await_references(h);
659
    prefetch_motion(h, 0);
660

    
661
    if(IS_16X16(mb_type)){
662
        mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
663
                qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
664
                weight_op, weight_avg,
665
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
666
    }else if(IS_16X8(mb_type)){
667
        mc_part(h, 0, 0, 4, 8*h->pixel_size, dest_y, dest_cb, dest_cr, 0, 0,
668
                qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
669
                &weight_op[1], &weight_avg[1],
670
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
671
        mc_part(h, 8, 0, 4, 8*h->pixel_size, dest_y, dest_cb, dest_cr, 0, 4,
672
                qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
673
                &weight_op[1], &weight_avg[1],
674
                IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
675
    }else if(IS_8X16(mb_type)){
676
        mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
677
                qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
678
                &weight_op[2], &weight_avg[2],
679
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
680
        mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
681
                qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
682
                &weight_op[2], &weight_avg[2],
683
                IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
684
    }else{
685
        int i;
686

    
687
        assert(IS_8X8(mb_type));
688

    
689
        for(i=0; i<4; i++){
690
            const int sub_mb_type= h->sub_mb_type[i];
691
            const int n= 4*i;
692
            int x_offset= (i&1)<<2;
693
            int y_offset= (i&2)<<1;
694

    
695
            if(IS_SUB_8X8(sub_mb_type)){
696
                mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
697
                    qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
698
                    &weight_op[3], &weight_avg[3],
699
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
700
            }else if(IS_SUB_8X4(sub_mb_type)){
701
                mc_part(h, n  , 0, 2, 4*h->pixel_size, dest_y, dest_cb, dest_cr, x_offset, y_offset,
702
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
703
                    &weight_op[4], &weight_avg[4],
704
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
705
                mc_part(h, n+2, 0, 2, 4*h->pixel_size, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
706
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
707
                    &weight_op[4], &weight_avg[4],
708
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
709
            }else if(IS_SUB_4X8(sub_mb_type)){
710
                mc_part(h, n  , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
711
                    qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
712
                    &weight_op[5], &weight_avg[5],
713
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
714
                mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
715
                    qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
716
                    &weight_op[5], &weight_avg[5],
717
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
718
            }else{
719
                int j;
720
                assert(IS_SUB_4X4(sub_mb_type));
721
                for(j=0; j<4; j++){
722
                    int sub_x_offset= x_offset + 2*(j&1);
723
                    int sub_y_offset= y_offset +   (j&2);
724
                    mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
725
                        qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
726
                        &weight_op[6], &weight_avg[6],
727
                        IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
728
                }
729
            }
730
        }
731
    }
732

    
733
    prefetch_motion(h, 1);
734
}
735

    
736

    
737
static void free_tables(H264Context *h, int free_rbsp){
738
    int i;
739
    H264Context *hx;
740
    av_freep(&h->intra4x4_pred_mode);
741
    av_freep(&h->chroma_pred_mode_table);
742
    av_freep(&h->cbp_table);
743
    av_freep(&h->mvd_table[0]);
744
    av_freep(&h->mvd_table[1]);
745
    av_freep(&h->direct_table);
746
    av_freep(&h->non_zero_count);
747
    av_freep(&h->slice_table_base);
748
    h->slice_table= NULL;
749
    av_freep(&h->list_counts);
750

    
751
    av_freep(&h->mb2b_xy);
752
    av_freep(&h->mb2br_xy);
753

    
754
    for(i = 0; i < MAX_THREADS; i++) {
755
        hx = h->thread_context[i];
756
        if(!hx) continue;
757
        av_freep(&hx->top_borders[1]);
758
        av_freep(&hx->top_borders[0]);
759
        av_freep(&hx->s.obmc_scratchpad);
760
        if (free_rbsp){
761
            av_freep(&hx->rbsp_buffer[1]);
762
            av_freep(&hx->rbsp_buffer[0]);
763
            hx->rbsp_buffer_size[0] = 0;
764
            hx->rbsp_buffer_size[1] = 0;
765
        }
766
        if (i) av_freep(&h->thread_context[i]);
767
    }
768
}
769

    
770
static void init_dequant8_coeff_table(H264Context *h){
771
    int i,q,x;
772
    h->dequant8_coeff[0] = h->dequant8_buffer[0];
773
    h->dequant8_coeff[1] = h->dequant8_buffer[1];
774

    
775
    for(i=0; i<2; i++ ){
776
        if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
777
            h->dequant8_coeff[1] = h->dequant8_buffer[0];
778
            break;
779
        }
780

    
781
        for(q=0; q<52; q++){
782
            int shift = div6[q];
783
            int idx = rem6[q];
784
            for(x=0; x<64; x++)
785
                h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
786
                    ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
787
                    h->pps.scaling_matrix8[i][x]) << shift;
788
        }
789
    }
790
}
791

    
792
static void init_dequant4_coeff_table(H264Context *h){
793
    int i,j,q,x;
794
    for(i=0; i<6; i++ ){
795
        h->dequant4_coeff[i] = h->dequant4_buffer[i];
796
        for(j=0; j<i; j++){
797
            if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
798
                h->dequant4_coeff[i] = h->dequant4_buffer[j];
799
                break;
800
            }
801
        }
802
        if(j<i)
803
            continue;
804

    
805
        for(q=0; q<52; q++){
806
            int shift = div6[q] + 2;
807
            int idx = rem6[q];
808
            for(x=0; x<16; x++)
809
                h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
810
                    ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
811
                    h->pps.scaling_matrix4[i][x]) << shift;
812
        }
813
    }
814
}
815

    
816
static void init_dequant_tables(H264Context *h){
817
    int i,x;
818
    init_dequant4_coeff_table(h);
819
    if(h->pps.transform_8x8_mode)
820
        init_dequant8_coeff_table(h);
821
    if(h->sps.transform_bypass){
822
        for(i=0; i<6; i++)
823
            for(x=0; x<16; x++)
824
                h->dequant4_coeff[i][0][x] = 1<<6;
825
        if(h->pps.transform_8x8_mode)
826
            for(i=0; i<2; i++)
827
                for(x=0; x<64; x++)
828
                    h->dequant8_coeff[i][0][x] = 1<<6;
829
    }
830
}
831

    
832

    
833
int ff_h264_alloc_tables(H264Context *h){
834
    MpegEncContext * const s = &h->s;
835
    const int big_mb_num= s->mb_stride * (s->mb_height+1);
836
    const int row_mb_num= 2*s->mb_stride*s->avctx->thread_count;
837
    int x,y;
838

    
839
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode, row_mb_num * 8  * sizeof(uint8_t), fail)
840

    
841
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count    , big_mb_num * 32 * sizeof(uint8_t), fail)
842
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
843
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
844

    
845
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
846
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
847
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
848
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
849
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
850

    
851
    memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(*h->slice_table_base));
852
    h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
853

    
854
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy  , big_mb_num * sizeof(uint32_t), fail);
855
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy , big_mb_num * sizeof(uint32_t), fail);
856
    for(y=0; y<s->mb_height; y++){
857
        for(x=0; x<s->mb_width; x++){
858
            const int mb_xy= x + y*s->mb_stride;
859
            const int b_xy = 4*x + 4*y*h->b_stride;
860

    
861
            h->mb2b_xy [mb_xy]= b_xy;
862
            h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
863
        }
864
    }
865

    
866
    s->obmc_scratchpad = NULL;
867

    
868
    if(!h->dequant4_coeff[0])
869
        init_dequant_tables(h);
870

    
871
    return 0;
872
fail:
873
    free_tables(h, 1);
874
    return -1;
875
}
876

    
877
/**
878
 * Mimic alloc_tables(), but for every context thread.
879
 */
880
static void clone_tables(H264Context *dst, H264Context *src, int i){
881
    MpegEncContext * const s = &src->s;
882
    dst->intra4x4_pred_mode       = src->intra4x4_pred_mode + i*8*2*s->mb_stride;
883
    dst->non_zero_count           = src->non_zero_count;
884
    dst->slice_table              = src->slice_table;
885
    dst->cbp_table                = src->cbp_table;
886
    dst->mb2b_xy                  = src->mb2b_xy;
887
    dst->mb2br_xy                 = src->mb2br_xy;
888
    dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;
889
    dst->mvd_table[0]             = src->mvd_table[0] + i*8*2*s->mb_stride;
890
    dst->mvd_table[1]             = src->mvd_table[1] + i*8*2*s->mb_stride;
891
    dst->direct_table             = src->direct_table;
892
    dst->list_counts              = src->list_counts;
893

    
894
    dst->s.obmc_scratchpad = NULL;
895
    ff_h264_pred_init(&dst->hpc, src->s.codec_id);
896
}
897

    
898
/**
899
 * Init context
900
 * Allocate buffers which are not shared amongst multiple threads.
901
 */
902
static int context_init(H264Context *h){
903
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t)*2, fail)
904
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t)*2, fail)
905

    
906
    h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
907
    h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
908

    
909
    return 0;
910
fail:
911
    return -1; // free_tables will clean up for us
912
}
913

    
914
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
915

    
916
static av_cold void common_init(H264Context *h){
917
    MpegEncContext * const s = &h->s;
918

    
919
    s->width = s->avctx->width;
920
    s->height = s->avctx->height;
921
    s->codec_id= s->avctx->codec->id;
922

    
923
    ff_h264dsp_init(&h->h264dsp);
924
    ff_h264_pred_init(&h->hpc, s->codec_id);
925

    
926
    h->dequant_coeff_pps= -1;
927
    s->unrestricted_mv=1;
928
    s->decode=1; //FIXME
929

    
930
    dsputil_init(&s->dsp, s->avctx); // needed so that idct permutation is known early
931

    
932
    memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
933
    memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
934
}
935

    
936
int ff_h264_decode_extradata(H264Context *h)
937
{
938
    AVCodecContext *avctx = h->s.avctx;
939

    
940
    if(*(char *)avctx->extradata == 1){
941
        int i, cnt, nalsize;
942
        unsigned char *p = avctx->extradata;
943

    
944
        h->is_avc = 1;
945

    
946
        if(avctx->extradata_size < 7) {
947
            av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
948
            return -1;
949
        }
950
        /* sps and pps in the avcC always have length coded with 2 bytes,
951
           so put a fake nal_length_size = 2 while parsing them */
952
        h->nal_length_size = 2;
953
        // Decode sps from avcC
954
        cnt = *(p+5) & 0x1f; // Number of sps
955
        p += 6;
956
        for (i = 0; i < cnt; i++) {
957
            nalsize = AV_RB16(p) + 2;
958
            if(decode_nal_units(h, p, nalsize) < 0) {
959
                av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
960
                return -1;
961
            }
962
            p += nalsize;
963
        }
964
        // Decode pps from avcC
965
        cnt = *(p++); // Number of pps
966
        for (i = 0; i < cnt; i++) {
967
            nalsize = AV_RB16(p) + 2;
968
            if(decode_nal_units(h, p, nalsize) < 0) {
969
                av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
970
                return -1;
971
            }
972
            p += nalsize;
973
        }
974
        // Now store right nal length size, that will be use to parse all other nals
975
        h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
976
    } else {
977
        h->is_avc = 0;
978
        if(decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
979
            return -1;
980
    }
981
    return 0;
982
}
983

    
984
av_cold int ff_h264_decode_init(AVCodecContext *avctx){
985
    H264Context *h= avctx->priv_data;
986
    MpegEncContext * const s = &h->s;
987

    
988
    MPV_decode_defaults(s);
989

    
990
    s->avctx = avctx;
991
    common_init(h);
992

    
993
    s->out_format = FMT_H264;
994
    s->workaround_bugs= avctx->workaround_bugs;
995

    
996
    // set defaults
997
//    s->decode_mb= ff_h263_decode_mb;
998
    s->quarter_sample = 1;
999
    if(!avctx->has_b_frames)
1000
    s->low_delay= 1;
1001

    
1002
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1003

    
1004
    ff_h264_decode_init_vlc();
1005

    
1006
    h->pixel_size = 1;
1007

    
1008
    h->thread_context[0] = h;
1009
    h->outputed_poc = h->next_outputed_poc = INT_MIN;
1010
    h->prev_poc_msb= 1<<16;
1011
    h->x264_build = -1;
1012
    ff_h264_reset_sei(h);
1013
    if(avctx->codec_id == CODEC_ID_H264){
1014
        if(avctx->ticks_per_frame == 1){
1015
            s->avctx->time_base.den *=2;
1016
        }
1017
        avctx->ticks_per_frame = 2;
1018
    }
1019

    
1020
    if(avctx->extradata_size > 0 && avctx->extradata &&
1021
        ff_h264_decode_extradata(h))
1022
        return -1;
1023

    
1024
    if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1025
        s->avctx->has_b_frames = h->sps.num_reorder_frames;
1026
        s->low_delay = 0;
1027
    }
1028

    
1029
    return 0;
1030
}
1031

    
1032
static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
1033
{
1034
    int i;
1035

    
1036
    for (i=0; i<count; i++){
1037
        to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1038
    }
1039
}
1040

    
1041
static void copy_parameter_set(void **to, void **from, int count, int size)
1042
{
1043
    int i;
1044

    
1045
    for (i=0; i<count; i++){
1046
        if (to[i] && !from[i]) av_freep(&to[i]);
1047
        else if (from[i] && !to[i]) to[i] = av_malloc(size);
1048

    
1049
        if (from[i]) memcpy(to[i], from[i], size);
1050
    }
1051
}
1052

    
1053
static int decode_init_thread_copy(AVCodecContext *avctx){
1054
    H264Context *h= avctx->priv_data;
1055

    
1056
    if (!avctx->is_copy) return 0;
1057
    memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1058
    memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1059

    
1060
    return 0;
1061
}
1062

    
1063
#define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
1064
static int decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src){
1065
    H264Context *h= dst->priv_data, *h1= src->priv_data;
1066
    MpegEncContext * const s = &h->s, * const s1 = &h1->s;
1067
    int inited = s->context_initialized, err;
1068
    int i;
1069

    
1070
    if(dst == src || !s1->context_initialized) return 0;
1071

    
1072
    err = ff_mpeg_update_thread_context(dst, src);
1073
    if(err) return err;
1074

    
1075
    //FIXME handle width/height changing
1076
    if(!inited){
1077
        for(i = 0; i < MAX_SPS_COUNT; i++)
1078
            av_freep(h->sps_buffers + i);
1079

    
1080
        for(i = 0; i < MAX_PPS_COUNT; i++)
1081
            av_freep(h->pps_buffers + i);
1082

    
1083
        memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
1084
        memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1085
        memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1086
        ff_h264_alloc_tables(h);
1087
        context_init(h);
1088

    
1089
        for(i=0; i<2; i++){
1090
            h->rbsp_buffer[i] = NULL;
1091
            h->rbsp_buffer_size[i] = 0;
1092
        }
1093

    
1094
        h->thread_context[0] = h;
1095

    
1096
        // frame_start may not be called for the next thread (if it's decoding a bottom field)
1097
        // so this has to be allocated here
1098
        h->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
1099

    
1100
        s->dsp.clear_blocks(h->mb);
1101
    }
1102

    
1103
    //extradata/NAL handling
1104
    h->is_avc          = h1->is_avc;
1105

    
1106
    //SPS/PPS
1107
    copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
1108
    h->sps             = h1->sps;
1109
    copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
1110
    h->pps             = h1->pps;
1111

    
1112
    //Dequantization matrices
1113
    //FIXME these are big - can they be only copied when PPS changes?
1114
    copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1115

    
1116
    for(i=0; i<6; i++)
1117
        h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1118

    
1119
    for(i=0; i<2; i++)
1120
        h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1121

    
1122
    h->dequant_coeff_pps = h1->dequant_coeff_pps;
1123

    
1124
    //POC timing
1125
    copy_fields(h, h1, poc_lsb, redundant_pic_count);
1126

    
1127
    //reference lists
1128
    copy_fields(h, h1, ref_count, intra_gb);
1129
    copy_fields(h, h1, short_ref, cabac_init_idc);
1130

    
1131
    copy_picture_range(h->short_ref,   h1->short_ref,   32, s, s1);
1132
    copy_picture_range(h->long_ref,    h1->long_ref,    32,  s, s1);
1133
    copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
1134

    
1135
    h->last_slice_type = h1->last_slice_type;
1136

    
1137
    if(!s->current_picture_ptr) return 0;
1138

    
1139
    if(!s->dropable) {
1140
        ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1141
        h->prev_poc_msb     = h->poc_msb;
1142
        h->prev_poc_lsb     = h->poc_lsb;
1143
    }
1144
    h->prev_frame_num_offset= h->frame_num_offset;
1145
    h->prev_frame_num       = h->frame_num;
1146
    h->outputed_poc         = h->next_outputed_poc;
1147

    
1148
    return 0;
1149
}
1150

    
1151
int ff_h264_frame_start(H264Context *h){
1152
    MpegEncContext * const s = &h->s;
1153
    int i;
1154

    
1155
    if(MPV_frame_start(s, s->avctx) < 0)
1156
        return -1;
1157
    ff_er_frame_start(s);
1158
    /*
1159
     * MPV_frame_start uses pict_type to derive key_frame.
1160
     * This is incorrect for H.264; IDR markings must be used.
1161
     * Zero here; IDR markings per slice in frame or fields are ORed in later.
1162
     * See decode_nal_units().
1163
     */
1164
    s->current_picture_ptr->key_frame= 0;
1165
    s->current_picture_ptr->mmco_reset= 0;
1166

    
1167
    assert(s->linesize && s->uvlinesize);
1168

    
1169
    for(i=0; i<16; i++){
1170
        h->block_offset[i]= 4*((scan8[i] - scan8[0])&7)*h->pixel_size + 4*s->linesize*((scan8[i] - scan8[0])>>3);
1171
        h->block_offset[24+i]= 4*((scan8[i] - scan8[0])&7)*h->pixel_size + 8*s->linesize*((scan8[i] - scan8[0])>>3);
1172
    }
1173
    for(i=0; i<4; i++){
1174
        h->block_offset[16+i]=
1175
        h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7)*h->pixel_size + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1176
        h->block_offset[24+16+i]=
1177
        h->block_offset[24+20+i]= 4*((scan8[i] - scan8[0])&7)*h->pixel_size + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1178
    }
1179

    
1180
    /* can't be in alloc_tables because linesize isn't known there.
1181
     * FIXME: redo bipred weight to not require extra buffer? */
1182
    for(i = 0; i < s->avctx->thread_count; i++)
1183
        if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
1184
            h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
1185

    
1186
    /* some macroblocks can be accessed before they're available in case of lost slices, mbaff or threading*/
1187
    memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(*h->slice_table));
1188

    
1189
//    s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
1190

    
1191
    // We mark the current picture as non-reference after allocating it, so
1192
    // that if we break out due to an error it can be released automatically
1193
    // in the next MPV_frame_start().
1194
    // SVQ3 as well as most other codecs have only last/next/current and thus
1195
    // get released even with set reference, besides SVQ3 and others do not
1196
    // mark frames as reference later "naturally".
1197
    if(s->codec_id != CODEC_ID_SVQ3)
1198
        s->current_picture_ptr->reference= 0;
1199

    
1200
    s->current_picture_ptr->field_poc[0]=
1201
    s->current_picture_ptr->field_poc[1]= INT_MAX;
1202

    
1203
    h->next_output_pic = NULL;
1204

    
1205
    assert(s->current_picture_ptr->long_ref==0);
1206

    
1207
    return 0;
1208
}
1209

    
1210
/**
1211
  * Run setup operations that must be run after slice header decoding.
1212
  * This includes finding the next displayed frame.
1213
  *
1214
  * @param h h264 master context
1215
  */
1216
static void decode_postinit(H264Context *h){
1217
    MpegEncContext * const s = &h->s;
1218
    Picture *out = s->current_picture_ptr;
1219
    Picture *cur = s->current_picture_ptr;
1220
    int i, pics, out_of_order, out_idx;
1221

    
1222
    s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
1223
    s->current_picture_ptr->pict_type= s->pict_type;
1224

    
1225
    if (h->next_output_pic) return;
1226

    
1227
    if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
1228
        //FIXME this allows the next thread to start once we encounter the first field of a PAFF packet
1229
        //This works if the next packet contains the second field. It does not work if both fields are
1230
        //in the same packet.
1231
        //ff_thread_finish_setup(s->avctx);
1232
        return;
1233
    }
1234

    
1235
    cur->interlaced_frame = 0;
1236
    cur->repeat_pict = 0;
1237

    
1238
    /* Signal interlacing information externally. */
1239
    /* Prioritize picture timing SEI information over used decoding process if it exists. */
1240

    
1241
    if(h->sps.pic_struct_present_flag){
1242
        switch (h->sei_pic_struct)
1243
        {
1244
        case SEI_PIC_STRUCT_FRAME:
1245
            break;
1246
        case SEI_PIC_STRUCT_TOP_FIELD:
1247
        case SEI_PIC_STRUCT_BOTTOM_FIELD:
1248
            cur->interlaced_frame = 1;
1249
            break;
1250
        case SEI_PIC_STRUCT_TOP_BOTTOM:
1251
        case SEI_PIC_STRUCT_BOTTOM_TOP:
1252
            if (FIELD_OR_MBAFF_PICTURE)
1253
                cur->interlaced_frame = 1;
1254
            else
1255
                // try to flag soft telecine progressive
1256
                cur->interlaced_frame = h->prev_interlaced_frame;
1257
            break;
1258
        case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1259
        case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1260
            // Signal the possibility of telecined film externally (pic_struct 5,6)
1261
            // From these hints, let the applications decide if they apply deinterlacing.
1262
            cur->repeat_pict = 1;
1263
            break;
1264
        case SEI_PIC_STRUCT_FRAME_DOUBLING:
1265
            // Force progressive here, as doubling interlaced frame is a bad idea.
1266
            cur->repeat_pict = 2;
1267
            break;
1268
        case SEI_PIC_STRUCT_FRAME_TRIPLING:
1269
            cur->repeat_pict = 4;
1270
            break;
1271
        }
1272

    
1273
        if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1274
            cur->interlaced_frame = (h->sei_ct_type & (1<<1)) != 0;
1275
    }else{
1276
        /* Derive interlacing flag from used decoding process. */
1277
        cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1278
    }
1279
    h->prev_interlaced_frame = cur->interlaced_frame;
1280

    
1281
    if (cur->field_poc[0] != cur->field_poc[1]){
1282
        /* Derive top_field_first from field pocs. */
1283
        cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
1284
    }else{
1285
        if(cur->interlaced_frame || h->sps.pic_struct_present_flag){
1286
            /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
1287
            if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
1288
              || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1289
                cur->top_field_first = 1;
1290
            else
1291
                cur->top_field_first = 0;
1292
        }else{
1293
            /* Most likely progressive */
1294
            cur->top_field_first = 0;
1295
        }
1296
    }
1297

    
1298
    //FIXME do something with unavailable reference frames
1299

    
1300
    /* Sort B-frames into display order */
1301

    
1302
    if(h->sps.bitstream_restriction_flag
1303
       && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1304
        s->avctx->has_b_frames = h->sps.num_reorder_frames;
1305
        s->low_delay = 0;
1306
    }
1307

    
1308
    if(   s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
1309
       && !h->sps.bitstream_restriction_flag){
1310
        s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;
1311
        s->low_delay= 0;
1312
    }
1313

    
1314
    pics = 0;
1315
    while(h->delayed_pic[pics]) pics++;
1316

    
1317
    assert(pics <= MAX_DELAYED_PIC_COUNT);
1318

    
1319
    h->delayed_pic[pics++] = cur;
1320
    if(cur->reference == 0)
1321
        cur->reference = DELAYED_PIC_REF;
1322

    
1323
    out = h->delayed_pic[0];
1324
    out_idx = 0;
1325
    for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
1326
        if(h->delayed_pic[i]->poc < out->poc){
1327
            out = h->delayed_pic[i];
1328
            out_idx = i;
1329
        }
1330
    if(s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset))
1331
        h->next_outputed_poc= INT_MIN;
1332
    out_of_order = out->poc < h->next_outputed_poc;
1333

    
1334
    if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
1335
        { }
1336
    else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)
1337
       || (s->low_delay &&
1338
        ((h->next_outputed_poc != INT_MIN && out->poc > h->next_outputed_poc + 2)
1339
         || cur->pict_type == FF_B_TYPE)))
1340
    {
1341
        s->low_delay = 0;
1342
        s->avctx->has_b_frames++;
1343
    }
1344

    
1345
    if(out_of_order || pics > s->avctx->has_b_frames){
1346
        out->reference &= ~DELAYED_PIC_REF;
1347
        for(i=out_idx; h->delayed_pic[i]; i++)
1348
            h->delayed_pic[i] = h->delayed_pic[i+1];
1349
    }
1350
    if(!out_of_order && pics > s->avctx->has_b_frames){
1351
        h->next_output_pic = out;
1352
        if(out_idx==0 && h->delayed_pic[0] && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset)) {
1353
            h->next_outputed_poc = INT_MIN;
1354
        } else
1355
            h->next_outputed_poc = out->poc;
1356
    }else{
1357
        av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
1358
    }
1359

    
1360
    ff_thread_finish_setup(s->avctx);
1361
}
1362

    
1363
static inline void backup_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int simple){
1364
    MpegEncContext * const s = &h->s;
1365
    uint8_t *top_border;
1366
    int top_idx = 1;
1367

    
1368
    src_y  -=   linesize;
1369
    src_cb -= uvlinesize;
1370
    src_cr -= uvlinesize;
1371

    
1372
    if(!simple && FRAME_MBAFF){
1373
        if(s->mb_y&1){
1374
            if(!MB_MBAFF){
1375
                top_border = h->top_borders[0][s->mb_x];
1376
                AV_COPY128(top_border, src_y + 15*linesize);
1377
                if (h->pixel_size == 2)
1378
                    AV_COPY128(top_border+16, src_y+15*linesize+16);
1379
                if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1380
                    if (h->pixel_size == 2) {
1381
                        AV_COPY128(top_border+32, src_cb+7*uvlinesize);
1382
                        AV_COPY128(top_border+48, src_cr+7*uvlinesize);
1383
                    } else {
1384
                    AV_COPY64(top_border+16, src_cb+7*uvlinesize);
1385
                    AV_COPY64(top_border+24, src_cr+7*uvlinesize);
1386
                    }
1387
                }
1388
            }
1389
        }else if(MB_MBAFF){
1390
            top_idx = 0;
1391
        }else
1392
            return;
1393
    }
1394

    
1395
    top_border = h->top_borders[top_idx][s->mb_x];
1396
    // There are two lines saved, the line above the the top macroblock of a pair,
1397
    // and the line above the bottom macroblock
1398
    AV_COPY128(top_border, src_y + 16*linesize);
1399
    if (h->pixel_size == 2)
1400
        AV_COPY128(top_border+16, src_y+16*linesize+16);
1401

    
1402
    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1403
        if (h->pixel_size == 2) {
1404
            AV_COPY128(top_border+32, src_cb+8*uvlinesize);
1405
            AV_COPY128(top_border+48, src_cr+8*uvlinesize);
1406
        } else {
1407
        AV_COPY64(top_border+16, src_cb+8*uvlinesize);
1408
        AV_COPY64(top_border+24, src_cr+8*uvlinesize);
1409
        }
1410
    }
1411
}
1412

    
1413
static inline void xchg_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg, int simple){
1414
    MpegEncContext * const s = &h->s;
1415
    int deblock_left;
1416
    int deblock_top;
1417
    int top_idx = 1;
1418
    uint8_t *top_border_m1;
1419
    uint8_t *top_border;
1420

    
1421
    if(!simple && FRAME_MBAFF){
1422
        if(s->mb_y&1){
1423
            if(!MB_MBAFF)
1424
                return;
1425
        }else{
1426
            top_idx = MB_MBAFF ? 0 : 1;
1427
        }
1428
    }
1429

    
1430
    if(h->deblocking_filter == 2) {
1431
        deblock_left = h->left_type[0];
1432
        deblock_top  = h->top_type;
1433
    } else {
1434
        deblock_left = (s->mb_x > 0);
1435
        deblock_top =  (s->mb_y > !!MB_FIELD);
1436
    }
1437

    
1438
    src_y  -=   linesize + h->pixel_size;
1439
    src_cb -= uvlinesize + h->pixel_size;
1440
    src_cr -= uvlinesize + h->pixel_size;
1441

    
1442
    top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1443
    top_border    = h->top_borders[top_idx][s->mb_x];
1444

    
1445
#define XCHG(a,b,xchg)\
1446
    if (h->pixel_size == 2) {\
1447
        if (xchg) {\
1448
            AV_SWAP64(b+0,a+0);\
1449
            AV_SWAP64(b+8,a+8);\
1450
        } else {\
1451
            AV_COPY128(b,a); \
1452
        }\
1453
    } else \
1454
if (xchg) AV_SWAP64(b,a);\
1455
else      AV_COPY64(b,a);
1456

    
1457
    if(deblock_top){
1458
        if(deblock_left){
1459
            XCHG(top_border_m1+8*h->pixel_size, src_y -7*h->pixel_size, 1);
1460
        }
1461
        XCHG(top_border+0*h->pixel_size, src_y +1*h->pixel_size, xchg);
1462
        XCHG(top_border+8*h->pixel_size, src_y +9*h->pixel_size, 1);
1463
        if(s->mb_x+1 < s->mb_width){
1464
            XCHG(h->top_borders[top_idx][s->mb_x+1], src_y +17*h->pixel_size, 1);
1465
        }
1466
    }
1467
    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1468
        if(deblock_top){
1469
            if(deblock_left){
1470
                XCHG(top_border_m1+16*h->pixel_size, src_cb -7*h->pixel_size, 1);
1471
                XCHG(top_border_m1+24*h->pixel_size, src_cr -7*h->pixel_size, 1);
1472
            }
1473
            XCHG(top_border+16*h->pixel_size, src_cb+h->pixel_size, 1);
1474
            XCHG(top_border+24*h->pixel_size, src_cr+h->pixel_size, 1);
1475
        }
1476
    }
1477
}
1478

    
1479
static av_always_inline int dctcoef_get(H264Context *h, DCTELEM *mb, int index) {
1480
    if (h->pixel_size == 1)
1481
        return mb[index];
1482
    else
1483
        return ((int32_t*)mb)[index];
1484
}
1485

    
1486
static av_always_inline void dctcoef_set(H264Context *h, DCTELEM *mb, int index, int value) {
1487
    if (h->pixel_size == 1)
1488
        mb[index] = value;
1489
    else
1490
        ((int32_t*)mb)[index] = value;
1491
}
1492

    
1493
static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
1494
    MpegEncContext * const s = &h->s;
1495
    const int mb_x= s->mb_x;
1496
    const int mb_y= s->mb_y;
1497
    const int mb_xy= h->mb_xy;
1498
    const int mb_type= s->current_picture.mb_type[mb_xy];
1499
    uint8_t  *dest_y, *dest_cb, *dest_cr;
1500
    int linesize, uvlinesize /*dct_offset*/;
1501
    int i;
1502
    int *block_offset = &h->block_offset[0];
1503
    const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
1504
    /* is_h264 should always be true if SVQ3 is disabled. */
1505
    const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
1506
    void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1507
    void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1508

    
1509
    dest_y  = s->current_picture.data[0] + (mb_x*h->pixel_size + mb_y * s->linesize  ) * 16;
1510
    dest_cb = s->current_picture.data[1] + (mb_x*h->pixel_size + mb_y * s->uvlinesize) * 8;
1511
    dest_cr = s->current_picture.data[2] + (mb_x*h->pixel_size + mb_y * s->uvlinesize) * 8;
1512

    
1513
    s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + 64*h->pixel_size, s->linesize, 4);
1514
    s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + 64*h->pixel_size, dest_cr - dest_cb, 2);
1515

    
1516
    h->list_counts[mb_xy]= h->list_count;
1517

    
1518
    if (!simple && MB_FIELD) {
1519
        linesize   = h->mb_linesize   = s->linesize * 2;
1520
        uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
1521
        block_offset = &h->block_offset[24];
1522
        if(mb_y&1){ //FIXME move out of this function?
1523
            dest_y -= s->linesize*15;
1524
            dest_cb-= s->uvlinesize*7;
1525
            dest_cr-= s->uvlinesize*7;
1526
        }
1527
        if(FRAME_MBAFF) {
1528
            int list;
1529
            for(list=0; list<h->list_count; list++){
1530
                if(!USES_LIST(mb_type, list))
1531
                    continue;
1532
                if(IS_16X16(mb_type)){
1533
                    int8_t *ref = &h->ref_cache[list][scan8[0]];
1534
                    fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
1535
                }else{
1536
                    for(i=0; i<16; i+=4){
1537
                        int ref = h->ref_cache[list][scan8[i]];
1538
                        if(ref >= 0)
1539
                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
1540
                    }
1541
                }
1542
            }
1543
        }
1544
    } else {
1545
        linesize   = h->mb_linesize   = s->linesize;
1546
        uvlinesize = h->mb_uvlinesize = s->uvlinesize;
1547
//        dct_offset = s->linesize * 16;
1548
    }
1549

    
1550
    if (!simple && IS_INTRA_PCM(mb_type)) {
1551
        if (h->pixel_size == 2) {
1552
            const int bit_depth = h->sps.bit_depth_luma;
1553
            int j;
1554
            GetBitContext gb;
1555
            init_get_bits(&gb, (uint8_t*)h->mb, 384*bit_depth);
1556

    
1557
            for (i = 0; i < 16; i++) {
1558
                uint16_t *tmp_y  = (uint16_t*)(dest_y  + i*linesize);
1559
                for (j = 0; j < 16; j++)
1560
                    tmp_y[j] = get_bits(&gb, bit_depth);
1561
            }
1562
            for (i = 0; i < 8; i++) {
1563
                uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
1564
                for (j = 0; j < 8; j++)
1565
                    tmp_cb[j] = get_bits(&gb, bit_depth);
1566
            }
1567
            for (i = 0; i < 8; i++) {
1568
                uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
1569
                for (j = 0; j < 8; j++)
1570
                    tmp_cr[j] = get_bits(&gb, bit_depth);
1571
            }
1572
        } else {
1573
        for (i=0; i<16; i++) {
1574
            memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
1575
        }
1576
        for (i=0; i<8; i++) {
1577
            memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4,  8);
1578
            memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4,  8);
1579
        }
1580
        }
1581
    } else {
1582
        if(IS_INTRA(mb_type)){
1583
            if(h->deblocking_filter)
1584
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
1585

    
1586
            if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1587
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
1588
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
1589
            }
1590

    
1591
            if(IS_INTRA4x4(mb_type)){
1592
                if(simple || !s->encoding){
1593
                    if(IS_8x8DCT(mb_type)){
1594
                        if(transform_bypass){
1595
                            idct_dc_add =
1596
                            idct_add    = s->dsp.add_pixels8;
1597
                        }else{
1598
                            idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1599
                            idct_add    = h->h264dsp.h264_idct8_add;
1600
                        }
1601
                        for(i=0; i<16; i+=4){
1602
                            uint8_t * const ptr= dest_y + block_offset[i];
1603
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1604
                            if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1605
                                h->hpc.pred8x8l_add[dir](ptr, h->mb + i*16*h->pixel_size, linesize);
1606
                            }else{
1607
                                const int nnz = h->non_zero_count_cache[ scan8[i] ];
1608
                                h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
1609
                                                            (h->topright_samples_available<<i)&0x4000, linesize);
1610
                                if(nnz){
1611
                                    if(nnz == 1 && dctcoef_get(h, h->mb, i*16))
1612
                                        idct_dc_add(ptr, h->mb + i*16*h->pixel_size, linesize);
1613
                                    else
1614
                                        idct_add   (ptr, h->mb + i*16*h->pixel_size, linesize);
1615
                                }
1616
                            }
1617
                        }
1618
                    }else{
1619
                        if(transform_bypass){
1620
                            idct_dc_add =
1621
                            idct_add    = s->dsp.add_pixels4;
1622
                        }else{
1623
                            idct_dc_add = h->h264dsp.h264_idct_dc_add;
1624
                            idct_add    = h->h264dsp.h264_idct_add;
1625
                        }
1626
                        for(i=0; i<16; i++){
1627
                            uint8_t * const ptr= dest_y + block_offset[i];
1628
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1629

    
1630
                            if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1631
                                h->hpc.pred4x4_add[dir](ptr, h->mb + i*16*h->pixel_size, linesize);
1632
                            }else{
1633
                                uint8_t *topright;
1634
                                int nnz, tr;
1635
                                uint64_t tr_high;
1636
                                if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
1637
                                    const int topright_avail= (h->topright_samples_available<<i)&0x8000;
1638
                                    assert(mb_y || linesize <= block_offset[i]);
1639
                                    if(!topright_avail){
1640
                                        if (h->pixel_size == 2) {
1641
                                            tr_high= ((uint16_t*)ptr)[3 - linesize/2]*0x0001000100010001ULL;
1642
                                            topright= (uint8_t*) &tr_high;
1643
                                        } else {
1644
                                        tr= ptr[3 - linesize]*0x01010101;
1645
                                        topright= (uint8_t*) &tr;
1646
                                        }
1647
                                    }else
1648
                                        topright= ptr + 4*h->pixel_size - linesize;
1649
                                }else
1650
                                    topright= NULL;
1651

    
1652
                                h->hpc.pred4x4[ dir ](ptr, topright, linesize);
1653
                                nnz = h->non_zero_count_cache[ scan8[i] ];
1654
                                if(nnz){
1655
                                    if(is_h264){
1656
                                        if(nnz == 1 && dctcoef_get(h, h->mb, i*16))
1657
                                            idct_dc_add(ptr, h->mb + i*16*h->pixel_size, linesize);
1658
                                        else
1659
                                            idct_add   (ptr, h->mb + i*16*h->pixel_size, linesize);
1660
                                    }
1661
#if CONFIG_SVQ3_DECODER
1662
                                    else
1663
                                        ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
1664
#endif
1665
                                }
1666
                            }
1667
                        }
1668
                    }
1669
                }
1670
            }else{
1671
                h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
1672
                if(is_h264){
1673
                    if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX] ]){
1674
                        if(!transform_bypass)
1675
                            h->h264dsp.h264_luma_dc_dequant_idct(h->mb, h->mb_luma_dc, h->dequant4_coeff[0][s->qscale][0]);
1676
                        else{
1677
                            static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
1678
                                                                    8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
1679
                            for(i = 0; i < 16; i++)
1680
                                dctcoef_set(h, h->mb, dc_mapping[i], dctcoef_get(h, h->mb_luma_dc, i));
1681
                        }
1682
                    }
1683
                }
1684
#if CONFIG_SVQ3_DECODER
1685
                else
1686
                    ff_svq3_luma_dc_dequant_idct_c(h->mb, h->mb_luma_dc, s->qscale);
1687
#endif
1688
            }
1689
            if(h->deblocking_filter)
1690
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
1691
        }else if(is_h264){
1692
            hl_motion(h, dest_y, dest_cb, dest_cr,
1693
                      s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
1694
                      s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
1695
                      h->h264dsp.weight_h264_pixels_tab, h->h264dsp.biweight_h264_pixels_tab);
1696
        }
1697

    
1698

    
1699
        if(!IS_INTRA4x4(mb_type)){
1700
            if(is_h264){
1701
                if(IS_INTRA16x16(mb_type)){
1702
                    if(transform_bypass){
1703
                        if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
1704
                            h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb, linesize);
1705
                        }else{
1706
                            for(i=0; i<16; i++){
1707
                                if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h, h->mb, i*16))
1708
                                    s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + i*16*h->pixel_size, linesize);
1709
                            }
1710
                        }
1711
                    }else{
1712
                         h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1713
                    }
1714
                }else if(h->cbp&15){
1715
                    if(transform_bypass){
1716
                        const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1717
                        idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
1718
                        for(i=0; i<16; i+=di){
1719
                            if(h->non_zero_count_cache[ scan8[i] ]){
1720
                                idct_add(dest_y + block_offset[i], h->mb + i*16*h->pixel_size, linesize);
1721
                            }
1722
                        }
1723
                    }else{
1724
                        if(IS_8x8DCT(mb_type)){
1725
                            h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1726
                        }else{
1727
                            h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1728
                        }
1729
                    }
1730
                }
1731
            }
1732
#if CONFIG_SVQ3_DECODER
1733
            else{
1734
                for(i=0; i<16; i++){
1735
                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
1736
                        uint8_t * const ptr= dest_y + block_offset[i];
1737
                        ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1738
                    }
1739
                }
1740
            }
1741
#endif
1742
        }
1743

    
1744
        if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
1745
            uint8_t *dest[2] = {dest_cb, dest_cr};
1746
            if(transform_bypass){
1747
                if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
1748
                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + 16*16*h->pixel_size, uvlinesize);
1749
                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 20, h->mb + 20*16*h->pixel_size, uvlinesize);
1750
                }else{
1751
                    idct_add = s->dsp.add_pixels4;
1752
                    for(i=16; i<16+8; i++){
1753
                        if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h, h->mb, i*16))
1754
                            idct_add   (dest[(i&4)>>2] + block_offset[i], h->mb + i*16*h->pixel_size, uvlinesize);
1755
                    }
1756
                }
1757
            }else{
1758
                if(is_h264){
1759
                    if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
1760
                        h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16*h->pixel_size       , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
1761
                    if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
1762
                        h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16*16+4*16)*h->pixel_size, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
1763
                    h->h264dsp.h264_idct_add8(dest, block_offset,
1764
                                              h->mb, uvlinesize,
1765
                                              h->non_zero_count_cache);
1766
                }
1767
#if CONFIG_SVQ3_DECODER
1768
                else{
1769
                    h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16     , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
1770
                    h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16+4*16, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
1771
                    for(i=16; i<16+8; i++){
1772
                        if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
1773
                            uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
1774
                            ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[s->qscale + 12] - 12, 2);
1775
                        }
1776
                    }
1777
                }
1778
#endif
1779
            }
1780
        }
1781
    }
1782
    if(h->cbp || IS_INTRA(mb_type))
1783
        s->dsp.clear_blocks(h->mb);
1784
}
1785

    
1786
/**
1787
 * Process a macroblock; this case avoids checks for expensive uncommon cases.
1788
 */
1789
static void hl_decode_mb_simple(H264Context *h){
1790
    hl_decode_mb_internal(h, 1);
1791
}
1792

    
1793
/**
1794
 * Process a macroblock; this handles edge cases, such as interlacing.
1795
 */
1796
static void av_noinline hl_decode_mb_complex(H264Context *h){
1797
    hl_decode_mb_internal(h, 0);
1798
}
1799

    
1800
void ff_h264_hl_decode_mb(H264Context *h){
1801
    MpegEncContext * const s = &h->s;
1802
    const int mb_xy= h->mb_xy;
1803
    const int mb_type= s->current_picture.mb_type[mb_xy];
1804
    int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
1805

    
1806
    if (is_complex)
1807
        hl_decode_mb_complex(h);
1808
    else hl_decode_mb_simple(h);
1809
}
1810

    
1811
static int pred_weight_table(H264Context *h){
1812
    MpegEncContext * const s = &h->s;
1813
    int list, i;
1814
    int luma_def, chroma_def;
1815

    
1816
    h->use_weight= 0;
1817
    h->use_weight_chroma= 0;
1818
    h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
1819
    if(CHROMA)
1820
        h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
1821
    luma_def = 1<<h->luma_log2_weight_denom;
1822
    chroma_def = 1<<h->chroma_log2_weight_denom;
1823

    
1824
    for(list=0; list<2; list++){
1825
        h->luma_weight_flag[list]   = 0;
1826
        h->chroma_weight_flag[list] = 0;
1827
        for(i=0; i<h->ref_count[list]; i++){
1828
            int luma_weight_flag, chroma_weight_flag;
1829

    
1830
            luma_weight_flag= get_bits1(&s->gb);
1831
            if(luma_weight_flag){
1832
                h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
1833
                h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
1834
                if(   h->luma_weight[i][list][0] != luma_def
1835
                   || h->luma_weight[i][list][1] != 0) {
1836
                    h->use_weight= 1;
1837
                    h->luma_weight_flag[list]= 1;
1838
                }
1839
            }else{
1840
                h->luma_weight[i][list][0]= luma_def;
1841
                h->luma_weight[i][list][1]= 0;
1842
            }
1843

    
1844
            if(CHROMA){
1845
                chroma_weight_flag= get_bits1(&s->gb);
1846
                if(chroma_weight_flag){
1847
                    int j;
1848
                    for(j=0; j<2; j++){
1849
                        h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
1850
                        h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
1851
                        if(   h->chroma_weight[i][list][j][0] != chroma_def
1852
                           || h->chroma_weight[i][list][j][1] != 0) {
1853
                            h->use_weight_chroma= 1;
1854
                            h->chroma_weight_flag[list]= 1;
1855
                        }
1856
                    }
1857
                }else{
1858
                    int j;
1859
                    for(j=0; j<2; j++){
1860
                        h->chroma_weight[i][list][j][0]= chroma_def;
1861
                        h->chroma_weight[i][list][j][1]= 0;
1862
                    }
1863
                }
1864
            }
1865
        }
1866
        if(h->slice_type_nos != FF_B_TYPE) break;
1867
    }
1868
    h->use_weight= h->use_weight || h->use_weight_chroma;
1869
    return 0;
1870
}
1871

    
1872
/**
1873
 * Initialize implicit_weight table.
1874
 * @param field  0/1 initialize the weight for interlaced MBAFF
1875
 *                -1 initializes the rest
1876
 */
1877
static void implicit_weight_table(H264Context *h, int field){
1878
    MpegEncContext * const s = &h->s;
1879
    int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
1880

    
1881
    for (i = 0; i < 2; i++) {
1882
        h->luma_weight_flag[i]   = 0;
1883
        h->chroma_weight_flag[i] = 0;
1884
    }
1885

    
1886
    if(field < 0){
1887
        cur_poc = s->current_picture_ptr->poc;
1888
    if(   h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
1889
       && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
1890
        h->use_weight= 0;
1891
        h->use_weight_chroma= 0;
1892
        return;
1893
    }
1894
        ref_start= 0;
1895
        ref_count0= h->ref_count[0];
1896
        ref_count1= h->ref_count[1];
1897
    }else{
1898
        cur_poc = s->current_picture_ptr->field_poc[field];
1899
        ref_start= 16;
1900
        ref_count0= 16+2*h->ref_count[0];
1901
        ref_count1= 16+2*h->ref_count[1];
1902
    }
1903

    
1904
    h->use_weight= 2;
1905
    h->use_weight_chroma= 2;
1906
    h->luma_log2_weight_denom= 5;
1907
    h->chroma_log2_weight_denom= 5;
1908

    
1909
    for(ref0=ref_start; ref0 < ref_count0; ref0++){
1910
        int poc0 = h->ref_list[0][ref0].poc;
1911
        for(ref1=ref_start; ref1 < ref_count1; ref1++){
1912
            int poc1 = h->ref_list[1][ref1].poc;
1913
            int td = av_clip(poc1 - poc0, -128, 127);
1914
            int w= 32;
1915
            if(td){
1916
                int tb = av_clip(cur_poc - poc0, -128, 127);
1917
                int tx = (16384 + (FFABS(td) >> 1)) / td;
1918
                int dist_scale_factor = (tb*tx + 32) >> 8;
1919
                if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
1920
                    w = 64 - dist_scale_factor;
1921
            }
1922
            if(field<0){
1923
                h->implicit_weight[ref0][ref1][0]=
1924
                h->implicit_weight[ref0][ref1][1]= w;
1925
            }else{
1926
                h->implicit_weight[ref0][ref1][field]=w;
1927
            }
1928
        }
1929
    }
1930
}
1931

    
1932
/**
1933
 * instantaneous decoder refresh.
1934
 */
1935
static void idr(H264Context *h){
1936
    ff_h264_remove_all_refs(h);
1937
    h->prev_frame_num= 0;
1938
    h->prev_frame_num_offset= 0;
1939
    h->prev_poc_msb=
1940
    h->prev_poc_lsb= 0;
1941
}
1942

    
1943
/* forget old pics after a seek */
1944
static void flush_dpb(AVCodecContext *avctx){
1945
    H264Context *h= avctx->priv_data;
1946
    int i;
1947
    for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
1948
        if(h->delayed_pic[i])
1949
            h->delayed_pic[i]->reference= 0;
1950
        h->delayed_pic[i]= NULL;
1951
    }
1952
    h->outputed_poc=h->next_outputed_poc= INT_MIN;
1953
    h->prev_interlaced_frame = 1;
1954
    idr(h);
1955
    if(h->s.current_picture_ptr)
1956
        h->s.current_picture_ptr->reference= 0;
1957
    h->s.first_field= 0;
1958
    ff_h264_reset_sei(h);
1959
    ff_mpeg_flush(avctx);
1960
}
1961

    
1962
static int init_poc(H264Context *h){
1963
    MpegEncContext * const s = &h->s;
1964
    const int max_frame_num= 1<<h->sps.log2_max_frame_num;
1965
    int field_poc[2];
1966
    Picture *cur = s->current_picture_ptr;
1967

    
1968
    h->frame_num_offset= h->prev_frame_num_offset;
1969
    if(h->frame_num < h->prev_frame_num)
1970
        h->frame_num_offset += max_frame_num;
1971

    
1972
    if(h->sps.poc_type==0){
1973
        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
1974

    
1975
        if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
1976
            h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1977
        else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
1978
            h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1979
        else
1980
            h->poc_msb = h->prev_poc_msb;
1981
//printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
1982
        field_poc[0] =
1983
        field_poc[1] = h->poc_msb + h->poc_lsb;
1984
        if(s->picture_structure == PICT_FRAME)
1985
            field_poc[1] += h->delta_poc_bottom;
1986
    }else if(h->sps.poc_type==1){
1987
        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1988
        int i;
1989

    
1990
        if(h->sps.poc_cycle_length != 0)
1991
            abs_frame_num = h->frame_num_offset + h->frame_num;
1992
        else
1993
            abs_frame_num = 0;
1994

    
1995
        if(h->nal_ref_idc==0 && abs_frame_num > 0)
1996
            abs_frame_num--;
1997

    
1998
        expected_delta_per_poc_cycle = 0;
1999
        for(i=0; i < h->sps.poc_cycle_length; i++)
2000
            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
2001

    
2002
        if(abs_frame_num > 0){
2003
            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2004
            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2005

    
2006
            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2007
            for(i = 0; i <= frame_num_in_poc_cycle; i++)
2008
                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
2009
        } else
2010
            expectedpoc = 0;
2011

    
2012
        if(h->nal_ref_idc == 0)
2013
            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2014

    
2015
        field_poc[0] = expectedpoc + h->delta_poc[0];
2016
        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2017

    
2018
        if(s->picture_structure == PICT_FRAME)
2019
            field_poc[1] += h->delta_poc[1];
2020
    }else{
2021
        int poc= 2*(h->frame_num_offset + h->frame_num);
2022

    
2023
        if(!h->nal_ref_idc)
2024
            poc--;
2025

    
2026
        field_poc[0]= poc;
2027
        field_poc[1]= poc;
2028
    }
2029

    
2030
    if(s->picture_structure != PICT_BOTTOM_FIELD)
2031
        s->current_picture_ptr->field_poc[0]= field_poc[0];
2032
    if(s->picture_structure != PICT_TOP_FIELD)
2033
        s->current_picture_ptr->field_poc[1]= field_poc[1];
2034
    cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
2035

    
2036
    return 0;
2037
}
2038

    
2039

    
2040
/**
2041
 * initialize scan tables
2042
 */
2043
static void init_scan_tables(H264Context *h){
2044
    int i;
2045
    for(i=0; i<16; i++){
2046
#define T(x) (x>>2) | ((x<<2) & 0xF)
2047
        h->zigzag_scan[i] = T(zigzag_scan[i]);
2048
        h-> field_scan[i] = T( field_scan[i]);
2049
#undef T
2050
    }
2051
    for(i=0; i<64; i++){
2052
#define T(x) (x>>3) | ((x&7)<<3)
2053
        h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
2054
        h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2055
        h->field_scan8x8[i]        = T(field_scan8x8[i]);
2056
        h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
2057
#undef T
2058
    }
2059
    if(h->sps.transform_bypass){ //FIXME same ugly
2060
        h->zigzag_scan_q0          = zigzag_scan;
2061
        h->zigzag_scan8x8_q0       = ff_zigzag_direct;
2062
        h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2063
        h->field_scan_q0           = field_scan;
2064
        h->field_scan8x8_q0        = field_scan8x8;
2065
        h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
2066
    }else{
2067
        h->zigzag_scan_q0          = h->zigzag_scan;
2068
        h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
2069
        h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2070
        h->field_scan_q0           = h->field_scan;
2071
        h->field_scan8x8_q0        = h->field_scan8x8;
2072
        h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
2073
    }
2074
}
2075

    
2076
static void field_end(H264Context *h, int in_setup){
2077
    MpegEncContext * const s = &h->s;
2078
    AVCodecContext * const avctx= s->avctx;
2079
    s->mb_y= 0;
2080

    
2081
    if (!in_setup && !s->dropable)
2082
        ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
2083
                                 s->picture_structure==PICT_BOTTOM_FIELD);
2084

    
2085
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2086
        ff_vdpau_h264_set_reference_frames(s);
2087

    
2088
    if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
2089
        if(!s->dropable) {
2090
            ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2091
            h->prev_poc_msb= h->poc_msb;
2092
            h->prev_poc_lsb= h->poc_lsb;
2093
        }
2094
        h->prev_frame_num_offset= h->frame_num_offset;
2095
        h->prev_frame_num= h->frame_num;
2096
        h->outputed_poc = h->next_outputed_poc;
2097
    }
2098

    
2099
    if (avctx->hwaccel) {
2100
        if (avctx->hwaccel->end_frame(avctx) < 0)
2101
            av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
2102
    }
2103

    
2104
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2105
        ff_vdpau_h264_picture_complete(s);
2106

    
2107
    /*
2108
     * FIXME: Error handling code does not seem to support interlaced
2109
     * when slices span multiple rows
2110
     * The ff_er_add_slice calls don't work right for bottom
2111
     * fields; they cause massive erroneous error concealing
2112
     * Error marking covers both fields (top and bottom).
2113
     * This causes a mismatched s->error_count
2114
     * and a bad error table. Further, the error count goes to
2115
     * INT_MAX when called for bottom field, because mb_y is
2116
     * past end by one (callers fault) and resync_mb_y != 0
2117
     * causes problems for the first MB line, too.
2118
     */
2119
    if (!FIELD_PICTURE)
2120
        ff_er_frame_end(s);
2121

    
2122
    MPV_frame_end(s);
2123

    
2124
    h->current_slice=0;
2125
}
2126

    
2127
/**
2128
 * Replicate H264 "master" context to thread contexts.
2129
 */
2130
static void clone_slice(H264Context *dst, H264Context *src)
2131
{
2132
    memcpy(dst->block_offset,     src->block_offset, sizeof(dst->block_offset));
2133
    dst->s.current_picture_ptr  = src->s.current_picture_ptr;
2134
    dst->s.current_picture      = src->s.current_picture;
2135
    dst->s.linesize             = src->s.linesize;
2136
    dst->s.uvlinesize           = src->s.uvlinesize;
2137
    dst->s.first_field          = src->s.first_field;
2138

    
2139
    dst->prev_poc_msb           = src->prev_poc_msb;
2140
    dst->prev_poc_lsb           = src->prev_poc_lsb;
2141
    dst->prev_frame_num_offset  = src->prev_frame_num_offset;
2142
    dst->prev_frame_num         = src->prev_frame_num;
2143
    dst->short_ref_count        = src->short_ref_count;
2144

    
2145
    memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
2146
    memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
2147
    memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2148
    memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
2149

    
2150
    memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
2151
    memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
2152
}
2153

    
2154
/**
2155
 * computes profile from profile_idc and constraint_set?_flags
2156
 *
2157
 * @param sps SPS
2158
 *
2159
 * @return profile as defined by FF_PROFILE_H264_*
2160
 */
2161
int ff_h264_get_profile(SPS *sps)
2162
{
2163
    int profile = sps->profile_idc;
2164

    
2165
    switch(sps->profile_idc) {
2166
    case FF_PROFILE_H264_BASELINE:
2167
        // constraint_set1_flag set to 1
2168
        profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2169
        break;
2170
    case FF_PROFILE_H264_HIGH_10:
2171
    case FF_PROFILE_H264_HIGH_422:
2172
    case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2173
        // constraint_set3_flag set to 1
2174
        profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
2175
        break;
2176
    }
2177

    
2178
    return profile;
2179
}
2180

    
2181
/**
2182
 * decodes a slice header.
2183
 * This will also call MPV_common_init() and frame_start() as needed.
2184
 *
2185
 * @param h h264context
2186
 * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
2187
 *
2188
 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2189
 */
2190
static int decode_slice_header(H264Context *h, H264Context *h0){
2191
    MpegEncContext * const s = &h->s;
2192
    MpegEncContext * const s0 = &h0->s;
2193
    unsigned int first_mb_in_slice;
2194
    unsigned int pps_id;
2195
    int num_ref_idx_active_override_flag;
2196
    unsigned int slice_type, tmp, i, j;
2197
    int default_ref_list_done = 0;
2198
    int last_pic_structure;
2199

    
2200
    s->dropable= h->nal_ref_idc == 0;
2201

    
2202
    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
2203
        s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
2204
        s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
2205
    }else{
2206
        s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
2207
        s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
2208
    }
2209

    
2210
    first_mb_in_slice= get_ue_golomb(&s->gb);
2211

    
2212
    if(first_mb_in_slice == 0){ //FIXME better field boundary detection
2213
        if(h0->current_slice && FIELD_PICTURE){
2214
            field_end(h, 1);
2215
        }
2216

    
2217
        h0->current_slice = 0;
2218
        if (!s0->first_field)
2219
            s->current_picture_ptr= NULL;
2220
    }
2221

    
2222
    slice_type= get_ue_golomb_31(&s->gb);
2223
    if(slice_type > 9){
2224
        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);
2225
        return -1;
2226
    }
2227
    if(slice_type > 4){
2228
        slice_type -= 5;
2229
        h->slice_type_fixed=1;
2230
    }else
2231
        h->slice_type_fixed=0;
2232

    
2233
    slice_type= golomb_to_pict_type[ slice_type ];
2234
    if (slice_type == FF_I_TYPE
2235
        || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
2236
        default_ref_list_done = 1;
2237
    }
2238
    h->slice_type= slice_type;
2239
    h->slice_type_nos= slice_type & 3;
2240

    
2241
    s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
2242

    
2243
    pps_id= get_ue_golomb(&s->gb);
2244
    if(pps_id>=MAX_PPS_COUNT){
2245
        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2246
        return -1;
2247
    }
2248
    if(!h0->pps_buffers[pps_id]) {
2249
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
2250
        return -1;
2251
    }
2252
    h->pps= *h0->pps_buffers[pps_id];
2253

    
2254
    if(!h0->sps_buffers[h->pps.sps_id]) {
2255
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
2256
        return -1;
2257
    }
2258
    h->sps = *h0->sps_buffers[h->pps.sps_id];
2259

    
2260
    s->avctx->profile = ff_h264_get_profile(&h->sps);
2261
    s->avctx->level   = h->sps.level_idc;
2262
    s->avctx->refs    = h->sps.ref_frame_count;
2263

    
2264
    if(h == h0 && h->dequant_coeff_pps != pps_id){
2265
        h->dequant_coeff_pps = pps_id;
2266
        init_dequant_tables(h);
2267
    }
2268

    
2269
    s->mb_width= h->sps.mb_width;
2270
    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2271

    
2272
    h->b_stride=  s->mb_width*4;
2273

    
2274
    s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
2275
    if(h->sps.frame_mbs_only_flag)
2276
        s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
2277
    else
2278
        s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 7);
2279

    
2280
    if (s->context_initialized
2281
        && (   s->width != s->avctx->width || s->height != s->avctx->height
2282
            || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2283
        if(h != h0) {
2284
            av_log_missing_feature(s->avctx, "Width/height changing with threads is", 0);
2285
            return -1;   // width / height changed during parallelized decoding
2286
        }
2287
        free_tables(h, 0);
2288
        flush_dpb(s->avctx);
2289
        MPV_common_end(s);
2290
    }
2291
    if (!s->context_initialized) {
2292
        if(h != h0){
2293
            av_log(h->s.avctx, AV_LOG_ERROR, "we cant (re-)initialize context during parallel decoding\n");
2294
            return -1;
2295
        }
2296

    
2297
        avcodec_set_dimensions(s->avctx, s->width, s->height);
2298
        s->avctx->sample_aspect_ratio= h->sps.sar;
2299
        av_assert0(s->avctx->sample_aspect_ratio.den);
2300

    
2301
        if(h->sps.video_signal_type_present_flag){
2302
            s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2303
            if(h->sps.colour_description_present_flag){
2304
                s->avctx->color_primaries = h->sps.color_primaries;
2305
                s->avctx->color_trc       = h->sps.color_trc;
2306
                s->avctx->colorspace      = h->sps.colorspace;
2307
            }
2308
        }
2309

    
2310
        if(h->sps.timing_info_present_flag){
2311
            int64_t den= h->sps.time_scale;
2312
            if(h->x264_build < 44U)
2313
                den *= 2;
2314
            av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2315
                      h->sps.num_units_in_tick, den, 1<<30);
2316
        }
2317
        s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2318
                                                 s->avctx->codec->pix_fmts ?
2319
                                                 s->avctx->codec->pix_fmts :
2320
                                                 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2321
                                                 hwaccel_pixfmt_list_h264_jpeg_420 :
2322
                                                 ff_hwaccel_pixfmt_list_420);
2323
        s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2324

    
2325
        if (MPV_common_init(s) < 0){
2326
            av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed\n");
2327
            return -1;
2328
        }
2329
        s->first_field = 0;
2330
        h->prev_interlaced_frame = 1;
2331

    
2332
        init_scan_tables(h);
2333
        ff_h264_alloc_tables(h);
2334

    
2335
        if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
2336
            if (context_init(h) < 0){
2337
                av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
2338
                return -1;
2339
            }
2340
        } else {
2341
            for(i = 1; i < s->avctx->thread_count; i++) {
2342
                H264Context *c;
2343
                c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2344
                memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2345
                memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2346
                c->h264dsp = h->h264dsp;
2347
                c->sps = h->sps;
2348
                c->pps = h->pps;
2349
                init_scan_tables(c);
2350
                clone_tables(c, h, i);
2351
            }
2352

    
2353
            for(i = 0; i < s->avctx->thread_count; i++)
2354
                if(context_init(h->thread_context[i]) < 0){
2355
                    av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
2356
                    return -1;
2357
                }
2358
        }
2359
    }
2360

    
2361
    h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
2362

    
2363
    h->mb_mbaff = 0;
2364
    h->mb_aff_frame = 0;
2365
    last_pic_structure = s0->picture_structure;
2366
    if(h->sps.frame_mbs_only_flag){
2367
        s->picture_structure= PICT_FRAME;
2368
    }else{
2369
        if(get_bits1(&s->gb)) { //field_pic_flag
2370
            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
2371
        } else {
2372
            s->picture_structure= PICT_FRAME;
2373
            h->mb_aff_frame = h->sps.mb_aff;
2374
        }
2375
    }
2376
    h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
2377

    
2378
    if(h0->current_slice == 0){
2379
        if(h->frame_num != h->prev_frame_num &&
2380
          (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num) < (h->frame_num - h->sps.ref_frame_count))
2381
            h->prev_frame_num = h->frame_num - h->sps.ref_frame_count - 1;
2382

    
2383
        while(h->frame_num !=  h->prev_frame_num &&
2384
              h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
2385
            Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2386
            av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
2387
            if (ff_h264_frame_start(h) < 0)
2388
                return -1;
2389
            h->prev_frame_num++;
2390
            h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
2391
            s->current_picture_ptr->frame_num= h->prev_frame_num;
2392
            ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
2393
            ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
2394
            ff_generate_sliding_window_mmcos(h);
2395
            ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2396
            /* Error concealment: if a ref is missing, copy the previous ref in its place.
2397
             * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2398
             * about there being no actual duplicates.
2399
             * FIXME: this doesn't copy padding for out-of-frame motion vectors.  Given we're
2400
             * concealing a lost frame, this probably isn't noticable by comparison, but it should
2401
             * be fixed. */
2402
            if (h->short_ref_count) {
2403
                if (prev) {
2404
                    av_image_copy(h->short_ref[0]->data, h->short_ref[0]->linesize,
2405
                                  (const uint8_t**)prev->data, prev->linesize,
2406
                                  s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
2407
                    h->short_ref[0]->poc = prev->poc+2;
2408
                }
2409
                h->short_ref[0]->frame_num = h->prev_frame_num;
2410
            }
2411
        }
2412

    
2413
        /* See if we have a decoded first field looking for a pair... */
2414
        if (s0->first_field) {
2415
            assert(s0->current_picture_ptr);
2416
            assert(s0->current_picture_ptr->data[0]);
2417
            assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
2418

    
2419
            /* figure out if we have a complementary field pair */
2420
            if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2421
                /*
2422
                 * Previous field is unmatched. Don't display it, but let it
2423
                 * remain for reference if marked as such.
2424
                 */
2425
                s0->current_picture_ptr = NULL;
2426
                s0->first_field = FIELD_PICTURE;
2427

    
2428
            } else {
2429
                if (h->nal_ref_idc &&
2430
                        s0->current_picture_ptr->reference &&
2431
                        s0->current_picture_ptr->frame_num != h->frame_num) {
2432
                    /*
2433
                     * This and previous field were reference, but had
2434
                     * different frame_nums. Consider this field first in
2435
                     * pair. Throw away previous field except for reference
2436
                     * purposes.
2437
                     */
2438
                    s0->first_field = 1;
2439
                    s0->current_picture_ptr = NULL;
2440

    
2441
                } else {
2442
                    /* Second field in complementary pair */
2443
                    s0->first_field = 0;
2444
                }
2445
            }
2446

    
2447
        } else {
2448
            /* Frame or first field in a potentially complementary pair */
2449
            assert(!s0->current_picture_ptr);
2450
            s0->first_field = FIELD_PICTURE;
2451
        }
2452

    
2453
        if((!FIELD_PICTURE || s0->first_field) && ff_h264_frame_start(h) < 0) {
2454
            s0->first_field = 0;
2455
            return -1;
2456
        }
2457
    }
2458
    if(h != h0)
2459
        clone_slice(h, h0);
2460

    
2461
    s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2462

    
2463
    assert(s->mb_num == s->mb_width * s->mb_height);
2464
    if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2465
       first_mb_in_slice                    >= s->mb_num){
2466
        av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2467
        return -1;
2468
    }
2469
    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2470
    s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2471
    if (s->picture_structure == PICT_BOTTOM_FIELD)
2472
        s->resync_mb_y = s->mb_y = s->mb_y + 1;
2473
    assert(s->mb_y < s->mb_height);
2474

    
2475
    if(s->picture_structure==PICT_FRAME){
2476
        h->curr_pic_num=   h->frame_num;
2477
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
2478
    }else{
2479
        h->curr_pic_num= 2*h->frame_num + 1;
2480
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
2481
    }
2482

    
2483
    if(h->nal_unit_type == NAL_IDR_SLICE){
2484
        get_ue_golomb(&s->gb); /* idr_pic_id */
2485
    }
2486

    
2487
    if(h->sps.poc_type==0){
2488
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2489

    
2490
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
2491
            h->delta_poc_bottom= get_se_golomb(&s->gb);
2492
        }
2493
    }
2494

    
2495
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
2496
        h->delta_poc[0]= get_se_golomb(&s->gb);
2497

    
2498
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
2499
            h->delta_poc[1]= get_se_golomb(&s->gb);
2500
    }
2501

    
2502
    init_poc(h);
2503

    
2504
    if(h->pps.redundant_pic_cnt_present){
2505
        h->redundant_pic_count= get_ue_golomb(&s->gb);
2506
    }
2507

    
2508
    //set defaults, might be overridden a few lines later
2509
    h->ref_count[0]= h->pps.ref_count[0];
2510
    h->ref_count[1]= h->pps.ref_count[1];
2511

    
2512
    if(h->slice_type_nos != FF_I_TYPE){
2513
        if(h->slice_type_nos == FF_B_TYPE){
2514
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
2515
        }
2516
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
2517

    
2518
        if(num_ref_idx_active_override_flag){
2519
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
2520
            if(h->slice_type_nos==FF_B_TYPE)
2521
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
2522

    
2523
            if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
2524
                av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
2525
                h->ref_count[0]= h->ref_count[1]= 1;
2526
                return -1;
2527
            }
2528
        }
2529
        if(h->slice_type_nos == FF_B_TYPE)
2530
            h->list_count= 2;
2531
        else
2532
            h->list_count= 1;
2533
    }else
2534
        h->list_count= 0;
2535

    
2536
    if(!default_ref_list_done){
2537
        ff_h264_fill_default_ref_list(h);
2538
    }
2539

    
2540
    if(h->slice_type_nos!=FF_I_TYPE && ff_h264_decode_ref_pic_list_reordering(h) < 0)
2541
        return -1;
2542

    
2543
    if(h->slice_type_nos!=FF_I_TYPE){
2544
        s->last_picture_ptr= &h->ref_list[0][0];
2545
        ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2546
    }
2547
    if(h->slice_type_nos==FF_B_TYPE){
2548
        s->next_picture_ptr= &h->ref_list[1][0];
2549
        ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2550
    }
2551

    
2552
    if(   (h->pps.weighted_pred          && h->slice_type_nos == FF_P_TYPE )
2553
       ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
2554
        pred_weight_table(h);
2555
    else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2556
        implicit_weight_table(h, -1);
2557
    }else {
2558
        h->use_weight = 0;
2559
        for (i = 0; i < 2; i++) {
2560
            h->luma_weight_flag[i]   = 0;
2561
            h->chroma_weight_flag[i] = 0;
2562
        }
2563
    }
2564

    
2565
    if(h->nal_ref_idc)
2566
        ff_h264_decode_ref_pic_marking(h0, &s->gb);
2567

    
2568
    if(FRAME_MBAFF){
2569
        ff_h264_fill_mbaff_ref_list(h);
2570

    
2571
        if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2572
            implicit_weight_table(h, 0);
2573
            implicit_weight_table(h, 1);
2574
        }
2575
    }
2576

    
2577
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2578
        ff_h264_direct_dist_scale_factor(h);
2579
    ff_h264_direct_ref_list_init(h);
2580

    
2581
    if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
2582
        tmp = get_ue_golomb_31(&s->gb);
2583
        if(tmp > 2){
2584
            av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2585
            return -1;
2586
        }
2587
        h->cabac_init_idc= tmp;
2588
    }
2589

    
2590
    h->last_qscale_diff = 0;
2591
    tmp = h->pps.init_qp + get_se_golomb(&s->gb);
2592
    if(tmp>51){
2593
        av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
2594
        return -1;
2595
    }
2596
    s->qscale= tmp;
2597
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2598
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2599
    //FIXME qscale / qp ... stuff
2600
    if(h->slice_type == FF_SP_TYPE){
2601
        get_bits1(&s->gb); /* sp_for_switch_flag */
2602
    }
2603
    if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
2604
        get_se_golomb(&s->gb); /* slice_qs_delta */
2605
    }
2606

    
2607
    h->deblocking_filter = 1;
2608
    h->slice_alpha_c0_offset = 52;
2609
    h->slice_beta_offset = 52;
2610
    if( h->pps.deblocking_filter_parameters_present ) {
2611
        tmp= get_ue_golomb_31(&s->gb);
2612
        if(tmp > 2){
2613
            av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
2614
            return -1;
2615
        }
2616
        h->deblocking_filter= tmp;
2617
        if(h->deblocking_filter < 2)
2618
            h->deblocking_filter^= 1; // 1<->0
2619

    
2620
        if( h->deblocking_filter ) {
2621
            h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
2622
            h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
2623
            if(   h->slice_alpha_c0_offset > 104U
2624
               || h->slice_beta_offset     > 104U){
2625
                av_log(s->avctx, AV_LOG_ERROR, "deblocking filter parameters %d %d out of range\n", h->slice_alpha_c0_offset, h->slice_beta_offset);
2626
                return -1;
2627
            }
2628
        }
2629
    }
2630

    
2631
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
2632
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
2633
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
2634
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
2635
        h->deblocking_filter= 0;
2636

    
2637
    if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
2638
        if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
2639
            /* Cheat slightly for speed:
2640
               Do not bother to deblock across slices. */
2641
            h->deblocking_filter = 2;
2642
        } else {
2643
            h0->max_contexts = 1;
2644
            if(!h0->single_decode_warning) {
2645
                av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
2646
                h0->single_decode_warning = 1;
2647
            }
2648
            if(h != h0){
2649
                av_log(h->s.avctx, AV_LOG_ERROR, "deblocking switched inside frame\n");
2650
                return 1;
2651
            }
2652
        }
2653
    }
2654
    h->qp_thresh= 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]);
2655

    
2656
#if 0 //FMO
2657
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
2658
        slice_group_change_cycle= get_bits(&s->gb, ?);
2659
#endif
2660

    
2661
    h0->last_slice_type = slice_type;
2662
    h->slice_num = ++h0->current_slice;
2663
    if(h->slice_num >= MAX_SLICES){
2664
        av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
2665
    }
2666

    
2667
    for(j=0; j<2; j++){
2668
        int id_list[16];
2669
        int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
2670
        for(i=0; i<16; i++){
2671
            id_list[i]= 60;
2672
            if(h->ref_list[j][i].data[0]){
2673
                int k;
2674
                uint8_t *base= h->ref_list[j][i].base[0];
2675
                for(k=0; k<h->short_ref_count; k++)
2676
                    if(h->short_ref[k]->base[0] == base){
2677
                        id_list[i]= k;
2678
                        break;
2679
                    }
2680
                for(k=0; k<h->long_ref_count; k++)
2681
                    if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
2682
                        id_list[i]= h->short_ref_count + k;
2683
                        break;
2684
                    }
2685
            }
2686
        }
2687

    
2688
        ref2frm[0]=
2689
        ref2frm[1]= -1;
2690
        for(i=0; i<16; i++)
2691
            ref2frm[i+2]= 4*id_list[i]
2692
                          +(h->ref_list[j][i].reference&3);
2693
        ref2frm[18+0]=
2694
        ref2frm[18+1]= -1;
2695
        for(i=16; i<48; i++)
2696
            ref2frm[i+4]= 4*id_list[(i-16)>>1]
2697
                          +(h->ref_list[j][i].reference&3);
2698
    }
2699

    
2700
    //FIXME: fix draw_edges+PAFF+frame threads
2701
    h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE || (!h->sps.frame_mbs_only_flag && s->avctx->active_thread_type&FF_THREAD_FRAME)) ? 0 : 16;
2702
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
2703

    
2704
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2705
        av_log(h->s.avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
2706
               h->slice_num,
2707
               (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
2708
               first_mb_in_slice,
2709
               av_get_pict_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
2710
               pps_id, h->frame_num,
2711
               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
2712
               h->ref_count[0], h->ref_count[1],
2713
               s->qscale,
2714
               h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
2715
               h->use_weight,
2716
               h->use_weight==1 && h->use_weight_chroma ? "c" : "",
2717
               h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
2718
               );
2719
    }
2720

    
2721
    return 0;
2722
}
2723

    
2724
int ff_h264_get_slice_type(const H264Context *h)
2725
{
2726
    switch (h->slice_type) {
2727
    case FF_P_TYPE:  return 0;
2728
    case FF_B_TYPE:  return 1;
2729
    case FF_I_TYPE:  return 2;
2730
    case FF_SP_TYPE: return 3;
2731
    case FF_SI_TYPE: return 4;
2732
    default:         return -1;
2733
    }
2734
}
2735

    
2736
/**
2737
 *
2738
 * @return non zero if the loop filter can be skiped
2739
 */
2740
static int fill_filter_caches(H264Context *h, int mb_type){
2741
    MpegEncContext * const s = &h->s;
2742
    const int mb_xy= h->mb_xy;
2743
    int top_xy, left_xy[2];
2744
    int top_type, left_type[2];
2745

    
2746
    top_xy     = mb_xy  - (s->mb_stride << MB_FIELD);
2747

    
2748
    //FIXME deblocking could skip the intra and nnz parts.
2749

    
2750
    /* Wow, what a mess, why didn't they simplify the interlacing & intra
2751
     * stuff, I can't imagine that these complex rules are worth it. */
2752

    
2753
    left_xy[1] = left_xy[0] = mb_xy-1;
2754
    if(FRAME_MBAFF){
2755
        const int left_mb_field_flag     = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);
2756
        const int curr_mb_field_flag     = IS_INTERLACED(mb_type);
2757
        if(s->mb_y&1){
2758
            if (left_mb_field_flag != curr_mb_field_flag) {
2759
                left_xy[0] -= s->mb_stride;
2760
            }
2761
        }else{
2762
            if(curr_mb_field_flag){
2763
                top_xy      += s->mb_stride & (((s->current_picture.mb_type[top_xy    ]>>7)&1)-1);
2764
            }
2765
            if (left_mb_field_flag != curr_mb_field_flag) {
2766
                left_xy[1] += s->mb_stride;
2767
            }
2768
        }
2769
    }
2770

    
2771
    h->top_mb_xy = top_xy;
2772
    h->left_mb_xy[0] = left_xy[0];
2773
    h->left_mb_xy[1] = left_xy[1];
2774
    {
2775
        //for sufficiently low qp, filtering wouldn't do anything
2776
        //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
2777
        int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
2778
        int qp = s->current_picture.qscale_table[mb_xy];
2779
        if(qp <= qp_thresh
2780
           && (left_xy[0]<0 || ((qp + s->current_picture.qscale_table[left_xy[0]] + 1)>>1) <= qp_thresh)
2781
           && (top_xy   < 0 || ((qp + s->current_picture.qscale_table[top_xy    ] + 1)>>1) <= qp_thresh)){
2782
            if(!FRAME_MBAFF)
2783
                return 1;
2784
            if(   (left_xy[0]< 0            || ((qp + s->current_picture.qscale_table[left_xy[1]             ] + 1)>>1) <= qp_thresh)
2785
               && (top_xy    < s->mb_stride || ((qp + s->current_picture.qscale_table[top_xy    -s->mb_stride] + 1)>>1) <= qp_thresh))
2786
                return 1;
2787
        }
2788
    }
2789

    
2790
    top_type     = s->current_picture.mb_type[top_xy]    ;
2791
    left_type[0] = s->current_picture.mb_type[left_xy[0]];
2792
    left_type[1] = s->current_picture.mb_type[left_xy[1]];
2793
    if(h->deblocking_filter == 2){
2794
        if(h->slice_table[top_xy     ] != h->slice_num) top_type= 0;
2795
        if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
2796
    }else{
2797
        if(h->slice_table[top_xy     ] == 0xFFFF) top_type= 0;
2798
        if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
2799
    }
2800
    h->top_type    = top_type    ;
2801
    h->left_type[0]= left_type[0];
2802
    h->left_type[1]= left_type[1];
2803

    
2804
    if(IS_INTRA(mb_type))
2805
        return 0;
2806

    
2807
    AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
2808
    AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
2809
    AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
2810
    AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
2811
    AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
2812

    
2813
    h->cbp= h->cbp_table[mb_xy];
2814

    
2815
    {
2816
        int list;
2817
        for(list=0; list<h->list_count; list++){
2818
            int8_t *ref;
2819
            int y, b_stride;
2820
            int16_t (*mv_dst)[2];
2821
            int16_t (*mv_src)[2];
2822

    
2823
            if(!USES_LIST(mb_type, list)){
2824
                fill_rectangle(  h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
2825
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2826
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2827
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2828
                AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2829
                continue;
2830
            }
2831

    
2832
            ref = &s->current_picture.ref_index[list][4*mb_xy];
2833
            {
2834
                int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2835
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2836
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2837
                ref += 2;
2838
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2839
                AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2840
            }
2841

    
2842
            b_stride = h->b_stride;
2843
            mv_dst   = &h->mv_cache[list][scan8[0]];
2844
            mv_src   = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
2845
            for(y=0; y<4; y++){
2846
                AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
2847
            }
2848

    
2849
        }
2850
    }
2851

    
2852

    
2853
/*
2854
0 . T T. T T T T
2855
1 L . .L . . . .
2856
2 L . .L . . . .
2857
3 . T TL . . . .
2858
4 L . .L . . . .
2859
5 L . .. . . . .
2860
*/
2861
//FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
2862
    if(top_type){
2863
        AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][4+3*8]);
2864
    }
2865

    
2866
    if(left_type[0]){
2867
        h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
2868
        h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
2869
        h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
2870
        h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
2871
    }
2872

    
2873
    // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
2874
    if(!CABAC && h->pps.transform_8x8_mode){
2875
        if(IS_8x8DCT(top_type)){
2876
            h->non_zero_count_cache[4+8*0]=
2877
            h->non_zero_count_cache[5+8*0]= h->cbp_table[top_xy] & 4;
2878
            h->non_zero_count_cache[6+8*0]=
2879
            h->non_zero_count_cache[7+8*0]= h->cbp_table[top_xy] & 8;
2880
        }
2881
        if(IS_8x8DCT(left_type[0])){
2882
            h->non_zero_count_cache[3+8*1]=
2883
            h->non_zero_count_cache[3+8*2]= h->cbp_table[left_xy[0]]&2; //FIXME check MBAFF
2884
        }
2885
        if(IS_8x8DCT(left_type[1])){
2886
            h->non_zero_count_cache[3+8*3]=
2887
            h->non_zero_count_cache[3+8*4]= h->cbp_table[left_xy[1]]&8; //FIXME check MBAFF
2888
        }
2889

    
2890
        if(IS_8x8DCT(mb_type)){
2891
            h->non_zero_count_cache[scan8[0   ]]= h->non_zero_count_cache[scan8[1   ]]=
2892
            h->non_zero_count_cache[scan8[2   ]]= h->non_zero_count_cache[scan8[3   ]]= h->cbp & 1;
2893

    
2894
            h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
2895
            h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
2896

    
2897
            h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
2898
            h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp & 4;
2899

    
2900
            h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
2901
            h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
2902
        }
2903
    }
2904

    
2905
    if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
2906
        int list;
2907
        for(list=0; list<h->list_count; list++){
2908
            if(USES_LIST(top_type, list)){
2909
                const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
2910
                const int b8_xy= 4*top_xy + 2;
2911
                int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2912
                AV_COPY128(h->mv_cache[list][scan8[0] + 0 - 1*8], s->current_picture.motion_val[list][b_xy + 0]);
2913
                h->ref_cache[list][scan8[0] + 0 - 1*8]=
2914
                h->ref_cache[list][scan8[0] + 1 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 0]];
2915
                h->ref_cache[list][scan8[0] + 2 - 1*8]=
2916
                h->ref_cache[list][scan8[0] + 3 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 1]];
2917
            }else{
2918
                AV_ZERO128(h->mv_cache[list][scan8[0] + 0 - 1*8]);
2919
                AV_WN32A(&h->ref_cache[list][scan8[0] + 0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2920
            }
2921

    
2922
            if(!IS_INTERLACED(mb_type^left_type[0])){
2923
                if(USES_LIST(left_type[0], list)){
2924
                    const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
2925
                    const int b8_xy= 4*left_xy[0] + 1;
2926
                    int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[0]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2927
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 0 ], s->current_picture.motion_val[list][b_xy + h->b_stride*0]);
2928
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 8 ], s->current_picture.motion_val[list][b_xy + h->b_stride*1]);
2929
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +16 ], s->current_picture.motion_val[list][b_xy + h->b_stride*2]);
2930
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +24 ], s->current_picture.motion_val[list][b_xy + h->b_stride*3]);
2931
                    h->ref_cache[list][scan8[0] - 1 + 0 ]=
2932
                    h->ref_cache[list][scan8[0] - 1 + 8 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*0]];
2933
                    h->ref_cache[list][scan8[0] - 1 +16 ]=
2934
                    h->ref_cache[list][scan8[0] - 1 +24 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*1]];
2935
                }else{
2936
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 0 ]);
2937
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 8 ]);
2938
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +16 ]);
2939
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +24 ]);
2940
                    h->ref_cache[list][scan8[0] - 1 + 0  ]=
2941
                    h->ref_cache[list][scan8[0] - 1 + 8  ]=
2942
                    h->ref_cache[list][scan8[0] - 1 + 16 ]=
2943
                    h->ref_cache[list][scan8[0] - 1 + 24 ]= LIST_NOT_USED;
2944
                }
2945
            }
2946
        }
2947
    }
2948

    
2949
    return 0;
2950
}
2951

    
2952
static void loop_filter(H264Context *h){
2953
    MpegEncContext * const s = &h->s;
2954
    uint8_t  *dest_y, *dest_cb, *dest_cr;
2955
    int linesize, uvlinesize, mb_x, mb_y;
2956
    const int end_mb_y= s->mb_y + FRAME_MBAFF;
2957
    const int old_slice_type= h->slice_type;
2958
    const int end_mb_x  = s->mb_x;
2959

    
2960
    if(h->deblocking_filter) {
2961
        int start_x= s->resync_mb_y == s->mb_y ? s->resync_mb_x : 0;
2962
        for(mb_x= start_x; mb_x<end_mb_x; mb_x++){
2963
            for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
2964
                int mb_xy, mb_type;
2965
                mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
2966
                h->slice_num= h->slice_table[mb_xy];
2967
                mb_type= s->current_picture.mb_type[mb_xy];
2968
                h->list_count= h->list_counts[mb_xy];
2969

    
2970
                if(FRAME_MBAFF)
2971
                    h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2972

    
2973
                s->mb_x= mb_x;
2974
                s->mb_y= mb_y;
2975
                dest_y  = s->current_picture.data[0] + (mb_x*h->pixel_size + mb_y * s->linesize  ) * 16;
2976
                dest_cb = s->current_picture.data[1] + (mb_x*h->pixel_size + mb_y * s->uvlinesize) * 8;
2977
                dest_cr = s->current_picture.data[2] + (mb_x*h->pixel_size + mb_y * s->uvlinesize) * 8;
2978
                    //FIXME simplify above
2979

    
2980
                if (MB_FIELD) {
2981
                    linesize   = h->mb_linesize   = s->linesize * 2;
2982
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2983
                    if(mb_y&1){ //FIXME move out of this function?
2984
                        dest_y -= s->linesize*15;
2985
                        dest_cb-= s->uvlinesize*7;
2986
                        dest_cr-= s->uvlinesize*7;
2987
                    }
2988
                } else {
2989
                    linesize   = h->mb_linesize   = s->linesize;
2990
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize;
2991
                }
2992
                backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
2993
                if(fill_filter_caches(h, mb_type))
2994
                    continue;
2995
                h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2996
                h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2997

    
2998
                if (FRAME_MBAFF) {
2999
                    ff_h264_filter_mb     (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
3000
                } else {
3001
                    ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
3002
                }
3003
            }
3004
        }
3005
    }
3006
    h->slice_type= old_slice_type;
3007
    s->mb_x= end_mb_x;
3008
    s->mb_y= end_mb_y - FRAME_MBAFF;
3009
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3010
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3011
}
3012

    
3013
static void predict_field_decoding_flag(H264Context *h){
3014
    MpegEncContext * const s = &h->s;
3015
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3016
    int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
3017
                ? s->current_picture.mb_type[mb_xy-1]
3018
                : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
3019
                ? s->current_picture.mb_type[mb_xy-s->mb_stride]
3020
                : 0;
3021
    h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3022
}
3023

    
3024
/**
3025
 * Draw edges and report progress for the last MB row.
3026
 */
3027
static void decode_finish_row(H264Context *h){
3028
    MpegEncContext * const s = &h->s;
3029
    int top = 16*(s->mb_y >> FIELD_PICTURE);
3030
    int height = 16 << FRAME_MBAFF;
3031
    int deblock_border = (16 + 4) << FRAME_MBAFF;
3032
    int pic_height = 16*s->mb_height >> FIELD_PICTURE;
3033

    
3034
    if (h->deblocking_filter) {
3035
        if((top + height) >= pic_height)
3036
            height += deblock_border;
3037

    
3038
        top -= deblock_border;
3039
    }
3040

    
3041
    if (top >= pic_height || (top + height) < h->emu_edge_height)
3042
        return;
3043

    
3044
    height = FFMIN(height, pic_height - top);
3045
    if (top < h->emu_edge_height) {
3046
        height = top+height;
3047
        top = 0;
3048
    }
3049

    
3050
    ff_draw_horiz_band(s, top, height);
3051

    
3052
    if (s->dropable) return;
3053

    
3054
    ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
3055
                             s->picture_structure==PICT_BOTTOM_FIELD);
3056
}
3057

    
3058
static int decode_slice(struct AVCodecContext *avctx, void *arg){
3059
    H264Context *h = *(void**)arg;
3060
    MpegEncContext * const s = &h->s;
3061
    const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
3062

    
3063
    s->mb_skip_run= -1;
3064

    
3065
    h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
3066
                    (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
3067

    
3068
    if( h->pps.cabac ) {
3069
        /* realign */
3070
        align_get_bits( &s->gb );
3071

    
3072
        /* init cabac */
3073
        ff_init_cabac_states( &h->cabac);
3074
        ff_init_cabac_decoder( &h->cabac,
3075
                               s->gb.buffer + get_bits_count(&s->gb)/8,
3076
                               (get_bits_left(&s->gb) + 7)/8);
3077

    
3078
        ff_h264_init_cabac_states(h);
3079

    
3080
        for(;;){
3081
//START_TIMER
3082
            int ret = ff_h264_decode_mb_cabac(h);
3083
            int eos;
3084
//STOP_TIMER("decode_mb_cabac")
3085

    
3086
            if(ret>=0) ff_h264_hl_decode_mb(h);
3087

    
3088
            if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
3089
                s->mb_y++;
3090

    
3091
                ret = ff_h264_decode_mb_cabac(h);
3092

    
3093
                if(ret>=0) ff_h264_hl_decode_mb(h);
3094
                s->mb_y--;
3095
            }
3096
            eos = get_cabac_terminate( &h->cabac );
3097

    
3098
            if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
3099
                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3100
                return 0;
3101
            }
3102
            if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3103
                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d, bytestream (%td)\n", s->mb_x, s->mb_y, h->cabac.bytestream_end - h->cabac.bytestream);
3104
                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
3105
                return -1;
3106
            }
3107

    
3108
            if( ++s->mb_x >= s->mb_width ) {
3109
                loop_filter(h);
3110
                s->mb_x = 0;
3111
                decode_finish_row(h);
3112
                ++s->mb_y;
3113
                if(FIELD_OR_MBAFF_PICTURE) {
3114
                    ++s->mb_y;
3115
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
3116
                        predict_field_decoding_flag(h);
3117
                }
3118
            }
3119

    
3120
            if( eos || s->mb_y >= s->mb_height ) {
3121
                if(s->mb_x)
3122
                    loop_filter(h);
3123
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3124
                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3125
                return 0;
3126
            }
3127
        }
3128

    
3129
    } else {
3130
        for(;;){
3131
            int ret = ff_h264_decode_mb_cavlc(h);
3132

    
3133
            if(ret>=0) ff_h264_hl_decode_mb(h);
3134

    
3135
            if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
3136
                s->mb_y++;
3137
                ret = ff_h264_decode_mb_cavlc(h);
3138

    
3139
                if(ret>=0) ff_h264_hl_decode_mb(h);
3140
                s->mb_y--;
3141
            }
3142

    
3143
            if(ret<0){
3144
                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3145
                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
3146

    
3147
                return -1;
3148
            }
3149

    
3150
            if(++s->mb_x >= s->mb_width){
3151
                loop_filter(h);
3152
                s->mb_x=0;
3153
                decode_finish_row(h);
3154
                ++s->mb_y;
3155
                if(FIELD_OR_MBAFF_PICTURE) {
3156
                    ++s->mb_y;
3157
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
3158
                        predict_field_decoding_flag(h);
3159
                }
3160
                if(s->mb_y >= s->mb_height){
3161
                    tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3162

    
3163
                    if(   get_bits_count(&s->gb) == s->gb.size_in_bits
3164
                       || get_bits_count(&s->gb) <  s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
3165
                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3166

    
3167
                        return 0;
3168
                    }else{
3169
                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3170

    
3171
                        return -1;
3172
                    }
3173
                }
3174
            }
3175

    
3176
            if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
3177
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3178
                if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
3179
                    if(s->mb_x)
3180
                        loop_filter(h);
3181
                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3182

    
3183
                    return 0;
3184
                }else{
3185
                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
3186

    
3187
                    return -1;
3188
                }
3189
            }
3190
        }
3191
    }
3192

    
3193
#if 0
3194
    for(;s->mb_y < s->mb_height; s->mb_y++){
3195
        for(;s->mb_x < s->mb_width; s->mb_x++){
3196
            int ret= decode_mb(h);
3197

3198
            ff_h264_hl_decode_mb(h);
3199

3200
            if(ret<0){
3201
                av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3202
                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
3203

3204
                return -1;
3205
            }
3206

3207
            if(++s->mb_x >= s->mb_width){
3208
                s->mb_x=0;
3209
                if(++s->mb_y >= s->mb_height){
3210
                    if(get_bits_count(s->gb) == s->gb.size_in_bits){
3211
                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3212

3213
                        return 0;
3214
                    }else{
3215
                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3216

3217
                        return -1;
3218
                    }
3219
                }
3220
            }
3221

3222
            if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
3223
                if(get_bits_count(s->gb) == s->gb.size_in_bits){
3224
                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3225

3226
                    return 0;
3227
                }else{
3228
                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
3229

3230
                    return -1;
3231
                }
3232
            }
3233
        }
3234
        s->mb_x=0;
3235
        ff_draw_horiz_band(s, 16*s->mb_y, 16);
3236
    }
3237
#endif
3238
    return -1; //not reached
3239
}
3240

    
3241
/**
3242
 * Call decode_slice() for each context.
3243
 *
3244
 * @param h h264 master context
3245
 * @param context_count number of contexts to execute
3246
 */
3247
static void execute_decode_slices(H264Context *h, int context_count){
3248
    MpegEncContext * const s = &h->s;
3249
    AVCodecContext * const avctx= s->avctx;
3250
    H264Context *hx;
3251
    int i;
3252

    
3253
    if (s->avctx->hwaccel)
3254
        return;
3255
    if(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3256
        return;
3257
    if(context_count == 1) {
3258
        decode_slice(avctx, &h);
3259
    } else {
3260
        for(i = 1; i < context_count; i++) {
3261
            hx = h->thread_context[i];
3262
            hx->s.error_recognition = avctx->error_recognition;
3263
            hx->s.error_count = 0;
3264
            hx->x264_build= h->x264_build;
3265
        }
3266

    
3267
        avctx->execute(avctx, (void *)decode_slice,
3268
                       h->thread_context, NULL, context_count, sizeof(void*));
3269

    
3270
        /* pull back stuff from slices to master context */
3271
        hx = h->thread_context[context_count - 1];
3272
        s->mb_x = hx->s.mb_x;
3273
        s->mb_y = hx->s.mb_y;
3274
        s->dropable = hx->s.dropable;
3275
        s->picture_structure = hx->s.picture_structure;
3276
        for(i = 1; i < context_count; i++)
3277
            h->s.error_count += h->thread_context[i]->s.error_count;
3278
    }
3279
}
3280

    
3281

    
3282
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
3283
    MpegEncContext * const s = &h->s;
3284
    AVCodecContext * const avctx= s->avctx;
3285
    int buf_index=0;
3286
    H264Context *hx; ///< thread context
3287
    int context_count = 0;
3288
    int next_avc= h->is_avc ? 0 : buf_size;
3289

    
3290
    h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
3291
#if 0
3292
    int i;
3293
    for(i=0; i<50; i++){
3294
        av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
3295
    }
3296
#endif
3297
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
3298
        h->current_slice = 0;
3299
        if (!s->first_field)
3300
            s->current_picture_ptr= NULL;
3301
        ff_h264_reset_sei(h);
3302
    }
3303

    
3304
    for(;;){
3305
        int consumed;
3306
        int dst_length;
3307
        int bit_length;
3308
        const uint8_t *ptr;
3309
        int i, nalsize = 0;
3310
        int err;
3311

    
3312
        if(buf_index >= next_avc) {
3313
            if(buf_index >= buf_size) break;
3314
            nalsize = 0;
3315
            for(i = 0; i < h->nal_length_size; i++)
3316
                nalsize = (nalsize << 8) | buf[buf_index++];
3317
            if(nalsize <= 0 || nalsize > buf_size - buf_index){
3318
                av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
3319
                break;
3320
            }
3321
            next_avc= buf_index + nalsize;
3322
        } else {
3323
            // start code prefix search
3324
            for(; buf_index + 3 < next_avc; buf_index++){
3325
                // This should always succeed in the first iteration.
3326
                if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
3327
                    break;
3328
            }
3329

    
3330
            if(buf_index+3 >= buf_size) break;
3331

    
3332
            buf_index+=3;
3333
            if(buf_index >= next_avc) continue;
3334
        }
3335

    
3336
        hx = h->thread_context[context_count];
3337

    
3338
        ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
3339
        if (ptr==NULL || dst_length < 0){
3340
            return -1;
3341
        }
3342
        i= buf_index + consumed;
3343
        if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
3344
           buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
3345
            s->workaround_bugs |= FF_BUG_TRUNCATED;
3346

    
3347
        if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
3348
        while(ptr[dst_length - 1] == 0 && dst_length > 0)
3349
            dst_length--;
3350
        }
3351
        bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
3352

    
3353
        if(s->avctx->debug&FF_DEBUG_STARTCODE){
3354
            av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d at %d/%d length %d\n", hx->nal_unit_type, buf_index, buf_size, dst_length);
3355
        }
3356

    
3357
        if (h->is_avc && (nalsize != consumed) && nalsize){
3358
            av_log(h->s.avctx, AV_LOG_DEBUG, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
3359
        }
3360

    
3361
        buf_index += consumed;
3362

    
3363
        //FIXME do not discard SEI id
3364
        if(
3365
#if FF_API_HURRY_UP
3366
           (s->hurry_up == 1 && h->nal_ref_idc  == 0) ||
3367
#endif
3368
           (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc  == 0))
3369
            continue;
3370

    
3371
      again:
3372
        err = 0;
3373
        switch(hx->nal_unit_type){
3374
        case NAL_IDR_SLICE:
3375
            if (h->nal_unit_type != NAL_IDR_SLICE) {
3376
                av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
3377
                return -1;
3378
            }
3379
            idr(h); //FIXME ensure we don't loose some frames if there is reordering
3380
        case NAL_SLICE:
3381
            init_get_bits(&hx->s.gb, ptr, bit_length);
3382
            hx->intra_gb_ptr=
3383
            hx->inter_gb_ptr= &hx->s.gb;
3384
            hx->s.data_partitioning = 0;
3385

    
3386
            if((err = decode_slice_header(hx, h)))
3387
               break;
3388

    
3389
            s->current_picture_ptr->key_frame |=
3390
                    (hx->nal_unit_type == NAL_IDR_SLICE) ||
3391
                    (h->sei_recovery_frame_cnt >= 0);
3392

    
3393
            if (h->current_slice == 1) {
3394
                if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3395
                    decode_postinit(h);
3396
                }
3397

    
3398
                if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
3399
                    return -1;
3400
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3401
                    ff_vdpau_h264_picture_start(s);
3402
            }
3403

    
3404
            if(hx->redundant_pic_count==0
3405
#if FF_API_HURRY_UP
3406
               && hx->s.hurry_up < 5
3407
#endif
3408
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3409
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3410
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3411
               && avctx->skip_frame < AVDISCARD_ALL){
3412
                if(avctx->hwaccel) {
3413
                    if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
3414
                        return -1;
3415
                }else
3416
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
3417
                    static const uint8_t start_code[] = {0x00, 0x00, 0x01};
3418
                    ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
3419
                    ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
3420
                }else
3421
                    context_count++;
3422
            }
3423
            break;
3424
        case NAL_DPA:
3425
            init_get_bits(&hx->s.gb, ptr, bit_length);
3426
            hx->intra_gb_ptr=
3427
            hx->inter_gb_ptr= NULL;
3428

    
3429
            if ((err = decode_slice_header(hx, h)) < 0)
3430
                break;
3431

    
3432
            hx->s.data_partitioning = 1;
3433

    
3434
            break;
3435
        case NAL_DPB:
3436
            init_get_bits(&hx->intra_gb, ptr, bit_length);
3437
            hx->intra_gb_ptr= &hx->intra_gb;
3438
            break;
3439
        case NAL_DPC:
3440
            init_get_bits(&hx->inter_gb, ptr, bit_length);
3441
            hx->inter_gb_ptr= &hx->inter_gb;
3442

    
3443
            if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
3444
               && s->context_initialized
3445
#if FF_API_HURRY_UP
3446
               && s->hurry_up < 5
3447
#endif
3448
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3449
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3450
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3451
               && avctx->skip_frame < AVDISCARD_ALL)
3452
                context_count++;
3453
            break;
3454
        case NAL_SEI:
3455
            init_get_bits(&s->gb, ptr, bit_length);
3456
            ff_h264_decode_sei(h);
3457
            break;
3458
        case NAL_SPS:
3459
            init_get_bits(&s->gb, ptr, bit_length);
3460
            ff_h264_decode_seq_parameter_set(h);
3461

    
3462
            if(s->flags& CODEC_FLAG_LOW_DELAY)
3463
                s->low_delay=1;
3464

    
3465
            if(avctx->has_b_frames < 2)
3466
                avctx->has_b_frames= !s->low_delay;
3467
            break;
3468
        case NAL_PPS:
3469
            init_get_bits(&s->gb, ptr, bit_length);
3470

    
3471
            ff_h264_decode_picture_parameter_set(h, bit_length);
3472

    
3473
            break;
3474
        case NAL_AUD:
3475
        case NAL_END_SEQUENCE:
3476
        case NAL_END_STREAM:
3477
        case NAL_FILLER_DATA:
3478
        case NAL_SPS_EXT:
3479
        case NAL_AUXILIARY_SLICE:
3480
            break;
3481
        default:
3482
            av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
3483
        }
3484

    
3485
        if(context_count == h->max_contexts) {
3486
            execute_decode_slices(h, context_count);
3487
            context_count = 0;
3488
        }
3489

    
3490
        if (err < 0)
3491
            av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
3492
        else if(err == 1) {
3493
            /* Slice could not be decoded in parallel mode, copy down
3494
             * NAL unit stuff to context 0 and restart. Note that
3495
             * rbsp_buffer is not transferred, but since we no longer
3496
             * run in parallel mode this should not be an issue. */
3497
            h->nal_unit_type = hx->nal_unit_type;
3498
            h->nal_ref_idc   = hx->nal_ref_idc;
3499
            hx = h;
3500
            goto again;
3501
        }
3502
    }
3503
    if(context_count)
3504
        execute_decode_slices(h, context_count);
3505
    return buf_index;
3506
}
3507

    
3508
/**
3509
 * returns the number of bytes consumed for building the current frame
3510
 */
3511
static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
3512
        if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
3513
        if(pos+10>buf_size) pos=buf_size; // oops ;)
3514

    
3515
        return pos;
3516
}
3517

    
3518
static int decode_frame(AVCodecContext *avctx,
3519
                             void *data, int *data_size,
3520
                             AVPacket *avpkt)
3521
{
3522
    const uint8_t *buf = avpkt->data;
3523
    int buf_size = avpkt->size;
3524
    H264Context *h = avctx->priv_data;
3525
    MpegEncContext *s = &h->s;
3526
    AVFrame *pict = data;
3527
    int buf_index;
3528

    
3529
    s->flags= avctx->flags;
3530
    s->flags2= avctx->flags2;
3531

    
3532
   /* end of stream, output what is still in the buffers */
3533
 out:
3534
    if (buf_size == 0) {
3535
        Picture *out;
3536
        int i, out_idx;
3537

    
3538
        s->current_picture_ptr = NULL;
3539

    
3540
//FIXME factorize this with the output code below
3541
        out = h->delayed_pic[0];
3542
        out_idx = 0;
3543
        for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
3544
            if(h->delayed_pic[i]->poc < out->poc){
3545
                out = h->delayed_pic[i];
3546
                out_idx = i;
3547
            }
3548

    
3549
        for(i=out_idx; h->delayed_pic[i]; i++)
3550
            h->delayed_pic[i] = h->delayed_pic[i+1];
3551

    
3552
        if(out){
3553
            *data_size = sizeof(AVFrame);
3554
            *pict= *(AVFrame*)out;
3555
        }
3556

    
3557
        return 0;
3558
    }
3559

    
3560
    buf_index=decode_nal_units(h, buf, buf_size);
3561
    if(buf_index < 0)
3562
        return -1;
3563

    
3564
    if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
3565
        buf_size = 0;
3566
        goto out;
3567
    }
3568

    
3569
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
3570
        if (avctx->skip_frame >= AVDISCARD_NONREF
3571
#if FF_API_HURRY_UP
3572
                || s->hurry_up
3573
#endif
3574
           )
3575
            return 0;
3576
        av_log(avctx, AV_LOG_ERROR, "no frame!\n");
3577
        return -1;
3578
    }
3579

    
3580
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
3581

    
3582
        if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h);
3583

    
3584
        field_end(h, 0);
3585

    
3586
        if (!h->next_output_pic) {
3587
            /* Wait for second field. */
3588
            *data_size = 0;
3589

    
3590
        } else {
3591
            *data_size = sizeof(AVFrame);
3592
            *pict = *(AVFrame*)h->next_output_pic;
3593
        }
3594
    }
3595

    
3596
    assert(pict->data[0] || !*data_size);
3597
    ff_print_debug_info(s, pict);
3598
//printf("out %d\n", (int)pict->data[0]);
3599

    
3600
    return get_consumed_bytes(s, buf_index, buf_size);
3601
}
3602
#if 0
3603
static inline void fill_mb_avail(H264Context *h){
3604
    MpegEncContext * const s = &h->s;
3605
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3606

3607
    if(s->mb_y){
3608
        h->mb_avail[0]= s->mb_x                 && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
3609
        h->mb_avail[1]=                            h->slice_table[mb_xy - s->mb_stride    ] == h->slice_num;
3610
        h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
3611
    }else{
3612
        h->mb_avail[0]=
3613
        h->mb_avail[1]=
3614
        h->mb_avail[2]= 0;
3615
    }
3616
    h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
3617
    h->mb_avail[4]= 1; //FIXME move out
3618
    h->mb_avail[5]= 0; //FIXME move out
3619
}
3620
#endif
3621

    
3622
#ifdef TEST
3623
#undef printf
3624
#undef random
3625
#define COUNT 8000
3626
#define SIZE (COUNT*40)
3627
int main(void){
3628
    int i;
3629
    uint8_t temp[SIZE];
3630
    PutBitContext pb;
3631
    GetBitContext gb;
3632
//    int int_temp[10000];
3633
    DSPContext dsp;
3634
    AVCodecContext avctx;
3635

    
3636
    dsputil_init(&dsp, &avctx);
3637

    
3638
    init_put_bits(&pb, temp, SIZE);
3639
    printf("testing unsigned exp golomb\n");
3640
    for(i=0; i<COUNT; i++){
3641
        START_TIMER
3642
        set_ue_golomb(&pb, i);
3643
        STOP_TIMER("set_ue_golomb");
3644
    }
3645
    flush_put_bits(&pb);
3646

    
3647
    init_get_bits(&gb, temp, 8*SIZE);
3648
    for(i=0; i<COUNT; i++){
3649
        int j, s;
3650

    
3651
        s= show_bits(&gb, 24);
3652

    
3653
        START_TIMER
3654
        j= get_ue_golomb(&gb);
3655
        if(j != i){
3656
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3657
//            return -1;
3658
        }
3659
        STOP_TIMER("get_ue_golomb");
3660
    }
3661

    
3662

    
3663
    init_put_bits(&pb, temp, SIZE);
3664
    printf("testing signed exp golomb\n");
3665
    for(i=0; i<COUNT; i++){
3666
        START_TIMER
3667
        set_se_golomb(&pb, i - COUNT/2);
3668
        STOP_TIMER("set_se_golomb");
3669
    }
3670
    flush_put_bits(&pb);
3671

    
3672
    init_get_bits(&gb, temp, 8*SIZE);
3673
    for(i=0; i<COUNT; i++){
3674
        int j, s;
3675

    
3676
        s= show_bits(&gb, 24);
3677

    
3678
        START_TIMER
3679
        j= get_se_golomb(&gb);
3680
        if(j != i - COUNT/2){
3681
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3682
//            return -1;
3683
        }
3684
        STOP_TIMER("get_se_golomb");
3685
    }
3686

    
3687
#if 0
3688
    printf("testing 4x4 (I)DCT\n");
3689

3690
    DCTELEM block[16];
3691
    uint8_t src[16], ref[16];
3692
    uint64_t error= 0, max_error=0;
3693

3694
    for(i=0; i<COUNT; i++){
3695
        int j;
3696
//        printf("%d %d %d\n", r1, r2, (r2-r1)*16);
3697
        for(j=0; j<16; j++){
3698
            ref[j]= random()%255;
3699
            src[j]= random()%255;
3700
        }
3701

3702
        h264_diff_dct_c(block, src, ref, 4);
3703

3704
        //normalize
3705
        for(j=0; j<16; j++){
3706
//            printf("%d ", block[j]);
3707
            block[j]= block[j]*4;
3708
            if(j&1) block[j]= (block[j]*4 + 2)/5;
3709
            if(j&4) block[j]= (block[j]*4 + 2)/5;
3710
        }
3711
//        printf("\n");
3712

3713
        h->h264dsp.h264_idct_add(ref, block, 4);
3714
/*        for(j=0; j<16; j++){
3715
            printf("%d ", ref[j]);
3716
        }
3717
        printf("\n");*/
3718

3719
        for(j=0; j<16; j++){
3720
            int diff= FFABS(src[j] - ref[j]);
3721

3722
            error+= diff*diff;
3723
            max_error= FFMAX(max_error, diff);
3724
        }
3725
    }
3726
    printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
3727
    printf("testing quantizer\n");
3728
    for(qp=0; qp<52; qp++){
3729
        for(i=0; i<16; i++)
3730
            src1_block[i]= src2_block[i]= random()%255;
3731

3732
    }
3733
    printf("Testing NAL layer\n");
3734

3735
    uint8_t bitstream[COUNT];
3736
    uint8_t nal[COUNT*2];
3737
    H264Context h;
3738
    memset(&h, 0, sizeof(H264Context));
3739

3740
    for(i=0; i<COUNT; i++){
3741
        int zeros= i;
3742
        int nal_length;
3743
        int consumed;
3744
        int out_length;
3745
        uint8_t *out;
3746
        int j;
3747

3748
        for(j=0; j<COUNT; j++){
3749
            bitstream[j]= (random() % 255) + 1;
3750
        }
3751

3752
        for(j=0; j<zeros; j++){
3753
            int pos= random() % COUNT;
3754
            while(bitstream[pos] == 0){
3755
                pos++;
3756
                pos %= COUNT;
3757
            }
3758
            bitstream[pos]=0;
3759
        }
3760

3761
        START_TIMER
3762

3763
        nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
3764
        if(nal_length<0){
3765
            printf("encoding failed\n");
3766
            return -1;
3767
        }
3768

3769
        out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
3770

3771
        STOP_TIMER("NAL")
3772

3773
        if(out_length != COUNT){
3774
            printf("incorrect length %d %d\n", out_length, COUNT);
3775
            return -1;
3776
        }
3777

3778
        if(consumed != nal_length){
3779
            printf("incorrect consumed length %d %d\n", nal_length, consumed);
3780
            return -1;
3781
        }
3782

3783
        if(memcmp(bitstream, out, COUNT)){
3784
            printf("mismatch\n");
3785
            return -1;
3786
        }
3787
    }
3788
#endif
3789

    
3790
    printf("Testing RBSP\n");
3791

    
3792

    
3793
    return 0;
3794
}
3795
#endif /* TEST */
3796

    
3797

    
3798
av_cold void ff_h264_free_context(H264Context *h)
3799
{
3800
    int i;
3801

    
3802
    free_tables(h, 1); //FIXME cleanup init stuff perhaps
3803

    
3804
    for(i = 0; i < MAX_SPS_COUNT; i++)
3805
        av_freep(h->sps_buffers + i);
3806

    
3807
    for(i = 0; i < MAX_PPS_COUNT; i++)
3808
        av_freep(h->pps_buffers + i);
3809
}
3810

    
3811
av_cold int ff_h264_decode_end(AVCodecContext *avctx)
3812
{
3813
    H264Context *h = avctx->priv_data;
3814
    MpegEncContext *s = &h->s;
3815

    
3816
    ff_h264_free_context(h);
3817

    
3818
    MPV_common_end(s);
3819

    
3820
//    memset(h, 0, sizeof(H264Context));
3821

    
3822
    return 0;
3823
}
3824

    
3825
static const AVProfile profiles[] = {
3826
    { FF_PROFILE_H264_BASELINE,             "Baseline"              },
3827
    { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
3828
    { FF_PROFILE_H264_MAIN,                 "Main"                  },
3829
    { FF_PROFILE_H264_EXTENDED,             "Extended"              },
3830
    { FF_PROFILE_H264_HIGH,                 "High"                  },
3831
    { FF_PROFILE_H264_HIGH_10,              "High 10"               },
3832
    { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
3833
    { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
3834
    { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
3835
    { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
3836
    { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
3837
    { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
3838
    { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
3839
    { FF_PROFILE_UNKNOWN },
3840
};
3841

    
3842
AVCodec ff_h264_decoder = {
3843
    "h264",
3844
    AVMEDIA_TYPE_VIDEO,
3845
    CODEC_ID_H264,
3846
    sizeof(H264Context),
3847
    ff_h264_decode_init,
3848
    NULL,
3849
    ff_h264_decode_end,
3850
    decode_frame,
3851
    /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
3852
    .flush= flush_dpb,
3853
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
3854
    .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
3855
    .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
3856
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3857
};
3858

    
3859
#if CONFIG_H264_VDPAU_DECODER
3860
AVCodec ff_h264_vdpau_decoder = {
3861
    "h264_vdpau",
3862
    AVMEDIA_TYPE_VIDEO,
3863
    CODEC_ID_H264,
3864
    sizeof(H264Context),
3865
    ff_h264_decode_init,
3866
    NULL,
3867
    ff_h264_decode_end,
3868
    decode_frame,
3869
    CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
3870
    .flush= flush_dpb,
3871
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
3872
    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
3873
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3874
};
3875
#endif