Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ af0b2d67

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
#if 0
432
static void chroma_dc_dct_c(DCTELEM *block){
433
    const int stride= 16*2;
434
    const int xStride= 16;
435
    int a,b,c,d,e;
436

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

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

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

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

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

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

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

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

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

    
499
    if(emu){
500
        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
501
            src_cb= s->edge_emu_buffer;
502
    }
503
    chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
504

    
505
    if(emu){
506
        s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
507
            src_cr= s->edge_emu_buffer;
508
    }
509
    chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
510
}
511

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
655
    assert(IS_INTER(mb_type));
656

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

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

    
687
        assert(IS_8X8(mb_type));
688

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

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

    
733
    prefetch_motion(h, 1);
734
}
735

    
736

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

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

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

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

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

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

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

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

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

    
832

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

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

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

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

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

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

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

    
866
    s->obmc_scratchpad = NULL;
867

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
944
        h->is_avc = 1;
945

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

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

    
988
    MPV_decode_defaults(s);
989

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

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

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

    
1002
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1003

    
1004
    ff_h264_decode_init_vlc();
1005

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

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

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

    
1027
    return 0;
1028
}
1029

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

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

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

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

    
1047
        if (from[i]) memcpy(to[i], from[i], size);
1048
    }
1049
}
1050

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

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

    
1058
    return 0;
1059
}
1060

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

    
1068
    if(dst == src || !s1->context_initialized) return 0;
1069

    
1070
    err = ff_mpeg_update_thread_context(dst, src);
1071
    if(err) return err;
1072

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

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

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

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

    
1092
        h->thread_context[0] = h;
1093

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

    
1098
        s->dsp.clear_blocks(h->mb);
1099
    }
1100

    
1101
    //extradata/NAL handling
1102
    h->is_avc          = h1->is_avc;
1103

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

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

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

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

    
1120
    h->dequant_coeff_pps = h1->dequant_coeff_pps;
1121

    
1122
    //POC timing
1123
    copy_fields(h, h1, poc_lsb, redundant_pic_count);
1124

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

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

    
1133
    h->last_slice_type = h1->last_slice_type;
1134

    
1135
    if(!s->current_picture_ptr) return 0;
1136

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

    
1146
    return 0;
1147
}
1148

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

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

    
1165
    assert(s->linesize && s->uvlinesize);
1166

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

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

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

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

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

    
1198
    s->current_picture_ptr->field_poc[0]=
1199
    s->current_picture_ptr->field_poc[1]= INT_MAX;
1200

    
1201
    h->next_output_pic = NULL;
1202

    
1203
    assert(s->current_picture_ptr->long_ref==0);
1204

    
1205
    return 0;
1206
}
1207

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

    
1220
    s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
1221
    s->current_picture_ptr->pict_type= s->pict_type;
1222

    
1223
    if (h->next_output_pic) return;
1224

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

    
1233
    cur->interlaced_frame = 0;
1234
    cur->repeat_pict = 0;
1235

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

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

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

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

    
1296
    //FIXME do something with unavailable reference frames
1297

    
1298
    /* Sort B-frames into display order */
1299

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

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

    
1312
    pics = 0;
1313
    while(h->delayed_pic[pics]) pics++;
1314

    
1315
    assert(pics <= MAX_DELAYED_PIC_COUNT);
1316

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

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

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

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

    
1358
    ff_thread_finish_setup(s->avctx);
1359
}
1360

    
1361
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){
1362
    MpegEncContext * const s = &h->s;
1363
    uint8_t *top_border;
1364
    int top_idx = 1;
1365

    
1366
    src_y  -=   linesize;
1367
    src_cb -= uvlinesize;
1368
    src_cr -= uvlinesize;
1369

    
1370
    if(!simple && FRAME_MBAFF){
1371
        if(s->mb_y&1){
1372
            if(!MB_MBAFF){
1373
                top_border = h->top_borders[0][s->mb_x];
1374
                AV_COPY128(top_border, src_y + 15*linesize);
1375
                if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1376
                    AV_COPY64(top_border+16, src_cb+7*uvlinesize);
1377
                    AV_COPY64(top_border+24, src_cr+7*uvlinesize);
1378
                }
1379
            }
1380
        }else if(MB_MBAFF){
1381
            top_idx = 0;
1382
        }else
1383
            return;
1384
    }
1385

    
1386
    top_border = h->top_borders[top_idx][s->mb_x];
1387
    // There are two lines saved, the line above the the top macroblock of a pair,
1388
    // and the line above the bottom macroblock
1389
    AV_COPY128(top_border, src_y + 16*linesize);
1390

    
1391
    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1392
        AV_COPY64(top_border+16, src_cb+8*uvlinesize);
1393
        AV_COPY64(top_border+24, src_cr+8*uvlinesize);
1394
    }
1395
}
1396

    
1397
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){
1398
    MpegEncContext * const s = &h->s;
1399
    int deblock_left;
1400
    int deblock_top;
1401
    int top_idx = 1;
1402
    uint8_t *top_border_m1;
1403
    uint8_t *top_border;
1404

    
1405
    if(!simple && FRAME_MBAFF){
1406
        if(s->mb_y&1){
1407
            if(!MB_MBAFF)
1408
                return;
1409
        }else{
1410
            top_idx = MB_MBAFF ? 0 : 1;
1411
        }
1412
    }
1413

    
1414
    if(h->deblocking_filter == 2) {
1415
        deblock_left = h->left_type[0];
1416
        deblock_top  = h->top_type;
1417
    } else {
1418
        deblock_left = (s->mb_x > 0);
1419
        deblock_top =  (s->mb_y > !!MB_FIELD);
1420
    }
1421

    
1422
    src_y  -=   linesize + 1;
1423
    src_cb -= uvlinesize + 1;
1424
    src_cr -= uvlinesize + 1;
1425

    
1426
    top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1427
    top_border    = h->top_borders[top_idx][s->mb_x];
1428

    
1429
#define XCHG(a,b,xchg)\
1430
if (xchg) AV_SWAP64(b,a);\
1431
else      AV_COPY64(b,a);
1432

    
1433
    if(deblock_top){
1434
        if(deblock_left){
1435
            XCHG(top_border_m1+8, src_y -7, 1);
1436
        }
1437
        XCHG(top_border+0, src_y +1, xchg);
1438
        XCHG(top_border+8, src_y +9, 1);
1439
        if(s->mb_x+1 < s->mb_width){
1440
            XCHG(h->top_borders[top_idx][s->mb_x+1], src_y +17, 1);
1441
        }
1442
    }
1443

    
1444
    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1445
        if(deblock_top){
1446
            if(deblock_left){
1447
                XCHG(top_border_m1+16, src_cb -7, 1);
1448
                XCHG(top_border_m1+24, src_cr -7, 1);
1449
            }
1450
            XCHG(top_border+16, src_cb+1, 1);
1451
            XCHG(top_border+24, src_cr+1, 1);
1452
        }
1453
    }
1454
}
1455

    
1456
static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
1457
    MpegEncContext * const s = &h->s;
1458
    const int mb_x= s->mb_x;
1459
    const int mb_y= s->mb_y;
1460
    const int mb_xy= h->mb_xy;
1461
    const int mb_type= s->current_picture.mb_type[mb_xy];
1462
    uint8_t  *dest_y, *dest_cb, *dest_cr;
1463
    int linesize, uvlinesize /*dct_offset*/;
1464
    int i;
1465
    int *block_offset = &h->block_offset[0];
1466
    const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
1467
    /* is_h264 should always be true if SVQ3 is disabled. */
1468
    const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
1469
    void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1470
    void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1471

    
1472
    dest_y  = s->current_picture.data[0] + (mb_x + mb_y * s->linesize  ) * 16;
1473
    dest_cb = s->current_picture.data[1] + (mb_x + mb_y * s->uvlinesize) * 8;
1474
    dest_cr = s->current_picture.data[2] + (mb_x + mb_y * s->uvlinesize) * 8;
1475

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

    
1479
    h->list_counts[mb_xy]= h->list_count;
1480

    
1481
    if (!simple && MB_FIELD) {
1482
        linesize   = h->mb_linesize   = s->linesize * 2;
1483
        uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
1484
        block_offset = &h->block_offset[24];
1485
        if(mb_y&1){ //FIXME move out of this function?
1486
            dest_y -= s->linesize*15;
1487
            dest_cb-= s->uvlinesize*7;
1488
            dest_cr-= s->uvlinesize*7;
1489
        }
1490
        if(FRAME_MBAFF) {
1491
            int list;
1492
            for(list=0; list<h->list_count; list++){
1493
                if(!USES_LIST(mb_type, list))
1494
                    continue;
1495
                if(IS_16X16(mb_type)){
1496
                    int8_t *ref = &h->ref_cache[list][scan8[0]];
1497
                    fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
1498
                }else{
1499
                    for(i=0; i<16; i+=4){
1500
                        int ref = h->ref_cache[list][scan8[i]];
1501
                        if(ref >= 0)
1502
                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
1503
                    }
1504
                }
1505
            }
1506
        }
1507
    } else {
1508
        linesize   = h->mb_linesize   = s->linesize;
1509
        uvlinesize = h->mb_uvlinesize = s->uvlinesize;
1510
//        dct_offset = s->linesize * 16;
1511
    }
1512

    
1513
    if (!simple && IS_INTRA_PCM(mb_type)) {
1514
        for (i=0; i<16; i++) {
1515
            memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
1516
        }
1517
        for (i=0; i<8; i++) {
1518
            memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4,  8);
1519
            memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4,  8);
1520
        }
1521
    } else {
1522
        if(IS_INTRA(mb_type)){
1523
            if(h->deblocking_filter)
1524
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
1525

    
1526
            if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1527
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
1528
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
1529
            }
1530

    
1531
            if(IS_INTRA4x4(mb_type)){
1532
                if(simple || !s->encoding){
1533
                    if(IS_8x8DCT(mb_type)){
1534
                        if(transform_bypass){
1535
                            idct_dc_add =
1536
                            idct_add    = s->dsp.add_pixels8;
1537
                        }else{
1538
                            idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1539
                            idct_add    = h->h264dsp.h264_idct8_add;
1540
                        }
1541
                        for(i=0; i<16; i+=4){
1542
                            uint8_t * const ptr= dest_y + block_offset[i];
1543
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1544
                            if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1545
                                h->hpc.pred8x8l_add[dir](ptr, h->mb + i*16, linesize);
1546
                            }else{
1547
                                const int nnz = h->non_zero_count_cache[ scan8[i] ];
1548
                                h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
1549
                                                            (h->topright_samples_available<<i)&0x4000, linesize);
1550
                                if(nnz){
1551
                                    if(nnz == 1 && h->mb[i*16])
1552
                                        idct_dc_add(ptr, h->mb + i*16, linesize);
1553
                                    else
1554
                                        idct_add   (ptr, h->mb + i*16, linesize);
1555
                                }
1556
                            }
1557
                        }
1558
                    }else{
1559
                        if(transform_bypass){
1560
                            idct_dc_add =
1561
                            idct_add    = s->dsp.add_pixels4;
1562
                        }else{
1563
                            idct_dc_add = h->h264dsp.h264_idct_dc_add;
1564
                            idct_add    = h->h264dsp.h264_idct_add;
1565
                        }
1566
                        for(i=0; i<16; i++){
1567
                            uint8_t * const ptr= dest_y + block_offset[i];
1568
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1569

    
1570
                            if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1571
                                h->hpc.pred4x4_add[dir](ptr, h->mb + i*16, linesize);
1572
                            }else{
1573
                                uint8_t *topright;
1574
                                int nnz, tr;
1575
                                if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
1576
                                    const int topright_avail= (h->topright_samples_available<<i)&0x8000;
1577
                                    assert(mb_y || linesize <= block_offset[i]);
1578
                                    if(!topright_avail){
1579
                                        tr= ptr[3 - linesize]*0x01010101;
1580
                                        topright= (uint8_t*) &tr;
1581
                                    }else
1582
                                        topright= ptr + 4 - linesize;
1583
                                }else
1584
                                    topright= NULL;
1585

    
1586
                                h->hpc.pred4x4[ dir ](ptr, topright, linesize);
1587
                                nnz = h->non_zero_count_cache[ scan8[i] ];
1588
                                if(nnz){
1589
                                    if(is_h264){
1590
                                        if(nnz == 1 && h->mb[i*16])
1591
                                            idct_dc_add(ptr, h->mb + i*16, linesize);
1592
                                        else
1593
                                            idct_add   (ptr, h->mb + i*16, linesize);
1594
                                    }
1595
#if CONFIG_SVQ3_DECODER
1596
                                    else
1597
                                        ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
1598
#endif
1599
                                }
1600
                            }
1601
                        }
