Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ 488efb33

History | View | Annotate | Download (141 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
static void chroma_dc_dequant_idct_c(DCTELEM *block, int qmul){
432
    const int stride= 16*2;
433
    const int xStride= 16;
434
    int a,b,c,d,e;
435

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

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

    
446
    block[stride*0 + xStride*0]= ((a+c)*qmul) >> 7;
447
    block[stride*0 + xStride*1]= ((e+b)*qmul) >> 7;
448
    block[stride*1 + xStride*0]= ((a-c)*qmul) >> 7;
449
    block[stride*1 + xStride*1]= ((e-b)*qmul) >> 7;
450
}
451

    
452
#if 0
453
static void chroma_dc_dct_c(DCTELEM *block){
454
    const int stride= 16*2;
455
    const int xStride= 16;
456
    int a,b,c,d,e;
457

458
    a= block[stride*0 + xStride*0];
459
    b= block[stride*0 + xStride*1];
460
    c= block[stride*1 + xStride*0];
461
    d= block[stride*1 + xStride*1];
462

463
    e= a-b;
464
    a= a+b;
465
    b= c-d;
466
    c= c+d;
467

468
    block[stride*0 + xStride*0]= (a+c);
469
    block[stride*0 + xStride*1]= (e+b);
470
    block[stride*1 + xStride*0]= (a-c);
471
    block[stride*1 + xStride*1]= (e-b);
472
}
473
#endif
474

    
475
static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
476
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
477
                           int src_x_offset, int src_y_offset,
478
                           qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
479
    MpegEncContext * const s = &h->s;
480
    const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
481
    int my=       h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
482
    const int luma_xy= (mx&3) + ((my&3)<<2);
483
    uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*h->mb_linesize;
484
    uint8_t * src_cb, * src_cr;
485
    int extra_width= h->emu_edge_width;
486
    int extra_height= h->emu_edge_height;
487
    int emu=0;
488
    const int full_mx= mx>>2;
489
    const int full_my= my>>2;
490
    const int pic_width  = 16*s->mb_width;
491
    const int pic_height = 16*s->mb_height >> MB_FIELD;
492

    
493
    if(mx&7) extra_width -= 3;
494
    if(my&7) extra_height -= 3;
495

    
496
    if(   full_mx < 0-extra_width
497
       || full_my < 0-extra_height
498
       || full_mx + 16/*FIXME*/ > pic_width + extra_width
499
       || full_my + 16/*FIXME*/ > pic_height + extra_height){
500
        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*h->mb_linesize, h->mb_linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
501
            src_y= s->edge_emu_buffer + 2 + 2*h->mb_linesize;
502
        emu=1;
503
    }
504

    
505
    qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
506
    if(!square){
507
        qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
508
    }
509

    
510
    if(CONFIG_GRAY && s->flags&CODEC_FLAG_GRAY) return;
511

    
512
    if(MB_FIELD){
513
        // chroma offset when predicting from a field of opposite parity
514
        my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
515
        emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
516
    }
517
    src_cb= pic->data[1] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
518
    src_cr= pic->data[2] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
519

    
520
    if(emu){
521
        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
522
            src_cb= s->edge_emu_buffer;
523
    }
524
    chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
525

    
526
    if(emu){
527
        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
528
            src_cr= s->edge_emu_buffer;
529
    }
530
    chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
531
}
532

    
533
static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
534
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
535
                           int x_offset, int y_offset,
536
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
537
                           qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
538
                           int list0, int list1){
539
    MpegEncContext * const s = &h->s;
540
    qpel_mc_func *qpix_op=  qpix_put;
541
    h264_chroma_mc_func chroma_op= chroma_put;
542

    
543
    dest_y  += 2*x_offset + 2*y_offset*h->  mb_linesize;
544
    dest_cb +=   x_offset +   y_offset*h->mb_uvlinesize;
545
    dest_cr +=   x_offset +   y_offset*h->mb_uvlinesize;
546
    x_offset += 8*s->mb_x;
547
    y_offset += 8*(s->mb_y >> MB_FIELD);
548

    
549
    if(list0){
550
        Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
551
        mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
552
                           dest_y, dest_cb, dest_cr, x_offset, y_offset,
553
                           qpix_op, chroma_op);
554

    
555
        qpix_op=  qpix_avg;
556
        chroma_op= chroma_avg;
557
    }
558

    
559
    if(list1){
560
        Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
561
        mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
562
                           dest_y, dest_cb, dest_cr, x_offset, y_offset,
563
                           qpix_op, chroma_op);
564
    }
565
}
566

    
567
static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
568
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
569
                           int x_offset, int y_offset,
570
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
571
                           h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
572
                           h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
573
                           int list0, int list1){
574
    MpegEncContext * const s = &h->s;
575

    
576
    dest_y  += 2*x_offset + 2*y_offset*h->  mb_linesize;
577
    dest_cb +=   x_offset +   y_offset*h->mb_uvlinesize;
578
    dest_cr +=   x_offset +   y_offset*h->mb_uvlinesize;
579
    x_offset += 8*s->mb_x;
580
    y_offset += 8*(s->mb_y >> MB_FIELD);
581

    
582
    if(list0 && list1){
583
        /* don't optimize for luma-only case, since B-frames usually
584
         * use implicit weights => chroma too. */
585
        uint8_t *tmp_cb = s->obmc_scratchpad;
586
        uint8_t *tmp_cr = s->obmc_scratchpad + 8;
587
        uint8_t *tmp_y  = s->obmc_scratchpad + 8*h->mb_uvlinesize;
588
        int refn0 = h->ref_cache[0][ scan8[n] ];
589
        int refn1 = h->ref_cache[1][ scan8[n] ];
590

    
591
        mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
592
                    dest_y, dest_cb, dest_cr,
593
                    x_offset, y_offset, qpix_put, chroma_put);
594
        mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
595
                    tmp_y, tmp_cb, tmp_cr,
596
                    x_offset, y_offset, qpix_put, chroma_put);
597

    
598
        if(h->use_weight == 2){
599
            int weight0 = h->implicit_weight[refn0][refn1][s->mb_y&1];
600
            int weight1 = 64 - weight0;
601
            luma_weight_avg(  dest_y,  tmp_y,  h->  mb_linesize, 5, weight0, weight1, 0);
602
            chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
603
            chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
604
        }else{
605
            luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
606
                            h->luma_weight[refn0][0][0] , h->luma_weight[refn1][1][0],
607
                            h->luma_weight[refn0][0][1] + h->luma_weight[refn1][1][1]);
608
            chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
609
                            h->chroma_weight[refn0][0][0][0] , h->chroma_weight[refn1][1][0][0],
610
                            h->chroma_weight[refn0][0][0][1] + h->chroma_weight[refn1][1][0][1]);
611
            chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
612
                            h->chroma_weight[refn0][0][1][0] , h->chroma_weight[refn1][1][1][0],
613
                            h->chroma_weight[refn0][0][1][1] + h->chroma_weight[refn1][1][1][1]);
614
        }
615
    }else{
616
        int list = list1 ? 1 : 0;
617
        int refn = h->ref_cache[list][ scan8[n] ];
618
        Picture *ref= &h->ref_list[list][refn];
619
        mc_dir_part(h, ref, n, square, chroma_height, delta, list,
620
                    dest_y, dest_cb, dest_cr, x_offset, y_offset,
621
                    qpix_put, chroma_put);
622

    
623
        luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
624
                       h->luma_weight[refn][list][0], h->luma_weight[refn][list][1]);
625
        if(h->use_weight_chroma){
626
            chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
627
                             h->chroma_weight[refn][list][0][0], h->chroma_weight[refn][list][0][1]);
628
            chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
629
                             h->chroma_weight[refn][list][1][0], h->chroma_weight[refn][list][1][1]);
630
        }
631
    }
632
}
633

    
634
static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
635
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
636
                           int x_offset, int y_offset,
637
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
638
                           qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
639
                           h264_weight_func *weight_op, h264_biweight_func *weight_avg,
640
                           int list0, int list1){
641
    if((h->use_weight==2 && list0 && list1
642
        && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ][h->s.mb_y&1] != 32))
643
       || h->use_weight==1)
644
        mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
645
                         x_offset, y_offset, qpix_put, chroma_put,
646
                         weight_op[0], weight_op[3], weight_avg[0], weight_avg[3], list0, list1);
647
    else
648
        mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
649
                    x_offset, y_offset, qpix_put, chroma_put, qpix_avg, chroma_avg, list0, list1);
650
}
651

    
652
static inline void prefetch_motion(H264Context *h, int list){
653
    /* fetch pixels for estimated mv 4 macroblocks ahead
654
     * optimized for 64byte cache lines */
655
    MpegEncContext * const s = &h->s;
656
    const int refn = h->ref_cache[list][scan8[0]];
657
    if(refn >= 0){
658
        const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
659
        const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
660
        uint8_t **src= h->ref_list[list][refn].data;
661
        int off= mx + (my + (s->mb_x&3)*4)*h->mb_linesize + 64;
662
        s->dsp.prefetch(src[0]+off, s->linesize, 4);
663
        off= (mx>>1) + ((my>>1) + (s->mb_x&7))*s->uvlinesize + 64;
664
        s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
665
    }
666
}
667

    
668
static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
669
                      qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
670
                      qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
671
                      h264_weight_func *weight_op, h264_biweight_func *weight_avg){
672
    MpegEncContext * const s = &h->s;
673
    const int mb_xy= h->mb_xy;
674
    const int mb_type= s->current_picture.mb_type[mb_xy];
675

    
676
    assert(IS_INTER(mb_type));
677

    
678
    if(HAVE_PTHREADS && s->avctx->active_thread_type&FF_THREAD_FRAME)
679
        await_references(h);
680
    prefetch_motion(h, 0);
681

    
682
    if(IS_16X16(mb_type)){
683
        mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
684
                qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
685
                weight_op, weight_avg,
686
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
687
    }else if(IS_16X8(mb_type)){
688
        mc_part(h, 0, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 0,
689
                qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
690
                &weight_op[1], &weight_avg[1],
691
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
692
        mc_part(h, 8, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 4,
693
                qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
694
                &weight_op[1], &weight_avg[1],
695
                IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
696
    }else if(IS_8X16(mb_type)){
697
        mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
698
                qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
699
                &weight_op[2], &weight_avg[2],
700
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
701
        mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
702
                qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
703
                &weight_op[2], &weight_avg[2],
704
                IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
705
    }else{
706
        int i;
707

    
708
        assert(IS_8X8(mb_type));
709

    
710
        for(i=0; i<4; i++){
711
            const int sub_mb_type= h->sub_mb_type[i];
712
            const int n= 4*i;
713
            int x_offset= (i&1)<<2;
714
            int y_offset= (i&2)<<1;
715

    
716
            if(IS_SUB_8X8(sub_mb_type)){
717
                mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
718
                    qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
719
                    &weight_op[3], &weight_avg[3],
720
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
721
            }else if(IS_SUB_8X4(sub_mb_type)){
722
                mc_part(h, n  , 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset,
723
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
724
                    &weight_op[4], &weight_avg[4],
725
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
726
                mc_part(h, n+2, 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
727
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
728
                    &weight_op[4], &weight_avg[4],
729
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
730
            }else if(IS_SUB_4X8(sub_mb_type)){
731
                mc_part(h, n  , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
732
                    qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
733
                    &weight_op[5], &weight_avg[5],
734
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
735
                mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
736
                    qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
737
                    &weight_op[5], &weight_avg[5],
738
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
739
            }else{
740
                int j;
741
                assert(IS_SUB_4X4(sub_mb_type));
742
                for(j=0; j<4; j++){
743
                    int sub_x_offset= x_offset + 2*(j&1);
744
                    int sub_y_offset= y_offset +   (j&2);
745
                    mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
746
                        qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
747
                        &weight_op[6], &weight_avg[6],
748
                        IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
749
                }
750
            }
751
        }
752
    }
753

    
754
    prefetch_motion(h, 1);
755
}
756

    
757

    
758
static void free_tables(H264Context *h, int free_rbsp){
759
    int i;
760
    H264Context *hx;
761
    av_freep(&h->intra4x4_pred_mode);
762
    av_freep(&h->chroma_pred_mode_table);
763
    av_freep(&h->cbp_table);
764
    av_freep(&h->mvd_table[0]);
765
    av_freep(&h->mvd_table[1]);
766
    av_freep(&h->direct_table);
767
    av_freep(&h->non_zero_count);
768
    av_freep(&h->slice_table_base);
769
    h->slice_table= NULL;
770
    av_freep(&h->list_counts);
771

    
772
    av_freep(&h->mb2b_xy);
773
    av_freep(&h->mb2br_xy);
774

    
775
    for(i = 0; i < MAX_THREADS; i++) {
776
        hx = h->thread_context[i];
777
        if(!hx) continue;
778
        av_freep(&hx->top_borders[1]);
779
        av_freep(&hx->top_borders[0]);
780
        av_freep(&hx->s.obmc_scratchpad);
781
        if (free_rbsp){
782
            av_freep(&hx->rbsp_buffer[1]);
783
            av_freep(&hx->rbsp_buffer[0]);
784
            hx->rbsp_buffer_size[0] = 0;
785
            hx->rbsp_buffer_size[1] = 0;
786
        }
787
        if (i) av_freep(&h->thread_context[i]);
788
    }
789
}
790

    
791
static void init_dequant8_coeff_table(H264Context *h){
792
    int i,q,x;
793
    h->dequant8_coeff[0] = h->dequant8_buffer[0];
794
    h->dequant8_coeff[1] = h->dequant8_buffer[1];
795

    
796
    for(i=0; i<2; i++ ){
797
        if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
798
            h->dequant8_coeff[1] = h->dequant8_buffer[0];
799
            break;
800
        }
801

    
802
        for(q=0; q<52; q++){
803
            int shift = div6[q];
804
            int idx = rem6[q];
805
            for(x=0; x<64; x++)
806
                h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
807
                    ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
808
                    h->pps.scaling_matrix8[i][x]) << shift;
809
        }
810
    }
811
}
812

    
813
static void init_dequant4_coeff_table(H264Context *h){
814
    int i,j,q,x;
815
    for(i=0; i<6; i++ ){
816
        h->dequant4_coeff[i] = h->dequant4_buffer[i];
817
        for(j=0; j<i; j++){
818
            if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
819
                h->dequant4_coeff[i] = h->dequant4_buffer[j];
820
                break;
821
            }
822
        }
823
        if(j<i)
824
            continue;
825

    
826
        for(q=0; q<52; q++){
827
            int shift = div6[q] + 2;
828
            int idx = rem6[q];
829
            for(x=0; x<16; x++)
830
                h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
831
                    ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
832
                    h->pps.scaling_matrix4[i][x]) << shift;
833
        }
834
    }
835
}
836

    
837
static void init_dequant_tables(H264Context *h){
838
    int i,x;
839
    init_dequant4_coeff_table(h);
840
    if(h->pps.transform_8x8_mode)
841
        init_dequant8_coeff_table(h);
842
    if(h->sps.transform_bypass){
843
        for(i=0; i<6; i++)
844
            for(x=0; x<16; x++)
845
                h->dequant4_coeff[i][0][x] = 1<<6;
846
        if(h->pps.transform_8x8_mode)
847
            for(i=0; i<2; i++)
848
                for(x=0; x<64; x++)
849
                    h->dequant8_coeff[i][0][x] = 1<<6;
850
    }
851
}
852

    
853

    
854
int ff_h264_alloc_tables(H264Context *h){
855
    MpegEncContext * const s = &h->s;
856
    const int big_mb_num= s->mb_stride * (s->mb_height+1);
857
    const int row_mb_num= 2*s->mb_stride*s->avctx->thread_count;
858
    int x,y;
859

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

    
862
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count    , big_mb_num * 32 * sizeof(uint8_t), fail)
863
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
864
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
865

    
866
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
867
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
868
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
869
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
870
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
871

    
872
    memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(*h->slice_table_base));
