Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ e7077f5e

History | View | Annotate | Download (145 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[QP_MAX_MAX+1]={
49
0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
50
};
51

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

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

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

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

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

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

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

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

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

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

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

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

    
143
    return mode;
144
}
145

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
329
        assert(IS_8X8(mb_type));
330

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

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

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

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

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

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

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

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

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

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

    
428
#undef xStride
429
#undef stride
430

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
561
    if(list0 && list1){
562
        /* don't optimize for luma-only case, since B-frames usually
563
         * use implicit weights => chroma too. */
564
        uint8_t *tmp_cb = s->obmc_scratchpad;
565
        uint8_t *tmp_cr = s->obmc_scratchpad + (8<<h->pixel_shift);
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+64)<<h->pixel_shift) + (my + (s->mb_x&3)*4)*h->mb_linesize;
641
        s->dsp.prefetch(src[0]+off, s->linesize, 4);
642
        off= (((mx>>1)+64)<<h->pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
643
        s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
644
    }
645
}
646

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

    
655
    assert(IS_INTER(mb_type));
656

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

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

    
687
        assert(IS_8X8(mb_type));
688

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

    
695
            if(IS_SUB_8X8(sub_mb_type)){
696
                mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
697
                    qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
698
                    &weight_op[3], &weight_avg[3],
699
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
700
            }else if(IS_SUB_8X4(sub_mb_type)){
701
                mc_part(h, n  , 0, 2, (4<<h->pixel_shift), dest_y, dest_cb, dest_cr, x_offset, y_offset,
702
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
703
                    &weight_op[4], &weight_avg[4],
704
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
705
                mc_part(h, n+2, 0, 2, (4<<h->pixel_shift), 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
    const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
773
    h->dequant8_coeff[0] = h->dequant8_buffer[0];
774
    h->dequant8_coeff[1] = h->dequant8_buffer[1];
775

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

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

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

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

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

    
834

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

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

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

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

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

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

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

    
868
    s->obmc_scratchpad = NULL;
869

    
870
    if(!h->dequant4_coeff[0])
871
        init_dequant_tables(h);
872

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

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

    
896
    dst->s.obmc_scratchpad = NULL;
897
    ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma);
898
}
899

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

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

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

    
916
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
917

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

    
921
    s->width = s->avctx->width;
922
    s->height = s->avctx->height;
923
    s->codec_id= s->avctx->codec->id;
924

    
925
    ff_h264dsp_init(&h->h264dsp, 8);
926
    ff_h264_pred_init(&h->hpc, s->codec_id, 8);
927

    
928
    h->dequant_coeff_pps= -1;
929
    s->unrestricted_mv=1;
930
    s->decode=1; //FIXME
931

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

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

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

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

    
946
        h->is_avc = 1;
947

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

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

    
990
    MPV_decode_defaults(s);
991

    
992
    s->avctx = avctx;
993
    common_init(h);
994

    
995
    s->out_format = FMT_H264;
996
    s->workaround_bugs= avctx->workaround_bugs;
997

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

    
1004
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1005

    
1006
    ff_h264_decode_init_vlc();
1007

    
1008
    h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1009
    h->pixel_shift = 0;
1010

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

    
1023
    if(avctx->extradata_size > 0 && avctx->extradata &&
1024
        ff_h264_decode_extradata(h))
1025
        return -1;
1026

    
1027
    if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
1028
        s->avctx->has_b_frames = h->sps.num_reorder_frames;
1029
        s->low_delay = 0;
1030
    }
1031

    
1032
    return 0;
1033
}
1034

    
1035
static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
1036
{
1037
    int i;
1038

    
1039
    for (i=0; i<count; i++){
1040
        to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1041
    }
1042
}
1043

    
1044
static void copy_parameter_set(void **to, void **from, int count, int size)
1045
{
1046
    int i;
1047

    
1048
    for (i=0; i<count; i++){
1049
        if (to[i] && !from[i]) av_freep(&to[i]);
1050
        else if (from[i] && !to[i]) to[i] = av_malloc(size);
1051

    
1052
        if (from[i]) memcpy(to[i], from[i], size);
1053
    }
1054
}
1055

    
1056
static int decode_init_thread_copy(AVCodecContext *avctx){
1057
    H264Context *h= avctx->priv_data;
1058

    
1059
    if (!avctx->is_copy) return 0;
1060
    memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1061
    memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1062

    
1063
    return 0;
1064
}
1065

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

    
1073
    if(dst == src || !s1->context_initialized) return 0;
1074

    
1075
    err = ff_mpeg_update_thread_context(dst, src);
1076
    if(err) return err;
1077

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

    
1083
        for(i = 0; i < MAX_PPS_COUNT; i++)
1084
            av_freep(h->pps_buffers + i);
1085

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

    
1092
        for(i=0; i<2; i++){
1093
            h->rbsp_buffer[i] = NULL;
1094
            h->rbsp_buffer_size[i] = 0;
1095
        }
1096

    
1097
        h->thread_context[0] = h;
1098

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

    
1103
        s->dsp.clear_blocks(h->mb);
1104
    }
1105

    
1106
    //extradata/NAL handling
1107
    h->is_avc          = h1->is_avc;
1108

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

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

    
1119
    for(i=0; i<6; i++)
1120
        h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1121

    
1122
    for(i=0; i<2; i++)
1123
        h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1124

    
1125
    h->dequant_coeff_pps = h1->dequant_coeff_pps;
1126

    
1127
    //POC timing
1128
    copy_fields(h, h1, poc_lsb, redundant_pic_count);
1129

    
1130
    //reference lists
1131
    copy_fields(h, h1, ref_count, intra_gb);
1132
    copy_fields(h, h1, short_ref, cabac_init_idc);
1133

    
1134
    copy_picture_range(h->short_ref,   h1->short_ref,   32, s, s1);
1135
    copy_picture_range(h->long_ref,    h1->long_ref,    32,  s, s1);
1136
    copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
1137

    
1138
    h->last_slice_type = h1->last_slice_type;
1139

    
1140
    if(!s->current_picture_ptr) return 0;
1141

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

    
1151
    return 0;
1152
}
1153

    
1154
int ff_h264_frame_start(H264Context *h){
1155
    MpegEncContext * const s = &h->s;
1156
    int i;
1157

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

    
1170
    assert(s->linesize && s->uvlinesize);
1171

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

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

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

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

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

    
1203
    s->current_picture_ptr->field_poc[0]=
1204
    s->current_picture_ptr->field_poc[1]= INT_MAX;
1205

    
1206
    h->next_output_pic = NULL;
1207

    
1208
    assert(s->current_picture_ptr->long_ref==0);
1209

    
1210
    return 0;
1211
}
1212

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

    
1225
    s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
1226
    s->current_picture_ptr->pict_type= s->pict_type;
1227

    
1228
    if (h->next_output_pic) return;
1229

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

    
1238
    cur->interlaced_frame = 0;
1239
    cur->repeat_pict = 0;
1240

    
1241
    /* Signal interlacing information externally. */
1242
    /* Prioritize picture timing SEI information over used decoding process if it exists. */
1243

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

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

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

    
1301
    //FIXME do something with unavailable reference frames
1302

    
1303
    /* Sort B-frames into display order */
1304

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

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

    
1317
    pics = 0;
1318
    while(h->delayed_pic[pics]) pics++;
1319

    
1320
    assert(pics <= MAX_DELAYED_PIC_COUNT);
1321

    
1322
    h->delayed_pic[pics++] = cur;
1323
    if(cur->reference == 0)
1324
        cur->reference = DELAYED_PIC_REF;
1325

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

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

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

    
1363
    ff_thread_finish_setup(s->avctx);