1602
                    }
1603
                }
1604
            }else{
1605
                h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
1606
                if(is_h264){
1607
                    if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX] ]){
1608
                        if(!transform_bypass)
1609
                            h->h264dsp.h264_luma_dc_dequant_idct(h->mb, h->mb_luma_dc, h->dequant4_coeff[0][s->qscale][0]);
1610
                        else{
1611
                            static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
1612
                                                                    8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
1613
                            for(i = 0; i < 16; i++)
1614
                                h->mb[dc_mapping[i]] = h->mb_luma_dc[i];
1615
                        }
1616
                    }
1617
                }
1618
#if CONFIG_SVQ3_DECODER
1619
                else
1620
                    ff_svq3_luma_dc_dequant_idct_c(h->mb, h->mb_luma_dc, s->qscale);
1621
#endif
1622
            }
1623
            if(h->deblocking_filter)
1624
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
1625
        }else if(is_h264){
1626
            hl_motion(h, dest_y, dest_cb, dest_cr,
1627
                      s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
1628
                      s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
1629
                      h->h264dsp.weight_h264_pixels_tab, h->h264dsp.biweight_h264_pixels_tab);
1630
        }
1631

    
1632

    
1633
        if(!IS_INTRA4x4(mb_type)){
1634
            if(is_h264){
1635
                if(IS_INTRA16x16(mb_type)){
1636
                    if(transform_bypass){
1637
                        if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
1638
                            h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb, linesize);
1639
                        }else{
1640
                            for(i=0; i<16; i++){
1641
                                if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16])
1642
                                    s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + i*16, linesize);
1643
                            }
1644
                        }
1645
                    }else{
1646
                         h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1647
                    }
1648
                }else if(h->cbp&15){
1649
                    if(transform_bypass){
1650
                        const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1651
                        idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
1652
                        for(i=0; i<16; i+=di){
1653
                            if(h->non_zero_count_cache[ scan8[i] ]){
1654
                                idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
1655
                            }
1656
                        }
1657
                    }else{
1658
                        if(IS_8x8DCT(mb_type)){
1659
                            h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1660
                        }else{
1661
                            h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1662
                        }
1663
                    }
1664
                }
1665
            }
1666
#if CONFIG_SVQ3_DECODER
1667
            else{
1668
                for(i=0; i<16; i++){
1669
                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
1670
                        uint8_t * const ptr= dest_y + block_offset[i];
1671
                        ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1672
                    }
1673
                }
1674
            }
1675
#endif
1676
        }
1677

    
1678
        if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
1679
            uint8_t *dest[2] = {dest_cb, dest_cr};
1680
            if(transform_bypass){
1681
                if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
1682
                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + 16*16, uvlinesize);
1683
                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 20, h->mb + 20*16, uvlinesize);
1684
                }else{
1685
                    idct_add = s->dsp.add_pixels4;
1686
                    for(i=16; i<16+8; i++){
1687
                        if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16])
1688
                            idct_add   (dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
1689
                    }
1690
                }
1691
            }else{
1692
                if(is_h264){
1693
                    if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
1694
                        h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16     , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
1695
                    if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
1696
                        h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16+4*16, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
1697
                    h->h264dsp.h264_idct_add8(dest, block_offset,
1698
                                              h->mb, uvlinesize,
1699
                                              h->non_zero_count_cache);
1700
                }
1701
#if CONFIG_SVQ3_DECODER
1702
                else{
1703
                    h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16     , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
1704
                    h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16+4*16, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
1705
                    for(i=16; i<16+8; i++){
1706
                        if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
1707
                            uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
1708
                            ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[s->qscale + 12] - 12, 2);
1709
                        }
1710
                    }
1711
                }
1712
#endif
1713
            }
1714
        }
1715
    }
1716
    if(h->cbp || IS_INTRA(mb_type))
1717
        s->dsp.clear_blocks(h->mb);
1718
}
1719

    
1720
/**
1721
 * Process a macroblock; this case avoids checks for expensive uncommon cases.
1722
 */
1723
static void hl_decode_mb_simple(H264Context *h){
1724
    hl_decode_mb_internal(h, 1);
1725
}
1726

    
1727
/**
1728
 * Process a macroblock; this handles edge cases, such as interlacing.
1729
 */
1730
static void av_noinline hl_decode_mb_complex(H264Context *h){
1731
    hl_decode_mb_internal(h, 0);
1732
}
1733

    
1734
void ff_h264_hl_decode_mb(H264Context *h){
1735
    MpegEncContext * const s = &h->s;
1736
    const int mb_xy= h->mb_xy;
1737
    const int mb_type= s->current_picture.mb_type[mb_xy];
1738
    int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
1739

    
1740
    if (is_complex)
1741
        hl_decode_mb_complex(h);
1742
    else hl_decode_mb_simple(h);
1743
}
1744

    
1745
static int pred_weight_table(H264Context *h){
1746
    MpegEncContext * const s = &h->s;
1747
    int list, i;
1748
    int luma_def, chroma_def;
1749

    
1750
    h->use_weight= 0;
1751
    h->use_weight_chroma= 0;
1752
    h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
1753
    if(CHROMA)
1754
        h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
1755
    luma_def = 1<<h->luma_log2_weight_denom;
1756
    chroma_def = 1<<h->chroma_log2_weight_denom;
1757

    
1758
    for(list=0; list<2; list++){
1759
        h->luma_weight_flag[list]   = 0;
1760
        h->chroma_weight_flag[list] = 0;
1761
        for(i=0; i<h->ref_count[list]; i++){
1762
            int luma_weight_flag, chroma_weight_flag;
1763

    
1764
            luma_weight_flag= get_bits1(&s->gb);
1765
            if(luma_weight_flag){
1766
                h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
1767
                h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
1768
                if(   h->luma_weight[i][list][0] != luma_def
1769
                   || h->luma_weight[i][list][1] != 0) {
1770
                    h->use_weight= 1;
1771
                    h->luma_weight_flag[list]= 1;
1772
                }
1773
            }else{
1774
                h->luma_weight[i][list][0]= luma_def;
1775
                h->luma_weight[i][list][1]= 0;
1776
            }
1777

    
1778
            if(CHROMA){
1779
                chroma_weight_flag= get_bits1(&s->gb);
1780
                if(chroma_weight_flag){
1781
                    int j;
1782
                    for(j=0; j<2; j++){
1783
                        h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
1784
                        h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
1785
                        if(   h->chroma_weight[i][list][j][0] != chroma_def
1786
                           || h->chroma_weight[i][list][j][1] != 0) {
1787
                            h->use_weight_chroma= 1;
1788
                            h->chroma_weight_flag[list]= 1;
1789
                        }
1790
                    }
1791
                }else{
1792
                    int j;
1793
                    for(j=0; j<2; j++){
1794
                        h->chroma_weight[i][list][j][0]= chroma_def;
1795
                        h->chroma_weight[i][list][j][1]= 0;
1796
                    }
1797
                }
1798
            }
1799
        }
1800
        if(h->slice_type_nos != FF_B_TYPE) break;
1801
    }
1802
    h->use_weight= h->use_weight || h->use_weight_chroma;
1803
    return 0;
1804
}
1805

    
1806
/**
1807
 * Initialize implicit_weight table.
1808
 * @param field  0/1 initialize the weight for interlaced MBAFF
1809
 *                -1 initializes the rest
1810
 */
1811
static void implicit_weight_table(H264Context *h, int field){
1812
    MpegEncContext * const s = &h->s;
1813
    int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
1814

    
1815
    for (i = 0; i < 2; i++) {
1816
        h->luma_weight_flag[i]   = 0;
1817
        h->chroma_weight_flag[i] = 0;
1818
    }
1819

    
1820
    if(field < 0){
1821
        cur_poc = s->current_picture_ptr->poc;
1822
    if(   h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
1823
       && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
1824
        h->use_weight= 0;
1825
        h->use_weight_chroma= 0;
1826
        return;
1827
    }
1828
        ref_start= 0;
1829
        ref_count0= h->ref_count[0];
1830
        ref_count1= h->ref_count[1];
1831
    }else{
1832
        cur_poc = s->current_picture_ptr->field_poc[field];
1833
        ref_start= 16;
1834
        ref_count0= 16+2*h->ref_count[0];
1835
        ref_count1= 16+2*h->ref_count[1];
1836
    }
1837

    
1838
    h->use_weight= 2;
1839
    h->use_weight_chroma= 2;
1840
    h->luma_log2_weight_denom= 5;
1841
    h->chroma_log2_weight_denom= 5;
1842

    
1843
    for(ref0=ref_start; ref0 < ref_count0; ref0++){
1844
        int poc0 = h->ref_list[0][ref0].poc;
1845
        for(ref1=ref_start; ref1 < ref_count1; ref1++){
1846
            int poc1 = h->ref_list[1][ref1].poc;
1847
            int td = av_clip(poc1 - poc0, -128, 127);
1848
            int w= 32;
1849
            if(td){
1850
                int tb = av_clip(cur_poc - poc0, -128, 127);
1851
                int tx = (16384 + (FFABS(td) >> 1)) / td;
1852
                int dist_scale_factor = (tb*tx + 32) >> 8;
1853
                if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
1854
                    w = 64 - dist_scale_factor;
1855
            }
1856
            if(field<0){
1857
                h->implicit_weight[ref0][ref1][0]=
1858
                h->implicit_weight[ref0][ref1][1]= w;
1859
            }else{
1860
                h->implicit_weight[ref0][ref1][field]=w;
1861
            }
1862
        }
1863
    }
1864
}
1865

    
1866
/**
1867
 * instantaneous decoder refresh.
1868
 */