873
    h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
874

    
875
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy  , big_mb_num * sizeof(uint32_t), fail);
876
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy , big_mb_num * sizeof(uint32_t), fail);
877
    for(y=0; y<s->mb_height; y++){
878
        for(x=0; x<s->mb_width; x++){
879
            const int mb_xy= x + y*s->mb_stride;
880
            const int b_xy = 4*x + 4*y*h->b_stride;
881

    
882
            h->mb2b_xy [mb_xy]= b_xy;
883
            h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
884
        }
885
    }
886

    
887
    s->obmc_scratchpad = NULL;
888

    
889
    if(!h->dequant4_coeff[0])
890
        init_dequant_tables(h);
891

    
892
    return 0;
893
fail:
894
    free_tables(h, 1);
895
    return -1;
896
}
897

    
898
/**
899
 * Mimic alloc_tables(), but for every context thread.
900
 */
901
static void clone_tables(H264Context *dst, H264Context *src, int i){
902
    MpegEncContext * const s = &src->s;
903
    dst->intra4x4_pred_mode       = src->intra4x4_pred_mode + i*8*2*s->mb_stride;
904
    dst->non_zero_count           = src->non_zero_count;
905
    dst->slice_table              = src->slice_table;
906
    dst->cbp_table                = src->cbp_table;
907
    dst->mb2b_xy                  = src->mb2b_xy;
908
    dst->mb2br_xy                 = src->mb2br_xy;
909
    dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;
910
    dst->mvd_table[0]             = src->mvd_table[0] + i*8*2*s->mb_stride;
911
    dst->mvd_table[1]             = src->mvd_table[1] + i*8*2*s->mb_stride;
912
    dst->direct_table             = src->direct_table;
913
    dst->list_counts              = src->list_counts;
914

    
915
    dst->s.obmc_scratchpad = NULL;
916
    ff_h264_pred_init(&dst->hpc, src->s.codec_id);
917
}
918

    
919
/**
920
 * Init context
921
 * Allocate buffers which are not shared amongst multiple threads.
922
 */
923
static int context_init(H264Context *h){
924
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t), fail)
925
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t), fail)
926

    
927
    h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
928
    h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
929

    
930
    return 0;
931
fail:
932
    return -1; // free_tables will clean up for us
933
}
934

    
935
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
936

    
937
static av_cold void common_init(H264Context *h){
938
    MpegEncContext * const s = &h->s;
939

    
940
    s->width = s->avctx->width;
941
    s->height = s->avctx->height;
942
    s->codec_id= s->avctx->codec->id;
943

    
944
    ff_h264dsp_init(&h->h264dsp);
945
    ff_h264_pred_init(&h->hpc, s->codec_id);
946

    
947
    h->dequant_coeff_pps= -1;
948
    s->unrestricted_mv=1;
949
    s->decode=1; //FIXME
950

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

    
953
    memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
954
    memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
955
}
956

    
957
int ff_h264_decode_extradata(H264Context *h)
958
{
959
    AVCodecContext *avctx = h->s.avctx;
960

    
961
    if(*(char *)avctx->extradata == 1){
962
        int i, cnt, nalsize;
963
        unsigned char *p = avctx->extradata;
964

    
965
        h->is_avc = 1;
966

    
967
        if(avctx->extradata_size < 7) {
968
            av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
969
            return -1;
970
        }
971
        /* sps and pps in the avcC always have length coded with 2 bytes,
972
           so put a fake nal_length_size = 2 while parsing them */
973
        h->nal_length_size = 2;
974
        // Decode sps from avcC
975
        cnt = *(p+5) & 0x1f; // Number of sps
976
        p += 6;
977
        for (i = 0; i < cnt; i++) {
978
            nalsize = AV_RB16(p) + 2;
979
            if(decode_nal_units(h, p, nalsize) < 0) {
980
                av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
981
                return -1;
982
            }
983
            p += nalsize;
984
        }
985
        // Decode pps from avcC
986
        cnt = *(p++); // Number of pps
987
        for (i = 0; i < cnt; i++) {
988
            nalsize = AV_RB16(p) + 2;
989
            if(decode_nal_units(h, p, nalsize) < 0) {
990
                av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
991
                return -1;
992
            }
993
            p += nalsize;
994
        }
995
        // Now store right nal length size, that will be use to parse all other nals
996
        h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
997
    } else {
998
        h->is_avc = 0;
999
        if(decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
1000
            return -1;
1001
    }
1002
    return 0;
1003
}
1004

    
1005
av_cold int ff_h264_decode_init(AVCodecContext *avctx){
1006
    H264Context *h= avctx->priv_data;
1007
    MpegEncContext * const s = &h->s;
1008

    
1009
    MPV_decode_defaults(s);
1010

    
1011
    s->avctx = avctx;
1012
    common_init(h);
1013

    
1014
    s->out_format = FMT_H264;
1015
    s->workaround_bugs= avctx->workaround_bugs;
1016

    
1017
    // set defaults
1018
//    s->decode_mb= ff_h263_decode_mb;
1019
    s->quarter_sample = 1;
1020
    if(!avctx->has_b_frames)
1021
    s->low_delay= 1;
1022

    
1023
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1024

    
1025
    ff_h264_decode_init_vlc();
1026

    
1027
    h->thread_context[0] = h;
1028
    h->outputed_poc = h->next_outputed_poc = INT_MIN;
1029
    h->prev_poc_msb= 1<<16;
1030
    h->x264_build = -1;
1031
    ff_h264_reset_sei(h);
1032
    if(avctx->codec_id == CODEC_ID_H264){
1033
        if(avctx->ticks_per_frame == 1){
1034
            s->avctx->time_base.den *=2;
1035
        }
1036
        avctx->ticks_per_frame = 2;
1037
    }
1038

    
1039
    if(avctx->extradata_size > 0 && avctx->extradata &&
1040
        ff_h264_decode_extradata(h))
1041
        return -1;
1042

    
1043
    if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1044
        s->avctx->has_b_frames = h->sps.num_reorder_frames;
1045
        s->low_delay = 0;
1046
    }
1047

    
1048
    return 0;
1049
}
1050

    
1051
static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
1052
{
1053
    int i;
1054

    
1055
    for (i=0; i<count; i++){
1056
        to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1057
    }
1058
}
1059

    
1060
static void copy_parameter_set(void **to, void **from, int count, int size)
1061
{
1062
    int i;
1063

    
1064
    for (i=0; i<count; i++){
1065
        if (to[i] && !from[i]) av_freep(&to[i]);
1066
        else if (from[i] && !to[i]) to[i] = av_malloc(size);
1067

    
1068
        if (from[i]) memcpy(to[i], from[i], size);
1069
    }
1070
}
1071

    
1072
static int decode_init_thread_copy(AVCodecContext *avctx){
1073
    H264Context *h= avctx->priv_data;
1074

    
1075
    if (!avctx->is_copy) return 0;
1076
    memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1077
    memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1078

    
1079
    return 0;
1080
}
1081

    
1082
#define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
1083
static int decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src){
1084
    H264Context *h= dst->priv_data, *h1= src->priv_data;
1085
    MpegEncContext * const s = &h->s, * const s1 = &h1->s;
1086
    int inited = s->context_initialized, err;
1087
    int i;
1088

    
1089
    if(dst == src || !s1->context_initialized) return 0;
1090

    
1091
    err = ff_mpeg_update_thread_context(dst, src);
1092
    if(err) return err;
1093

    
1094
    //FIXME handle width/height changing
1095
    if(!inited){
1096
        for(i = 0; i < MAX_SPS_COUNT; i++)
1097
            av_freep(h->sps_buffers + i);
1098

    
1099
        for(i = 0; i < MAX_PPS_COUNT; i++)
1100
            av_freep(h->pps_buffers + i);
1101

    
1102
        memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
1103
        memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1104
        memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1105
        ff_h264_alloc_tables(h);
1106
        context_init(h);
1107

    
1108
        for(i=0; i<2; i++){
1109
            h->rbsp_buffer[i] = NULL;
1110
            h->rbsp_buffer_size[i] = 0;
1111
        }
1112

    
1113
        h->thread_context[0] = h;
1114

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

    
1119
        s->dsp.clear_blocks(h->mb);
1120
    }
1121

    
1122
    //extradata/NAL handling
1123
    h->is_avc          = h1->is_avc;
1124

    
1125
    //SPS/PPS
1126
    copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
1127
    h->sps             = h1->sps;
1128
    copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
1129
    h->pps             = h1->pps;
1130

    
1131
    //Dequantization matrices
1132
    //FIXME these are big - can they be only copied when PPS changes?
1133
    copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1134

    
1135
    for(i=0; i<6; i++)
1136
        h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1137

    
1138
    for(i=0; i<2; i++)
1139
        h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1140

    
1141
    h->dequant_coeff_pps = h1->dequant_coeff_pps;
1142

    
1143
    //POC timing
1144
    copy_fields(h, h1, poc_lsb, redundant_pic_count);
1145

    
1146
    //reference lists
1147
    copy_fields(h, h1, ref_count, intra_gb);
1148
    copy_fields(h, h1, short_ref, cabac_init_idc);
1149

    
1150
    copy_picture_range(h->short_ref,   h1->short_ref,   32, s, s1);
1151
    copy_picture_range(h->long_ref,    h1->long_ref,    32,  s, s1);
1152
    copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
1153

    
1154
    h->last_slice_type = h1->last_slice_type;
1155

    
1156
    if(!s->current_picture_ptr) return 0;
1157

    
1158
    if(!s->dropable) {
1159
        ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1160
        h->prev_poc_msb     = h->poc_msb;
1161
        h->prev_poc_lsb     = h->poc_lsb;
1162
    }
1163
    h->prev_frame_num_offset= h->frame_num_offset;
1164
    h->prev_frame_num       = h->frame_num;
1165
    h->outputed_poc         = h->next_outputed_poc;
1166

    
1167
    return 0;
1168
}
1169

    
1170
int ff_h264_frame_start(H264Context *h){
1171
    MpegEncContext * const s = &h->s;
1172
    int i;
1173

    
1174
    if(MPV_frame_start(s, s->avctx) < 0)
1175
        return -1;
1176
    ff_er_frame_start(s);
1177
    /*
1178
     * MPV_frame_start uses pict_type to derive key_frame.
1179
     * This is incorrect for H.264; IDR markings must be used.
1180
     * Zero here; IDR markings per slice in frame or fields are ORed in later.
1181
     * See decode_nal_units().
1182
     */
1183
    s->current_picture_ptr->key_frame= 0;
1184
    s->current_picture_ptr->mmco_reset= 0;
1185

    
1186
    assert(s->linesize && s->uvlinesize);
1187

    
1188
    for(i=0; i<16; i++){
1189
        h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
1190
        h->block_offset[24+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
1191
    }
1192
    for(i=0; i<4; i++){
1193
        h->block_offset[16+i]=
1194
        h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1195
        h->block_offset[24+16+i]=
1196
        h->block_offset[24+20+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1197
    }
1198

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

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

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

    
1210
    // We mark the current picture as non-reference after allocating it, so
1211
    // that if we break out due to an error it can be released automatically
1212
    // in the next MPV_frame_start().
1213
    // SVQ3 as well as most other codecs have only last/next/current and thus
1214
    // get released even with set reference, besides SVQ3 and others do not
1215
    // mark frames as reference later "naturally".
1216
    if(s->codec_id != CODEC_ID_SVQ3)
1217
        s->current_picture_ptr->reference= 0;
1218

    
1219
    s->current_picture_ptr->field_poc[0]=
1220
    s->current_picture_ptr->field_poc[1]= INT_MAX;
1221

    
1222
    h->next_output_pic = NULL;
1223

    
1224
    assert(s->current_picture_ptr->long_ref==0);
1225

    
1226
    return 0;
1227
}
1228

    
1229
/**
1230
  * Run setup operations that must be run after slice header decoding.
1231
  * This includes finding the next displayed frame.
1232
  *
1233
  * @param h h264 master context
1234
  */
1235
static void decode_postinit(H264Context *h){
1236
    MpegEncContext * const s = &h->s;
1237
    Picture *out = s->current_picture_ptr;
1238
    Picture *cur = s->current_picture_ptr;
1239
    int i, pics, out_of_order, out_idx;
1240

    
1241
    s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
1242
    s->current_picture_ptr->pict_type= s->pict_type;
1243

    
1244
    if (h->next_output_pic) return;
1245

    
1246
    if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
1247
        //FIXME this allows the next thread to start once we encounter the first field of a PAFF packet
1248
        //This works if the next packet contains the second field. It does not work if both fields are
1249
        //in the same packet.
1250
        //ff_thread_finish_setup(s->avctx);
1251
        return;
1252
    }
1253

    
1254
    cur->interlaced_frame = 0;
1255
    cur->repeat_pict = 0;
1256

    
1257
    /* Signal interlacing information externally. */
1258
    /* Prioritize picture timing SEI information over used decoding process if it exists. */
1259

    
1260
    if(h->sps.pic_struct_present_flag){
1261
        switch (h->sei_pic_struct)
1262
        {
1263
        case SEI_PIC_STRUCT_FRAME:
1264
            break;
1265
        case SEI_PIC_STRUCT_TOP_FIELD:
1266
        case SEI_PIC_STRUCT_BOTTOM_FIELD:
1267
            cur->interlaced_frame = 1;
1268
            break;
1269
        case SEI_PIC_STRUCT_TOP_BOTTOM:
1270
        case SEI_PIC_STRUCT_BOTTOM_TOP:
1271
            if (FIELD_OR_MBAFF_PICTURE)
1272
                cur->interlaced_frame = 1;
1273
            else
1274
                // try to flag soft telecine progressive
1275
                cur->interlaced_frame = h->prev_interlaced_frame;
1276
            break;
1277
        case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1278
        case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1279
            // Signal the possibility of telecined film externally (pic_struct 5,6)
1280
            // From these hints, let the applications decide if they apply deinterlacing.
1281
            cur->repeat_pict = 1;
1282
            break;
1283
        case SEI_PIC_STRUCT_FRAME_DOUBLING:
1284
            // Force progressive here, as doubling interlaced frame is a bad idea.
1285
            cur->repeat_pict = 2;
1286
            break;
1287
        case SEI_PIC_STRUCT_FRAME_TRIPLING:
1288
            cur->repeat_pict = 4;
1289
            break;
1290
        }
1291

    
1292
        if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1293
            cur->interlaced_frame = (h->sei_ct_type & (1<<1)) != 0;
1294
    }else{
1295
        /* Derive interlacing flag from used decoding process. */
1296
        cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1297
    }
1298
    h->prev_interlaced_frame = cur->interlaced_frame;
1299

    
1300
    if (cur->field_poc[0] != cur->field_poc[1]){
1301
        /* Derive top_field_first from field pocs. */
1302
        cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
1303
    }else{
1304
        if(cur->interlaced_frame || h->sps.pic_struct_present_flag){
1305
            /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
1306
            if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
1307
              || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1308
                cur->top_field_first = 1;
1309
            else
1310
                cur->top_field_first = 0;
1311
        }else{
1312
            /* Most likely progressive */
1313
            cur->top_field_first = 0;
1314
        }
1315
    }
1316

    
1317
    //FIXME do something with unavailable reference frames
1318

    
1319
    /* Sort B-frames into display order */
1320

    
1321
    if(h->sps.bitstream_restriction_flag
1322
       && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1323
        s->avctx->has_b_frames = h->sps.num_reorder_frames;
1324
        s->low_delay = 0;
1325
    }
1326

    
1327
    if(   s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
1328
       && !h->sps.bitstream_restriction_flag){
1329
        s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;
1330
        s->low_delay= 0;
1331
    }
1332

    
1333
    pics = 0;
1334
    while(h->delayed_pic[pics]) pics++;
1335

    
1336
    assert(pics <= MAX_DELAYED_PIC_COUNT);
1337

    
1338
    h->delayed_pic[pics++] = cur;
1339
    if(cur->reference == 0)
1340
        cur->reference = DELAYED_PIC_REF;
1341

    
1342
    out = h->delayed_pic[0];
1343
    out_idx = 0;
1344
    for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
1345
        if(h->delayed_pic[i]->poc < out->poc){
1346
            out = h->delayed_pic[i];
1347
            out_idx = i;
1348
        }
1349
    if(s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset))
1350
        h->next_outputed_poc= INT_MIN;
1351
    out_of_order = out->poc < h->next_outputed_poc;
1352

    
1353
    if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
1354
        { }
1355
    else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)