1364
}
1365

    
1366
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){
1367
    MpegEncContext * const s = &h->s;
1368
    uint8_t *top_border;
1369
    int top_idx = 1;
1370

    
1371
    src_y  -=   linesize;
1372
    src_cb -= uvlinesize;
1373
    src_cr -= uvlinesize;
1374

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

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

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

    
1416
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){
1417
    MpegEncContext * const s = &h->s;
1418
    int deblock_left;
1419
    int deblock_top;
1420
    int top_idx = 1;
1421
    uint8_t *top_border_m1;
1422
    uint8_t *top_border;
1423

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

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

    
1441
    src_y  -=   linesize + 1 + h->pixel_shift;
1442
    src_cb -= uvlinesize + 1 + h->pixel_shift;
1443
    src_cr -= uvlinesize + 1 + h->pixel_shift;
1444

    
1445
    top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1446
    top_border    = h->top_borders[top_idx][s->mb_x];
1447

    
1448
#define XCHG(a,b,xchg)\
1449
    if (h->pixel_shift) {\
1450
        if (xchg) {\
1451
            AV_SWAP64(b+0,a+0);\
1452
            AV_SWAP64(b+8,a+8);\
1453
        } else {\
1454
            AV_COPY128(b,a); \
1455
        }\
1456
    } else \
1457
if (xchg) AV_SWAP64(b,a);\
1458
else      AV_COPY64(b,a);
1459

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

    
1482
static av_always_inline int dctcoef_get(H264Context *h, DCTELEM *mb, int index) {
1483
    if (!h->pixel_shift)
1484
        return mb[index];
1485
    else
1486
        return ((int32_t*)mb)[index];
1487
}
1488

    
1489
static av_always_inline void dctcoef_set(H264Context *h, DCTELEM *mb, int index, int value) {
1490
    if (!h->pixel_shift)
1491
        mb[index] = value;
1492
    else
1493
        ((int32_t*)mb)[index] = value;
1494
}
1495

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

    
1512
    dest_y  = s->current_picture.data[0] + ((mb_x<<h->pixel_shift) + mb_y * s->linesize  ) * 16;
1513
    dest_cb = s->current_picture.data[1] + ((mb_x<<h->pixel_shift) + mb_y * s->uvlinesize) * 8;
1514
    dest_cr = s->current_picture.data[2] + ((mb_x<<h->pixel_shift) + mb_y * s->uvlinesize) * 8;
1515

    
1516
    s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + (64<<h->pixel_shift), s->linesize, 4);
1517
    s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + (64<<h->pixel_shift), dest_cr - dest_cb, 2);
1518

    
1519
    h->list_counts[mb_xy]= h->list_count;
1520

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

    
1553
    if (!simple && IS_INTRA_PCM(mb_type)) {
1554
        if (h->pixel_shift) {
1555
            const int bit_depth = h->sps.bit_depth_luma;
1556
            int j;
1557
            GetBitContext gb;
1558
            init_get_bits(&gb, (uint8_t*)h->mb, 384*bit_depth);
1559

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

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

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

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

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

    
1701

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

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

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

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

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

    
1809
    if (is_complex)
1810
        hl_decode_mb_complex(h);
1811
    else hl_decode_mb_simple(h);
1812
}
1813

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

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

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

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

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

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

    
1884
    for (i = 0; i < 2; i++) {
1885
        h->luma_weight_flag[i]   = 0;
1886
        h->chroma_weight_flag[i] = 0;
1887
    }
1888

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

    
1907
    h->use_weight= 2;
1908
    h->use_weight_chroma= 2;
1909
    h->luma_log2_weight_denom= 5;
1910
    h->chroma_log2_weight_denom= 5;
1911

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

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

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

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

    
1971
    h->frame_num_offset= h->prev_frame_num_offset;
1972
    if(h->frame_num < h->prev_frame_num)
1973
        h->frame_num_offset += max_frame_num;
1974

    
1975
    if(h->sps.poc_type==0){
1976
        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
1977

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

    
1993
        if(h->sps.poc_cycle_length != 0)
1994
            abs_frame_num = h->frame_num_offset + h->frame_num;
1995
        else
1996
            abs_frame_num = 0;
1997

    
1998
        if(h->nal_ref_idc==0 && abs_frame_num > 0)
1999
            abs_frame_num--;
2000

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

    
2005
        if(abs_frame_num > 0){
2006
            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2007
            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2008

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

    
2015
        if(h->nal_ref_idc == 0)
2016
            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2017

    
2018
        field_poc[0] = expectedpoc + h->delta_poc[0];
2019
        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2020

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

    
2026
        if(!h->nal_ref_idc)
2027
            poc--;
2028

    
2029
        field_poc[0]= poc;
2030
        field_poc[1]= poc;
2031
    }
2032

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

    
2039
    return 0;
2040
}
2041

    
2042

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

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

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

    
2088
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2089
        ff_vdpau_h264_set_reference_frames(s);
2090

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

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

    
2107
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2108
        ff_vdpau_h264_picture_complete(s);
2109

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

    
2125
    MPV_frame_end(s);
2126

    
2127
    h->current_slice=0;
2128
}
2129

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

    
2142
    dst->prev_poc_msb           = src->prev_poc_msb;
2143
    dst->prev_poc_lsb           = src->prev_poc_lsb;
2144
    dst->prev_frame_num_offset  = src->prev_frame_num_offset;
2145
    dst->prev_frame_num         = src->prev_frame_num;
2146
    dst->short_ref_count        = src->short_ref_count;
2147

    
2148
    memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
2149
    memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
2150
    memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2151
    memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
2152

    
2153
    memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
2154
    memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
2155
}
2156

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

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

    
2181
    return profile;
2182
}
2183

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

    
2203
    s->dropable= h->nal_ref_idc == 0;
2204

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

    
2213
    first_mb_in_slice= get_ue_golomb(&s->gb);
2214

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

    
2220
        h0->current_slice = 0;
2221
        if (!s0->first_field)
2222
            s->current_picture_ptr= NULL;
2223
    }
2224

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

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

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

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

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

    
2263
    s->avctx->profile = ff_h264_get_profile(&h->sps);
2264
    s->avctx->level   = h->sps.level_idc;
2265
    s->avctx->refs    = h->sps.ref_frame_count;
2266

    
2267
    if(h == h0 && h->dequant_coeff_pps != pps_id){
2268
        h->dequant_coeff_pps = pps_id;
2269
        init_dequant_tables(h);
2270
    }
2271

    
2272
    s->mb_width= h->sps.mb_width;
2273
    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
2274

    
2275
    h->b_stride=  s->mb_width*4;
2276

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

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

    
2300
        avcodec_set_dimensions(s->avctx, s->width, s->height);
2301
        s->avctx->sample_aspect_ratio= h->sps.sar;
2302
        av_assert0(s->avctx->sample_aspect_ratio.den);
2303

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

    
2313
        if(h->sps.timing_info_present_flag){
2314
            int64_t den= h->sps.time_scale;
2315
            if(h->x264_build < 44U)
2316
                den *= 2;
2317
            av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
2318
                      h->sps.num_units_in_tick, den, 1<<30);
2319
        }
2320

    
2321
        switch (h->sps.bit_depth_luma) {
2322
            case 9 :
2323
                s->avctx->pix_fmt = PIX_FMT_YUV420P9;
2324
                break;
2325
            case 10 :
2326
                s->avctx->pix_fmt = PIX_FMT_YUV420P10;
2327
                break;
2328
            default:
2329
        s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
2330
                                                 s->avctx->codec->pix_fmts ?
2331
                                                 s->avctx->codec->pix_fmts :
2332
                                                 s->avctx->color_range == AVCOL_RANGE_JPEG ?
2333
                                                 hwaccel_pixfmt_list_h264_jpeg_420 :
2334
                                                 ff_hwaccel_pixfmt_list_420);
2335
        }
2336

    
2337
        s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
2338

    
2339
        if (MPV_common_init(s) < 0){
2340
            av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed\n");
2341
            return -1;
2342
        }
2343
        s->first_field = 0;
2344
        h->prev_interlaced_frame = 1;
2345

    
2346
        init_scan_tables(h);
2347
        ff_h264_alloc_tables(h);
2348

    
2349
        if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
2350
            if (context_init(h) < 0){
2351
                av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
2352
                return -1;
2353
            }
2354
        } else {
2355
            for(i = 1; i < s->avctx->thread_count; i++) {
2356
                H264Context *c;
2357
                c = h->thread_context[i] = av_malloc(sizeof(H264Context));
2358
                memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
2359
                memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
2360
                c->h264dsp = h->h264dsp;
2361
                c->sps = h->sps;
2362
                c->pps = h->pps;
2363
                init_scan_tables(c);
2364
                clone_tables(c, h, i);
2365
            }
2366

    
2367
            for(i = 0; i < s->avctx->thread_count; i++)
2368
                if(context_init(h->thread_context[i]) < 0){
2369
                    av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
2370
                    return -1;
2371
                }
2372
        }
2373
    }
2374

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

    
2377
    h->mb_mbaff = 0;
2378
    h->mb_aff_frame = 0;
2379
    last_pic_structure = s0->picture_structure;
