Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ 6e77feb2

History | View | Annotate | Download (140 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
    //FIXME mt gives valgrind warnings and crashes if this is uncommented
2499
    /*
2500

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

2510
    */
2511

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

    
2525
    if(h->nal_ref_idc)
2526
        ff_h264_decode_ref_pic_marking(h0, &s->gb);
2527

    
2528
    if(FRAME_MBAFF){
2529
        ff_h264_fill_mbaff_ref_list(h);
2530

    
2531
        if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2532
            implicit_weight_table(h, 0);
2533
            implicit_weight_table(h, 1);
2534
        }
2535
    }
2536

    
2537
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2538
        ff_h264_direct_dist_scale_factor(h);
2539
    ff_h264_direct_ref_list_init(h);
2540

    
2541
    if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
2542
        tmp = get_ue_golomb_31(&s->gb);
2543
        if(tmp > 2){
2544
            av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2545
            return -1;
2546
        }
2547
        h->cabac_init_idc= tmp;
2548
    }
2549

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

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

    
2580
        if( h->deblocking_filter ) {
2581
            h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
2582
            h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
2583
            if(   h->slice_alpha_c0_offset > 104U
2584
               || h->slice_beta_offset     > 104U){
2585
                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);
2586
                return -1;
2587
            }
2588
        }
2589
    }
2590

    
2591
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
2592
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
2593
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
2594
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
2595
        h->deblocking_filter= 0;
2596

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

    
2616
#if 0 //FMO
2617
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
2618
        slice_group_change_cycle= get_bits(&s->gb, ?);
2619
#endif
2620

    
2621
    h0->last_slice_type = slice_type;
2622
    h->slice_num = ++h0->current_slice;
2623
    if(h->slice_num >= MAX_SLICES){
2624
        av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
2625
    }
2626

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

    
2648
        ref2frm[0]=
2649
        ref2frm[1]= -1;
2650
        for(i=0; i<16; i++)
2651
            ref2frm[i+2]= 4*id_list[i]
2652
                          +(h->ref_list[j][i].reference&3);
2653
        ref2frm[18+0]=
2654
        ref2frm[18+1]= -1;
2655
        for(i=16; i<48; i++)
2656
            ref2frm[i+4]= 4*id_list[(i-16)>>1]
2657
                          +(h->ref_list[j][i].reference&3);
2658
    }
2659

    
2660
    //FIXME: fix draw_edges+PAFF+frame threads
2661
    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;
2662
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
2663

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

    
2681
    return 0;
2682
}
2683

    
2684
int ff_h264_get_slice_type(const H264Context *h)
2685
{
2686
    switch (h->slice_type) {
2687
    case FF_P_TYPE:  return 0;
2688
    case FF_B_TYPE:  return 1;
2689
    case FF_I_TYPE:  return 2;
2690
    case FF_SP_TYPE: return 3;
2691
    case FF_SI_TYPE: return 4;
2692
    default:         return -1;
2693
    }
2694
}
2695

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

    
2706
    top_xy     = mb_xy  - (s->mb_stride << MB_FIELD);
2707

    
2708
    //FIXME deblocking could skip the intra and nnz parts.
2709

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

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

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

    
2750
    top_type     = s->current_picture.mb_type[top_xy]    ;
2751
    left_type[0] = s->current_picture.mb_type[left_xy[0]];
2752
    left_type[1] = s->current_picture.mb_type[left_xy[1]];
2753
    if(h->deblocking_filter == 2){
2754
        if(h->slice_table[top_xy     ] != h->slice_num) top_type= 0;
2755
        if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
2756
    }else{
2757
        if(h->slice_table[top_xy     ] == 0xFFFF) top_type= 0;
2758
        if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
2759
    }
2760
    h->top_type    = top_type    ;
2761
    h->left_type[0]= left_type[0];
2762
    h->left_type[1]= left_type[1];
2763

    
2764
    if(IS_INTRA(mb_type))
2765
        return 0;
2766

    
2767
    AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
2768
    AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
2769
    AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
2770
    AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
2771
    AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
2772

    
2773
    h->cbp= h->cbp_table[mb_xy];
2774

    
2775
    {
2776
        int list;
2777
        for(list=0; list<h->list_count; list++){
2778
            int8_t *ref;
2779
            int y, b_stride;
2780
            int16_t (*mv_dst)[2];
2781
            int16_t (*mv_src)[2];
2782

    
2783
            if(!USES_LIST(mb_type, list)){
2784
                fill_rectangle(  h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
2785
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2786
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2787
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2788
                AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2789
                continue;
2790
            }
2791

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

    
2802
            b_stride = h->b_stride;
2803
            mv_dst   = &h->mv_cache[list][scan8[0]];
2804
            mv_src   = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
2805
            for(y=0; y<4; y++){
2806
                AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
2807
            }
2808

    
2809
        }
2810
    }
2811

    
2812

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

    
2826
    if(left_type[0]){
2827
        h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
2828
        h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
2829
        h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
2830
        h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
2831
    }
2832

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

    
2850
        if(IS_8x8DCT(mb_type)){
2851
            h->non_zero_count_cache[scan8[0   ]]= h->non_zero_count_cache[scan8[1   ]]=
2852
            h->non_zero_count_cache[scan8[2   ]]= h->non_zero_count_cache[scan8[3   ]]= h->cbp & 1;
2853

    
2854
            h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
2855
            h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
2856

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

    
2860
            h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
2861
            h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
2862
        }
2863
    }
2864

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

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

    
2909
    return 0;