1356
       || (s->low_delay &&
1357
        ((h->next_outputed_poc != INT_MIN && out->poc > h->next_outputed_poc + 2)
1358
         || cur->pict_type == FF_B_TYPE)))
1359
    {
1360
        s->low_delay = 0;
1361
        s->avctx->has_b_frames++;
1362
    }
1363

    
1364
    if(out_of_order || pics > s->avctx->has_b_frames){
1365
        out->reference &= ~DELAYED_PIC_REF;
1366
        for(i=out_idx; h->delayed_pic[i]; i++)
1367
            h->delayed_pic[i] = h->delayed_pic[i+1];
1368
    }
1369
    if(!out_of_order && pics > s->avctx->has_b_frames){
1370
        h->next_output_pic = out;
1371
        if(out_idx==0 && h->delayed_pic[0] && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset)) {
1372
            h->next_outputed_poc = INT_MIN;
1373
        } else
1374
            h->next_outputed_poc = out->poc;
1375
    }else{
1376
        av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
1377
    }
1378

    
1379
    ff_thread_finish_setup(s->avctx);
1380
}
1381

    
1382
static inline void backup_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int simple){
1383
    MpegEncContext * const s = &h->s;
1384
    uint8_t *top_border;
1385
    int top_idx = 1;
1386

    
1387
    src_y  -=   linesize;
1388
    src_cb -= uvlinesize;
1389
    src_cr -= uvlinesize;
1390

    
1391
    if(!simple && FRAME_MBAFF){
1392
        if(s->mb_y&1){
1393
            if(!MB_MBAFF){
1394
                top_border = h->top_borders[0][s->mb_x];
1395
                AV_COPY128(top_border, src_y + 15*linesize);
1396
                if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1397
                    AV_COPY64(top_border+16, src_cb+7*uvlinesize);
1398
                    AV_COPY64(top_border+24, src_cr+7*uvlinesize);
1399
                }
1400
            }
1401
        }else if(MB_MBAFF){
1402
            top_idx = 0;
1403
        }else
1404
            return;
1405
    }
1406

    
1407
    top_border = h->top_borders[top_idx][s->mb_x];
1408
    // There are two lines saved, the line above the the top macroblock of a pair,
1409
    // and the line above the bottom macroblock
1410
    AV_COPY128(top_border, src_y + 16*linesize);
1411

    
1412
    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1413
        AV_COPY64(top_border+16, src_cb+8*uvlinesize);
1414
        AV_COPY64(top_border+24, src_cr+8*uvlinesize);
1415
    }
1416
}
1417

    
1418
static inline void xchg_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg, int simple){
1419
    MpegEncContext * const s = &h->s;
1420
    int deblock_left;
1421
    int deblock_top;
1422
    int top_idx = 1;
1423
    uint8_t *top_border_m1;
1424
    uint8_t *top_border;
1425

    
1426
    if(!simple && FRAME_MBAFF){
1427
        if(s->mb_y&1){
1428
            if(!MB_MBAFF)
1429
                return;
1430
        }else{
1431
            top_idx = MB_MBAFF ? 0 : 1;
1432
        }
1433
    }
1434

    
1435
    if(h->deblocking_filter == 2) {
1436
        deblock_left = h->left_type[0];
1437
        deblock_top  = h->top_type;
1438
    } else {
1439
        deblock_left = (s->mb_x > 0);
1440
        deblock_top =  (s->mb_y > !!MB_FIELD);
1441
    }
1442

    
1443
    src_y  -=   linesize + 1;
1444
    src_cb -= uvlinesize + 1;
1445
    src_cr -= uvlinesize + 1;
1446

    
1447
    top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1448
    top_border    = h->top_borders[top_idx][s->mb_x];
1449

    
1450
#define XCHG(a,b,xchg)\
1451
if (xchg) AV_SWAP64(b,a);\
1452
else      AV_COPY64(b,a);
1453

    
1454
    if(deblock_top){
1455
        if(deblock_left){
1456
            XCHG(top_border_m1+8, src_y -7, 1);
1457
        }
1458
        XCHG(top_border+0, src_y +1, xchg);
1459
        XCHG(top_border+8, src_y +9, 1);
1460
        if(s->mb_x+1 < s->mb_width){
1461
            XCHG(h->top_borders[top_idx][s->mb_x+1], src_y +17, 1);
1462
        }
1463
    }
1464

    
1465
    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1466
        if(deblock_top){
1467
            if(deblock_left){
1468
                XCHG(top_border_m1+16, src_cb -7, 1);
1469
                XCHG(top_border_m1+24, src_cr -7, 1);
1470
            }
1471
            XCHG(top_border+16, src_cb+1, 1);
1472
            XCHG(top_border+24, src_cr+1, 1);
1473
        }
1474
    }
1475
}
1476

    
1477
static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
1478
    MpegEncContext * const s = &h->s;
1479
    const int mb_x= s->mb_x;
1480
    const int mb_y= s->mb_y;
1481
    const int mb_xy= h->mb_xy;
1482
    const int mb_type= s->current_picture.mb_type[mb_xy];
1483
    uint8_t  *dest_y, *dest_cb, *dest_cr;
1484
    int linesize, uvlinesize /*dct_offset*/;
1485
    int i;
1486
    int *block_offset = &h->block_offset[0];
1487
    const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
1488
    /* is_h264 should always be true if SVQ3 is disabled. */
1489
    const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
1490
    void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1491
    void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1492

    
1493
    dest_y  = s->current_picture.data[0] + (mb_x + mb_y * s->linesize  ) * 16;
1494
    dest_cb = s->current_picture.data[1] + (mb_x + mb_y * s->uvlinesize) * 8;
1495
    dest_cr = s->current_picture.data[2] + (mb_x + mb_y * s->uvlinesize) * 8;
1496

    
1497
    s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + 64, s->linesize, 4);
1498
    s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + 64, dest_cr - dest_cb, 2);
1499

    
1500
    h->list_counts[mb_xy]= h->list_count;
1501

    
1502
    if (!simple && MB_FIELD) {
1503
        linesize   = h->mb_linesize   = s->linesize * 2;
1504
        uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
1505
        block_offset = &h->block_offset[24];
1506
        if(mb_y&1){ //FIXME move out of this function?
1507
            dest_y -= s->linesize*15;
1508
            dest_cb-= s->uvlinesize*7;
1509
            dest_cr-= s->uvlinesize*7;
1510
        }
1511
        if(FRAME_MBAFF) {
1512
            int list;
1513
            for(list=0; list<h->list_count; list++){
1514
                if(!USES_LIST(mb_type, list))
1515
                    continue;
1516
                if(IS_16X16(mb_type)){
1517
                    int8_t *ref = &h->ref_cache[list][scan8[0]];
1518
                    fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
1519
                }else{
1520
                    for(i=0; i<16; i+=4){
1521
                        int ref = h->ref_cache[list][scan8[i]];
1522
                        if(ref >= 0)
1523
                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
1524
                    }
1525
                }
1526
            }
1527
        }
1528
    } else {
1529
        linesize   = h->mb_linesize   = s->linesize;
1530
        uvlinesize = h->mb_uvlinesize = s->uvlinesize;
1531
//        dct_offset = s->linesize * 16;
1532
    }
1533

    
1534
    if (!simple && IS_INTRA_PCM(mb_type)) {
1535
        for (i=0; i<16; i++) {
1536
            memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
1537
        }
1538
        for (i=0; i<8; i++) {
1539
            memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4,  8);
1540
            memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4,  8);
1541
        }
1542
    } else {
1543
        if(IS_INTRA(mb_type)){
1544
            if(h->deblocking_filter)
1545
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
1546

    
1547
            if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1548
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
1549
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
1550
            }
1551

    
1552
            if(IS_INTRA4x4(mb_type)){
1553
                if(simple || !s->encoding){
1554
                    if(IS_8x8DCT(mb_type)){
1555
                        if(transform_bypass){
1556
                            idct_dc_add =
1557
                            idct_add    = s->dsp.add_pixels8;
1558
                        }else{
1559
                            idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1560
                            idct_add    = h->h264dsp.h264_idct8_add;
1561
                        }
1562
                        for(i=0; i<16; i+=4){
1563
                            uint8_t * const ptr= dest_y + block_offset[i];
1564
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1565
                            if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1566
                                h->hpc.pred8x8l_add[dir](ptr, h->mb + i*16, linesize);
1567
                            }else{
1568
                                const int nnz = h->non_zero_count_cache[ scan8[i] ];
1569
                                h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
1570
                                                            (h->topright_samples_available<<i)&0x4000, linesize);
1571
                                if(nnz){
1572
                                    if(nnz == 1 && h->mb[i*16])
1573
                                        idct_dc_add(ptr, h->mb + i*16, linesize);
1574
                                    else
1575
                                        idct_add   (ptr, h->mb + i*16, linesize);
1576
                                }
1577
                            }
1578
                        }
1579
                    }else{
1580
                        if(transform_bypass){
1581
                            idct_dc_add =
1582
                            idct_add    = s->dsp.add_pixels4;
1583
                        }else{
1584
                            idct_dc_add = h->h264dsp.h264_idct_dc_add;
1585
                            idct_add    = h->h264dsp.h264_idct_add;
1586
                        }
1587
                        for(i=0; i<16; i++){
1588
                            uint8_t * const ptr= dest_y + block_offset[i];
1589
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1590

    
1591
                            if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1592
                                h->hpc.pred4x4_add[dir](ptr, h->mb + i*16, linesize);
1593
                            }else{
1594
                                uint8_t *topright;
1595
                                int nnz, tr;
1596
                                if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
1597
                                    const int topright_avail= (h->topright_samples_available<<i)&0x8000;
1598
                                    assert(mb_y || linesize <= block_offset[i]);
1599
                                    if(!topright_avail){
1600
                                        tr= ptr[3 - linesize]*0x01010101;
1601
                                        topright= (uint8_t*) &tr;
1602
                                    }else
1603
                                        topright= ptr + 4 - linesize;
1604
                                }else
1605
                                    topright= NULL;
1606

    
1607
                                h->hpc.pred4x4[ dir ](ptr, topright, linesize);
1608
                                nnz = h->non_zero_count_cache[ scan8[i] ];
1609
                                if(nnz){
1610
                                    if(is_h264){
1611
                                        if(nnz == 1 && h->mb[i*16])
1612
                                            idct_dc_add(ptr, h->mb + i*16, linesize);
1613
                                        else
1614
                                            idct_add   (ptr, h->mb + i*16, linesize);
1615
                                    }
1616
#if CONFIG_SVQ3_DECODER
1617
                                    else
1618
                                        ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
1619
#endif
1620
                                }
1621
                            }
1622
                        }
1623
                    }
1624
                }
1625
            }else{
1626
                h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
1627
                if(is_h264){
1628
                    if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX] ]){
1629
                        if(!transform_bypass)
1630
                            h->h264dsp.h264_luma_dc_dequant_idct(h->mb, h->mb_luma_dc, h->dequant4_coeff[0][s->qscale][0]);
1631
                        else{
1632
                            static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
1633
                                                                    8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
1634
                            for(i = 0; i < 16; i++)
1635
                                h->mb[dc_mapping[i]] = h->mb_luma_dc[i];
1636
                        }
1637
                    }
1638
                }
1639
#if CONFIG_SVQ3_DECODER
1640
                else
1641
                    ff_svq3_luma_dc_dequant_idct_c(h->mb, h->mb_luma_dc, s->qscale);
1642
#endif
1643
            }
1644
            if(h->deblocking_filter)
1645
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
1646
        }else if(is_h264){
1647
            hl_motion(h, dest_y, dest_cb, dest_cr,
1648
                      s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
1649
                      s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
1650
                      h->h264dsp.weight_h264_pixels_tab, h->h264dsp.biweight_h264_pixels_tab);
1651
        }
1652

    
1653

    
1654
        if(!IS_INTRA4x4(mb_type)){
1655
            if(is_h264){
1656
                if(IS_INTRA16x16(mb_type)){
1657
                    if(transform_bypass){
1658
                        if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
1659
                            h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb, linesize);
1660
                        }else{
1661
                            for(i=0; i<16; i++){
1662
                                if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16])
1663
                                    s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + i*16, linesize);
1664
                            }
1665
                        }
1666
                    }else{
1667
                         h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1668
                    }