2380
    if(h->sps.frame_mbs_only_flag){
2381
        s->picture_structure= PICT_FRAME;
2382
    }else{
2383
        if(get_bits1(&s->gb)) { //field_pic_flag
2384
            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
2385
        } else {
2386
            s->picture_structure= PICT_FRAME;
2387
            h->mb_aff_frame = h->sps.mb_aff;
2388
        }
2389
    }
2390
    h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
2391

    
2392
    if(h0->current_slice == 0){
2393
        if(h->frame_num != h->prev_frame_num &&
2394
          (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num) < (h->frame_num - h->sps.ref_frame_count))
2395
            h->prev_frame_num = h->frame_num - h->sps.ref_frame_count - 1;
2396

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

    
2427
        /* See if we have a decoded first field looking for a pair... */
2428
        if (s0->first_field) {
2429
            assert(s0->current_picture_ptr);
2430
            assert(s0->current_picture_ptr->data[0]);
2431
            assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
2432

    
2433
            /* figure out if we have a complementary field pair */
2434
            if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2435
                /*
2436
                 * Previous field is unmatched. Don't display it, but let it
2437
                 * remain for reference if marked as such.
2438
                 */
2439
                s0->current_picture_ptr = NULL;
2440
                s0->first_field = FIELD_PICTURE;
2441

    
2442
            } else {
2443
                if (h->nal_ref_idc &&
2444
                        s0->current_picture_ptr->reference &&
2445
                        s0->current_picture_ptr->frame_num != h->frame_num) {
2446
                    /*
2447
                     * This and previous field were reference, but had
2448
                     * different frame_nums. Consider this field first in
2449
                     * pair. Throw away previous field except for reference
2450
                     * purposes.
2451
                     */
2452
                    s0->first_field = 1;
2453
                    s0->current_picture_ptr = NULL;
2454

    
2455
                } else {
2456
                    /* Second field in complementary pair */
2457
                    s0->first_field = 0;
2458
                }
2459
            }
2460

    
2461
        } else {
2462
            /* Frame or first field in a potentially complementary pair */
2463
            assert(!s0->current_picture_ptr);
2464
            s0->first_field = FIELD_PICTURE;
2465
        }
2466

    
2467
        if((!FIELD_PICTURE || s0->first_field) && ff_h264_frame_start(h) < 0) {
2468
            s0->first_field = 0;
2469
            return -1;
2470
        }
2471
    }
2472
    if(h != h0)
2473
        clone_slice(h, h0);
2474

    
2475
    s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2476

    
2477
    assert(s->mb_num == s->mb_width * s->mb_height);
2478
    if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2479
       first_mb_in_slice                    >= s->mb_num){
2480
        av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2481
        return -1;
2482
    }
2483
    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2484
    s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2485
    if (s->picture_structure == PICT_BOTTOM_FIELD)
2486
        s->resync_mb_y = s->mb_y = s->mb_y + 1;
2487
    assert(s->mb_y < s->mb_height);
2488

    
2489
    if(s->picture_structure==PICT_FRAME){
2490
        h->curr_pic_num=   h->frame_num;
2491
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
2492
    }else{
2493
        h->curr_pic_num= 2*h->frame_num + 1;
2494
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
2495
    }
2496

    
2497
    if(h->nal_unit_type == NAL_IDR_SLICE){
2498
        get_ue_golomb(&s->gb); /* idr_pic_id */
2499
    }
2500

    
2501
    if(h->sps.poc_type==0){
2502
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2503

    
2504
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
2505
            h->delta_poc_bottom= get_se_golomb(&s->gb);
2506
        }
2507
    }
2508

    
2509
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
2510
        h->delta_poc[0]= get_se_golomb(&s->gb);
2511

    
2512
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
2513
            h->delta_poc[1]= get_se_golomb(&s->gb);
2514
    }
2515

    
2516
    init_poc(h);
2517

    
2518
    if(h->pps.redundant_pic_cnt_present){
2519
        h->redundant_pic_count= get_ue_golomb(&s->gb);
2520
    }
2521

    
2522
    //set defaults, might be overridden a few lines later
2523
    h->ref_count[0]= h->pps.ref_count[0];
2524
    h->ref_count[1]= h->pps.ref_count[1];
2525

    
2526
    if(h->slice_type_nos != FF_I_TYPE){
2527
        if(h->slice_type_nos == FF_B_TYPE){
2528
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
2529
        }
2530
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
2531

    
2532
        if(num_ref_idx_active_override_flag){
2533
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
2534
            if(h->slice_type_nos==FF_B_TYPE)
2535
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
2536

    
2537
            if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
2538
                av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
2539
                h->ref_count[0]= h->ref_count[1]= 1;
2540
                return -1;
2541
            }
2542
        }
2543
        if(h->slice_type_nos == FF_B_TYPE)
2544
            h->list_count= 2;
2545
        else
2546
            h->list_count= 1;
2547
    }else
2548
        h->list_count= 0;
2549

    
2550
    if(!default_ref_list_done){
2551
        ff_h264_fill_default_ref_list(h);
2552
    }
2553

    
2554
    if(h->slice_type_nos!=FF_I_TYPE && ff_h264_decode_ref_pic_list_reordering(h) < 0)
2555
        return -1;
2556

    
2557
    if(h->slice_type_nos!=FF_I_TYPE){
2558
        s->last_picture_ptr= &h->ref_list[0][0];
2559
        ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2560
    }
2561
    if(h->slice_type_nos==FF_B_TYPE){
2562
        s->next_picture_ptr= &h->ref_list[1][0];
2563
        ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2564
    }
2565

    
2566
    if(   (h->pps.weighted_pred          && h->slice_type_nos == FF_P_TYPE )
2567
       ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
2568
        pred_weight_table(h);
2569
    else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2570
        implicit_weight_table(h, -1);
2571
    }else {
2572
        h->use_weight = 0;
2573
        for (i = 0; i < 2; i++) {
2574
            h->luma_weight_flag[i]   = 0;
2575
            h->chroma_weight_flag[i] = 0;
2576
        }
2577
    }
2578

    
2579
    if(h->nal_ref_idc)
2580
        ff_h264_decode_ref_pic_marking(h0, &s->gb);
2581

    
2582
    if(FRAME_MBAFF){
2583
        ff_h264_fill_mbaff_ref_list(h);
2584

    
2585
        if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2586
            implicit_weight_table(h, 0);
2587
            implicit_weight_table(h, 1);
2588
        }
2589
    }
2590

    
2591
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2592
        ff_h264_direct_dist_scale_factor(h);
2593
    ff_h264_direct_ref_list_init(h);
2594

    
2595
    if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
2596
        tmp = get_ue_golomb_31(&s->gb);
2597
        if(tmp > 2){
2598
            av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2599
            return -1;
2600
        }
2601
        h->cabac_init_idc= tmp;
2602
    }
2603

    
2604
    h->last_qscale_diff = 0;
2605
    tmp = h->pps.init_qp + get_se_golomb(&s->gb);
2606
    if(tmp>51+6*(h->sps.bit_depth_luma-8)){
2607
        av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
2608
        return -1;
2609
    }
2610
    s->qscale= tmp;
2611
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2612
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2613
    //FIXME qscale / qp ... stuff
2614
    if(h->slice_type == FF_SP_TYPE){
2615
        get_bits1(&s->gb); /* sp_for_switch_flag */
2616
    }
2617
    if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
2618
        get_se_golomb(&s->gb); /* slice_qs_delta */
2619
    }
2620

    
2621
    h->deblocking_filter = 1;
2622
    h->slice_alpha_c0_offset = 52;
2623
    h->slice_beta_offset = 52;
2624
    if( h->pps.deblocking_filter_parameters_present ) {
2625
        tmp= get_ue_golomb_31(&s->gb);
2626
        if(tmp > 2){
2627
            av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
2628
            return -1;
2629
        }
2630
        h->deblocking_filter= tmp;
2631
        if(h->deblocking_filter < 2)
2632
            h->deblocking_filter^= 1; // 1<->0
2633

    
2634
        if( h->deblocking_filter ) {
2635
            h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
2636
            h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
2637
            if(   h->slice_alpha_c0_offset > 104U
2638
               || h->slice_beta_offset     > 104U){
2639
                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);
2640
                return -1;
2641
            }
2642
        }
2643
    }
2644

    
2645
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
2646
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
2647
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
2648
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
2649
        h->deblocking_filter= 0;
2650

    
2651
    if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
2652
        if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
2653
            /* Cheat slightly for speed:
2654
               Do not bother to deblock across slices. */
2655
            h->deblocking_filter = 2;