1869
static void idr(H264Context *h){
1870
    ff_h264_remove_all_refs(h);
1871
    h->prev_frame_num= 0;
1872
    h->prev_frame_num_offset= 0;
1873
    h->prev_poc_msb=
1874
    h->prev_poc_lsb= 0;
1875
}
1876

    
1877
/* forget old pics after a seek */
1878
static void flush_dpb(AVCodecContext *avctx){
1879
    H264Context *h= avctx->priv_data;
1880
    int i;
1881
    for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
1882
        if(h->delayed_pic[i])
1883
            h->delayed_pic[i]->reference= 0;
1884
        h->delayed_pic[i]= NULL;
1885
    }
1886
    h->outputed_poc=h->next_outputed_poc= INT_MIN;
1887
    h->prev_interlaced_frame = 1;
1888
    idr(h);
1889
    if(h->s.current_picture_ptr)
1890
        h->s.current_picture_ptr->reference= 0;
1891
    h->s.first_field= 0;
1892
    ff_h264_reset_sei(h);
1893
    ff_mpeg_flush(avctx);
1894
}
1895

    
1896
static int init_poc(H264Context *h){
1897
    MpegEncContext * const s = &h->s;
1898
    const int max_frame_num= 1<<h->sps.log2_max_frame_num;
1899
    int field_poc[2];
1900
    Picture *cur = s->current_picture_ptr;
1901

    
1902
    h->frame_num_offset= h->prev_frame_num_offset;
1903
    if(h->frame_num < h->prev_frame_num)
1904
        h->frame_num_offset += max_frame_num;
1905

    
1906
    if(h->sps.poc_type==0){
1907
        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
1908

    
1909
        if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
1910
            h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1911
        else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
1912
            h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1913
        else
1914
            h->poc_msb = h->prev_poc_msb;
1915
//printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
1916
        field_poc[0] =
1917
        field_poc[1] = h->poc_msb + h->poc_lsb;
1918
        if(s->picture_structure == PICT_FRAME)
1919
            field_poc[1] += h->delta_poc_bottom;
1920
    }else if(h->sps.poc_type==1){
1921
        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1922
        int i;
1923

    
1924
        if(h->sps.poc_cycle_length != 0)
1925
            abs_frame_num = h->frame_num_offset + h->frame_num;
1926
        else
1927
            abs_frame_num = 0;
1928

    
1929
        if(h->nal_ref_idc==0 && abs_frame_num > 0)
1930
            abs_frame_num--;
1931

    
1932
        expected_delta_per_poc_cycle = 0;
1933
        for(i=0; i < h->sps.poc_cycle_length; i++)
1934
            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
1935

    
1936
        if(abs_frame_num > 0){
1937
            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1938
            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1939

    
1940
            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1941
            for(i = 0; i <= frame_num_in_poc_cycle; i++)
1942
                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
1943
        } else
1944
            expectedpoc = 0;
1945

    
1946
        if(h->nal_ref_idc == 0)
1947
            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1948

    
1949
        field_poc[0] = expectedpoc + h->delta_poc[0];
1950
        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1951

    
1952
        if(s->picture_structure == PICT_FRAME)
1953
            field_poc[1] += h->delta_poc[1];
1954
    }else{
1955
        int poc= 2*(h->frame_num_offset + h->frame_num);
1956

    
1957
        if(!h->nal_ref_idc)
1958
            poc--;
1959

    
1960
        field_poc[0]= poc;
1961
        field_poc[1]= poc;
1962
    }
1963

    
1964
    if(s->picture_structure != PICT_BOTTOM_FIELD)
1965
        s->current_picture_ptr->field_poc[0]= field_poc[0];
1966
    if(s->picture_structure != PICT_TOP_FIELD)
1967
        s->current_picture_ptr->field_poc[1]= field_poc[1];
1968
    cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
1969

    
1970
    return 0;
1971
}
1972

    
1973

    
1974
/**
1975
 * initialize scan tables
1976
 */
1977
static void init_scan_tables(H264Context *h){
1978
    int i;
1979
    for(i=0; i<16; i++){
1980
#define T(x) (x>>2) | ((x<<2) & 0xF)
1981
        h->zigzag_scan[i] = T(zigzag_scan[i]);
1982
        h-> field_scan[i] = T( field_scan[i]);
1983
#undef T
1984
    }
1985
    for(i=0; i<64; i++){
1986
#define T(x) (x>>3) | ((x&7)<<3)
1987
        h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
1988
        h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
1989
        h->field_scan8x8[i]        = T(field_scan8x8[i]);
1990
        h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
1991
#undef T
1992
    }
1993
    if(h->sps.transform_bypass){ //FIXME same ugly
1994
        h->zigzag_scan_q0          = zigzag_scan;
1995
        h->zigzag_scan8x8_q0       = ff_zigzag_direct;
1996
        h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
1997
        h->field_scan_q0           = field_scan;
1998
        h->field_scan8x8_q0        = field_scan8x8;
1999
        h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
2000
    }else{
2001
        h->zigzag_scan_q0          = h->zigzag_scan;
2002
        h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
2003
        h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2004
        h->field_scan_q0           = h->field_scan;
2005
        h->field_scan8x8_q0        = h->field_scan8x8;
2006
        h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
2007
    }
2008
}
2009

    
2010
static void field_end(H264Context *h, int in_setup){
2011
    MpegEncContext * const s = &h->s;
2012
    AVCodecContext * const avctx= s->avctx;
2013
    s->mb_y= 0;
2014

    
2015
    if (!in_setup && !s->dropable)
2016
        ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
2017
                                 s->picture_structure==PICT_BOTTOM_FIELD);
2018

    
2019
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2020
        ff_vdpau_h264_set_reference_frames(s);
2021

    
2022
    if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
2023
        if(!s->dropable) {
2024
            ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2025
            h->prev_poc_msb= h->poc_msb;
2026
            h->prev_poc_lsb= h->poc_lsb;
2027
        }
2028
        h->prev_frame_num_offset= h->frame_num_offset;
2029
        h->prev_frame_num= h->frame_num;
2030
        h->outputed_poc = h->next_outputed_poc;
2031
    }
2032

    
2033
    if (avctx->hwaccel) {
2034
        if (avctx->hwaccel->end_frame(avctx) < 0)
2035
            av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
2036
    }
2037

    
2038
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2039
        ff_vdpau_h264_picture_complete(s);
2040

    
2041
    /*
2042
     * FIXME: Error handling code does not seem to support interlaced
2043
     * when slices span multiple rows
2044
     * The ff_er_add_slice calls don't work right for bottom
2045
     * fields; they cause massive erroneous error concealing
2046
     * Error marking covers both fields (top and bottom).
2047
     * This causes a mismatched s->error_count
2048
     * and a bad error table. Further, the error count goes to
2049
     * INT_MAX when called for bottom field, because mb_y is
2050
     * past end by one (callers fault) and resync_mb_y != 0
2051
     * causes problems for the first MB line, too.
2052
     */
2053
    if (!FIELD_PICTURE)
2054
        ff_er_frame_end(s);
2055

    
2056
    MPV_frame_end(s);
2057

    
2058
    h->current_slice=0;
2059
}
2060

    
2061
/**
2062
 * Replicate H264 "master" context to thread contexts.
2063
 */
2064
static void clone_slice(H264Context *dst, H264Context *src)
2065
{
2066
    memcpy(dst->block_offset,     src->block_offset, sizeof(dst->block_offset));
2067
    dst->s.current_picture_ptr  = src->s.current_picture_ptr;
2068
    dst->s.current_picture      = src->s.current_picture;
2069
    dst->s.linesize             = src->s.linesize;
2070
    dst->s.uvlinesize           = src->s.uvlinesize;
2071
    dst->s.first_field          = src->s.first_field;
2072

    
2073
    dst->prev_poc_msb           = src->prev_poc_msb;
2074
    dst->prev_poc_lsb           = src->prev_poc_lsb;
2075
    dst->prev_frame_num_offset  = src->prev_frame_num_offset;
2076
    dst->prev_frame_num         = src->prev_frame_num;
2077
    dst->short_ref_count        = src->short_ref_count;
2078

    
2079
    memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
2080
    memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
2081
    memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2082
    memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
2083

    
2084
    memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
2085
    memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
2086
}
2087

    
2088
/**
2089
 * computes profile from profile_idc and constraint_set?_flags
2090
 *
2091
 * @param sps SPS
2092
 *
2093
 * @return profile as defined by FF_PROFILE_H264_*
2094
 */
2095
int ff_h264_get_profile(SPS *sps)
2096
{
2097
    int profile = sps->profile_idc;
2098

    
2099
    switch(sps->profile_idc) {
2100
    case FF_PROFILE_H264_BASELINE:
2101
        // constraint_set1_flag set to 1
2102
        profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2103
        break;
2104
    case FF_PROFILE_H264_HIGH_10:
2105
    case FF_PROFILE_H264_HIGH_422:
2106
    case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2107
        // constraint_set3_flag set to 1
2108
        profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
2109
        break;
2110
    }
2111

    
2112
    return profile;
2113
}
2114

    
2115
/**
2116
 * decodes a slice header.
2117
 * This will also call MPV_common_init() and frame_start() as needed.
2118
 *
2119
 * @param h h264context
2120
 * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
2121
 *
2122
 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2123
 */
2124
static int decode_slice_header(H264Context *h, H264Context *h0){
2125
    MpegEncContext * const s = &h->s;
2126
    MpegEncContext * const s0 = &h0->s;
2127
    unsigned int first_mb_in_slice;
2128
    unsigned int pps_id;
2129
    int num_ref_idx_active_override_flag;
2130
    unsigned int slice_type, tmp, i, j;
2131
    int default_ref_list_done = 0;
2132
    int last_pic_structure;
2133

    
2134
    s->dropable= h->nal_ref_idc == 0;
2135

    
2136
    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
2137
        s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
2138
        s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
2139
    }else{
2140
        s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
2141
        s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
2142
    }
2143

    
2144
    first_mb_in_slice= get_ue_golomb(&s->gb);
2145

    
2146
    if(first_mb_in_slice == 0){ //FIXME better field boundary detection
2147
        if(h0->current_slice && FIELD_PICTURE){
2148
            field_end(h, 1);
2149
        }
2150

    
2151
        h0->current_slice = 0;
2152
        if (!s0->first_field)
2153
            s->current_picture_ptr= NULL;
2154
    }
2155

    
2156
    slice_type= get_ue_golomb_31(&s->gb);
2157
    if(slice_type > 9){
2158
        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);
2159
        return -1;
2160
    }
2161
    if(slice_type > 4){
2162
        slice_type -= 5;
2163
        h->slice_type_fixed=1;
2164
    }else
2165
        h->slice_type_fixed=0;
2166

    
2167
    slice_type= golomb_to_pict_type[ slice_type ];
2168
    if (slice_type == FF_I_TYPE
2169
        || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
2170
        default_ref_list_done = 1;
2171
    }
2172
    h->slice_type= slice_type;
2173
    h->slice_type_nos= slice_type & 3;
2174

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

    
2177
    pps_id= get_ue_golomb(&s->gb);
2178
    if(pps_id>=MAX_PPS_COUNT){
2179
        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
2180
        return -1;
2181
    }