1669
                }else if(h->cbp&15){
1670
                    if(transform_bypass){
1671
                        const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1672
                        idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
1673
                        for(i=0; i<16; i+=di){
1674
                            if(h->non_zero_count_cache[ scan8[i] ]){
1675
                                idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
1676
                            }
1677
                        }
1678
                    }else{
1679
                        if(IS_8x8DCT(mb_type)){
1680
                            h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1681
                        }else{
1682
                            h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1683
                        }
1684
                    }
1685
                }
1686
            }
1687
#if CONFIG_SVQ3_DECODER
1688
            else{
1689
                for(i=0; i<16; i++){
1690
                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
1691
                        uint8_t * const ptr= dest_y + block_offset[i];
1692
                        ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1693
                    }
1694
                }
1695
            }
1696
#endif
1697
        }
1698

    
1699
        if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
1700
            uint8_t *dest[2] = {dest_cb, dest_cr};
1701
            if(transform_bypass){
1702
                if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
1703
                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + 16*16, uvlinesize);
1704
                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 20, h->mb + 20*16, uvlinesize);
1705
                }else{
1706
                    idct_add = s->dsp.add_pixels4;
1707
                    for(i=16; i<16+8; i++){
1708
                        if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16])
1709
                            idct_add   (dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
1710
                    }
1711
                }
1712
            }else{
1713
                if(is_h264){
1714
                    if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
1715
                        chroma_dc_dequant_idct_c(h->mb + 16*16     , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
1716
                    if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
1717
                        chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
1718
                    h->h264dsp.h264_idct_add8(dest, block_offset,
1719
                                              h->mb, uvlinesize,
1720
                                              h->non_zero_count_cache);
1721
                }
1722
#if CONFIG_SVQ3_DECODER
1723
                else{
1724
                    chroma_dc_dequant_idct_c(h->mb + 16*16     , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
1725
                    chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
1726
                    for(i=16; i<16+8; i++){
1727
                        if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
1728
                            uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
1729
                            ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[s->qscale + 12] - 12, 2);
1730
                        }
1731
                    }
1732
                }
1733
#endif
1734
            }
1735
        }
1736
    }
1737
    if(h->cbp || IS_INTRA(mb_type))
1738
        s->dsp.clear_blocks(h->mb);
1739
}
1740

    
1741
/**
1742
 * Process a macroblock; this case avoids checks for expensive uncommon cases.
1743
 */
1744
static void hl_decode_mb_simple(H264Context *h){
1745
    hl_decode_mb_internal(h, 1);
1746
}
1747

    
1748
/**
1749
 * Process a macroblock; this handles edge cases, such as interlacing.
1750
 */
1751
static void av_noinline hl_decode_mb_complex(H264Context *h){
1752
    hl_decode_mb_internal(h, 0);
1753
}
1754

    
1755
void ff_h264_hl_decode_mb(H264Context *h){
1756
    MpegEncContext * const s = &h->s;
1757
    const int mb_xy= h->mb_xy;
1758
    const int mb_type= s->current_picture.mb_type[mb_xy];
1759
    int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
1760

    
1761
    if (is_complex)
1762
        hl_decode_mb_complex(h);
1763
    else hl_decode_mb_simple(h);
1764
}
1765

    
1766
static int pred_weight_table(H264Context *h){
1767
    MpegEncContext * const s = &h->s;
1768
    int list, i;
1769
    int luma_def, chroma_def;
1770

    
1771
    h->use_weight= 0;
1772
    h->use_weight_chroma= 0;
1773
    h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
1774
    if(CHROMA)
1775
        h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
1776
    luma_def = 1<<h->luma_log2_weight_denom;
1777
    chroma_def = 1<<h->chroma_log2_weight_denom;
1778

    
1779
    for(list=0; list<2; list++){
1780
        h->luma_weight_flag[list]   = 0;
1781
        h->chroma_weight_flag[list] = 0;
1782
        for(i=0; i<h->ref_count[list]; i++){
1783
            int luma_weight_flag, chroma_weight_flag;
1784

    
1785
            luma_weight_flag= get_bits1(&s->gb);
1786
            if(luma_weight_flag){
1787
                h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
1788
                h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
1789
                if(   h->luma_weight[i][list][0] != luma_def
1790
                   || h->luma_weight[i][list][1] != 0) {
1791
                    h->use_weight= 1;
1792
                    h->luma_weight_flag[list]= 1;
1793
                }
1794
            }else{
1795
                h->luma_weight[i][list][0]= luma_def;
1796
                h->luma_weight[i][list][1]= 0;
1797
            }
1798

    
1799
            if(CHROMA){
1800
                chroma_weight_flag= get_bits1(&s->gb);
1801
                if(chroma_weight_flag){
1802
                    int j;
1803
                    for(j=0; j<2; j++){
1804
                        h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
1805
                        h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
1806
                        if(   h->chroma_weight[i][list][j][0] != chroma_def
1807
                           || h->chroma_weight[i][list][j][1] != 0) {
1808
                            h->use_weight_chroma= 1;
1809
                            h->chroma_weight_flag[list]= 1;
1810
                        }
1811
                    }
1812
                }else{
1813
                    int j;
1814
                    for(j=0; j<2; j++){
1815
                        h->chroma_weight[i][list][j][0]= chroma_def;
1816
                        h->chroma_weight[i][list][j][1]= 0;
1817
                    }
1818
                }
1819
            }
1820
        }
1821
        if(h->slice_type_nos != FF_B_TYPE) break;
1822
    }
1823
    h->use_weight= h->use_weight || h->use_weight_chroma;
1824
    return 0;
1825
}
1826

    
1827
/**
1828
 * Initialize implicit_weight table.
1829
 * @param field  0/1 initialize the weight for interlaced MBAFF
1830
 *                -1 initializes the rest
1831
 */
1832
static void implicit_weight_table(H264Context *h, int field){
1833
    MpegEncContext * const s = &h->s;
1834
    int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
1835

    
1836
    for (i = 0; i < 2; i++) {
1837
        h->luma_weight_flag[i]   = 0;
1838
        h->chroma_weight_flag[i] = 0;
1839
    }
1840

    
1841
    if(field < 0){
1842
        cur_poc = s->current_picture_ptr->poc;
1843
    if(   h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
1844
       && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
1845
        h->use_weight= 0;
1846
        h->use_weight_chroma= 0;
1847
        return;
1848
    }
1849
        ref_start= 0;
1850
        ref_count0= h->ref_count[0];
1851
        ref_count1= h->ref_count[1];
1852
    }else{
1853
        cur_poc = s->current_picture_ptr->field_poc[field];
1854
        ref_start= 16;
1855
        ref_count0= 16+2*h->ref_count[0];
1856
        ref_count1= 16+2*h->ref_count[1];
1857
    }
1858

    
1859
    h->use_weight= 2;
1860
    h->use_weight_chroma= 2;
1861
    h->luma_log2_weight_denom= 5;
1862
    h->chroma_log2_weight_denom= 5;
1863

    
1864
    for(ref0=ref_start; ref0 < ref_count0; ref0++){
1865
        int poc0 = h->ref_list[0][ref0].poc;
1866
        for(ref1=ref_start; ref1 < ref_count1; ref1++){
1867
            int poc1 = h->ref_list[1][ref1].poc;
1868
            int td = av_clip(poc1 - poc0, -128, 127);
1869
            int w= 32;
1870
            if(td){
1871
                int tb = av_clip(cur_poc - poc0, -128, 127);
1872
                int tx = (16384 + (FFABS(td) >> 1)) / td;
1873
                int dist_scale_factor = (tb*tx + 32) >> 8;
1874
                if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
1875
                    w = 64 - dist_scale_factor;
1876
            }
1877
            if(field<0){
1878
                h->implicit_weight[ref0][ref1][0]=
1879
                h->implicit_weight[ref0][ref1][1]= w;
1880
            }else{
1881
                h->implicit_weight[ref0][ref1][field]=w;
1882
            }
1883
        }
1884
    }
1885
}
1886

    
1887
/**
1888
 * instantaneous decoder refresh.
1889
 */
1890
static void idr(H264Context *h){
1891
    ff_h264_remove_all_refs(h);
1892
    h->prev_frame_num= 0;
1893
    h->prev_frame_num_offset= 0;
1894
    h->prev_poc_msb=
1895
    h->prev_poc_lsb= 0;
1896
}
1897

    
1898
/* forget old pics after a seek */
1899
static void flush_dpb(AVCodecContext *avctx){
1900
    H264Context *h= avctx->priv_data;
1901
    int i;
1902
    for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
1903
        if(h->delayed_pic[i])
1904
            h->delayed_pic[i]->reference= 0;
1905
        h->delayed_pic[i]= NULL;
1906
    }
1907
    h->outputed_poc=h->next_outputed_poc= INT_MIN;
1908
    h->prev_interlaced_frame = 1;
1909
    idr(h);
1910
    if(h->s.current_picture_ptr)
1911
        h->s.current_picture_ptr->reference= 0;
1912
    h->s.first_field= 0;
1913
    ff_h264_reset_sei(h);
1914
    ff_mpeg_flush(avctx);
1915
}
1916

    
1917
static int init_poc(H264Context *h){
1918
    MpegEncContext * const s = &h->s;
1919
    const int max_frame_num= 1<<h->sps.log2_max_frame_num;
1920
    int field_poc[2];
1921
    Picture *cur = s->current_picture_ptr;
1922

    
1923
    h->frame_num_offset= h->prev_frame_num_offset;
1924
    if(h->frame_num < h->prev_frame_num)
1925
        h->frame_num_offset += max_frame_num;
1926

    
1927
    if(h->sps.poc_type==0){
1928
        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
1929

    
1930
        if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
1931
            h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1932
        else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
1933
            h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1934
        else
1935
            h->poc_msb = h->prev_poc_msb;
1936
//printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
1937
        field_poc[0] =
1938
        field_poc[1] = h->poc_msb + h->poc_lsb;
1939
        if(s->picture_structure == PICT_FRAME)
1940
            field_poc[1] += h->delta_poc_bottom;
1941
    }else if(h->sps.poc_type==1){
1942
        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1943
        int i;
1944

    
1945
        if(h->sps.poc_cycle_length != 0)
1946
            abs_frame_num = h->frame_num_offset + h->frame_num;
1947
        else
1948
            abs_frame_num = 0;
1949

    
1950
        if(h->nal_ref_idc==0 && abs_frame_num > 0)
1951
            abs_frame_num--;
1952

    
1953
        expected_delta_per_poc_cycle = 0;
1954
        for(i=0; i < h->sps.poc_cycle_length; i++)
1955
            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
1956

    
1957
        if(abs_frame_num > 0){
1958
            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1959
            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1960

    
1961
            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1962
            for(i = 0; i <= frame_num_in_poc_cycle; i++)
1963
                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
1964
        } else
1965
            expectedpoc = 0;
1966

    
1967
        if(h->nal_ref_idc == 0)
1968
            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1969

    
1970
        field_poc[0] = expectedpoc + h->delta_poc[0];
1971
        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1972

    
1973
        if(s->picture_structure == PICT_FRAME)
1974
            field_poc[1] += h->delta_poc[1];
1975
    }else{
1976
        int poc= 2*(h->frame_num_offset + h->frame_num);
1977

    
1978
        if(!h->nal_ref_idc)
1979
            poc--;
1980

    
1981
        field_poc[0]= poc;
1982
        field_poc[1]= poc;
1983
    }
1984

    
1985
    if(s->picture_structure != PICT_BOTTOM_FIELD)
1986
        s->current_picture_ptr->field_poc[0]= field_poc[0];
1987
    if(s->picture_structure != PICT_TOP_FIELD)
1988
        s->current_picture_ptr->field_poc[1]= field_poc[1];
1989
    cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
1990

    
1991
    return 0;
1992
}
1993

    
1994

    
1995
/**
1996
 * initialize scan tables
1997
 */
1998
static void init_scan_tables(H264Context *h){
1999
    int i;
2000
    for(i=0; i<16; i++){
2001
#define T(x) (x>>2) | ((x<<2) & 0xF)
2002
        h->zigzag_scan[i] = T(zigzag_scan[i]);
2003
        h-> field_scan[i] = T( field_scan[i]);
2004
#undef T
2005
    }
2006
    for(i=0; i<64; i++){
2007
#define T(x) (x>>3) | ((x&7)<<3)
2008
        h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
2009
        h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2010
        h->field_scan8x8[i]        = T(field_scan8x8[i]);
2011
        h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
2012
#undef T
2013
    }
2014
    if(h->sps.transform_bypass){ //FIXME same ugly
2015
        h->zigzag_scan_q0          = zigzag_scan;
2016
        h->zigzag_scan8x8_q0       = ff_zigzag_direct;
2017
        h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2018
        h->field_scan_q0           = field_scan;
2019
        h->field_scan8x8_q0        = field_scan8x8;
2020
        h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
2021
    }else{
2022
        h->zigzag_scan_q0          = h->zigzag_scan;
2023
        h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
2024
        h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2025
        h->field_scan_q0           = h->field_scan;
2026
        h->field_scan8x8_q0        = h->field_scan8x8;
2027
        h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
2028
    }
2029
}
2030

    
2031
static void field_end(H264Context *h, int in_setup){
2032
    MpegEncContext * const s = &h->s;
2033
    AVCodecContext * const avctx= s->avctx;
2034
    s->mb_y= 0;
2035

    
2036
    if (!in_setup && !s->dropable)
2037
        ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
2038
                                 s->picture_structure==PICT_BOTTOM_FIELD);
2039

    
2040
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2041
        ff_vdpau_h264_set_reference_frames(s);
2042

    
2043
    if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
2044
        if(!s->dropable) {
2045
            ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2046
            h->prev_poc_msb= h->poc_msb;
2047
            h->prev_poc_lsb= h->poc_lsb;
2048
        }
2049
        h->prev_frame_num_offset= h->frame_num_offset;
2050
        h->prev_frame_num= h->frame_num;
2051
        h->outputed_poc = h->next_outputed_poc;
2052
    }
2053

    
2054
    if (avctx->hwaccel) {
2055
        if (avctx->hwaccel->end_frame(avctx) < 0)
2056
            av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
2057
    }
2058

    
2059
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2060
        ff_vdpau_h264_picture_complete(s);
2061

    
2062
    /*
2063
     * FIXME: Error handling code does not seem to support interlaced
2064
     * when slices span multiple rows
2065
     * The ff_er_add_slice calls don't work right for bottom
2066
     * fields; they cause massive erroneous error concealing
2067
     * Error marking covers both fields (top and bottom).
2068
     * This causes a mismatched s->error_count
2069
     * and a bad error table. Further, the error count goes to
2070
     * INT_MAX when called for bottom field, because mb_y is
2071
     * past end by one (callers fault) and resync_mb_y != 0
2072
     * causes problems for the first MB line, too.
2073
     */
2074
    if (!FIELD_PICTURE)
2075
        ff_er_frame_end(s);
2076

    
2077
    MPV_frame_end(s);
2078

    
2079
    h->current_slice=0;
2080
}
2081

    
2082
/**
2083
 * Replicate H264 "master" context to thread contexts.
2084
 */