2656
        } else {
2657
            h0->max_contexts = 1;
2658
            if(!h0->single_decode_warning) {
2659
                av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
2660
                h0->single_decode_warning = 1;
2661
            }
2662
            if(h != h0){
2663
                av_log(h->s.avctx, AV_LOG_ERROR, "deblocking switched inside frame\n");
2664
                return 1;
2665
            }
2666
        }
2667
    }
2668
    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]);
2669

    
2670
#if 0 //FMO
2671
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
2672
        slice_group_change_cycle= get_bits(&s->gb, ?);
2673
#endif
2674

    
2675
    h0->last_slice_type = slice_type;
2676
    h->slice_num = ++h0->current_slice;
2677
    if(h->slice_num >= MAX_SLICES){
2678
        av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
2679
    }
2680

    
2681
    for(j=0; j<2; j++){
2682
        int id_list[16];
2683
        int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
2684
        for(i=0; i<16; i++){
2685
            id_list[i]= 60;
2686
            if(h->ref_list[j][i].data[0]){
2687
                int k;
2688
                uint8_t *base= h->ref_list[j][i].base[0];
2689
                for(k=0; k<h->short_ref_count; k++)
2690
                    if(h->short_ref[k]->base[0] == base){
2691
                        id_list[i]= k;
2692
                        break;
2693
                    }
2694
                for(k=0; k<h->long_ref_count; k++)
2695
                    if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
2696
                        id_list[i]= h->short_ref_count + k;
2697
                        break;
2698
                    }
2699
            }
2700
        }
2701

    
2702
        ref2frm[0]=
2703
        ref2frm[1]= -1;
2704
        for(i=0; i<16; i++)
2705
            ref2frm[i+2]= 4*id_list[i]
2706
                          +(h->ref_list[j][i].reference&3);
2707
        ref2frm[18+0]=
2708
        ref2frm[18+1]= -1;
2709
        for(i=16; i<48; i++)
2710
            ref2frm[i+4]= 4*id_list[(i-16)>>1]
2711
                          +(h->ref_list[j][i].reference&3);
2712
    }
2713

    
2714
    //FIXME: fix draw_edges+PAFF+frame threads
2715
    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;
2716
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
2717

    
2718
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2719
        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",
2720
               h->slice_num,
2721
               (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
2722
               first_mb_in_slice,
2723
               av_get_pict_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
2724
               pps_id, h->frame_num,
2725
               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
2726
               h->ref_count[0], h->ref_count[1],
2727
               s->qscale,
2728
               h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
2729
               h->use_weight,
2730
               h->use_weight==1 && h->use_weight_chroma ? "c" : "",
2731
               h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
2732
               );
2733
    }
2734

    
2735
    return 0;
2736
}
2737

    
2738
int ff_h264_get_slice_type(const H264Context *h)
2739
{
2740
    switch (h->slice_type) {
2741
    case FF_P_TYPE:  return 0;
2742
    case FF_B_TYPE:  return 1;
2743
    case FF_I_TYPE:  return 2;
2744
    case FF_SP_TYPE: return 3;
2745
    case FF_SI_TYPE: return 4;
2746
    default:         return -1;
2747
    }
2748
}
2749

    
2750
/**
2751
 *
2752
 * @return non zero if the loop filter can be skiped
2753
 */
2754
static int fill_filter_caches(H264Context *h, int mb_type){
2755
    MpegEncContext * const s = &h->s;
2756
    const int mb_xy= h->mb_xy;
2757
    int top_xy, left_xy[2];
2758
    int top_type, left_type[2];
2759

    
2760
    top_xy     = mb_xy  - (s->mb_stride << MB_FIELD);
2761

    
2762
    //FIXME deblocking could skip the intra and nnz parts.
2763

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

    
2767
    left_xy[1] = left_xy[0] = mb_xy-1;
2768
    if(FRAME_MBAFF){
2769
        const int left_mb_field_flag     = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);
2770
        const int curr_mb_field_flag     = IS_INTERLACED(mb_type);
2771
        if(s->mb_y&1){
2772
            if (left_mb_field_flag != curr_mb_field_flag) {
2773
                left_xy[0] -= s->mb_stride;
2774
            }
2775
        }else{
2776
            if(curr_mb_field_flag){
2777
                top_xy      += s->mb_stride & (((s->current_picture.mb_type[top_xy    ]>>7)&1)-1);
2778
            }
2779
            if (left_mb_field_flag != curr_mb_field_flag) {
2780
                left_xy[1] += s->mb_stride;
2781
            }
2782
        }
2783
    }
2784

    
2785
    h->top_mb_xy = top_xy;
2786
    h->left_mb_xy[0] = left_xy[0];
2787
    h->left_mb_xy[1] = left_xy[1];
2788
    {
2789
        //for sufficiently low qp, filtering wouldn't do anything
2790
        //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
2791
        int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
2792
        int qp = s->current_picture.qscale_table[mb_xy];
2793
        if(qp <= qp_thresh
2794
           && (left_xy[0]<0 || ((qp + s->current_picture.qscale_table[left_xy[0]] + 1)>>1) <= qp_thresh)
2795
           && (top_xy   < 0 || ((qp + s->current_picture.qscale_table[top_xy    ] + 1)>>1) <= qp_thresh)){
2796
            if(!FRAME_MBAFF)
2797
                return 1;
2798
            if(   (left_xy[0]< 0            || ((qp + s->current_picture.qscale_table[left_xy[1]             ] + 1)>>1) <= qp_thresh)
2799
               && (top_xy    < s->mb_stride || ((qp + s->current_picture.qscale_table[top_xy    -s->mb_stride] + 1)>>1) <= qp_thresh))
2800
                return 1;
2801
        }
2802
    }
2803

    
2804
    top_type     = s->current_picture.mb_type[top_xy]    ;
2805
    left_type[0] = s->current_picture.mb_type[left_xy[0]];
2806
    left_type[1] = s->current_picture.mb_type[left_xy[1]];
2807
    if(h->deblocking_filter == 2){
2808
        if(h->slice_table[top_xy     ] != h->slice_num) top_type= 0;
2809
        if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
2810
    }else{
2811
        if(h->slice_table[top_xy     ] == 0xFFFF) top_type= 0;
2812
        if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
2813
    }
2814
    h->top_type    = top_type    ;
2815
    h->left_type[0]= left_type[0];
2816
    h->left_type[1]= left_type[1];
2817

    
2818
    if(IS_INTRA(mb_type))
2819
        return 0;
2820

    
2821
    AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
2822
    AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
2823
    AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
2824
    AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
2825
    AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
2826

    
2827
    h->cbp= h->cbp_table[mb_xy];
2828

    
2829
    {
2830
        int list;
2831
        for(list=0; list<h->list_count; list++){
2832
            int8_t *ref;
2833
            int y, b_stride;
2834
            int16_t (*mv_dst)[2];
2835
            int16_t (*mv_src)[2];
2836

    
2837
            if(!USES_LIST(mb_type, list)){
2838
                fill_rectangle(  h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
2839
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2840
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2841
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2842
                AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2843
                continue;
2844
            }
2845

    
2846
            ref = &s->current_picture.ref_index[list][4*mb_xy];
2847
            {
2848
                int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2849
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2850
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2851
                ref += 2;
2852
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2853
                AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2854
            }
2855

    
2856
            b_stride = h->b_stride;
2857
            mv_dst   = &h->mv_cache[list][scan8[0]];
2858
            mv_src   = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
2859
            for(y=0; y<4; y++){
2860
                AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
2861
            }
2862

    
2863
        }
2864
    }
2865

    
2866

    
2867
/*
2868
0 . T T. T T T T
2869
1 L . .L . . . .
2870
2 L . .L . . . .
2871
3 . T TL . . . .
2872
4 L . .L . . . .
2873
5 L . .. . . . .
2874
*/
2875
//FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
2876
    if(top_type){
2877
        AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][4+3*8]);
2878
    }
2879

    
2880
    if(left_type[0]){
2881
        h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
2882
        h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
2883
        h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
2884
        h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
2885
    }
2886

    
2887
    // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