2182
    if(!h0->pps_buffers[pps_id]) {
2183
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
2184
        return -1;
2185
    }
2186
    h->pps= *h0->pps_buffers[pps_id];
2187

    
2188
    if(!h0->sps_buffers[h->pps.sps_id]) {
2189
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
2190
        return -1;
2191
    }
2192
    h->sps = *h0->sps_buffers[h->pps.sps_id];
2193

    
2194
    s->avctx->profile = ff_h264_get_profile(&h->sps);
2195
    s->avctx->level   = h->sps.level_idc;
2196
    s->avctx->refs    = h->sps.ref_frame_count;
2197

    
2198
    if(h == h0 && h->dequant_coeff_pps != pps_id){
2199
        h->dequant_coeff_pps = pps_id;
2200
        init_dequant_tables(h);
2201
    }
2202

    
2203
    s->mb_width= h->sps.mb_width;
2204
    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2205

    
2206
    h->b_stride=  s->mb_width*4;
2207

    
2208
    s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
2209
    if(h->sps.frame_mbs_only_flag)
2210
        s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
2211
    else
2212
        s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 7);
2213

    
2214
    if (s->context_initialized
2215
        && (   s->width != s->avctx->width || s->height != s->avctx->height
2216
            || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
2217
        if(h != h0) {
2218
            av_log_missing_feature(s->avctx, "Width/height changing with threads is", 0);
2219
            return -1;   // width / height changed during parallelized decoding
2220
        }
2221
        free_tables(h, 0);
2222
        flush_dpb(s->avctx);
2223
        MPV_common_end(s);
2224
    }
2225
    if (!s->context_initialized) {
2226
        if(h != h0){
2227
            av_log(h->s.avctx, AV_LOG_ERROR, "we cant (re-)initialize context during parallel decoding\n");
2228
            return -1;
2229
        }
2230

    
2231
        avcodec_set_dimensions(s->avctx, s->width, s->height);
2232
        s->avctx->sample_aspect_ratio= h->sps.sar;
2233
        av_assert0(s->avctx->sample_aspect_ratio.den);
2234

    
2235
        if(h->sps.video_signal_type_present_flag){
2236
            s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2237
            if(h->sps.colour_description_present_flag){
2238
                s->avctx->color_primaries = h->sps.color_primaries;
2239
                s->avctx->color_trc       = h->sps.color_trc;
2240
                s->avctx->colorspace      = h->sps.colorspace;
2241
            }
2242
        }
2243

    
2244
        if(h->sps.timing_info_present_flag){
2245
            int64_t den= h->sps.time_scale;
2246
            if(h->x264_build < 44U)
2247
                den *= 2;
2248
            av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2249
                      h->sps.num_units_in_tick, den, 1<<30);
2250
        }
2251
        s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2252
                                                 s->avctx->codec->pix_fmts ?
2253
                                                 s->avctx->codec->pix_fmts :
2254
                                                 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2255
                                                 hwaccel_pixfmt_list_h264_jpeg_420 :
2256
                                                 ff_hwaccel_pixfmt_list_420);
2257
        s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2258

    
2259
        if (MPV_common_init(s) < 0){
2260
            av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed\n");
2261
            return -1;
2262
        }
2263
        s->first_field = 0;
2264
        h->prev_interlaced_frame = 1;
2265

    
2266
        init_scan_tables(h);
2267
        ff_h264_alloc_tables(h);
2268

    
2269
        if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
2270
            if (context_init(h) < 0){
2271
                av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
2272
                return -1;
2273
            }
2274
        } else {
2275
            for(i = 1; i < s->avctx->thread_count; i++) {
2276
                H264Context *c;
2277
                c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2278
                memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2279
                memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2280
                c->h264dsp = h->h264dsp;
2281
                c->sps = h->sps;
2282
                c->pps = h->pps;
2283
                init_scan_tables(c);
2284
                clone_tables(c, h, i);
2285
            }
2286

    
2287
            for(i = 0; i < s->avctx->thread_count; i++)
2288
                if(context_init(h->thread_context[i]) < 0){
2289
                    av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
2290
                    return -1;
2291
                }
2292
        }
2293
    }
2294

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

    
2297
    h->mb_mbaff = 0;
2298
    h->mb_aff_frame = 0;
2299
    last_pic_structure = s0->picture_structure;
2300
    if(h->sps.frame_mbs_only_flag){
2301
        s->picture_structure= PICT_FRAME;
2302
    }else{
2303
        if(get_bits1(&s->gb)) { //field_pic_flag
2304
            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
2305
        } else {
2306
            s->picture_structure= PICT_FRAME;
2307
            h->mb_aff_frame = h->sps.mb_aff;
2308
        }
2309
    }
2310
    h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
2311

    
2312
    if(h0->current_slice == 0){
2313
        if(h->frame_num != h->prev_frame_num &&
2314
          (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num) < (h->frame_num - h->sps.ref_frame_count))
2315
            h->prev_frame_num = h->frame_num - h->sps.ref_frame_count - 1;
2316

    
2317
        while(h->frame_num !=  h->prev_frame_num &&
2318
              h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
2319
            Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
2320
            av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
2321
            if (ff_h264_frame_start(h) < 0)
2322
                return -1;
2323
            h->prev_frame_num++;
2324
            h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
2325
            s->current_picture_ptr->frame_num= h->prev_frame_num;
2326
            ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
2327
            ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
2328
            ff_generate_sliding_window_mmcos(h);
2329
            ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2330
            /* Error concealment: if a ref is missing, copy the previous ref in its place.
2331
             * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
2332
             * about there being no actual duplicates.
2333
             * FIXME: this doesn't copy padding for out-of-frame motion vectors.  Given we're
2334
             * concealing a lost frame, this probably isn't noticable by comparison, but it should
2335
             * be fixed. */
2336
            if (h->short_ref_count) {
2337
                if (prev) {
2338
                    av_image_copy(h->short_ref[0]->data, h->short_ref[0]->linesize,
2339
                                  (const uint8_t**)prev->data, prev->linesize,
2340
                                  s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
2341
                    h->short_ref[0]->poc = prev->poc+2;
2342
                }
2343
                h->short_ref[0]->frame_num = h->prev_frame_num;
2344
            }
2345
        }
2346

    
2347
        /* See if we have a decoded first field looking for a pair... */
2348
        if (s0->first_field) {
2349
            assert(s0->current_picture_ptr);
2350
            assert(s0->current_picture_ptr->data[0]);
2351
            assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
2352

    
2353
            /* figure out if we have a complementary field pair */
2354
            if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2355
                /*
2356
                 * Previous field is unmatched. Don't display it, but let it
2357
                 * remain for reference if marked as such.
2358
                 */
2359
                s0->current_picture_ptr = NULL;
2360
                s0->first_field = FIELD_PICTURE;
2361

    
2362
            } else {
2363
                if (h->nal_ref_idc &&
2364
                        s0->current_picture_ptr->reference &&
2365
                        s0->current_picture_ptr->frame_num != h->frame_num) {
2366
                    /*
2367
                     * This and previous field were reference, but had
2368
                     * different frame_nums. Consider this field first in
2369
                     * pair. Throw away previous field except for reference
2370
                     * purposes.
2371
                     */
2372
                    s0->first_field = 1;
2373
                    s0->current_picture_ptr = NULL;
2374

    
2375
                } else {
2376
                    /* Second field in complementary pair */
2377
                    s0->first_field = 0;
2378
                }
2379
            }
2380

    
2381
        } else {
2382
            /* Frame or first field in a potentially complementary pair */
2383
            assert(!s0->current_picture_ptr);
2384
            s0->first_field = FIELD_PICTURE;
2385
        }
2386

    
2387
        if((!FIELD_PICTURE || s0->first_field) && ff_h264_frame_start(h) < 0) {
2388
            s0->first_field = 0;
2389
            return -1;
2390
        }
2391
    }
2392
    if(h != h0)
2393
        clone_slice(h, h0);
2394

    
2395
    s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2396

    
2397
    assert(s->mb_num == s->mb_width * s->mb_height);
2398
    if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2399
       first_mb_in_slice                    >= s->mb_num){
2400
        av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2401
        return -1;
2402
    }
2403
    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2404
    s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2405
    if (s->picture_structure == PICT_BOTTOM_FIELD)
2406
        s->resync_mb_y = s->mb_y = s->mb_y + 1;
2407
    assert(s->mb_y < s->mb_height);
2408

    
2409
    if(s->picture_structure==PICT_FRAME){
2410
        h->curr_pic_num=   h->frame_num;
2411
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
2412
    }else{
2413
        h->curr_pic_num= 2*h->frame_num + 1;
2414
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
2415
    }
2416

    
2417
    if(h->nal_unit_type == NAL_IDR_SLICE){
2418
        get_ue_golomb(&s->gb); /* idr_pic_id */
2419
    }
2420

    
2421
    if(h->sps.poc_type==0){
2422
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2423

    
2424
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
2425
            h->delta_poc_bottom= get_se_golomb(&s->gb);
2426
        }
2427
    }
2428

    
2429
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
2430
        h->delta_poc[0]= get_se_golomb(&s->gb);
2431

    
2432
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
2433
            h->delta_poc[1]= get_se_golomb(&s->gb);
2434
    }
2435

    
2436
    init_poc(h);
2437

    
2438
    if(h->pps.redundant_pic_cnt_present){
2439
        h->redundant_pic_count= get_ue_golomb(&s->gb);
2440
    }
2441

    
2442
    //set defaults, might be overridden a few lines later
2443
    h->ref_count[0]= h->pps.ref_count[0];
2444
    h->ref_count[1]= h->pps.ref_count[1];
2445

    
2446
    if(h->slice_type_nos != FF_I_TYPE){
2447
        if(h->slice_type_nos == FF_B_TYPE){
2448
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
2449
        }
2450
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
2451

    
2452
        if(num_ref_idx_active_override_flag){
2453
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
2454
            if(h->slice_type_nos==FF_B_TYPE)
2455
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
2456

    
2457
            if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
2458
                av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
2459
                h->ref_count[0]= h->ref_count[1]= 1;
2460
                return -1;
2461
            }
2462
        }
2463
        if(h->slice_type_nos == FF_B_TYPE)
2464
            h->list_count= 2;
2465
        else
2466
            h->list_count= 1;
2467
    }else
2468
        h->list_count= 0;
2469

    
2470
    if(!default_ref_list_done){
2471
        ff_h264_fill_default_ref_list(h);
2472
    }
2473

    
2474
    if(h->slice_type_nos!=FF_I_TYPE && ff_h264_decode_ref_pic_list_reordering(h) < 0)
2475
        return -1;
2476

    
2477
    if(h->slice_type_nos!=FF_I_TYPE){
2478
        s->last_picture_ptr= &h->ref_list[0][0];
2479
        ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2480
    }
2481
    if(h->slice_type_nos==FF_B_TYPE){
2482
        s->next_picture_ptr= &h->ref_list[1][0];
2483
        ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2484
    }
2485

    
2486
    if(   (h->pps.weighted_pred          && h->slice_type_nos == FF_P_TYPE )
2487
       ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
2488
        pred_weight_table(h);
2489
    else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2490
        implicit_weight_table(h, -1);
2491
    }else {
2492
        h->use_weight = 0;
2493
        for (i = 0; i < 2; i++) {
2494
            h->luma_weight_flag[i]   = 0;
2495
            h->chroma_weight_flag[i] = 0;
2496
        }
2497
    }