2085
static void clone_slice(H264Context *dst, H264Context *src)
2086
{
2087
    memcpy(dst->block_offset,     src->block_offset, sizeof(dst->block_offset));
2088
    dst->s.current_picture_ptr  = src->s.current_picture_ptr;
2089
    dst->s.current_picture      = src->s.current_picture;
2090
    dst->s.linesize             = src->s.linesize;
2091
    dst->s.uvlinesize           = src->s.uvlinesize;
2092
    dst->s.first_field          = src->s.first_field;
2093

    
2094
    dst->prev_poc_msb           = src->prev_poc_msb;
2095
    dst->prev_poc_lsb           = src->prev_poc_lsb;
2096
    dst->prev_frame_num_offset  = src->prev_frame_num_offset;
2097
    dst->prev_frame_num         = src->prev_frame_num;
2098
    dst->short_ref_count        = src->short_ref_count;
2099

    
2100
    memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
2101
    memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
2102
    memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2103
    memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
2104

    
2105
    memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
2106
    memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
2107
}
2108

    
2109
/**
2110
 * computes profile from profile_idc and constraint_set?_flags
2111
 *
2112
 * @param sps SPS
2113
 *
2114
 * @return profile as defined by FF_PROFILE_H264_*
2115
 */
2116
int ff_h264_get_profile(SPS *sps)
2117
{
2118
    int profile = sps->profile_idc;
2119

    
2120
    switch(sps->profile_idc) {
2121
    case FF_PROFILE_H264_BASELINE:
2122
        // constraint_set1_flag set to 1
2123
        profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2124
        break;
2125
    case FF_PROFILE_H264_HIGH_10:
2126
    case FF_PROFILE_H264_HIGH_422:
2127
    case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2128
        // constraint_set3_flag set to 1
2129
        profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
2130
        break;
2131
    }
2132

    
2133
    return profile;
2134
}
2135

    
2136
/**
2137
 * decodes a slice header.
2138
 * This will also call MPV_common_init() and frame_start() as needed.
2139
 *
2140
 * @param h h264context
2141
 * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
2142
 *
2143
 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2144
 */
2145
static int decode_slice_header(H264Context *h, H264Context *h0){
2146
    MpegEncContext * const s = &h->s;
2147
    MpegEncContext * const s0 = &h0->s;
2148
    unsigned int first_mb_in_slice;
2149
    unsigned int pps_id;
2150
    int num_ref_idx_active_override_flag;
2151
    unsigned int slice_type, tmp, i, j;
2152
    int default_ref_list_done = 0;
2153
    int last_pic_structure;
2154

    
2155
    s->dropable= h->nal_ref_idc == 0;
2156

    
2157
    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
2158
        s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
2159
        s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
2160
    }else{
2161
        s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
2162
        s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
2163
    }
2164

    
2165
    first_mb_in_slice= get_ue_golomb(&s->gb);
2166

    
2167
    if(first_mb_in_slice == 0){ //FIXME better field boundary detection
2168
        if(h0->current_slice && FIELD_PICTURE){
2169
            field_end(h, 1);
2170
        }
2171

    
2172
        h0->current_slice = 0;
2173
        if (!s0->first_field)
2174
            s->current_picture_ptr= NULL;
2175
    }
2176

    
2177
    slice_type= get_ue_golomb_31(&s->gb);
2178
    if(slice_type > 9){
2179
        av_log(h->s.avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", h->slice_type, s->mb_x, s->mb_y);
2180
        return -1;
2181
    }
2182
    if(slice_type > 4){
2183
        slice_type -= 5;
2184
        h->slice_type_fixed=1;
2185
    }else
2186
        h->slice_type_fixed=0;
2187

    
2188
    slice_type= golomb_to_pict_type[ slice_type ];
2189
    if (slice_type == FF_I_TYPE
2190
        || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
2191
        default_ref_list_done = 1;
2192
    }
2193
    h->slice_type= slice_type;
2194
    h->slice_type_nos= slice_type & 3;
2195

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

    
2198
    pps_id= get_ue_golomb(&s->gb);
2199
    if(pps_id>=MAX_PPS_COUNT){
2200
        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2201
        return -1;
2202
    }
2203
    if(!h0->pps_buffers[pps_id]) {
2204
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
2205
        return -1;
2206
    }
2207
    h->pps= *h0->pps_buffers[pps_id];
2208

    
2209
    if(!h0->sps_buffers[h->pps.sps_id]) {
2210
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
2211
        return -1;
2212
    }
2213
    h->sps = *h0->sps_buffers[h->pps.sps_id];
2214

    
2215
    s->avctx->profile = ff_h264_get_profile(&h->sps);
2216
    s->avctx->level   = h->sps.level_idc;
2217
    s->avctx->refs    = h->sps.ref_frame_count;
2218

    
2219
    if(h == h0 && h->dequant_coeff_pps != pps_id){
2220
        h->dequant_coeff_pps = pps_id;
2221
        init_dequant_tables(h);
2222
    }
2223

    
2224
    s->mb_width= h->sps.mb_width;
2225
    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2226

    
2227
    h->b_stride=  s->mb_width*4;
2228

    
2229
    s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
2230
    if(h->sps.frame_mbs_only_flag)
2231
        s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
2232
    else
2233
        s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 7);
2234

    
2235
    if (s->context_initialized
2236
        && (   s->width != s->avctx->width || s->height != s->avctx->height
2237
            || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2238
        if(h != h0) {
2239
            av_log_missing_feature(s->avctx, "Width/height changing with threads is", 0);
2240
            return -1;   // width / height changed during parallelized decoding
2241
        }
2242
        free_tables(h, 0);
2243
        flush_dpb(s->avctx);
2244
        MPV_common_end(s);
2245
    }
2246
    if (!s->context_initialized) {
2247
        if(h != h0){
2248
            av_log(h->s.avctx, AV_LOG_ERROR, "we cant (re-)initialize context during parallel decoding\n");
2249
            return -1;
2250
        }
2251

    
2252
        avcodec_set_dimensions(s->avctx, s->width, s->height);
2253
        s->avctx->sample_aspect_ratio= h->sps.sar;
2254
        av_assert0(s->avctx->sample_aspect_ratio.den);
2255

    
2256
        if(h->sps.video_signal_type_present_flag){
2257
            s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2258
            if(h->sps.colour_description_present_flag){
2259
                s->avctx->color_primaries = h->sps.color_primaries;
2260
                s->avctx->color_trc       = h->sps.color_trc;
2261
                s->avctx->colorspace      = h->sps.colorspace;
2262
            }
2263
        }
2264

    
2265
        if(h->sps.timing_info_present_flag){
2266
            int64_t den= h->sps.time_scale;
2267
            if(h->x264_build < 44U)
2268
                den *= 2;
2269
            av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2270
                      h->sps.num_units_in_tick, den, 1<<30);
2271
        }
2272
        s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2273
                                                 s->avctx->codec->pix_fmts ?
2274
                                                 s->avctx->codec->pix_fmts :
2275
                                                 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2276
                                                 hwaccel_pixfmt_list_h264_jpeg_420 :
2277
                                                 ff_hwaccel_pixfmt_list_420);
2278
        s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2279

    
2280
        if (MPV_common_init(s) < 0){
2281
            av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed\n");
2282
            return -1;
2283
        }
2284
        s->first_field = 0;
2285
        h->prev_interlaced_frame = 1;
2286

    
2287
        init_scan_tables(h);
2288
        ff_h264_alloc_tables(h);
2289

    
2290
        if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
2291
            if (context_init(h) < 0){
2292
                av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
2293
                return -1;
2294
            }
2295
        } else {
2296
            for(i = 1; i < s->avctx->thread_count; i++) {
2297
                H264Context *c;
2298
                c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2299
                memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2300
                memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2301
                c->h264dsp = h->h264dsp;
2302
                c->sps = h->sps;
2303
                c->pps = h->pps;
2304
                init_scan_tables(c);
2305
                clone_tables(c, h, i);
2306
            }
2307

    
2308
            for(i = 0; i < s->avctx->thread_count; i++)
2309
                if(context_init(h->thread_context[i]) < 0){
2310
                    av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
2311
                    return -1;
2312
                }
2313
        }
2314
    }
2315

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

    
2318
    h->mb_mbaff = 0;
2319
    h->mb_aff_frame = 0;
2320
    last_pic_structure = s0->picture_structure;
2321
    if(h->sps.frame_mbs_only_flag){
2322
        s->picture_structure= PICT_FRAME;
2323
    }else{
2324
        if(get_bits1(&s->gb)) { //field_pic_flag
2325
            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
2326
        } else {
2327
            s->picture_structure= PICT_FRAME;
2328
            h->mb_aff_frame = h->sps.mb_aff;
2329
        }
2330
    }
2331
    h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
2332

    
2333
    if(h0->current_slice == 0){
2334
        if(h->frame_num != h->prev_frame_num &&
2335
          (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num) < (h->frame_num - h->sps.ref_frame_count))
2336
            h->prev_frame_num = h->frame_num - h->sps.ref_frame_count - 1;
2337

    
2338
        while(h->frame_num !=  h->prev_frame_num &&
2339
              h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
2340
            Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2341
            av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
2342
            if (ff_h264_frame_start(h) < 0)
2343
                return -1;
2344
            h->prev_frame_num++;
2345
            h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
2346
            s->current_picture_ptr->frame_num= h->prev_frame_num;
2347
            ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
2348
            ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
2349
            ff_generate_sliding_window_mmcos(h);
2350
            ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2351
            /* Error concealment: if a ref is missing, copy the previous ref in its place.
2352
             * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2353
             * about there being no actual duplicates.
2354
             * FIXME: this doesn't copy padding for out-of-frame motion vectors.  Given we're
2355
             * concealing a lost frame, this probably isn't noticable by comparison, but it should
2356
             * be fixed. */
2357
            if (h->short_ref_count) {
2358
                if (prev) {
2359
                    av_image_copy(h->short_ref[0]->data, h->short_ref[0]->linesize,
2360
                                  (const uint8_t**)prev->data, prev->linesize,
2361
                                  s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
2362
                    h->short_ref[0]->poc = prev->poc+2;
2363
                }
2364
                h->short_ref[0]->frame_num = h->prev_frame_num;
2365
            }
2366
        }
2367

    
2368
        /* See if we have a decoded first field looking for a pair... */
2369
        if (s0->first_field) {
2370
            assert(s0->current_picture_ptr);
2371
            assert(s0->current_picture_ptr->data[0]);
2372
            assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
2373

    
2374
            /* figure out if we have a complementary field pair */
2375
            if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2376
                /*
2377
                 * Previous field is unmatched. Don't display it, but let it
2378
                 * remain for reference if marked as such.
2379
                 */
2380
                s0->current_picture_ptr = NULL;
2381
                s0->first_field = FIELD_PICTURE;
2382

    
2383
            } else {
2384
                if (h->nal_ref_idc &&
2385
                        s0->current_picture_ptr->reference &&
2386
                        s0->current_picture_ptr->frame_num != h->frame_num) {
2387
                    /*
2388
                     * This and previous field were reference, but had
2389
                     * different frame_nums. Consider this field first in
2390
                     * pair. Throw away previous field except for reference
2391
                     * purposes.
2392
                     */
2393
                    s0->first_field = 1;
2394
                    s0->current_picture_ptr = NULL;
2395

    
2396
                } else {
2397
                    /* Second field in complementary pair */
2398
                    s0->first_field = 0;
2399
                }
2400
            }
2401

    
2402
        } else {
2403
            /* Frame or first field in a potentially complementary pair */
2404
            assert(!s0->current_picture_ptr);
2405
            s0->first_field = FIELD_PICTURE;
2406
        }
2407

    
2408
        if((!FIELD_PICTURE || s0->first_field) && ff_h264_frame_start(h) < 0) {
2409
            s0->first_field = 0;
2410
            return -1;
2411
        }
2412
    }
2413
    if(h != h0)
2414
        clone_slice(h, h0);
2415

    
2416
    s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2417

    
2418
    assert(s->mb_num == s->mb_width * s->mb_height);
2419
    if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2420
       first_mb_in_slice                    >= s->mb_num){
2421
        av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2422
        return -1;
2423
    }
2424
    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2425
    s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2426
    if (s->picture_structure == PICT_BOTTOM_FIELD)
2427
        s->resync_mb_y = s->mb_y = s->mb_y + 1;
2428
    assert(s->mb_y < s->mb_height);
2429

    
2430
    if(s->picture_structure==PICT_FRAME){
2431
        h->curr_pic_num=   h->frame_num;
2432
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
2433
    }else{
2434
        h->curr_pic_num= 2*h->frame_num + 1;
2435
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
2436
    }
2437

    
2438
    if(h->nal_unit_type == NAL_IDR_SLICE){
2439
        get_ue_golomb(&s->gb); /* idr_pic_id */
2440
    }
2441

    
2442
    if(h->sps.poc_type==0){
2443
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2444

    
2445
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
2446
            h->delta_poc_bottom= get_se_golomb(&s->gb);
2447
        }
2448
    }
2449

    
2450
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
2451
        h->delta_poc[0]= get_se_golomb(&s->gb);
2452

    
2453
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
2454
            h->delta_poc[1]= get_se_golomb(&s->gb);
2455
    }
2456

    
2457
    init_poc(h);
2458

    
2459
    if(h->pps.redundant_pic_cnt_present){
2460
        h->redundant_pic_count= get_ue_golomb(&s->gb);
2461
    }
2462

    
2463
    //set defaults, might be overridden a few lines later
2464
    h->ref_count[0]= h->pps.ref_count[0];
2465
    h->ref_count[1]= h->pps.ref_count[1];
2466

    
2467
    if(h->slice_type_nos != FF_I_TYPE){
2468
        if(h->slice_type_nos == FF_B_TYPE){
2469
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
2470
        }
2471
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
2472

    
2473
        if(num_ref_idx_active_override_flag){
2474
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
2475
            if(h->slice_type_nos==FF_B_TYPE)
2476
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
2477

    
2478
            if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
2479
                av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
2480
                h->ref_count[0]= h->ref_count[1]= 1;
2481
                return -1;
2482
            }
2483
        }
2484
        if(h->slice_type_nos == FF_B_TYPE)
2485
            h->list_count= 2;
2486
        else
2487
            h->list_count= 1;
2488
    }else
2489
        h->list_count= 0;
2490

    
2491
    if(!default_ref_list_done){
2492
        ff_h264_fill_default_ref_list(h);
2493
    }
2494

    
2495
    if(h->slice_type_nos!=FF_I_TYPE && ff_h264_decode_ref_pic_list_reordering(h) < 0)
2496
        return -1;
2497

    
2498
    if(h->slice_type_nos!=FF_I_TYPE){
2499
        s->last_picture_ptr= &h->ref_list[0][0];
2500
        ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2501
    }
2502
    if(h->slice_type_nos==FF_B_TYPE){
2503
        s->next_picture_ptr= &h->ref_list[1][0];
2504
        ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2505
    }