2888
    if(!CABAC && h->pps.transform_8x8_mode){
2889
        if(IS_8x8DCT(top_type)){
2890
            h->non_zero_count_cache[4+8*0]=
2891
            h->non_zero_count_cache[5+8*0]= h->cbp_table[top_xy] & 4;
2892
            h->non_zero_count_cache[6+8*0]=
2893
            h->non_zero_count_cache[7+8*0]= h->cbp_table[top_xy] & 8;
2894
        }
2895
        if(IS_8x8DCT(left_type[0])){
2896
            h->non_zero_count_cache[3+8*1]=
2897
            h->non_zero_count_cache[3+8*2]= h->cbp_table[left_xy[0]]&2; //FIXME check MBAFF
2898
        }
2899
        if(IS_8x8DCT(left_type[1])){
2900
            h->non_zero_count_cache[3+8*3]=
2901
            h->non_zero_count_cache[3+8*4]= h->cbp_table[left_xy[1]]&8; //FIXME check MBAFF
2902
        }
2903

    
2904
        if(IS_8x8DCT(mb_type)){
2905
            h->non_zero_count_cache[scan8[0   ]]= h->non_zero_count_cache[scan8[1   ]]=
2906
            h->non_zero_count_cache[scan8[2   ]]= h->non_zero_count_cache[scan8[3   ]]= h->cbp & 1;
2907

    
2908
            h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
2909
            h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
2910

    
2911
            h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
2912
            h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp & 4;
2913

    
2914
            h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
2915
            h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
2916
        }
2917
    }
2918

    
2919
    if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
2920
        int list;
2921
        for(list=0; list<h->list_count; list++){
2922
            if(USES_LIST(top_type, list)){
2923
                const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
2924
                const int b8_xy= 4*top_xy + 2;
2925
                int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2926
                AV_COPY128(h->mv_cache[list][scan8[0] + 0 - 1*8], s->current_picture.motion_val[list][b_xy + 0]);
2927
                h->ref_cache[list][scan8[0] + 0 - 1*8]=
2928
                h->ref_cache[list][scan8[0] + 1 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 0]];
2929
                h->ref_cache[list][scan8[0] + 2 - 1*8]=
2930
                h->ref_cache[list][scan8[0] + 3 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 1]];
2931
            }else{
2932
                AV_ZERO128(h->mv_cache[list][scan8[0] + 0 - 1*8]);
2933
                AV_WN32A(&h->ref_cache[list][scan8[0] + 0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2934
            }
2935

    
2936
            if(!IS_INTERLACED(mb_type^left_type[0])){
2937
                if(USES_LIST(left_type[0], list)){
2938
                    const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
2939
                    const int b8_xy= 4*left_xy[0] + 1;
2940
                    int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[0]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2941
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 0 ], s->current_picture.motion_val[list][b_xy + h->b_stride*0]);
2942
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 8 ], s->current_picture.motion_val[list][b_xy + h->b_stride*1]);
2943
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +16 ], s->current_picture.motion_val[list][b_xy + h->b_stride*2]);
2944
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +24 ], s->current_picture.motion_val[list][b_xy + h->b_stride*3]);
2945
                    h->ref_cache[list][scan8[0] - 1 + 0 ]=
2946
                    h->ref_cache[list][scan8[0] - 1 + 8 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*0]];
2947
                    h->ref_cache[list][scan8[0] - 1 +16 ]=
2948
                    h->ref_cache[list][scan8[0] - 1 +24 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*1]];
2949
                }else{
2950
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 0 ]);
2951
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 8 ]);
2952
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +16 ]);
2953
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +24 ]);
2954
                    h->ref_cache[list][scan8[0] - 1 + 0  ]=
2955
                    h->ref_cache[list][scan8[0] - 1 + 8  ]=
2956
                    h->ref_cache[list][scan8[0] - 1 + 16 ]=
2957
                    h->ref_cache[list][scan8[0] - 1 + 24 ]= LIST_NOT_USED;
2958
                }
2959
            }
2960
        }
2961
    }
2962

    
2963
    return 0;
2964
}
2965

    
2966
static void loop_filter(H264Context *h){
2967
    MpegEncContext * const s = &h->s;
2968
    uint8_t  *dest_y, *dest_cb, *dest_cr;
2969
    int linesize, uvlinesize, mb_x, mb_y;
2970
    const int end_mb_y= s->mb_y + FRAME_MBAFF;
2971
    const int old_slice_type= h->slice_type;
2972
    const int end_mb_x  = s->mb_x;
2973

    
2974
    if(h->deblocking_filter) {
2975
        int start_x= s->resync_mb_y == s->mb_y ? s->resync_mb_x : 0;
2976
        for(mb_x= start_x; mb_x<end_mb_x; mb_x++){
2977
            for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
2978
                int mb_xy, mb_type;
2979
                mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
2980
                h->slice_num= h->slice_table[mb_xy];
2981
                mb_type= s->current_picture.mb_type[mb_xy];
2982
                h->list_count= h->list_counts[mb_xy];
2983

    
2984
                if(FRAME_MBAFF)
2985
                    h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2986

    
2987
                s->mb_x= mb_x;
2988
                s->mb_y= mb_y;
2989
                dest_y  = s->current_picture.data[0] + ((mb_x<<h->pixel_shift) + mb_y * s->linesize  ) * 16;
2990
                dest_cb = s->current_picture.data[1] + ((mb_x<<h->pixel_shift) + mb_y * s->uvlinesize) * 8;
2991
                dest_cr = s->current_picture.data[2] + ((mb_x<<h->pixel_shift) + mb_y * s->uvlinesize) * 8;
2992
                    //FIXME simplify above
2993

    
2994
                if (MB_FIELD) {
2995
                    linesize   = h->mb_linesize   = s->linesize * 2;
2996
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2997
                    if(mb_y&1){ //FIXME move out of this function?
2998
                        dest_y -= s->linesize*15;
2999
                        dest_cb-= s->uvlinesize*7;
3000
                        dest_cr-= s->uvlinesize*7;
3001
                    }
3002
                } else {
3003
                    linesize   = h->mb_linesize   = s->linesize;
3004
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize;
3005
                }
3006
                backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
3007
                if(fill_filter_caches(h, mb_type))
3008
                    continue;
3009
                h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
3010
                h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
3011

    
3012
                if (FRAME_MBAFF) {
3013
                    ff_h264_filter_mb     (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
3014
                } else {
3015
                    ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
3016
                }
3017
            }
3018
        }
3019
    }
3020
    h->slice_type= old_slice_type;
3021
    s->mb_x= end_mb_x;
3022
    s->mb_y= end_mb_y - FRAME_MBAFF;
3023
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3024
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3025
}
3026

    
3027
static void predict_field_decoding_flag(H264Context *h){
3028
    MpegEncContext * const s = &h->s;
3029
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3030
    int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
3031
                ? s->current_picture.mb_type[mb_xy-1]
3032
                : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
3033
                ? s->current_picture.mb_type[mb_xy-s->mb_stride]
3034
                : 0;
3035
    h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3036
}
3037

    
3038
/**
3039
 * Draw edges and report progress for the last MB row.
3040
 */
3041
static void decode_finish_row(H264Context *h){
3042
    MpegEncContext * const s = &h->s;
3043
    int top = 16*(s->mb_y >> FIELD_PICTURE);
3044
    int height = 16 << FRAME_MBAFF;
3045
    int deblock_border = (16 + 4) << FRAME_MBAFF;
3046
    int pic_height = 16*s->mb_height >> FIELD_PICTURE;
3047

    
3048
    if (h->deblocking_filter) {
3049
        if((top + height) >= pic_height)
3050
            height += deblock_border;
3051

    
3052
        top -= deblock_border;
3053
    }
3054

    
3055
    if (top >= pic_height || (top + height) < h->emu_edge_height)
3056
        return;
3057

    
3058
    height = FFMIN(height, pic_height - top);
3059
    if (top < h->emu_edge_height) {
3060
        height = top+height;
3061
        top = 0;
3062
    }
3063

    
3064
    ff_draw_horiz_band(s, top, height);
3065

    
3066
    if (s->dropable) return;
3067

    
3068
    ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
3069
                             s->picture_structure==PICT_BOTTOM_FIELD);
3070
}
3071

    
3072
static int decode_slice(struct AVCodecContext *avctx, void *arg){
3073
    H264Context *h = *(void**)arg;
3074
    MpegEncContext * const s = &h->s;
3075
    const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
3076

    
3077
    s->mb_skip_run= -1;
3078

    
3079
    h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
3080
                    (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
3081

    
3082
    if( h->pps.cabac ) {
3083
        /* realign */
3084
        align_get_bits( &s->gb );
3085

    
3086
        /* init cabac */
3087
        ff_init_cabac_states( &h->cabac);
3088
        ff_init_cabac_decoder( &h->cabac,
3089
                               s->gb.buffer + get_bits_count(&s->gb)/8,
3090
                               (get_bits_left(&s->gb) + 7)/8);
3091

    
3092
        ff_h264_init_cabac_states(h);
3093

    
3094
        for(;;){
3095
//START_TIMER
3096
            int ret = ff_h264_decode_mb_cabac(h);
3097
            int eos;
3098
//STOP_TIMER("decode_mb_cabac")
3099

    
3100
            if(ret>=0) ff_h264_hl_decode_mb(h);
3101

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

    
3105
                ret = ff_h264_decode_mb_cabac(h);
3106

    
3107
                if(ret>=0) ff_h264_hl_decode_mb(h);
3108
                s->mb_y--;
3109
            }
3110
            eos = get_cabac_terminate( &h->cabac );
3111

    
3112
            if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
3113
                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);
3114
                return 0;
3115
            }
3116
            if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
3117
                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);