2498

    
2499
    if(h->nal_ref_idc)
2500
        ff_h264_decode_ref_pic_marking(h0, &s->gb);
2501

    
2502
    if(FRAME_MBAFF){
2503
        ff_h264_fill_mbaff_ref_list(h);
2504

    
2505
        if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2506
            implicit_weight_table(h, 0);
2507
            implicit_weight_table(h, 1);
2508
        }
2509
    }
2510

    
2511
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2512
        ff_h264_direct_dist_scale_factor(h);
2513
    ff_h264_direct_ref_list_init(h);
2514

    
2515
    if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
2516
        tmp = get_ue_golomb_31(&s->gb);
2517
        if(tmp > 2){
2518
            av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2519
            return -1;
2520
        }
2521
        h->cabac_init_idc= tmp;
2522
    }
2523

    
2524
    h->last_qscale_diff = 0;
2525
    tmp = h->pps.init_qp + get_se_golomb(&s->gb);
2526
    if(tmp>51){
2527
        av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
2528
        return -1;
2529
    }
2530
    s->qscale= tmp;
2531
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2532
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2533
    //FIXME qscale / qp ... stuff
2534
    if(h->slice_type == FF_SP_TYPE){
2535
        get_bits1(&s->gb); /* sp_for_switch_flag */
2536
    }
2537
    if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
2538
        get_se_golomb(&s->gb); /* slice_qs_delta */
2539
    }
2540

    
2541
    h->deblocking_filter = 1;
2542
    h->slice_alpha_c0_offset = 52;
2543
    h->slice_beta_offset = 52;
2544
    if( h->pps.deblocking_filter_parameters_present ) {
2545
        tmp= get_ue_golomb_31(&s->gb);
2546
        if(tmp > 2){
2547
            av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
2548
            return -1;
2549
        }
2550
        h->deblocking_filter= tmp;
2551
        if(h->deblocking_filter < 2)
2552
            h->deblocking_filter^= 1; // 1<->0
2553

    
2554
        if( h->deblocking_filter ) {
2555
            h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
2556
            h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
2557
            if(   h->slice_alpha_c0_offset > 104U
2558
               || h->slice_beta_offset     > 104U){
2559
                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);
2560
                return -1;
2561
            }
2562
        }
2563
    }
2564

    
2565
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
2566
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
2567
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
2568
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
2569
        h->deblocking_filter= 0;
2570

    
2571
    if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
2572
        if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
2573
            /* Cheat slightly for speed:
2574
               Do not bother to deblock across slices. */
2575
            h->deblocking_filter = 2;
2576
        } else {
2577
            h0->max_contexts = 1;
2578
            if(!h0->single_decode_warning) {
2579
                av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
2580
                h0->single_decode_warning = 1;
2581
            }
2582
            if(h != h0){
2583
                av_log(h->s.avctx, AV_LOG_ERROR, "deblocking switched inside frame\n");
2584
                return 1;
2585
            }
2586
        }
2587
    }
2588
    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]);
2589

    
2590
#if 0 //FMO
2591
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
2592
        slice_group_change_cycle= get_bits(&s->gb, ?);
2593
#endif
2594

    
2595
    h0->last_slice_type = slice_type;
2596
    h->slice_num = ++h0->current_slice;
2597
    if(h->slice_num >= MAX_SLICES){
2598
        av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
2599
    }
2600

    
2601
    for(j=0; j<2; j++){
2602
        int id_list[16];
2603
        int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
2604
        for(i=0; i<16; i++){
2605
            id_list[i]= 60;
2606
            if(h->ref_list[j][i].data[0]){
2607
                int k;
2608
                uint8_t *base= h->ref_list[j][i].base[0];
2609
                for(k=0; k<h->short_ref_count; k++)
2610
                    if(h->short_ref[k]->base[0] == base){
2611
                        id_list[i]= k;
2612
                        break;
2613
                    }
2614
                for(k=0; k<h->long_ref_count; k++)
2615
                    if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
2616
                        id_list[i]= h->short_ref_count + k;
2617
                        break;
2618
                    }
2619
            }
2620
        }
2621

    
2622
        ref2frm[0]=
2623
        ref2frm[1]= -1;
2624
        for(i=0; i<16; i++)
2625
            ref2frm[i+2]= 4*id_list[i]
2626
                          +(h->ref_list[j][i].reference&3);
2627
        ref2frm[18+0]=
2628
        ref2frm[18+1]= -1;
2629
        for(i=16; i<48; i++)
2630
            ref2frm[i+4]= 4*id_list[(i-16)>>1]
2631
                          +(h->ref_list[j][i].reference&3);
2632
    }
2633

    
2634
    //FIXME: fix draw_edges+PAFF+frame threads
2635
    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;
2636
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
2637

    
2638
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2639
        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",
2640
               h->slice_num,
2641
               (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
2642
               first_mb_in_slice,
2643
               av_get_pict_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
2644
               pps_id, h->frame_num,
2645
               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
2646
               h->ref_count[0], h->ref_count[1],
2647
               s->qscale,
2648
               h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
2649
               h->use_weight,
2650
               h->use_weight==1 && h->use_weight_chroma ? "c" : "",
2651
               h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
2652
               );
2653
    }
2654

    
2655
    return 0;
2656
}
2657

    
2658
int ff_h264_get_slice_type(const H264Context *h)
2659
{
2660
    switch (h->slice_type) {
2661
    case FF_P_TYPE:  return 0;
2662
    case FF_B_TYPE:  return 1;
2663
    case FF_I_TYPE:  return 2;
2664
    case FF_SP_TYPE: return 3;
2665
    case FF_SI_TYPE: return 4;
2666
    default:         return -1;
2667
    }
2668
}
2669

    
2670
/**
2671
 *
2672
 * @return non zero if the loop filter can be skiped
2673
 */
2674
static int fill_filter_caches(H264Context *h, int mb_type){
2675
    MpegEncContext * const s = &h->s;
2676
    const int mb_xy= h->mb_xy;
2677
    int top_xy, left_xy[2];
2678
    int top_type, left_type[2];
2679

    
2680
    top_xy     = mb_xy  - (s->mb_stride << MB_FIELD);
2681

    
2682
    //FIXME deblocking could skip the intra and nnz parts.
2683

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

    
2687
    left_xy[1] = left_xy[0] = mb_xy-1;
2688
    if(FRAME_MBAFF){
2689
        const int left_mb_field_flag     = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);
2690
        const int curr_mb_field_flag     = IS_INTERLACED(mb_type);
2691
        if(s->mb_y&1){
2692
            if (left_mb_field_flag != curr_mb_field_flag) {
2693
                left_xy[0] -= s->mb_stride;
2694
            }
2695
        }else{
2696
            if(curr_mb_field_flag){
2697
                top_xy      += s->mb_stride & (((s->current_picture.mb_type[top_xy    ]>>7)&1)-1);
2698
            }
2699
            if (left_mb_field_flag != curr_mb_field_flag) {
2700
                left_xy[1] += s->mb_stride;
2701
            }
2702
        }
2703
    }
2704

    
2705
    h->top_mb_xy = top_xy;
2706
    h->left_mb_xy[0] = left_xy[0];
2707
    h->left_mb_xy[1] = left_xy[1];
2708
    {
2709
        //for sufficiently low qp, filtering wouldn't do anything
2710
        //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
2711
        int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
2712
        int qp = s->current_picture.qscale_table[mb_xy];
2713
        if(qp <= qp_thresh
2714
           && (left_xy[0]<0 || ((qp + s->current_picture.qscale_table[left_xy[0]] + 1)>>1) <= qp_thresh)
2715
           && (top_xy   < 0 || ((qp + s->current_picture.qscale_table[top_xy    ] + 1)>>1) <= qp_thresh)){
2716
            if(!FRAME_MBAFF)
2717
                return 1;
2718
            if(   (left_xy[0]< 0            || ((qp + s->current_picture.qscale_table[left_xy[1]             ] + 1)>>1) <= qp_thresh)
2719
               && (top_xy    < s->mb_stride || ((qp + s->current_picture.qscale_table[top_xy    -s->mb_stride] + 1)>>1) <= qp_thresh))
2720
                return 1;
2721
        }
2722
    }
2723

    
2724
    top_type     = s->current_picture.mb_type[top_xy]    ;
2725
    left_type[0] = s->current_picture.mb_type[left_xy[0]];
2726
    left_type[1] = s->current_picture.mb_type[left_xy[1]];
2727
    if(h->deblocking_filter == 2){
2728
        if(h->slice_table[top_xy     ] != h->slice_num) top_type= 0;
2729
        if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
2730
    }else{
2731
        if(h->slice_table[top_xy     ] == 0xFFFF) top_type= 0;
2732
        if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
2733
    }
2734
    h->top_type    = top_type    ;
2735
    h->left_type[0]= left_type[0];
2736
    h->left_type[1]= left_type[1];
2737

    
2738
    if(IS_INTRA(mb_type))
2739
        return 0;
2740

    
2741
    AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
2742
    AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
2743
    AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
2744
    AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
2745
    AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
2746

    
2747
    h->cbp= h->cbp_table[mb_xy];
2748

    
2749
    {
2750
        int list;
2751
        for(list=0; list<h->list_count; list++){
2752
            int8_t *ref;
2753
            int y, b_stride;
2754
            int16_t (*mv_dst)[2];
2755
            int16_t (*mv_src)[2];
2756

    
2757
            if(!USES_LIST(mb_type, list)){
2758
                fill_rectangle(  h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
2759
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2760
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2761
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2762
                AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2763
                continue;
2764
            }
2765

    
2766
            ref = &s->current_picture.ref_index[list][4*mb_xy];
2767
            {
2768
                int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2769
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2770
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2771
                ref += 2;
2772
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2773
                AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2774
            }
2775

    
2776
            b_stride = h->b_stride;
2777
            mv_dst   = &h->mv_cache[list][scan8[0]];
2778
            mv_src   = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
2779
            for(y=0; y<4; y++){
2780
                AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
2781
            }
2782

    
2783
        }
2784
    }
2785

    
2786

    
2787
/*
2788
0 . T T. T T T T
2789
1 L . .L . . . .
2790
2 L . .L . . . .
2791
3 . T TL . . . .
2792
4 L . .L . . . .
2793
5 L . .. . . . .
2794
*/
2795
//FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
2796
    if(top_type){
2797
        AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][4+3*8]);
2798
    }
2799

    
2800
    if(left_type[0]){
2801
        h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
2802
        h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
2803
        h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
2804
        h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
2805
    }
2806

    
2807
    // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