2506

    
2507
    if(   (h->pps.weighted_pred          && h->slice_type_nos == FF_P_TYPE )
2508
       ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
2509
        pred_weight_table(h);
2510
    else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2511
        implicit_weight_table(h, -1);
2512
    }else {
2513
        h->use_weight = 0;
2514
        for (i = 0; i < 2; i++) {
2515
            h->luma_weight_flag[i]   = 0;
2516
            h->chroma_weight_flag[i] = 0;
2517
        }
2518
    }
2519

    
2520
    if(h->nal_ref_idc)
2521
        ff_h264_decode_ref_pic_marking(h0, &s->gb);
2522

    
2523
    if(FRAME_MBAFF){
2524
        ff_h264_fill_mbaff_ref_list(h);
2525

    
2526
        if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2527
            implicit_weight_table(h, 0);
2528
            implicit_weight_table(h, 1);
2529
        }
2530
    }
2531

    
2532
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2533
        ff_h264_direct_dist_scale_factor(h);
2534
    ff_h264_direct_ref_list_init(h);
2535

    
2536
    if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
2537
        tmp = get_ue_golomb_31(&s->gb);
2538
        if(tmp > 2){
2539
            av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2540
            return -1;
2541
        }
2542
        h->cabac_init_idc= tmp;
2543
    }
2544

    
2545
    h->last_qscale_diff = 0;
2546
    tmp = h->pps.init_qp + get_se_golomb(&s->gb);
2547
    if(tmp>51){
2548
        av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
2549
        return -1;
2550
    }
2551
    s->qscale= tmp;
2552
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2553
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2554
    //FIXME qscale / qp ... stuff
2555
    if(h->slice_type == FF_SP_TYPE){
2556
        get_bits1(&s->gb); /* sp_for_switch_flag */
2557
    }
2558
    if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
2559
        get_se_golomb(&s->gb); /* slice_qs_delta */
2560
    }
2561

    
2562
    h->deblocking_filter = 1;
2563
    h->slice_alpha_c0_offset = 52;
2564
    h->slice_beta_offset = 52;
2565
    if( h->pps.deblocking_filter_parameters_present ) {
2566
        tmp= get_ue_golomb_31(&s->gb);
2567
        if(tmp > 2){
2568
            av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
2569
            return -1;
2570
        }
2571
        h->deblocking_filter= tmp;
2572
        if(h->deblocking_filter < 2)
2573
            h->deblocking_filter^= 1; // 1<->0
2574

    
2575
        if( h->deblocking_filter ) {
2576
            h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
2577
            h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
2578
            if(   h->slice_alpha_c0_offset > 104U
2579
               || h->slice_beta_offset     > 104U){
2580
                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);
2581
                return -1;
2582
            }
2583
        }
2584
    }
2585

    
2586
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
2587
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
2588
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
2589
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
2590
        h->deblocking_filter= 0;
2591

    
2592
    if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
2593
        if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
2594
            /* Cheat slightly for speed:
2595
               Do not bother to deblock across slices. */
2596
            h->deblocking_filter = 2;
2597
        } else {
2598
            h0->max_contexts = 1;
2599
            if(!h0->single_decode_warning) {
2600
                av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
2601
                h0->single_decode_warning = 1;
2602
            }
2603
            if(h != h0){
2604
                av_log(h->s.avctx, AV_LOG_ERROR, "deblocking switched inside frame\n");
2605
                return 1;
2606
            }
2607
        }
2608
    }
2609
    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]);
2610

    
2611
#if 0 //FMO
2612
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
2613
        slice_group_change_cycle= get_bits(&s->gb, ?);
2614
#endif
2615

    
2616
    h0->last_slice_type = slice_type;
2617
    h->slice_num = ++h0->current_slice;
2618
    if(h->slice_num >= MAX_SLICES){
2619
        av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
2620
    }
2621

    
2622
    for(j=0; j<2; j++){
2623
        int id_list[16];
2624
        int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
2625
        for(i=0; i<16; i++){
2626
            id_list[i]= 60;
2627
            if(h->ref_list[j][i].data[0]){
2628
                int k;
2629
                uint8_t *base= h->ref_list[j][i].base[0];
2630
                for(k=0; k<h->short_ref_count; k++)
2631
                    if(h->short_ref[k]->base[0] == base){
2632
                        id_list[i]= k;
2633
                        break;
2634
                    }
2635
                for(k=0; k<h->long_ref_count; k++)
2636
                    if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
2637
                        id_list[i]= h->short_ref_count + k;
2638
                        break;
2639
                    }
2640
            }
2641
        }
2642

    
2643
        ref2frm[0]=
2644
        ref2frm[1]= -1;
2645
        for(i=0; i<16; i++)
2646
            ref2frm[i+2]= 4*id_list[i]
2647
                          +(h->ref_list[j][i].reference&3);
2648
        ref2frm[18+0]=
2649
        ref2frm[18+1]= -1;
2650
        for(i=16; i<48; i++)
2651
            ref2frm[i+4]= 4*id_list[(i-16)>>1]
2652
                          +(h->ref_list[j][i].reference&3);
2653
    }
2654

    
2655
    //FIXME: fix draw_edges+PAFF+frame threads
2656
    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;
2657
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
2658

    
2659
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2660
        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",
2661
               h->slice_num,
2662
               (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
2663
               first_mb_in_slice,
2664
               av_get_pict_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
2665
               pps_id, h->frame_num,
2666
               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
2667
               h->ref_count[0], h->ref_count[1],
2668
               s->qscale,
2669
               h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
2670
               h->use_weight,
2671
               h->use_weight==1 && h->use_weight_chroma ? "c" : "",
2672
               h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
2673
               );
2674
    }
2675

    
2676
    return 0;
2677
}
2678

    
2679
int ff_h264_get_slice_type(const H264Context *h)
2680
{
2681
    switch (h->slice_type) {
2682
    case FF_P_TYPE:  return 0;
2683
    case FF_B_TYPE:  return 1;
2684
    case FF_I_TYPE:  return 2;
2685
    case FF_SP_TYPE: return 3;
2686
    case FF_SI_TYPE: return 4;
2687
    default:         return -1;
2688
    }
2689
}
2690

    
2691
/**
2692
 *
2693
 * @return non zero if the loop filter can be skiped
2694
 */
2695
static int fill_filter_caches(H264Context *h, int mb_type){
2696
    MpegEncContext * const s = &h->s;
2697
    const int mb_xy= h->mb_xy;
2698
    int top_xy, left_xy[2];
2699
    int top_type, left_type[2];
2700

    
2701
    top_xy     = mb_xy  - (s->mb_stride << MB_FIELD);
2702

    
2703
    //FIXME deblocking could skip the intra and nnz parts.
2704

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

    
2708
    left_xy[1] = left_xy[0] = mb_xy-1;
2709
    if(FRAME_MBAFF){
2710
        const int left_mb_field_flag     = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);
2711
        const int curr_mb_field_flag     = IS_INTERLACED(mb_type);
2712
        if(s->mb_y&1){
2713
            if (left_mb_field_flag != curr_mb_field_flag) {
2714
                left_xy[0] -= s->mb_stride;
2715
            }
2716
        }else{
2717
            if(curr_mb_field_flag){
2718
                top_xy      += s->mb_stride & (((s->current_picture.mb_type[top_xy    ]>>7)&1)-1);
2719
            }
2720
            if (left_mb_field_flag != curr_mb_field_flag) {
2721
                left_xy[1] += s->mb_stride;
2722
            }
2723
        }
2724
    }
2725

    
2726
    h->top_mb_xy = top_xy;
2727
    h->left_mb_xy[0] = left_xy[0];
2728
    h->left_mb_xy[1] = left_xy[1];
2729
    {
2730
        //for sufficiently low qp, filtering wouldn't do anything
2731
        //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
2732
        int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
2733
        int qp = s->current_picture.qscale_table[mb_xy];
2734
        if(qp <= qp_thresh
2735
           && (left_xy[0]<0 || ((qp + s->current_picture.qscale_table[left_xy[0]] + 1)>>1) <= qp_thresh)
2736
           && (top_xy   < 0 || ((qp + s->current_picture.qscale_table[top_xy    ] + 1)>>1) <= qp_thresh)){
2737
            if(!FRAME_MBAFF)
2738
                return 1;
2739
            if(   (left_xy[0]< 0            || ((qp + s->current_picture.qscale_table[left_xy[1]             ] + 1)>>1) <= qp_thresh)
2740
               && (top_xy    < s->mb_stride || ((qp + s->current_picture.qscale_table[top_xy    -s->mb_stride] + 1)>>1) <= qp_thresh))
2741
                return 1;
2742
        }
2743
    }
2744

    
2745
    top_type     = s->current_picture.mb_type[top_xy]    ;
2746
    left_type[0] = s->current_picture.mb_type[left_xy[0]];
2747
    left_type[1] = s->current_picture.mb_type[left_xy[1]];
2748
    if(h->deblocking_filter == 2){
2749
        if(h->slice_table[top_xy     ] != h->slice_num) top_type= 0;
2750
        if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
2751
    }else{
2752
        if(h->slice_table[top_xy     ] == 0xFFFF) top_type= 0;
2753
        if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
2754
    }
2755
    h->top_type    = top_type    ;
2756
    h->left_type[0]= left_type[0];
2757
    h->left_type[1]= left_type[1];
2758

    
2759
    if(IS_INTRA(mb_type))
2760
        return 0;
2761

    
2762
    AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
2763
    AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
2764
    AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
2765
    AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
2766
    AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
2767

    
2768
    h->cbp= h->cbp_table[mb_xy];
2769

    
2770
    {
2771
        int list;
2772
        for(list=0; list<h->list_count; list++){
2773
            int8_t *ref;
2774
            int y, b_stride;
2775
            int16_t (*mv_dst)[2];
2776
            int16_t (*mv_src)[2];
2777

    
2778
            if(!USES_LIST(mb_type, list)){
2779
                fill_rectangle(  h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
2780
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2781
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2782
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2783
                AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2784
                continue;
2785
            }
2786

    
2787
            ref = &s->current_picture.ref_index[list][4*mb_xy];
2788
            {
2789
                int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2790
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2791
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2792
                ref += 2;
2793
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2794
                AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2795
            }
2796

    
2797
            b_stride = h->b_stride;
2798
            mv_dst   = &h->mv_cache[list][scan8[0]];
2799
            mv_src   = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
2800
            for(y=0; y<4; y++){
2801
                AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
2802
            }
2803

    
2804
        }
2805
    }
2806

    
2807

    
2808
/*
2809
0 . T T. T T T T
2810
1 L . .L . . . .
2811
2 L . .L . . . .
2812
3 . T TL . . . .
2813
4 L . .L . . . .
2814
5 L . .. . . . .
2815
*/
2816
//FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
2817
    if(top_type){
2818
        AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][4+3*8]);
2819
    }
2820

    
2821
    if(left_type[0]){
2822
        h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
2823
        h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
2824
        h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
2825
        h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
2826
    }
2827

    
2828
    // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
2829
    if(!CABAC && h->pps.transform_8x8_mode){
2830
        if(IS_8x8DCT(top_type)){
2831
            h->non_zero_count_cache[4+8*0]=
2832
            h->non_zero_count_cache[5+8*0]= h->cbp_table[top_xy] & 4;
2833
            h->non_zero_count_cache[6+8*0]=
2834
            h->non_zero_count_cache[7+8*0]= h->cbp_table[top_xy] & 8;
2835
        }
2836
        if(IS_8x8DCT(left_type[0])){
2837
            h->non_zero_count_cache[3+8*1]=
2838
            h->non_zero_count_cache[3+8*2]= h->cbp_table[left_xy[0]]&2; //FIXME check MBAFF
2839
        }
2840
        if(IS_8x8DCT(left_type[1])){
2841
            h->non_zero_count_cache[3+8*3]=
2842
            h->non_zero_count_cache[3+8*4]= h->cbp_table[left_xy[1]]&8; //FIXME check MBAFF
2843
        }
2844

    
2845
        if(IS_8x8DCT(mb_type)){
2846
            h->non_zero_count_cache[scan8[0   ]]= h->non_zero_count_cache[scan8[1   ]]=
2847
            h->non_zero_count_cache[scan8[2   ]]= h->non_zero_count_cache[scan8[3   ]]= h->cbp & 1;
2848

    
2849
            h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
2850
            h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
2851

    
2852
            h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
2853
            h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp & 4;
2854

    
2855
            h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
2856
            h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
2857
        }
2858
    }
2859

    
2860
    if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
2861
        int list;
2862
        for(list=0; list<h->list_count; list++){
2863
            if(USES_LIST(top_type, list)){
2864
                const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
2865
                const int b8_xy= 4*top_xy + 2;
2866
                int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2867
                AV_COPY128(h->mv_cache[list][scan8[0] + 0 - 1*8], s->current_picture.motion_val[list][b_xy + 0]);
2868
                h->ref_cache[list][scan8[0] + 0 - 1*8]=
2869
                h->ref_cache[list][scan8[0] + 1 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 0]];
2870
                h->ref_cache[list][scan8[0] + 2 - 1*8]=
2871
                h->ref_cache[list][scan8[0] + 3 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 1]];
2872
            }else{
2873
                AV_ZERO128(h->mv_cache[list][scan8[0] + 0 - 1*8]);
2874
                AV_WN32A(&h->ref_cache[list][scan8[0] + 0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2875
            }
2876

    
2877
            if(!IS_INTERLACED(mb_type^left_type[0])){
2878
                if(USES_LIST(left_type[0], list)){
2879
                    const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
2880
                    const int b8_xy= 4*left_xy[0] + 1;
2881
                    int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[0]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2882
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 0 ], s->current_picture.motion_val[list][b_xy + h->b_stride*0]);
2883
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 8 ], s->current_picture.motion_val[list][b_xy + h->b_stride*1]);
2884
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +16 ], s->current_picture.motion_val[list][b_xy + h->b_stride*2]);
2885
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +24 ], s->current_picture.motion_val[list][b_xy + h->b_stride*3]);
2886
                    h->ref_cache[list][scan8[0] - 1 + 0 ]=
2887
                    h->ref_cache[list][scan8[0] - 1 + 8 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*0]];
2888
                    h->ref_cache[list][scan8[0] - 1 +16 ]=
2889
                    h->ref_cache[list][scan8[0] - 1 +24 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*1]];
2890
                }else{
2891
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 0 ]);
2892
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 8 ]);
2893
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +16 ]);
2894
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +24 ]);
2895
                    h->ref_cache[list][scan8[0] - 1 + 0  ]=
2896
                    h->ref_cache[list][scan8[0] - 1 + 8  ]=
2897
                    h->ref_cache[list][scan8[0] - 1 + 16 ]=
2898
                    h->ref_cache[list][scan8[0] - 1 + 24 ]= LIST_NOT_USED;
2899
                }
2900
            }
2901
        }
2902
    }
2903

    
2904
    return 0;