3118
                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);
3119
                return -1;
3120
            }
3121

    
3122
            if( ++s->mb_x >= s->mb_width ) {
3123
                loop_filter(h);
3124
                s->mb_x = 0;
3125
                decode_finish_row(h);
3126
                ++s->mb_y;
3127
                if(FIELD_OR_MBAFF_PICTURE) {
3128
                    ++s->mb_y;
3129
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
3130
                        predict_field_decoding_flag(h);
3131
                }
3132
            }
3133

    
3134
            if( eos || s->mb_y >= s->mb_height ) {
3135
                if(s->mb_x)
3136
                    loop_filter(h);
3137
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3138
                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);
3139
                return 0;
3140
            }
3141
        }
3142

    
3143
    } else {
3144
        for(;;){
3145
            int ret = ff_h264_decode_mb_cavlc(h);
3146

    
3147
            if(ret>=0) ff_h264_hl_decode_mb(h);
3148

    
3149
            if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
3150
                s->mb_y++;
3151
                ret = ff_h264_decode_mb_cavlc(h);
3152

    
3153
                if(ret>=0) ff_h264_hl_decode_mb(h);
3154
                s->mb_y--;
3155
            }
3156

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

    
3161
                return -1;
3162
            }
3163

    
3164
            if(++s->mb_x >= s->mb_width){
3165
                loop_filter(h);
3166
                s->mb_x=0;
3167
                decode_finish_row(h);
3168
                ++s->mb_y;
3169
                if(FIELD_OR_MBAFF_PICTURE) {
3170
                    ++s->mb_y;
3171
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
3172
                        predict_field_decoding_flag(h);
3173
                }
3174
                if(s->mb_y >= s->mb_height){
3175
                    tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3176

    
3177
                    if(   get_bits_count(&s->gb) == s->gb.size_in_bits
3178
                       || get_bits_count(&s->gb) <  s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
3179
                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3180

    
3181
                        return 0;
3182
                    }else{
3183
                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3184

    
3185
                        return -1;
3186
                    }
3187
                }
3188
            }
3189

    
3190
            if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
3191
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3192
                if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
3193
                    if(s->mb_x)
3194
                        loop_filter(h);
3195
                    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);
3196

    
3197
                    return 0;
3198
                }else{
3199
                    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);
3200

    
3201
                    return -1;
3202
                }
3203
            }
3204
        }
3205
    }
3206

    
3207
#if 0
3208
    for(;s->mb_y < s->mb_height; s->mb_y++){
3209
        for(;s->mb_x < s->mb_width; s->mb_x++){
3210
            int ret= decode_mb(h);
3211

3212
            ff_h264_hl_decode_mb(h);
3213

3214
            if(ret<0){
3215
                av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3216
                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);
3217

3218
                return -1;
3219
            }
3220

3221
            if(++s->mb_x >= s->mb_width){
3222
                s->mb_x=0;
3223
                if(++s->mb_y >= s->mb_height){
3224
                    if(get_bits_count(s->gb) == s->gb.size_in_bits){
3225
                        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);
3226

3227
                        return 0;
3228
                    }else{
3229
                        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);
3230

3231
                        return -1;
3232
                    }
3233
                }
3234
            }
3235

3236
            if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
3237
                if(get_bits_count(s->gb) == s->gb.size_in_bits){
3238
                    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);
3239

3240
                    return 0;
3241
                }else{
3242
                    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);
3243

3244
                    return -1;
3245
                }
3246
            }
3247
        }
3248
        s->mb_x=0;
3249
        ff_draw_horiz_band(s, 16*s->mb_y, 16);
3250
    }
3251
#endif
3252
    return -1; //not reached
3253
}
3254

    
3255
/**
3256
 * Call decode_slice() for each context.
3257
 *
3258
 * @param h h264 master context
3259
 * @param context_count number of contexts to execute
3260
 */
3261
static void execute_decode_slices(H264Context *h, int context_count){
3262
    MpegEncContext * const s = &h->s;
3263
    AVCodecContext * const avctx= s->avctx;
3264
    H264Context *hx;
3265
    int i;
3266

    
3267
    if (s->avctx->hwaccel)
3268
        return;
3269
    if(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3270
        return;
3271
    if(context_count == 1) {
3272
        decode_slice(avctx, &h);
3273
    } else {
3274
        for(i = 1; i < context_count; i++) {
3275
            hx = h->thread_context[i];
3276
            hx->s.error_recognition = avctx->error_recognition;
3277
            hx->s.error_count = 0;
3278
            hx->x264_build= h->x264_build;
3279
        }
3280

    
3281
        avctx->execute(avctx, (void *)decode_slice,
3282
                       h->thread_context, NULL, context_count, sizeof(void*));
3283

    
3284
        /* pull back stuff from slices to master context */
3285
        hx = h->thread_context[context_count - 1];
3286
        s->mb_x = hx->s.mb_x;
3287
        s->mb_y = hx->s.mb_y;
3288
        s->dropable = hx->s.dropable;
3289
        s->picture_structure = hx->s.picture_structure;
3290
        for(i = 1; i < context_count; i++)
3291
            h->s.error_count += h->thread_context[i]->s.error_count;
3292
    }
3293
}
3294

    
3295

    
3296
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
3297
    MpegEncContext * const s = &h->s;
3298
    AVCodecContext * const avctx= s->avctx;
3299
    int buf_index=0;
3300
    H264Context *hx; ///< thread context
3301
    int context_count = 0;
3302
    int next_avc= h->is_avc ? 0 : buf_size;
3303

    
3304
    h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
3305
#if 0
3306
    int i;
3307
    for(i=0; i<50; i++){
3308
        av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
3309
    }
3310
#endif
3311
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
3312
        h->current_slice = 0;
3313
        if (!s->first_field)
3314
            s->current_picture_ptr= NULL;
3315
        ff_h264_reset_sei(h);
3316
    }
3317

    
3318
    for(;;){
3319
        int consumed;
3320
        int dst_length;
3321
        int bit_length;
3322
        const uint8_t *ptr;
3323
        int i, nalsize = 0;
3324
        int err;
3325

    
3326
        if(buf_index >= next_avc) {
3327
            if(buf_index >= buf_size) break;
3328
            nalsize = 0;
3329
            for(i = 0; i < h->nal_length_size; i++)
3330
                nalsize = (nalsize << 8) | buf[buf_index++];
3331
            if(nalsize <= 0 || nalsize > buf_size - buf_index){
3332
                av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
3333
                break;
3334
            }
3335
            next_avc= buf_index + nalsize;
3336
        } else {
3337
            // start code prefix search
3338
            for(; buf_index + 3 < next_avc; buf_index++){
3339
                // This should always succeed in the first iteration.
3340
                if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
3341
                    break;
3342
            }
3343

    
3344
            if(buf_index+3 >= buf_size) break;
3345

    
3346
            buf_index+=3;
3347
            if(buf_index >= next_avc) continue;
3348
        }
3349

    
3350
        hx = h->thread_context[context_count];
3351

    
3352
        ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
3353
        if (ptr==NULL || dst_length < 0){
3354
            return -1;
3355
        }
3356
        i= buf_index + consumed;
3357
        if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
3358
           buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
3359
            s->workaround_bugs |= FF_BUG_TRUNCATED;
3360

    
3361
        if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
3362
        while(ptr[dst_length - 1] == 0 && dst_length > 0)
3363
            dst_length--;
3364
        }
3365
        bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
3366

    
3367
        if(s->avctx->debug&FF_DEBUG_STARTCODE){
3368
            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);
3369
        }
3370

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

    
3375
        buf_index += consumed;
3376

    
3377
        //FIXME do not discard SEI id
3378
        if(
3379
#if FF_API_HURRY_UP
3380
           (s->hurry_up == 1 && h->nal_ref_idc  == 0) ||
3381
#endif
3382
           (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc  == 0))
3383
            continue;