2808
    if(!CABAC && h->pps.transform_8x8_mode){
2809
        if(IS_8x8DCT(top_type)){
2810
            h->non_zero_count_cache[4+8*0]=
2811
            h->non_zero_count_cache[5+8*0]= h->cbp_table[top_xy] & 4;
2812
            h->non_zero_count_cache[6+8*0]=
2813
            h->non_zero_count_cache[7+8*0]= h->cbp_table[top_xy] & 8;
2814
        }
2815
        if(IS_8x8DCT(left_type[0])){
2816
            h->non_zero_count_cache[3+8*1]=
2817
            h->non_zero_count_cache[3+8*2]= h->cbp_table[left_xy[0]]&2; //FIXME check MBAFF
2818
        }
2819
        if(IS_8x8DCT(left_type[1])){
2820
            h->non_zero_count_cache[3+8*3]=
2821
            h->non_zero_count_cache[3+8*4]= h->cbp_table[left_xy[1]]&8; //FIXME check MBAFF
2822
        }
2823

    
2824
        if(IS_8x8DCT(mb_type)){
2825
            h->non_zero_count_cache[scan8[0   ]]= h->non_zero_count_cache[scan8[1   ]]=
2826
            h->non_zero_count_cache[scan8[2   ]]= h->non_zero_count_cache[scan8[3   ]]= h->cbp & 1;
2827

    
2828
            h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
2829
            h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
2830

    
2831
            h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
2832
            h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp & 4;
2833

    
2834
            h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
2835
            h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
2836
        }
2837
    }
2838

    
2839
    if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
2840
        int list;
2841
        for(list=0; list<h->list_count; list++){
2842
            if(USES_LIST(top_type, list)){
2843
                const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
2844
                const int b8_xy= 4*top_xy + 2;
2845
                int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2846
                AV_COPY128(h->mv_cache[list][scan8[0] + 0 - 1*8], s->current_picture.motion_val[list][b_xy + 0]);
2847
                h->ref_cache[list][scan8[0] + 0 - 1*8]=
2848
                h->ref_cache[list][scan8[0] + 1 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 0]];
2849
                h->ref_cache[list][scan8[0] + 2 - 1*8]=
2850
                h->ref_cache[list][scan8[0] + 3 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 1]];
2851
            }else{
2852
                AV_ZERO128(h->mv_cache[list][scan8[0] + 0 - 1*8]);
2853
                AV_WN32A(&h->ref_cache[list][scan8[0] + 0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2854
            }
2855

    
2856
            if(!IS_INTERLACED(mb_type^left_type[0])){
2857
                if(USES_LIST(left_type[0], list)){
2858
                    const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
2859
                    const int b8_xy= 4*left_xy[0] + 1;
2860
                    int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[0]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2861
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 0 ], s->current_picture.motion_val[list][b_xy + h->b_stride*0]);
2862
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 8 ], s->current_picture.motion_val[list][b_xy + h->b_stride*1]);
2863
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +16 ], s->current_picture.motion_val[list][b_xy + h->b_stride*2]);
2864
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +24 ], s->current_picture.motion_val[list][b_xy + h->b_stride*3]);
2865
                    h->ref_cache[list][scan8[0] - 1 + 0 ]=
2866
                    h->ref_cache[list][scan8[0] - 1 + 8 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*0]];
2867
                    h->ref_cache[list][scan8[0] - 1 +16 ]=
2868
                    h->ref_cache[list][scan8[0] - 1 +24 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*1]];
2869
                }else{
2870
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 0 ]);
2871
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 8 ]);
2872
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +16 ]);
2873
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +24 ]);
2874
                    h->ref_cache[list][scan8[0] - 1 + 0  ]=
2875
                    h->ref_cache[list][scan8[0] - 1 + 8  ]=
2876
                    h->ref_cache[list][scan8[0] - 1 + 16 ]=
2877
                    h->ref_cache[list][scan8[0] - 1 + 24 ]= LIST_NOT_USED;
2878
                }
2879
            }
2880
        }
2881
    }
2882

    
2883
    return 0;
2884
}
2885

    
2886
static void loop_filter(H264Context *h){
2887
    MpegEncContext * const s = &h->s;
2888
    uint8_t  *dest_y, *dest_cb, *dest_cr;
2889
    int linesize, uvlinesize, mb_x, mb_y;
2890
    const int end_mb_y= s->mb_y + FRAME_MBAFF;
2891
    const int old_slice_type= h->slice_type;
2892
    const int end_mb_x  = s->mb_x;
2893

    
2894
    if(h->deblocking_filter) {
2895
        int start_x= s->resync_mb_y == s->mb_y ? s->resync_mb_x : 0;
2896
        for(mb_x= start_x; mb_x<end_mb_x; mb_x++){
2897
            for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
2898
                int mb_xy, mb_type;
2899
                mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
2900
                h->slice_num= h->slice_table[mb_xy];
2901
                mb_type= s->current_picture.mb_type[mb_xy];
2902
                h->list_count= h->list_counts[mb_xy];
2903

    
2904
                if(FRAME_MBAFF)
2905
                    h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2906

    
2907
                s->mb_x= mb_x;
2908
                s->mb_y= mb_y;
2909
                dest_y  = s->current_picture.data[0] + (mb_x + mb_y * s->linesize  ) * 16;
2910
                dest_cb = s->current_picture.data[1] + (mb_x + mb_y * s->uvlinesize) * 8;
2911
                dest_cr = s->current_picture.data[2] + (mb_x + mb_y * s->uvlinesize) * 8;
2912
                    //FIXME simplify above
2913

    
2914
                if (MB_FIELD) {
2915
                    linesize   = h->mb_linesize   = s->linesize * 2;
2916
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2917
                    if(mb_y&1){ //FIXME move out of this function?
2918
                        dest_y -= s->linesize*15;
2919
                        dest_cb-= s->uvlinesize*7;
2920
                        dest_cr-= s->uvlinesize*7;
2921
                    }
2922
                } else {
2923
                    linesize   = h->mb_linesize   = s->linesize;
2924
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize;
2925
                }
2926
                backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
2927
                if(fill_filter_caches(h, mb_type))
2928
                    continue;
2929
                h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2930
                h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2931

    
2932
                if (FRAME_MBAFF) {
2933
                    ff_h264_filter_mb     (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2934
                } else {
2935
                    ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2936
                }
2937
            }
2938
        }
2939
    }
2940
    h->slice_type= old_slice_type;
2941
    s->mb_x= end_mb_x;
2942
    s->mb_y= end_mb_y - FRAME_MBAFF;
2943
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2944
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2945
}
2946

    
2947
static void predict_field_decoding_flag(H264Context *h){
2948
    MpegEncContext * const s = &h->s;
2949
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
2950
    int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
2951
                ? s->current_picture.mb_type[mb_xy-1]
2952
                : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
2953
                ? s->current_picture.mb_type[mb_xy-s->mb_stride]
2954
                : 0;
2955
    h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
2956
}
2957

    
2958
/**
2959
 * Draw edges and report progress for the last MB row.
2960
 */
2961
static void decode_finish_row(H264Context *h){
2962
    MpegEncContext * const s = &h->s;
2963
    int top = 16*(s->mb_y >> FIELD_PICTURE);
2964
    int height = 16 << FRAME_MBAFF;
2965
    int deblock_border = (16 + 4) << FRAME_MBAFF;
2966
    int pic_height = 16*s->mb_height >> FIELD_PICTURE;
2967

    
2968
    if (h->deblocking_filter) {
2969
        if((top + height) >= pic_height)
2970
            height += deblock_border;
2971

    
2972
        top -= deblock_border;
2973
    }
2974

    
2975
    if (top >= pic_height || (top + height) < h->emu_edge_height)
2976
        return;
2977

    
2978
    height = FFMIN(height, pic_height - top);
2979
    if (top < h->emu_edge_height) {
2980
        height = top+height;
2981
        top = 0;
2982
    }
2983

    
2984
    ff_draw_horiz_band(s, top, height);
2985

    
2986
    if (s->dropable) return;
2987

    
2988
    ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
2989
                             s->picture_structure==PICT_BOTTOM_FIELD);
2990
}
2991

    
2992
static int decode_slice(struct AVCodecContext *avctx, void *arg){
2993
    H264Context *h = *(void**)arg;
2994
    MpegEncContext * const s = &h->s;
2995
    const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
2996

    
2997
    s->mb_skip_run= -1;
2998

    
2999
    h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
3000
                    (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
3001

    
3002
    if( h->pps.cabac ) {
3003
        /* realign */
3004
        align_get_bits( &s->gb );
3005

    
3006
        /* init cabac */
3007
        ff_init_cabac_states( &h->cabac);
3008
        ff_init_cabac_decoder( &h->cabac,
3009
                               s->gb.buffer + get_bits_count(&s->gb)/8,
3010
                               (get_bits_left(&s->gb) + 7)/8);
3011

    
3012
        ff_h264_init_cabac_states(h);
3013

    
3014
        for(;;){
3015
//START_TIMER
3016
            int ret = ff_h264_decode_mb_cabac(h);
3017
            int eos;
3018
//STOP_TIMER("decode_mb_cabac")
3019

    
3020
            if(ret>=0) ff_h264_hl_decode_mb(h);
3021

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

    
3025
                ret = ff_h264_decode_mb_cabac(h);
3026

    
3027
                if(ret>=0) ff_h264_hl_decode_mb(h);
3028
                s->mb_y--;
3029
            }
3030
            eos = get_cabac_terminate( &h->cabac );
3031

    
3032
            if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
3033
                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);
3034
                return 0;
3035
            }
3036
            if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3037
                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);
3038
                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);
3039
                return -1;
3040
            }
3041

    
3042
            if( ++s->mb_x >= s->mb_width ) {
3043
                loop_filter(h);
3044
                s->mb_x = 0;
3045
                decode_finish_row(h);
3046
                ++s->mb_y;
3047
                if(FIELD_OR_MBAFF_PICTURE) {
3048
                    ++s->mb_y;
3049
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
3050
                        predict_field_decoding_flag(h);
3051
                }
3052
            }
3053

    
3054
            if( eos || s->mb_y >= s->mb_height ) {
3055
                if(s->mb_x)
3056
                    loop_filter(h);
3057
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3058
                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);
3059
                return 0;
3060
            }
3061
        }
3062

    
3063
    } else {
3064
        for(;;){
3065
            int ret = ff_h264_decode_mb_cavlc(h);
3066

    
3067
            if(ret>=0) ff_h264_hl_decode_mb(h);
3068

    
3069
            if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
3070
                s->mb_y++;
3071
                ret = ff_h264_decode_mb_cavlc(h);
3072

    
3073
                if(ret>=0) ff_h264_hl_decode_mb(h);
3074
                s->mb_y--;
3075
            }
3076

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

    
3081
                return -1;
3082
            }
3083

    
3084
            if(++s->mb_x >= s->mb_width){
3085
                loop_filter(h);
3086
                s->mb_x=0;
3087
                decode_finish_row(h);
3088
                ++s->mb_y;
3089
                if(FIELD_OR_MBAFF_PICTURE) {
3090
                    ++s->mb_y;
3091
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
3092
                        predict_field_decoding_flag(h);
3093
                }
3094
                if(s->mb_y >= s->mb_height){
3095
                    tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3096

    
3097
                    if(   get_bits_count(&s->gb) == s->gb.size_in_bits
3098
                       || get_bits_count(&s->gb) <  s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
3099
                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3100

    
3101
                        return 0;
3102
                    }else{
3103
                        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);
3104

    
3105
                        return -1;
3106
                    }
3107
                }
3108
            }
3109

    
3110
            if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
3111
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3112
                if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
3113
                    if(s->mb_x)