2905
}
2906

    
2907
static void loop_filter(H264Context *h){
2908
    MpegEncContext * const s = &h->s;
2909
    uint8_t  *dest_y, *dest_cb, *dest_cr;
2910
    int linesize, uvlinesize, mb_x, mb_y;
2911
    const int end_mb_y= s->mb_y + FRAME_MBAFF;
2912
    const int old_slice_type= h->slice_type;
2913
    const int end_mb_x  = s->mb_x;
2914

    
2915
    if(h->deblocking_filter) {
2916
        int start_x= s->resync_mb_y == s->mb_y ? s->resync_mb_x : 0;
2917
        for(mb_x= start_x; mb_x<end_mb_x; mb_x++){
2918
            for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
2919
                int mb_xy, mb_type;
2920
                mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
2921
                h->slice_num= h->slice_table[mb_xy];
2922
                mb_type= s->current_picture.mb_type[mb_xy];
2923
                h->list_count= h->list_counts[mb_xy];
2924

    
2925
                if(FRAME_MBAFF)
2926
                    h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2927

    
2928
                s->mb_x= mb_x;
2929
                s->mb_y= mb_y;
2930
                dest_y  = s->current_picture.data[0] + (mb_x + mb_y * s->linesize  ) * 16;
2931
                dest_cb = s->current_picture.data[1] + (mb_x + mb_y * s->uvlinesize) * 8;
2932
                dest_cr = s->current_picture.data[2] + (mb_x + mb_y * s->uvlinesize) * 8;
2933
                    //FIXME simplify above
2934

    
2935
                if (MB_FIELD) {
2936
                    linesize   = h->mb_linesize   = s->linesize * 2;
2937
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2938
                    if(mb_y&1){ //FIXME move out of this function?
2939
                        dest_y -= s->linesize*15;
2940
                        dest_cb-= s->uvlinesize*7;
2941
                        dest_cr-= s->uvlinesize*7;
2942
                    }
2943
                } else {
2944
                    linesize   = h->mb_linesize   = s->linesize;
2945
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize;
2946
                }
2947
                backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
2948
                if(fill_filter_caches(h, mb_type))
2949
                    continue;
2950
                h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2951
                h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2952

    
2953
                if (FRAME_MBAFF) {
2954
                    ff_h264_filter_mb     (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2955
                } else {
2956
                    ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2957
                }
2958
            }
2959
        }
2960
    }
2961
    h->slice_type= old_slice_type;
2962
    s->mb_x= end_mb_x;
2963
    s->mb_y= end_mb_y - FRAME_MBAFF;
2964
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2965
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2966
}
2967

    
2968
static void predict_field_decoding_flag(H264Context *h){
2969
    MpegEncContext * const s = &h->s;
2970
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
2971
    int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
2972
                ? s->current_picture.mb_type[mb_xy-1]
2973
                : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
2974
                ? s->current_picture.mb_type[mb_xy-s->mb_stride]
2975
                : 0;
2976
    h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
2977
}
2978

    
2979
/**
2980
 * Draw edges and report progress for the last MB row.
2981
 */
2982
static void decode_finish_row(H264Context *h){
2983
    MpegEncContext * const s = &h->s;
2984
    int top = 16*(s->mb_y >> FIELD_PICTURE);
2985
    int height = 16 << FRAME_MBAFF;
2986
    int deblock_border = (16 + 4) << FRAME_MBAFF;
2987
    int pic_height = 16*s->mb_height >> FIELD_PICTURE;
2988

    
2989
    if (h->deblocking_filter) {
2990
        if((top + height) >= pic_height)
2991
            height += deblock_border;
2992

    
2993
        top -= deblock_border;
2994
    }
2995

    
2996
    if (top >= pic_height || (top + height) < h->emu_edge_height)
2997
        return;
2998

    
2999
    height = FFMIN(height, pic_height - top);
3000
    if (top < h->emu_edge_height) {
3001
        height = top+height;
3002
        top = 0;
3003
    }
3004

    
3005
    ff_draw_horiz_band(s, top, height);
3006

    
3007
    if (s->dropable) return;
3008

    
3009
    ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
3010
                             s->picture_structure==PICT_BOTTOM_FIELD);
3011
}
3012

    
3013
static int decode_slice(struct AVCodecContext *avctx, void *arg){
3014
    H264Context *h = *(void**)arg;
3015
    MpegEncContext * const s = &h->s;
3016
    const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
3017

    
3018
    s->mb_skip_run= -1;
3019

    
3020
    h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
3021
                    (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
3022

    
3023
    if( h->pps.cabac ) {
3024
        /* realign */
3025
        align_get_bits( &s->gb );
3026

    
3027
        /* init cabac */
3028
        ff_init_cabac_states( &h->cabac);
3029
        ff_init_cabac_decoder( &h->cabac,
3030
                               s->gb.buffer + get_bits_count(&s->gb)/8,
3031
                               (get_bits_left(&s->gb) + 7)/8);
3032

    
3033
        ff_h264_init_cabac_states(h);
3034

    
3035
        for(;;){
3036
//START_TIMER
3037
            int ret = ff_h264_decode_mb_cabac(h);
3038
            int eos;
3039
//STOP_TIMER("decode_mb_cabac")
3040

    
3041
            if(ret>=0) ff_h264_hl_decode_mb(h);
3042

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

    
3046
                ret = ff_h264_decode_mb_cabac(h);
3047

    
3048
                if(ret>=0) ff_h264_hl_decode_mb(h);
3049
                s->mb_y--;
3050
            }
3051
            eos = get_cabac_terminate( &h->cabac );
3052

    
3053
            if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
3054
                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);
3055
                return 0;
3056
            }
3057
            if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3058
                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);
3059
                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);
3060
                return -1;
3061
            }
3062

    
3063
            if( ++s->mb_x >= s->mb_width ) {
3064
                loop_filter(h);
3065
                s->mb_x = 0;
3066
                decode_finish_row(h);
3067
                ++s->mb_y;
3068
                if(FIELD_OR_MBAFF_PICTURE) {
3069
                    ++s->mb_y;
3070
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
3071
                        predict_field_decoding_flag(h);
3072
                }
3073
            }
3074

    
3075
            if( eos || s->mb_y >= s->mb_height ) {
3076
                if(s->mb_x)
3077
                    loop_filter(h);
3078
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3079
                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);
3080
                return 0;
3081
            }
3082
        }
3083

    
3084
    } else {
3085
        for(;;){
3086
            int ret = ff_h264_decode_mb_cavlc(h);
3087

    
3088
            if(ret>=0) ff_h264_hl_decode_mb(h);
3089

    
3090
            if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
3091
                s->mb_y++;
3092
                ret = ff_h264_decode_mb_cavlc(h);
3093

    
3094
                if(ret>=0) ff_h264_hl_decode_mb(h);
3095
                s->mb_y--;
3096
            }
3097

    
3098
            if(ret<0){
3099
                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3100
                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);
3101

    
3102
                return -1;
3103
            }
3104

    
3105
            if(++s->mb_x >= s->mb_width){
3106
                loop_filter(h);
3107
                s->mb_x=0;
3108
                decode_finish_row(h);
3109
                ++s->mb_y;
3110
                if(FIELD_OR_MBAFF_PICTURE) {
3111
                    ++s->mb_y;
3112
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
3113
                        predict_field_decoding_flag(h);
3114
                }
3115
                if(s->mb_y >= s->mb_height){
3116
                    tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3117

    
3118
                    if(   get_bits_count(&s->gb) == s->gb.size_in_bits
3119
                       || get_bits_count(&s->gb) <  s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
3120
                        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);
3121

    
3122
                        return 0;
3123
                    }else{
3124
                        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);
3125

    
3126
                        return -1;
3127
                    }
3128
                }
3129
            }
3130

    
3131
            if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
3132
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3133
                if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
3134
                    if(s->mb_x)
3135
                        loop_filter(h);
3136
                    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);
3137

    
3138
                    return 0;
3139
                }else{
3140
                    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);
3141

    
3142
                    return -1;
3143
                }
3144
            }
3145
        }
3146
    }
3147

    
3148
#if 0
3149
    for(;s->mb_y < s->mb_height; s->mb_y++){
3150
        for(;s->mb_x < s->mb_width; s->mb_x++){
3151
            int ret= decode_mb(h);
3152

3153
            ff_h264_hl_decode_mb(h);
3154

3155
            if(ret<0){
3156
                av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3157
                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);
3158

3159
                return -1;
3160
            }
3161

3162
            if(++s->mb_x >= s->mb_width){
3163
                s->mb_x=0;
3164
                if(++s->mb_y >= s->mb_height){
3165
                    if(get_bits_count(s->gb) == s->gb.size_in_bits){
3166
                        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);
3167

3168
                        return 0;
3169
                    }else{
3170
                        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);
3171

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

3177
            if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
3178
                if(get_bits_count(s->gb) == s->gb.size_in_bits){
3179
                    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);
3180

3181
                    return 0;
3182
                }else{
3183
                    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);
3184

3185
                    return -1;
3186
                }
3187
            }
3188
        }
3189
        s->mb_x=0;
3190
        ff_draw_horiz_band(s, 16*s->mb_y, 16);
3191
    }
3192
#endif
3193
    return -1; //not reached
3194
}
3195

    
3196
/**
3197
 * Call decode_slice() for each context.
3198
 *
3199
 * @param h h264 master context
3200
 * @param context_count number of contexts to execute
3201
 */
3202
static void execute_decode_slices(H264Context *h, int context_count){
3203
    MpegEncContext * const s = &h->s;
3204
    AVCodecContext * const avctx= s->avctx;
3205
    H264Context *hx;
3206
    int i;
3207

    
3208
    if (s->avctx->hwaccel)
3209
        return;
3210
    if(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3211
        return;
3212
    if(context_count == 1) {
3213
        decode_slice(avctx, &h);
3214
    } else {
3215
        for(i = 1; i < context_count; i++) {
3216
            hx = h->thread_context[i];
3217
            hx->s.error_recognition = avctx->error_recognition;
3218
            hx->s.error_count = 0;
3219
            hx->x264_build= h->x264_build;
3220
        }
3221

    
3222
        avctx->execute(avctx, (void *)decode_slice,
3223
                       h->thread_context, NULL, context_count, sizeof(void*));
3224

    
3225
        /* pull back stuff from slices to master context */
3226
        hx = h->thread_context[context_count - 1];
3227
        s->mb_x = hx->s.mb_x;
3228
        s->mb_y = hx->s.mb_y;
3229
        s->dropable = hx->s.dropable;
3230
        s->picture_structure = hx->s.picture_structure;
3231
        for(i = 1; i < context_count; i++)
3232
            h->s.error_count += h->thread_context[i]->s.error_count;
3233
    }
3234
}
3235

    
3236

    
3237
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
3238
    MpegEncContext * const s = &h->s;
3239
    AVCodecContext * const avctx= s->avctx;
3240
    int buf_index=0;
3241
    H264Context *hx; ///< thread context
3242
    int context_count = 0;
3243
    int next_avc= h->is_avc ? 0 : buf_size;
3244

    
3245
    h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
3246
#if 0
3247
    int i;
3248
    for(i=0; i<50; i++){
3249
        av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
3250
    }
3251
#endif
3252
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
3253
        h->current_slice = 0;
3254
        if (!s->first_field)
3255
            s->current_picture_ptr= NULL;
3256
        ff_h264_reset_sei(h);
3257
    }
3258

    
3259
    for(;;){
3260
        int consumed;
3261
        int dst_length;
3262
        int bit_length;
3263
        const uint8_t *ptr;
3264
        int i, nalsize = 0;
3265
        int err;
3266

    
3267
        if(buf_index >= next_avc) {
3268
            if(buf_index >= buf_size) break;
3269
            nalsize = 0;
3270
            for(i = 0; i < h->nal_length_size; i++)
3271
                nalsize = (nalsize << 8) | buf[buf_index++];
3272
            if(nalsize <= 0 || nalsize > buf_size - buf_index){
3273
                av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
3274
                break;
3275
            }
3276
            next_avc= buf_index + nalsize;
3277
        } else {
3278
            // start code prefix search
3279
            for(; buf_index + 3 < next_avc; buf_index++){
3280
                // This should always succeed in the first iteration.
3281
                if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
3282
                    break;
3283
            }
3284

    
3285
            if(buf_index+3 >= buf_size) break;
3286

    
3287
            buf_index+=3;
3288
            if(buf_index >= next_avc) continue;
3289
        }
3290

    
3291
        hx = h->thread_context[context_count];
3292

    
3293
        ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
3294
        if (ptr==NULL || dst_length < 0){
3295
            return -1;
3296
        }
3297
        i= buf_index + consumed;
3298
        if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
3299
           buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
3300
            s->workaround_bugs |= FF_BUG_TRUNCATED;
3301

    
3302
        if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
3303
        while(ptr[dst_length - 1] == 0 && dst_length > 0)
3304
            dst_length--;
3305
        }
3306
        bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
3307

    
3308
        if(s->avctx->debug&FF_DEBUG_STARTCODE){
3309
            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);
3310
        }
3311

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

    
3316
        buf_index += consumed;
3317

    
3318
        //FIXME do not discard SEI id
3319
        if(
3320
#if FF_API_HURRY_UP
3321
           (s->hurry_up == 1 && h->nal_ref_idc  == 0) ||
3322
#endif
3323
           (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc  == 0))
3324
            continue;
3325

    
3326
      again:
3327
        err = 0;
3328
        switch(hx->nal_unit_type){
3329
        case NAL_IDR_SLICE:
3330
            if (h->nal_unit_type != NAL_IDR_SLICE) {
3331
                av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
3332
                return -1;
3333
            }
3334
            idr(h); //FIXME ensure we don't loose some frames if there is reordering
3335
        case NAL_SLICE:
3336
            init_get_bits(&hx->s.gb, ptr, bit_length);
3337
            hx->intra_gb_ptr=
3338
            hx->inter_gb_ptr= &hx->s.gb;
3339
            hx->s.data_partitioning = 0;
3340

    
3341
            if((err = decode_slice_header(hx, h)))
3342
               break;
3343

    
3344
            s->current_picture_ptr->key_frame |=
3345
                    (hx->nal_unit_type == NAL_IDR_SLICE) ||
3346
                    (h->sei_recovery_frame_cnt >= 0);
3347

    
3348
            if (h->current_slice == 1) {
3349
                if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3350
                    decode_postinit(h);
3351
                }
3352

    
3353
                if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
3354
                    return -1;
3355
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3356
                    ff_vdpau_h264_picture_start(s);
3357
            }
3358

    
3359
            if(hx->redundant_pic_count==0
3360
#if FF_API_HURRY_UP
3361
               && hx->s.hurry_up < 5
3362
#endif
3363
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3364
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3365
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3366
               && avctx->skip_frame < AVDISCARD_ALL){
3367
                if(avctx->hwaccel) {
3368
                    if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
3369
                        return -1;
3370
                }else
3371
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
3372
                    static const uint8_t start_code[] = {0x00, 0x00, 0x01};
3373
                    ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
3374
                    ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
3375
                }else