3384

    
3385
      again:
3386
        err = 0;
3387
        switch(hx->nal_unit_type){
3388
        case NAL_IDR_SLICE:
3389
            if (h->nal_unit_type != NAL_IDR_SLICE) {
3390
                av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
3391
                return -1;
3392
            }
3393
            idr(h); //FIXME ensure we don't loose some frames if there is reordering
3394
        case NAL_SLICE:
3395
            init_get_bits(&hx->s.gb, ptr, bit_length);
3396
            hx->intra_gb_ptr=
3397
            hx->inter_gb_ptr= &hx->s.gb;
3398
            hx->s.data_partitioning = 0;
3399

    
3400
            if((err = decode_slice_header(hx, h)))
3401
               break;
3402

    
3403
            s->current_picture_ptr->key_frame |=
3404
                    (hx->nal_unit_type == NAL_IDR_SLICE) ||
3405
                    (h->sei_recovery_frame_cnt >= 0);
3406

    
3407
            if (h->current_slice == 1) {
3408
                if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3409
                    decode_postinit(h);
3410
                }
3411

    
3412
                if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
3413
                    return -1;
3414
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3415
                    ff_vdpau_h264_picture_start(s);
3416
            }
3417

    
3418
            if(hx->redundant_pic_count==0
3419
#if FF_API_HURRY_UP
3420
               && hx->s.hurry_up < 5
3421
#endif
3422
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3423
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3424
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3425
               && avctx->skip_frame < AVDISCARD_ALL){
3426
                if(avctx->hwaccel) {
3427
                    if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
3428
                        return -1;
3429
                }else
3430
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
3431
                    static const uint8_t start_code[] = {0x00, 0x00, 0x01};
3432
                    ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
3433
                    ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
3434
                }else
3435
                    context_count++;
3436
            }
3437
            break;
3438
        case NAL_DPA:
3439
            init_get_bits(&hx->s.gb, ptr, bit_length);
3440
            hx->intra_gb_ptr=
3441
            hx->inter_gb_ptr= NULL;
3442

    
3443
            if ((err = decode_slice_header(hx, h)) < 0)
3444
                break;
3445

    
3446
            hx->s.data_partitioning = 1;
3447

    
3448
            break;
3449
        case NAL_DPB:
3450
            init_get_bits(&hx->intra_gb, ptr, bit_length);
3451
            hx->intra_gb_ptr= &hx->intra_gb;
3452
            break;
3453
        case NAL_DPC:
3454
            init_get_bits(&hx->inter_gb, ptr, bit_length);
3455
            hx->inter_gb_ptr= &hx->inter_gb;
3456

    
3457
            if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
3458
               && s->context_initialized
3459
#if FF_API_HURRY_UP
3460
               && s->hurry_up < 5
3461
#endif
3462
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3463
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3464
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3465
               && avctx->skip_frame < AVDISCARD_ALL)
3466
                context_count++;
3467
            break;
3468
        case NAL_SEI:
3469
            init_get_bits(&s->gb, ptr, bit_length);
3470
            ff_h264_decode_sei(h);
3471
            break;
3472
        case NAL_SPS:
3473
            init_get_bits(&s->gb, ptr, bit_length);
3474
            ff_h264_decode_seq_parameter_set(h);
3475

    
3476
            if(s->flags& CODEC_FLAG_LOW_DELAY)
3477
                s->low_delay=1;
3478

    
3479
            if(avctx->has_b_frames < 2)
3480
                avctx->has_b_frames= !s->low_delay;
3481

    
3482
            if (avctx->bits_per_raw_sample != h->sps.bit_depth_luma) {
3483
                if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
3484
                    avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3485
                    h->pixel_shift = h->sps.bit_depth_luma/9;
3486

    
3487
                    ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma);
3488
                    ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma);
3489
                    dsputil_init(&s->dsp, s->avctx);
3490
                } else {
3491
                    av_log(avctx, AV_LOG_DEBUG, "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3492
                    return -1;
3493
                }
3494
            }
3495
            break;
3496
        case NAL_PPS:
3497
            init_get_bits(&s->gb, ptr, bit_length);
3498

    
3499
            ff_h264_decode_picture_parameter_set(h, bit_length);
3500

    
3501
            break;
3502
        case NAL_AUD:
3503
        case NAL_END_SEQUENCE:
3504
        case NAL_END_STREAM:
3505
        case NAL_FILLER_DATA:
3506
        case NAL_SPS_EXT:
3507
        case NAL_AUXILIARY_SLICE:
3508
            break;
3509
        default:
3510
            av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
3511
        }
3512

    
3513
        if(context_count == h->max_contexts) {
3514
            execute_decode_slices(h, context_count);
3515
            context_count = 0;
3516
        }
3517

    
3518
        if (err < 0)
3519
            av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
3520
        else if(err == 1) {
3521
            /* Slice could not be decoded in parallel mode, copy down
3522
             * NAL unit stuff to context 0 and restart. Note that
3523
             * rbsp_buffer is not transferred, but since we no longer
3524
             * run in parallel mode this should not be an issue. */
3525
            h->nal_unit_type = hx->nal_unit_type;
3526
            h->nal_ref_idc   = hx->nal_ref_idc;
3527
            hx = h;
3528
            goto again;
3529
        }
3530
    }
3531
    if(context_count)
3532
        execute_decode_slices(h, context_count);
3533
    return buf_index;
3534
}
3535

    
3536
/**
3537
 * returns the number of bytes consumed for building the current frame
3538
 */
3539
static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
3540
        if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
3541
        if(pos+10>buf_size) pos=buf_size; // oops ;)
3542

    
3543
        return pos;
3544
}
3545

    
3546
static int decode_frame(AVCodecContext *avctx,
3547
                             void *data, int *data_size,
3548
                             AVPacket *avpkt)
3549
{
3550
    const uint8_t *buf = avpkt->data;
3551
    int buf_size = avpkt->size;
3552
    H264Context *h = avctx->priv_data;
3553
    MpegEncContext *s = &h->s;
3554
    AVFrame *pict = data;
3555
    int buf_index;
3556

    
3557
    s->flags= avctx->flags;
3558
    s->flags2= avctx->flags2;
3559

    
3560
   /* end of stream, output what is still in the buffers */
3561
 out:
3562
    if (buf_size == 0) {
3563
        Picture *out;
3564
        int i, out_idx;
3565

    
3566
        s->current_picture_ptr = NULL;
3567

    
3568
//FIXME factorize this with the output code below
3569
        out = h->delayed_pic[0];
3570
        out_idx = 0;
3571
        for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
3572
            if(h->delayed_pic[i]->poc < out->poc){
3573
                out = h->delayed_pic[i];
3574
                out_idx = i;
3575
            }
3576

    
3577
        for(i=out_idx; h->delayed_pic[i]; i++)
3578
            h->delayed_pic[i] = h->delayed_pic[i+1];
3579

    
3580
        if(out){
3581
            *data_size = sizeof(AVFrame);
3582
            *pict= *(AVFrame*)out;
3583
        }
3584

    
3585
        return 0;
3586
    }
3587

    
3588
    buf_index=decode_nal_units(h, buf, buf_size);
3589
    if(buf_index < 0)
3590
        return -1;
3591

    
3592
    if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
3593
        buf_size = 0;
3594
        goto out;
3595
    }
3596

    
3597
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
3598
        if (avctx->skip_frame >= AVDISCARD_NONREF
3599
#if FF_API_HURRY_UP
3600
                || s->hurry_up
3601
#endif
3602
           )
3603
            return 0;
3604
        av_log(avctx, AV_LOG_ERROR, "no frame!\n");
3605
        return -1;
3606
    }
3607

    
3608
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
3609

    
3610
        if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h);
3611

    
3612
        field_end(h, 0);
3613

    
3614
        if (!h->next_output_pic) {
3615
            /* Wait for second field. */
3616
            *data_size = 0;
3617

    
3618
        } else {
3619
            *data_size = sizeof(AVFrame);
3620
            *pict = *(AVFrame*)h->next_output_pic;
3621
        }
3622
    }
3623

    
3624
    assert(pict->data[0] || !*data_size);
3625
    ff_print_debug_info(s, pict);
3626
//printf("out %d\n", (int)pict->data[0]);
3627

    
3628
    return get_consumed_bytes(s, buf_index, buf_size);