3114
                        loop_filter(h);
3115
                    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);
3116

    
3117
                    return 0;
3118
                }else{
3119
                    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);
3120

    
3121
                    return -1;
3122
                }
3123
            }
3124
        }
3125
    }
3126

    
3127
#if 0
3128
    for(;s->mb_y < s->mb_height; s->mb_y++){
3129
        for(;s->mb_x < s->mb_width; s->mb_x++){
3130
            int ret= decode_mb(h);
3131

3132
            ff_h264_hl_decode_mb(h);
3133

3134
            if(ret<0){
3135
                av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3136
                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);
3137

3138
                return -1;
3139
            }
3140

3141
            if(++s->mb_x >= s->mb_width){
3142
                s->mb_x=0;
3143
                if(++s->mb_y >= s->mb_height){
3144
                    if(get_bits_count(s->gb) == s->gb.size_in_bits){
3145
                        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);
3146

3147
                        return 0;
3148
                    }else{
3149
                        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);
3150

3151
                        return -1;
3152
                    }
3153
                }
3154
            }
3155

3156
            if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
3157
                if(get_bits_count(s->gb) == s->gb.size_in_bits){
3158
                    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);
3159

3160
                    return 0;
3161
                }else{
3162
                    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);
3163

3164
                    return -1;
3165
                }
3166
            }
3167
        }
3168
        s->mb_x=0;
3169
        ff_draw_horiz_band(s, 16*s->mb_y, 16);
3170
    }
3171
#endif
3172
    return -1; //not reached
3173
}
3174

    
3175
/**
3176
 * Call decode_slice() for each context.
3177
 *
3178
 * @param h h264 master context
3179
 * @param context_count number of contexts to execute
3180
 */
3181
static void execute_decode_slices(H264Context *h, int context_count){
3182
    MpegEncContext * const s = &h->s;
3183
    AVCodecContext * const avctx= s->avctx;
3184
    H264Context *hx;
3185
    int i;
3186

    
3187
    if (s->avctx->hwaccel)
3188
        return;
3189
    if(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3190
        return;
3191
    if(context_count == 1) {
3192
        decode_slice(avctx, &h);
3193
    } else {
3194
        for(i = 1; i < context_count; i++) {
3195
            hx = h->thread_context[i];
3196
            hx->s.error_recognition = avctx->error_recognition;
3197
            hx->s.error_count = 0;
3198
            hx->x264_build= h->x264_build;
3199
        }
3200

    
3201
        avctx->execute(avctx, (void *)decode_slice,
3202
                       h->thread_context, NULL, context_count, sizeof(void*));
3203

    
3204
        /* pull back stuff from slices to master context */
3205
        hx = h->thread_context[context_count - 1];
3206
        s->mb_x = hx->s.mb_x;
3207
        s->mb_y = hx->s.mb_y;
3208
        s->dropable = hx->s.dropable;
3209
        s->picture_structure = hx->s.picture_structure;
3210
        for(i = 1; i < context_count; i++)
3211
            h->s.error_count += h->thread_context[i]->s.error_count;
3212
    }
3213
}
3214

    
3215

    
3216
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
3217
    MpegEncContext * const s = &h->s;
3218
    AVCodecContext * const avctx= s->avctx;
3219
    int buf_index=0;
3220
    H264Context *hx; ///< thread context
3221
    int context_count = 0;
3222
    int next_avc= h->is_avc ? 0 : buf_size;
3223

    
3224
    h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
3225
#if 0
3226
    int i;
3227
    for(i=0; i<50; i++){
3228
        av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
3229
    }
3230
#endif
3231
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
3232
        h->current_slice = 0;
3233
        if (!s->first_field)
3234
            s->current_picture_ptr= NULL;
3235
        ff_h264_reset_sei(h);
3236
    }
3237

    
3238
    for(;;){
3239
        int consumed;
3240
        int dst_length;
3241
        int bit_length;
3242
        const uint8_t *ptr;
3243
        int i, nalsize = 0;
3244
        int err;
3245

    
3246
        if(buf_index >= next_avc) {
3247
            if(buf_index >= buf_size) break;
3248
            nalsize = 0;
3249
            for(i = 0; i < h->nal_length_size; i++)
3250
                nalsize = (nalsize << 8) | buf[buf_index++];
3251
            if(nalsize <= 0 || nalsize > buf_size - buf_index){
3252
                av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
3253
                break;
3254
            }
3255
            next_avc= buf_index + nalsize;
3256
        } else {
3257
            // start code prefix search
3258
            for(; buf_index + 3 < next_avc; buf_index++){
3259
                // This should always succeed in the first iteration.
3260
                if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
3261
                    break;
3262
            }
3263

    
3264
            if(buf_index+3 >= buf_size) break;
3265

    
3266
            buf_index+=3;
3267
            if(buf_index >= next_avc) continue;
3268
        }
3269

    
3270
        hx = h->thread_context[context_count];
3271

    
3272
        ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
3273
        if (ptr==NULL || dst_length < 0){
3274
            return -1;
3275
        }
3276
        i= buf_index + consumed;
3277
        if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
3278
           buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
3279
            s->workaround_bugs |= FF_BUG_TRUNCATED;
3280

    
3281
        if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
3282
        while(ptr[dst_length - 1] == 0 && dst_length > 0)
3283
            dst_length--;
3284
        }
3285
        bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
3286

    
3287
        if(s->avctx->debug&FF_DEBUG_STARTCODE){
3288
            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);
3289
        }
3290

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

    
3295
        buf_index += consumed;
3296

    
3297
        //FIXME do not discard SEI id
3298
        if(
3299
#if FF_API_HURRY_UP
3300
           (s->hurry_up == 1 && h->nal_ref_idc  == 0) ||
3301
#endif
3302
           (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc  == 0))
3303
            continue;
3304

    
3305
      again:
3306
        err = 0;
3307
        switch(hx->nal_unit_type){
3308
        case NAL_IDR_SLICE:
3309
            if (h->nal_unit_type != NAL_IDR_SLICE) {
3310
                av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
3311
                return -1;
3312
            }
3313
            idr(h); //FIXME ensure we don't loose some frames if there is reordering
3314
        case NAL_SLICE:
3315
            init_get_bits(&hx->s.gb, ptr, bit_length);
3316
            hx->intra_gb_ptr=
3317
            hx->inter_gb_ptr= &hx->s.gb;
3318
            hx->s.data_partitioning = 0;
3319

    
3320
            if((err = decode_slice_header(hx, h)))
3321
               break;
3322

    
3323
            s->current_picture_ptr->key_frame |=
3324
                    (hx->nal_unit_type == NAL_IDR_SLICE) ||
3325
                    (h->sei_recovery_frame_cnt >= 0);
3326

    
3327
            if (h->current_slice == 1) {
3328
                if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3329
                    decode_postinit(h);
3330
                }
3331

    
3332
                if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
3333
                    return -1;
3334
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3335
                    ff_vdpau_h264_picture_start(s);
3336
            }
3337

    
3338
            if(hx->redundant_pic_count==0
3339
#if FF_API_HURRY_UP
3340
               && hx->s.hurry_up < 5
3341
#endif
3342
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3343
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3344
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3345
               && avctx->skip_frame < AVDISCARD_ALL){
3346
                if(avctx->hwaccel) {
3347
                    if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
3348
                        return -1;
3349
                }else
3350
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
3351
                    static const uint8_t start_code[] = {0x00, 0x00, 0x01};
3352
                    ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
3353
                    ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
3354
                }else
3355
                    context_count++;
3356
            }
3357
            break;
3358
        case NAL_DPA:
3359
            init_get_bits(&hx->s.gb, ptr, bit_length);
3360
            hx->intra_gb_ptr=
3361
            hx->inter_gb_ptr= NULL;
3362

    
3363
            if ((err = decode_slice_header(hx, h)) < 0)
3364
                break;
3365

    
3366
            hx->s.data_partitioning = 1;
3367

    
3368
            break;
3369
        case NAL_DPB:
3370
            init_get_bits(&hx->intra_gb, ptr, bit_length);
3371
            hx->intra_gb_ptr= &hx->intra_gb;
3372
            break;
3373
        case NAL_DPC:
3374
            init_get_bits(&hx->inter_gb, ptr, bit_length);
3375
            hx->inter_gb_ptr= &hx->inter_gb;
3376

    
3377
            if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
3378
               && s->context_initialized
3379
#if FF_API_HURRY_UP
3380
               && s->hurry_up < 5
3381
#endif
3382
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3383
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3384
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3385
               && avctx->skip_frame < AVDISCARD_ALL)
3386
                context_count++;
3387
            break;
3388
        case NAL_SEI:
3389
            init_get_bits(&s->gb, ptr, bit_length);
3390
            ff_h264_decode_sei(h);
3391
            break;
3392
        case NAL_SPS:
3393
            init_get_bits(&s->gb, ptr, bit_length);
3394
            ff_h264_decode_seq_parameter_set(h);
3395

    
3396
            if(s->flags& CODEC_FLAG_LOW_DELAY)
3397
                s->low_delay=1;
3398

    
3399
            if(avctx->has_b_frames < 2)
3400
                avctx->has_b_frames= !s->low_delay;
3401
            break;
3402
        case NAL_PPS:
3403
            init_get_bits(&s->gb, ptr, bit_length);
3404

    
3405
            ff_h264_decode_picture_parameter_set(h, bit_length);
3406

    
3407
            break;
3408
        case NAL_AUD:
3409
        case NAL_END_SEQUENCE:
3410
        case NAL_END_STREAM:
3411
        case NAL_FILLER_DATA:
3412
        case NAL_SPS_EXT:
3413
        case NAL_AUXILIARY_SLICE:
3414
            break;
3415
        default:
3416
            av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
3417
        }
3418

    
3419
        if(context_count == h->max_contexts) {
3420
            execute_decode_slices(h, context_count);
3421
            context_count = 0;
3422
        }
3423

    
3424
        if (err < 0)
3425
            av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
3426
        else if(err == 1) {
3427
            /* Slice could not be decoded in parallel mode, copy down
3428
             * NAL unit stuff to context 0 and restart. Note that
3429
             * rbsp_buffer is not transferred, but since we no longer
3430
             * run in parallel mode this should not be an issue. */
3431
            h->nal_unit_type = hx->nal_unit_type;
3432
            h->nal_ref_idc   = hx->nal_ref_idc;
3433
            hx = h;
3434
            goto again;
3435
        }
3436
    }
3437
    if(context_count)
3438
        execute_decode_slices(h, context_count);
3439
    return buf_index;
3440
}
3441

    
3442
/**
3443
 * returns the number of bytes consumed for building the current frame
3444
 */
3445
static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
3446
        if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
3447
        if(pos+10>buf_size) pos=buf_size; // oops ;)
3448

    
3449
        return pos;
3450
}
3451

    
3452
static int decode_frame(AVCodecContext *avctx,
3453
                             void *data, int *data_size,
3454
                             AVPacket *avpkt)