3376
                    context_count++;
3377
            }
3378
            break;
3379
        case NAL_DPA:
3380
            init_get_bits(&hx->s.gb, ptr, bit_length);
3381
            hx->intra_gb_ptr=
3382
            hx->inter_gb_ptr= NULL;
3383

    
3384
            if ((err = decode_slice_header(hx, h)) < 0)
3385
                break;
3386

    
3387
            hx->s.data_partitioning = 1;
3388

    
3389
            break;
3390
        case NAL_DPB:
3391
            init_get_bits(&hx->intra_gb, ptr, bit_length);
3392
            hx->intra_gb_ptr= &hx->intra_gb;
3393
            break;
3394
        case NAL_DPC:
3395
            init_get_bits(&hx->inter_gb, ptr, bit_length);
3396
            hx->inter_gb_ptr= &hx->inter_gb;
3397

    
3398
            if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
3399
               && s->context_initialized
3400
#if FF_API_HURRY_UP
3401
               && s->hurry_up < 5
3402
#endif
3403
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3404
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3405
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3406
               && avctx->skip_frame < AVDISCARD_ALL)
3407
                context_count++;
3408
            break;
3409
        case NAL_SEI:
3410
            init_get_bits(&s->gb, ptr, bit_length);
3411
            ff_h264_decode_sei(h);
3412
            break;
3413
        case NAL_SPS:
3414
            init_get_bits(&s->gb, ptr, bit_length);
3415
            ff_h264_decode_seq_parameter_set(h);
3416

    
3417
            if(s->flags& CODEC_FLAG_LOW_DELAY)
3418
                s->low_delay=1;
3419

    
3420
            if(avctx->has_b_frames < 2)
3421
                avctx->has_b_frames= !s->low_delay;
3422
            break;
3423
        case NAL_PPS:
3424
            init_get_bits(&s->gb, ptr, bit_length);
3425

    
3426
            ff_h264_decode_picture_parameter_set(h, bit_length);
3427

    
3428
            break;
3429
        case NAL_AUD:
3430
        case NAL_END_SEQUENCE:
3431
        case NAL_END_STREAM:
3432
        case NAL_FILLER_DATA:
3433
        case NAL_SPS_EXT:
3434
        case NAL_AUXILIARY_SLICE:
3435
            break;
3436
        default:
3437
            av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
3438
        }
3439

    
3440
        if(context_count == h->max_contexts) {
3441
            execute_decode_slices(h, context_count);
3442
            context_count = 0;
3443
        }
3444

    
3445
        if (err < 0)
3446
            av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
3447
        else if(err == 1) {
3448
            /* Slice could not be decoded in parallel mode, copy down
3449
             * NAL unit stuff to context 0 and restart. Note that
3450
             * rbsp_buffer is not transferred, but since we no longer
3451
             * run in parallel mode this should not be an issue. */
3452
            h->nal_unit_type = hx->nal_unit_type;
3453
            h->nal_ref_idc   = hx->nal_ref_idc;
3454
            hx = h;
3455
            goto again;
3456
        }
3457
    }
3458
    if(context_count)
3459
        execute_decode_slices(h, context_count);
3460
    return buf_index;
3461
}
3462

    
3463
/**
3464
 * returns the number of bytes consumed for building the current frame
3465
 */
3466
static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
3467
        if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
3468
        if(pos+10>buf_size) pos=buf_size; // oops ;)
3469

    
3470
        return pos;
3471
}
3472

    
3473
static int decode_frame(AVCodecContext *avctx,
3474
                             void *data, int *data_size,
3475
                             AVPacket *avpkt)
3476
{
3477
    const uint8_t *buf = avpkt->data;
3478
    int buf_size = avpkt->size;
3479
    H264Context *h = avctx->priv_data;
3480
    MpegEncContext *s = &h->s;
3481
    AVFrame *pict = data;
3482
    int buf_index;
3483

    
3484
    s->flags= avctx->flags;
3485
    s->flags2= avctx->flags2;
3486

    
3487
   /* end of stream, output what is still in the buffers */
3488
 out:
3489
    if (buf_size == 0) {
3490
        Picture *out;
3491
        int i, out_idx;
3492

    
3493
        s->current_picture_ptr = NULL;
3494

    
3495
//FIXME factorize this with the output code below
3496
        out = h->delayed_pic[0];
3497
        out_idx = 0;
3498
        for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
3499
            if(h->delayed_pic[i]->poc < out->poc){
3500
                out = h->delayed_pic[i];
3501
                out_idx = i;
3502
            }
3503

    
3504
        for(i=out_idx; h->delayed_pic[i]; i++)
3505
            h->delayed_pic[i] = h->delayed_pic[i+1];
3506

    
3507
        if(out){
3508
            *data_size = sizeof(AVFrame);
3509
            *pict= *(AVFrame*)out;
3510
        }
3511

    
3512
        return 0;
3513
    }
3514

    
3515
    buf_index=decode_nal_units(h, buf, buf_size);
3516
    if(buf_index < 0)
3517
        return -1;
3518

    
3519
    if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
3520
        buf_size = 0;
3521
        goto out;
3522
    }
3523

    
3524
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
3525
        if (avctx->skip_frame >= AVDISCARD_NONREF
3526
#if FF_API_HURRY_UP
3527
                || s->hurry_up
3528
#endif
3529
           )
3530
            return 0;
3531
        av_log(avctx, AV_LOG_ERROR, "no frame!\n");
3532
        return -1;
3533
    }
3534

    
3535
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
3536

    
3537
        if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h);
3538

    
3539
        field_end(h, 0);
3540

    
3541
        if (!h->next_output_pic) {
3542
            /* Wait for second field. */
3543
            *data_size = 0;
3544

    
3545
        } else {
3546
            *data_size = sizeof(AVFrame);
3547
            *pict = *(AVFrame*)h->next_output_pic;
3548
        }
3549
    }
3550

    
3551
    assert(pict->data[0] || !*data_size);
3552
    ff_print_debug_info(s, pict);
3553
//printf("out %d\n", (int)pict->data[0]);
3554

    
3555
    return get_consumed_bytes(s, buf_index, buf_size);
3556
}
3557
#if 0
3558
static inline void fill_mb_avail(H264Context *h){
3559
    MpegEncContext * const s = &h->s;
3560
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3561

3562
    if(s->mb_y){
3563
        h->mb_avail[0]= s->mb_x                 && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
3564
        h->mb_avail[1]=                            h->slice_table[mb_xy - s->mb_stride    ] == h->slice_num;
3565
        h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
3566
    }else{
3567
        h->mb_avail[0]=
3568
        h->mb_avail[1]=
3569
        h->mb_avail[2]= 0;
3570
    }
3571
    h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
3572
    h->mb_avail[4]= 1; //FIXME move out
3573
    h->mb_avail[5]= 0; //FIXME move out
3574
}
3575
#endif
3576

    
3577
#ifdef TEST
3578
#undef printf
3579
#undef random
3580
#define COUNT 8000
3581
#define SIZE (COUNT*40)
3582
int main(void){
3583
    int i;
3584
    uint8_t temp[SIZE];
3585
    PutBitContext pb;
3586
    GetBitContext gb;
3587
//    int int_temp[10000];
3588
    DSPContext dsp;
3589
    AVCodecContext avctx;
3590

    
3591
    dsputil_init(&dsp, &avctx);
3592

    
3593
    init_put_bits(&pb, temp, SIZE);
3594
    printf("testing unsigned exp golomb\n");
3595
    for(i=0; i<COUNT; i++){
3596
        START_TIMER
3597
        set_ue_golomb(&pb, i);
3598
        STOP_TIMER("set_ue_golomb");
3599
    }
3600
    flush_put_bits(&pb);
3601

    
3602
    init_get_bits(&gb, temp, 8*SIZE);
3603
    for(i=0; i<COUNT; i++){
3604
        int j, s;
3605

    
3606
        s= show_bits(&gb, 24);
3607

    
3608
        START_TIMER
3609
        j= get_ue_golomb(&gb);
3610
        if(j != i){
3611
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3612
//            return -1;
3613
        }
3614
        STOP_TIMER("get_ue_golomb");
3615
    }
3616

    
3617

    
3618
    init_put_bits(&pb, temp, SIZE);
3619
    printf("testing signed exp golomb\n");
3620
    for(i=0; i<COUNT; i++){
3621
        START_TIMER
3622
        set_se_golomb(&pb, i - COUNT/2);
3623
        STOP_TIMER("set_se_golomb");
3624
    }
3625
    flush_put_bits(&pb);
3626

    
3627
    init_get_bits(&gb, temp, 8*SIZE);
3628
    for(i=0; i<COUNT; i++){
3629
        int j, s;
3630

    
3631
        s= show_bits(&gb, 24);
3632

    
3633
        START_TIMER
3634
        j= get_se_golomb(&gb);
3635
        if(j != i - COUNT/2){
3636
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3637
//            return -1;
3638
        }
3639
        STOP_TIMER("get_se_golomb");
3640
    }
3641

    
3642
#if 0
3643
    printf("testing 4x4 (I)DCT\n");
3644

3645
    DCTELEM block[16];
3646
    uint8_t src[16], ref[16];
3647
    uint64_t error= 0, max_error=0;
3648

3649
    for(i=0; i<COUNT; i++){
3650
        int j;
3651
//        printf("%d %d %d\n", r1, r2, (r2-r1)*16);
3652
        for(j=0; j<16; j++){
3653
            ref[j]= random()%255;
3654
            src[j]= random()%255;
3655
        }
3656

3657
        h264_diff_dct_c(block, src, ref, 4);
3658

3659
        //normalize
3660
        for(j=0; j<16; j++){
3661
//            printf("%d ", block[j]);
3662
            block[j]= block[j]*4;
3663
            if(j&1) block[j]= (block[j]*4 + 2)/5;
3664
            if(j&4) block[j]= (block[j]*4 + 2)/5;
3665
        }
3666
//        printf("\n");
3667

3668
        h->h264dsp.h264_idct_add(ref, block, 4);
3669
/*        for(j=0; j<16; j++){
3670
            printf("%d ", ref[j]);
3671
        }
3672
        printf("\n");*/
3673

3674
        for(j=0; j<16; j++){
3675
            int diff= FFABS(src[j] - ref[j]);
3676

3677
            error+= diff*diff;
3678
            max_error= FFMAX(max_error, diff);
3679
        }
3680
    }
3681
    printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
3682
    printf("testing quantizer\n");
3683
    for(qp=0; qp<52; qp++){
3684
        for(i=0; i<16; i++)
3685
            src1_block[i]= src2_block[i]= random()%255;
3686

3687
    }
3688
    printf("Testing NAL layer\n");
3689

3690
    uint8_t bitstream[COUNT];
3691
    uint8_t nal[COUNT*2];
3692
    H264Context h;
3693
    memset(&h, 0, sizeof(H264Context));
3694

3695
    for(i=0; i<COUNT; i++){
3696
        int zeros= i;
3697
        int nal_length;
3698
        int consumed;
3699
        int out_length;
3700
        uint8_t *out;
3701
        int j;
3702

3703
        for(j=0; j<COUNT; j++){
3704
            bitstream[j]= (random() % 255) + 1;
3705
        }
3706

3707
        for(j=0; j<zeros; j++){
3708
            int pos= random() % COUNT;
3709
            while(bitstream[pos] == 0){
3710
                pos++;
3711
                pos %= COUNT;
3712
            }
3713
            bitstream[pos]=0;
3714
        }
3715

3716
        START_TIMER
3717

3718
        nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
3719
        if(nal_length<0){
3720
            printf("encoding failed\n");
3721
            return -1;
3722
        }
3723

3724
        out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
3725

3726
        STOP_TIMER("NAL")
3727

3728
        if(out_length != COUNT){
3729
            printf("incorrect length %d %d\n", out_length, COUNT);
3730
            return -1;
3731
        }
3732

3733
        if(consumed != nal_length){
3734
            printf("incorrect consumed length %d %d\n", nal_length, consumed);
3735
            return -1;
3736
        }
3737

3738
        if(memcmp(bitstream, out, COUNT)){
3739
            printf("mismatch\n");
3740
            return -1;
3741
        }
3742
    }
3743
#endif
3744

    
3745
    printf("Testing RBSP\n");
3746

    
3747

    
3748
    return 0;
3749
}
3750
#endif /* TEST */
3751

    
3752

    
3753
av_cold void ff_h264_free_context(H264Context *h)
3754
{
3755
    int i;
3756

    
3757
    free_tables(h, 1); //FIXME cleanup init stuff perhaps
3758

    
3759
    for(i = 0; i < MAX_SPS_COUNT; i++)
3760
        av_freep(h->sps_buffers + i);
3761

    
3762
    for(i = 0; i < MAX_PPS_COUNT; i++)
3763
        av_freep(h->pps_buffers + i);
3764
}
3765

    
3766
av_cold int ff_h264_decode_end(AVCodecContext *avctx)
3767
{
3768
    H264Context *h = avctx->priv_data;
3769
    MpegEncContext *s = &h->s;
3770

    
3771
    ff_h264_free_context(h);
3772

    
3773
    MPV_common_end(s);
3774

    
3775
//    memset(h, 0, sizeof(H264Context));
3776

    
3777
    return 0;
3778
}
3779

    
3780
static const AVProfile profiles[] = {
3781
    { FF_PROFILE_H264_BASELINE,             "Baseline"              },
3782
    { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
3783
    { FF_PROFILE_H264_MAIN,                 "Main"                  },
3784
    { FF_PROFILE_H264_EXTENDED,             "Extended"              },
3785
    { FF_PROFILE_H264_HIGH,                 "High"                  },
3786
    { FF_PROFILE_H264_HIGH_10,              "High 10"               },
3787
    { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
3788
    { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
3789
    { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
3790
    { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
3791
    { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
3792
    { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
3793
    { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
3794
    { FF_PROFILE_UNKNOWN },
3795
};
3796

    
3797
AVCodec ff_h264_decoder = {
3798
    "h264",
3799
    AVMEDIA_TYPE_VIDEO,
3800
    CODEC_ID_H264,
3801
    sizeof(H264Context),
3802
    ff_h264_decode_init,
3803
    NULL,
3804
    ff_h264_decode_end,
3805
    decode_frame,
3806
    /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
3807
    .flush= flush_dpb,
3808
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
3809
    .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
3810
    .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
3811
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3812
};
3813

    
3814
#if CONFIG_H264_VDPAU_DECODER
3815
AVCodec ff_h264_vdpau_decoder = {
3816
    "h264_vdpau",
3817
    AVMEDIA_TYPE_VIDEO,
3818
    CODEC_ID_H264,
3819
    sizeof(H264Context),
3820
    ff_h264_decode_init,
3821
    NULL,
3822
    ff_h264_decode_end,
3823
    decode_frame,
3824
    CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
3825
    .flush= flush_dpb,
3826
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
3827
    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
3828
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3829
};
3830
#endif