3629
}
3630
#if 0
3631
static inline void fill_mb_avail(H264Context *h){
3632
    MpegEncContext * const s = &h->s;
3633
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3634

3635
    if(s->mb_y){
3636
        h->mb_avail[0]= s->mb_x                 && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
3637
        h->mb_avail[1]=                            h->slice_table[mb_xy - s->mb_stride    ] == h->slice_num;
3638
        h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
3639
    }else{
3640
        h->mb_avail[0]=
3641
        h->mb_avail[1]=
3642
        h->mb_avail[2]= 0;
3643
    }
3644
    h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
3645
    h->mb_avail[4]= 1; //FIXME move out
3646
    h->mb_avail[5]= 0; //FIXME move out
3647
}
3648
#endif
3649

    
3650
#ifdef TEST
3651
#undef printf
3652
#undef random
3653
#define COUNT 8000
3654
#define SIZE (COUNT*40)
3655
int main(void){
3656
    int i;
3657
    uint8_t temp[SIZE];
3658
    PutBitContext pb;
3659
    GetBitContext gb;
3660
//    int int_temp[10000];
3661
    DSPContext dsp;
3662
    AVCodecContext avctx;
3663

    
3664
    dsputil_init(&dsp, &avctx);
3665

    
3666
    init_put_bits(&pb, temp, SIZE);
3667
    printf("testing unsigned exp golomb\n");
3668
    for(i=0; i<COUNT; i++){
3669
        START_TIMER
3670
        set_ue_golomb(&pb, i);
3671
        STOP_TIMER("set_ue_golomb");
3672
    }
3673
    flush_put_bits(&pb);
3674

    
3675
    init_get_bits(&gb, temp, 8*SIZE);
3676
    for(i=0; i<COUNT; i++){
3677
        int j, s;
3678

    
3679
        s= show_bits(&gb, 24);
3680

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

    
3690

    
3691
    init_put_bits(&pb, temp, SIZE);
3692
    printf("testing signed exp golomb\n");
3693
    for(i=0; i<COUNT; i++){
3694
        START_TIMER
3695
        set_se_golomb(&pb, i - COUNT/2);
3696
        STOP_TIMER("set_se_golomb");
3697
    }
3698
    flush_put_bits(&pb);
3699

    
3700
    init_get_bits(&gb, temp, 8*SIZE);
3701
    for(i=0; i<COUNT; i++){
3702
        int j, s;
3703

    
3704
        s= show_bits(&gb, 24);
3705

    
3706
        START_TIMER
3707
        j= get_se_golomb(&gb);
3708
        if(j != i - COUNT/2){
3709
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3710
//            return -1;
3711
        }
3712
        STOP_TIMER("get_se_golomb");
3713
    }
3714

    
3715
#if 0
3716
    printf("testing 4x4 (I)DCT\n");
3717

3718
    DCTELEM block[16];
3719
    uint8_t src[16], ref[16];
3720
    uint64_t error= 0, max_error=0;
3721

3722
    for(i=0; i<COUNT; i++){
3723
        int j;
3724
//        printf("%d %d %d\n", r1, r2, (r2-r1)*16);
3725
        for(j=0; j<16; j++){
3726
            ref[j]= random()%255;
3727
            src[j]= random()%255;
3728
        }
3729

3730
        h264_diff_dct_c(block, src, ref, 4);
3731

3732
        //normalize
3733
        for(j=0; j<16; j++){
3734
//            printf("%d ", block[j]);
3735
            block[j]= block[j]*4;
3736
            if(j&1) block[j]= (block[j]*4 + 2)/5;
3737
            if(j&4) block[j]= (block[j]*4 + 2)/5;
3738
        }
3739
//        printf("\n");
3740

3741
        h->h264dsp.h264_idct_add(ref, block, 4);
3742
/*        for(j=0; j<16; j++){
3743
            printf("%d ", ref[j]);
3744
        }
3745
        printf("\n");*/
3746

3747
        for(j=0; j<16; j++){
3748
            int diff= FFABS(src[j] - ref[j]);
3749

3750
            error+= diff*diff;
3751
            max_error= FFMAX(max_error, diff);
3752
        }
3753
    }
3754
    printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
3755
    printf("testing quantizer\n");
3756
    for(qp=0; qp<52; qp++){
3757
        for(i=0; i<16; i++)
3758
            src1_block[i]= src2_block[i]= random()%255;
3759

3760
    }
3761
    printf("Testing NAL layer\n");
3762

3763
    uint8_t bitstream[COUNT];
3764
    uint8_t nal[COUNT*2];
3765
    H264Context h;
3766
    memset(&h, 0, sizeof(H264Context));
3767

3768
    for(i=0; i<COUNT; i++){
3769
        int zeros= i;
3770
        int nal_length;
3771
        int consumed;
3772
        int out_length;
3773
        uint8_t *out;
3774
        int j;
3775

3776
        for(j=0; j<COUNT; j++){
3777
            bitstream[j]= (random() % 255) + 1;
3778
        }
3779

3780
        for(j=0; j<zeros; j++){
3781
            int pos= random() % COUNT;
3782
            while(bitstream[pos] == 0){
3783
                pos++;
3784
                pos %= COUNT;
3785
            }
3786
            bitstream[pos]=0;
3787
        }
3788

3789
        START_TIMER
3790

3791
        nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
3792
        if(nal_length<0){
3793
            printf("encoding failed\n");
3794
            return -1;
3795
        }
3796

3797
        out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
3798

3799
        STOP_TIMER("NAL")
3800

3801
        if(out_length != COUNT){
3802
            printf("incorrect length %d %d\n", out_length, COUNT);
3803
            return -1;
3804
        }
3805

3806
        if(consumed != nal_length){
3807
            printf("incorrect consumed length %d %d\n", nal_length, consumed);
3808
            return -1;
3809
        }
3810

3811
        if(memcmp(bitstream, out, COUNT)){
3812
            printf("mismatch\n");
3813
            return -1;
3814
        }
3815
    }
3816
#endif
3817

    
3818
    printf("Testing RBSP\n");
3819

    
3820

    
3821
    return 0;
3822
}
3823
#endif /* TEST */
3824

    
3825

    
3826
av_cold void ff_h264_free_context(H264Context *h)
3827
{
3828
    int i;
3829

    
3830
    free_tables(h, 1); //FIXME cleanup init stuff perhaps
3831

    
3832
    for(i = 0; i < MAX_SPS_COUNT; i++)
3833
        av_freep(h->sps_buffers + i);
3834

    
3835
    for(i = 0; i < MAX_PPS_COUNT; i++)
3836
        av_freep(h->pps_buffers + i);
3837
}
3838

    
3839
av_cold int ff_h264_decode_end(AVCodecContext *avctx)
3840
{
3841
    H264Context *h = avctx->priv_data;
3842
    MpegEncContext *s = &h->s;
3843

    
3844
    ff_h264_free_context(h);
3845

    
3846
    MPV_common_end(s);
3847

    
3848
//    memset(h, 0, sizeof(H264Context));
3849

    
3850
    return 0;
3851
}
3852

    
3853
static const AVProfile profiles[] = {
3854
    { FF_PROFILE_H264_BASELINE,             "Baseline"              },
3855
    { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
3856
    { FF_PROFILE_H264_MAIN,                 "Main"                  },
3857
    { FF_PROFILE_H264_EXTENDED,             "Extended"              },
3858
    { FF_PROFILE_H264_HIGH,                 "High"                  },
3859
    { FF_PROFILE_H264_HIGH_10,              "High 10"               },
3860
    { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
3861
    { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
3862
    { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
3863
    { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
3864
    { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
3865
    { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
3866
    { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
3867
    { FF_PROFILE_UNKNOWN },
3868
};
3869

    
3870
AVCodec ff_h264_decoder = {
3871
    "h264",
3872
    AVMEDIA_TYPE_VIDEO,
3873
    CODEC_ID_H264,
3874
    sizeof(H264Context),
3875
    ff_h264_decode_init,
3876
    NULL,
3877
    ff_h264_decode_end,
3878
    decode_frame,
3879
    /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
3880
    .flush= flush_dpb,
3881
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
3882
    .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
3883
    .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
3884
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3885
};
3886

    
3887
#if CONFIG_H264_VDPAU_DECODER
3888
AVCodec ff_h264_vdpau_decoder = {
3889
    "h264_vdpau",
3890
    AVMEDIA_TYPE_VIDEO,
3891
    CODEC_ID_H264,
3892
    sizeof(H264Context),
3893
    ff_h264_decode_init,
3894
    NULL,
3895
    ff_h264_decode_end,
3896
    decode_frame,
3897
    CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
3898
    .flush= flush_dpb,
3899
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
3900
    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
3901
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3902
};
3903
#endif