3455
{
3456
    const uint8_t *buf = avpkt->data;
3457
    int buf_size = avpkt->size;
3458
    H264Context *h = avctx->priv_data;
3459
    MpegEncContext *s = &h->s;
3460
    AVFrame *pict = data;
3461
    int buf_index;
3462

    
3463
    s->flags= avctx->flags;
3464
    s->flags2= avctx->flags2;
3465

    
3466
   /* end of stream, output what is still in the buffers */
3467
 out:
3468
    if (buf_size == 0) {
3469
        Picture *out;
3470
        int i, out_idx;
3471

    
3472
        s->current_picture_ptr = NULL;
3473

    
3474
//FIXME factorize this with the output code below
3475
        out = h->delayed_pic[0];
3476
        out_idx = 0;
3477
        for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
3478
            if(h->delayed_pic[i]->poc < out->poc){
3479
                out = h->delayed_pic[i];
3480
                out_idx = i;
3481
            }
3482

    
3483
        for(i=out_idx; h->delayed_pic[i]; i++)
3484
            h->delayed_pic[i] = h->delayed_pic[i+1];
3485

    
3486
        if(out){
3487
            *data_size = sizeof(AVFrame);
3488
            *pict= *(AVFrame*)out;
3489
        }
3490

    
3491
        return 0;
3492
    }
3493

    
3494
    buf_index=decode_nal_units(h, buf, buf_size);
3495
    if(buf_index < 0)
3496
        return -1;
3497

    
3498
    if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
3499
        buf_size = 0;
3500
        goto out;
3501
    }
3502

    
3503
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
3504
        if (avctx->skip_frame >= AVDISCARD_NONREF
3505
#if FF_API_HURRY_UP
3506
                || s->hurry_up
3507
#endif
3508
           )
3509
            return 0;
3510
        av_log(avctx, AV_LOG_ERROR, "no frame!\n");
3511
        return -1;
3512
    }
3513

    
3514
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
3515

    
3516
        if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h);
3517

    
3518
        field_end(h, 0);
3519

    
3520
        if (!h->next_output_pic) {
3521
            /* Wait for second field. */
3522
            *data_size = 0;
3523

    
3524
        } else {
3525
            *data_size = sizeof(AVFrame);
3526
            *pict = *(AVFrame*)h->next_output_pic;
3527
        }
3528
    }
3529

    
3530
    assert(pict->data[0] || !*data_size);
3531
    ff_print_debug_info(s, pict);
3532
//printf("out %d\n", (int)pict->data[0]);
3533

    
3534
    return get_consumed_bytes(s, buf_index, buf_size);
3535
}
3536
#if 0
3537
static inline void fill_mb_avail(H264Context *h){
3538
    MpegEncContext * const s = &h->s;
3539
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3540

3541
    if(s->mb_y){
3542
        h->mb_avail[0]= s->mb_x                 && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
3543
        h->mb_avail[1]=                            h->slice_table[mb_xy - s->mb_stride    ] == h->slice_num;
3544
        h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
3545
    }else{
3546
        h->mb_avail[0]=
3547
        h->mb_avail[1]=
3548
        h->mb_avail[2]= 0;
3549
    }
3550
    h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
3551
    h->mb_avail[4]= 1; //FIXME move out
3552
    h->mb_avail[5]= 0; //FIXME move out
3553
}
3554
#endif
3555

    
3556
#ifdef TEST
3557
#undef printf
3558
#undef random
3559
#define COUNT 8000
3560
#define SIZE (COUNT*40)
3561
int main(void){
3562
    int i;
3563
    uint8_t temp[SIZE];
3564
    PutBitContext pb;
3565
    GetBitContext gb;
3566
//    int int_temp[10000];
3567
    DSPContext dsp;
3568
    AVCodecContext avctx;
3569

    
3570
    dsputil_init(&dsp, &avctx);
3571

    
3572
    init_put_bits(&pb, temp, SIZE);
3573
    printf("testing unsigned exp golomb\n");
3574
    for(i=0; i<COUNT; i++){
3575
        START_TIMER
3576
        set_ue_golomb(&pb, i);
3577
        STOP_TIMER("set_ue_golomb");
3578
    }
3579
    flush_put_bits(&pb);
3580

    
3581
    init_get_bits(&gb, temp, 8*SIZE);
3582
    for(i=0; i<COUNT; i++){
3583
        int j, s;
3584

    
3585
        s= show_bits(&gb, 24);
3586

    
3587
        START_TIMER
3588
        j= get_ue_golomb(&gb);
3589
        if(j != i){
3590
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3591
//            return -1;
3592
        }
3593
        STOP_TIMER("get_ue_golomb");
3594
    }
3595

    
3596

    
3597
    init_put_bits(&pb, temp, SIZE);
3598
    printf("testing signed exp golomb\n");
3599
    for(i=0; i<COUNT; i++){
3600
        START_TIMER
3601
        set_se_golomb(&pb, i - COUNT/2);
3602
        STOP_TIMER("set_se_golomb");
3603
    }
3604
    flush_put_bits(&pb);
3605

    
3606
    init_get_bits(&gb, temp, 8*SIZE);
3607
    for(i=0; i<COUNT; i++){
3608
        int j, s;
3609

    
3610
        s= show_bits(&gb, 24);
3611

    
3612
        START_TIMER
3613
        j= get_se_golomb(&gb);
3614
        if(j != i - COUNT/2){
3615
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3616
//            return -1;
3617
        }
3618
        STOP_TIMER("get_se_golomb");
3619
    }
3620

    
3621
#if 0
3622
    printf("testing 4x4 (I)DCT\n");
3623

3624
    DCTELEM block[16];
3625
    uint8_t src[16], ref[16];
3626
    uint64_t error= 0, max_error=0;
3627

3628
    for(i=0; i<COUNT; i++){
3629
        int j;
3630
//        printf("%d %d %d\n", r1, r2, (r2-r1)*16);
3631
        for(j=0; j<16; j++){
3632
            ref[j]= random()%255;
3633
            src[j]= random()%255;
3634
        }
3635

3636
        h264_diff_dct_c(block, src, ref, 4);
3637

3638
        //normalize
3639
        for(j=0; j<16; j++){
3640
//            printf("%d ", block[j]);
3641
            block[j]= block[j]*4;
3642
            if(j&1) block[j]= (block[j]*4 + 2)/5;
3643
            if(j&4) block[j]= (block[j]*4 + 2)/5;
3644
        }
3645
//        printf("\n");
3646

3647
        h->h264dsp.h264_idct_add(ref, block, 4);
3648
/*        for(j=0; j<16; j++){
3649
            printf("%d ", ref[j]);
3650
        }
3651
        printf("\n");*/
3652

3653
        for(j=0; j<16; j++){
3654
            int diff= FFABS(src[j] - ref[j]);
3655

3656
            error+= diff*diff;
3657
            max_error= FFMAX(max_error, diff);
3658
        }
3659
    }
3660
    printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
3661
    printf("testing quantizer\n");
3662
    for(qp=0; qp<52; qp++){
3663
        for(i=0; i<16; i++)
3664
            src1_block[i]= src2_block[i]= random()%255;
3665

3666
    }
3667
    printf("Testing NAL layer\n");
3668

3669
    uint8_t bitstream[COUNT];
3670
    uint8_t nal[COUNT*2];
3671
    H264Context h;
3672
    memset(&h, 0, sizeof(H264Context));
3673

3674
    for(i=0; i<COUNT; i++){
3675
        int zeros= i;
3676
        int nal_length;
3677
        int consumed;
3678
        int out_length;
3679
        uint8_t *out;
3680
        int j;
3681

3682
        for(j=0; j<COUNT; j++){
3683
            bitstream[j]= (random() % 255) + 1;
3684
        }
3685

3686
        for(j=0; j<zeros; j++){
3687
            int pos= random() % COUNT;
3688
            while(bitstream[pos] == 0){
3689
                pos++;
3690
                pos %= COUNT;
3691
            }
3692
            bitstream[pos]=0;
3693
        }
3694

3695
        START_TIMER
3696

3697
        nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
3698
        if(nal_length<0){
3699
            printf("encoding failed\n");
3700
            return -1;
3701
        }
3702

3703
        out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
3704

3705
        STOP_TIMER("NAL")
3706

3707
        if(out_length != COUNT){
3708
            printf("incorrect length %d %d\n", out_length, COUNT);
3709
            return -1;
3710
        }
3711

3712
        if(consumed != nal_length){
3713
            printf("incorrect consumed length %d %d\n", nal_length, consumed);
3714
            return -1;
3715
        }
3716

3717
        if(memcmp(bitstream, out, COUNT)){
3718
            printf("mismatch\n");
3719
            return -1;
3720
        }
3721
    }
3722
#endif
3723

    
3724
    printf("Testing RBSP\n");
3725

    
3726

    
3727
    return 0;
3728
}
3729
#endif /* TEST */
3730

    
3731

    
3732
av_cold void ff_h264_free_context(H264Context *h)
3733
{
3734
    int i;
3735

    
3736
    free_tables(h, 1); //FIXME cleanup init stuff perhaps
3737

    
3738
    for(i = 0; i < MAX_SPS_COUNT; i++)
3739
        av_freep(h->sps_buffers + i);
3740

    
3741
    for(i = 0; i < MAX_PPS_COUNT; i++)
3742
        av_freep(h->pps_buffers + i);
3743
}
3744

    
3745
av_cold int ff_h264_decode_end(AVCodecContext *avctx)
3746
{
3747
    H264Context *h = avctx->priv_data;
3748
    MpegEncContext *s = &h->s;
3749

    
3750
    ff_h264_free_context(h);
3751

    
3752
    MPV_common_end(s);
3753

    
3754
//    memset(h, 0, sizeof(H264Context));
3755

    
3756
    return 0;
3757
}
3758

    
3759
static const AVProfile profiles[] = {
3760
    { FF_PROFILE_H264_BASELINE,             "Baseline"              },
3761
    { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
3762
    { FF_PROFILE_H264_MAIN,                 "Main"                  },
3763
    { FF_PROFILE_H264_EXTENDED,             "Extended"              },
3764
    { FF_PROFILE_H264_HIGH,                 "High"                  },
3765
    { FF_PROFILE_H264_HIGH_10,              "High 10"               },
3766
    { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
3767
    { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
3768
    { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
3769
    { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
3770
    { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
3771
    { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
3772
    { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
3773
    { FF_PROFILE_UNKNOWN },
3774
};
3775

    
3776
AVCodec ff_h264_decoder = {
3777
    "h264",
3778
    AVMEDIA_TYPE_VIDEO,
3779
    CODEC_ID_H264,
3780
    sizeof(H264Context),
3781
    ff_h264_decode_init,
3782
    NULL,
3783
    ff_h264_decode_end,
3784
    decode_frame,
3785
    /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
3786
    .flush= flush_dpb,
3787
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
3788
    .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
3789
    .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
3790
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3791
};
3792

    
3793
#if CONFIG_H264_VDPAU_DECODER
3794
AVCodec ff_h264_vdpau_decoder = {
3795
    "h264_vdpau",
3796
    AVMEDIA_TYPE_VIDEO,
3797
    CODEC_ID_H264,
3798
    sizeof(H264Context),
3799
    ff_h264_decode_init,
3800
    NULL,
3801
    ff_h264_decode_end,
3802
    decode_frame,
3803
    CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
3804
    .flush= flush_dpb,
3805
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
3806
    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
3807
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3808
};
3809
#endif