2910
}
2911

    
2912
static void loop_filter(H264Context *h){
2913
    MpegEncContext * const s = &h->s;
2914
    uint8_t  *dest_y, *dest_cb, *dest_cr;
2915
    int linesize, uvlinesize, mb_x, mb_y;
2916
    const int end_mb_y= s->mb_y + FRAME_MBAFF;
2917
    const int old_slice_type= h->slice_type;
2918

    
2919
    if(h->deblocking_filter) {
2920
        for(mb_x= 0; mb_x<s->mb_width; mb_x++){
2921
            for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
2922
                int mb_xy, mb_type;
2923
                mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
2924
                h->slice_num= h->slice_table[mb_xy];
2925
                mb_type= s->current_picture.mb_type[mb_xy];
2926
                h->list_count= h->list_counts[mb_xy];
2927

    
2928
                if(FRAME_MBAFF)
2929
                    h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2930

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

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

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

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

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

    
2992
    if (h->deblocking_filter) {
2993
        if((top + height) >= pic_height)
2994
            height += deblock_border;
2995

    
2996
        top -= deblock_border;
2997
    }
2998

    
2999
    if (top >= pic_height || (top + height) < h->emu_edge_height)
3000
        return;
3001

    
3002
    height = FFMIN(height, pic_height - top);
3003
    if (top < h->emu_edge_height) {
3004
        height = top+height;
3005
        top = 0;
3006
    }
3007

    
3008
    ff_draw_horiz_band(s, top, height);
3009

    
3010
    if (s->dropable) return;
3011

    
3012
    ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
3013
                             s->picture_structure==PICT_BOTTOM_FIELD);
3014
}
3015

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

    
3021
    s->mb_skip_run= -1;
3022

    
3023
    h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
3024
                    (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
3025

    
3026
    if( h->pps.cabac ) {
3027
        /* realign */
3028
        align_get_bits( &s->gb );
3029

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

    
3036
        ff_h264_init_cabac_states(h);
3037

    
3038
        for(;;){
3039
//START_TIMER
3040
            int ret = ff_h264_decode_mb_cabac(h);
3041
            int eos;
3042
//STOP_TIMER("decode_mb_cabac")
3043

    
3044
            if(ret>=0) ff_h264_hl_decode_mb(h);
3045

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

    
3049
                ret = ff_h264_decode_mb_cabac(h);
3050

    
3051
                if(ret>=0) ff_h264_hl_decode_mb(h);
3052
                s->mb_y--;
3053
            }
3054
            eos = get_cabac_terminate( &h->cabac );
3055

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

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

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

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

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

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

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

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

    
3103
                return -1;
3104
            }
3105

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

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

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

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

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

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

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

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

3152
            ff_h264_hl_decode_mb(h);
3153

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

3158
                return -1;
3159
            }
3160

3161
            if(++s->mb_x >= s->mb_width){
3162
                s->mb_x=0;
3163
                if(++s->mb_y >= s->mb_height){
3164
                    if(get_bits_count(s->gb) == s->gb.size_in_bits){
3165
                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3166

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

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

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

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

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

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

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

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

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

    
3234

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

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

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

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

    
3283
            if(buf_index+3 >= buf_size) break;
3284

    
3285
            buf_index+=3;
3286
            if(buf_index >= next_avc) continue;
3287
        }
3288

    
3289
        hx = h->thread_context[context_count];
3290

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

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

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

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

    
3314
        buf_index += consumed;
3315

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

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

    
3339
            if((err = decode_slice_header(hx, h)))
3340
               break;
3341

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

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

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

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

    
3382
            if ((err = decode_slice_header(hx, h)) < 0)
3383
                break;
3384

    
3385
            hx->s.data_partitioning = 1;
3386

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

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

    
3415
            if(s->flags& CODEC_FLAG_LOW_DELAY)
3416
                s->low_delay=1;
3417

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

    
3424
            ff_h264_decode_picture_parameter_set(h, bit_length);
3425

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

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

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

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

    
3468
        return pos;
3469
}
3470

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

    
3482
    s->flags= avctx->flags;
3483
    s->flags2= avctx->flags2;
3484

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

    
3491
        s->current_picture_ptr = NULL;
3492

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

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

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

    
3510
        return 0;
3511
    }
3512

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

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

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

    
3533
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
3534

    
3535
        if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h);
3536

    
3537
        field_end(h, 0);
3538

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

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

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

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

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

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

    
3589
    dsputil_init(&dsp, &avctx);
3590

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

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

    
3604
        s= show_bits(&gb, 24);
3605

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

    
3615

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

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

    
3629
        s= show_bits(&gb, 24);
3630

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

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

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

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

3655
        h264_diff_dct_c(block, src, ref, 4);
3656

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

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

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

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

3685
    }
3686
    printf("Testing NAL layer\n");
3687

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

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

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

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

3714
        START_TIMER
3715

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

3722
        out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
3723

3724
        STOP_TIMER("NAL")
3725

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

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

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

    
3743
    printf("Testing RBSP\n");
3744

    
3745

    
3746
    return 0;
3747
}
3748
#endif /* TEST */
3749

    
3750

    
3751
av_cold void ff_h264_free_context(H264Context *h)
3752
{
3753
    int i;
3754

    
3755
    free_tables(h, 1); //FIXME cleanup init stuff perhaps
3756

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

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

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

    
3769
    ff_h264_free_context(h);
3770

    
3771
    MPV_common_end(s);
3772

    
3773
//    memset(h, 0, sizeof(H264Context));
3774

    
3775
    return 0;
3776
}
3777

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

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

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