Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ 7e2eb4ba

History | View | Annotate | Download (126 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
#if 0
254
/**
255
 * DCT transforms the 16 dc values.
256
 * @param qp quantization parameter ??? FIXME
257
 */
258
static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
259
//    const int qmul= dequant_coeff[qp][0];
260
    int i;
261
    int temp[16]; //FIXME check if this is a good idea
262
    static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
263
    static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
264

265
    for(i=0; i<4; i++){
266
        const int offset= y_offset[i];
267
        const int z0= block[offset+stride*0] + block[offset+stride*4];
268
        const int z1= block[offset+stride*0] - block[offset+stride*4];
269
        const int z2= block[offset+stride*1] - block[offset+stride*5];
270
        const int z3= block[offset+stride*1] + block[offset+stride*5];
271

272
        temp[4*i+0]= z0+z3;
273
        temp[4*i+1]= z1+z2;
274
        temp[4*i+2]= z1-z2;
275
        temp[4*i+3]= z0-z3;
276
    }
277

278
    for(i=0; i<4; i++){
279
        const int offset= x_offset[i];
280
        const int z0= temp[4*0+i] + temp[4*2+i];
281
        const int z1= temp[4*0+i] - temp[4*2+i];
282
        const int z2= temp[4*1+i] - temp[4*3+i];
283
        const int z3= temp[4*1+i] + temp[4*3+i];
284

285
        block[stride*0 +offset]= (z0 + z3)>>1;
286
        block[stride*2 +offset]= (z1 + z2)>>1;
287
        block[stride*8 +offset]= (z1 - z2)>>1;
288
        block[stride*10+offset]= (z0 - z3)>>1;
289
    }
290
}
291
#endif
292

    
293
#undef xStride
294
#undef stride
295

    
296
#if 0
297
static void chroma_dc_dct_c(DCTELEM *block){
298
    const int stride= 16*2;
299
    const int xStride= 16;
300
    int a,b,c,d,e;
301

302
    a= block[stride*0 + xStride*0];
303
    b= block[stride*0 + xStride*1];
304
    c= block[stride*1 + xStride*0];
305
    d= block[stride*1 + xStride*1];
306

307
    e= a-b;
308
    a= a+b;
309
    b= c-d;
310
    c= c+d;
311

312
    block[stride*0 + xStride*0]= (a+c);
313
    block[stride*0 + xStride*1]= (e+b);
314
    block[stride*1 + xStride*0]= (a-c);
315
    block[stride*1 + xStride*1]= (e-b);
316
}
317
#endif
318

    
319

    
320
static void free_tables(H264Context *h, int free_rbsp){
321
    int i;
322
    H264Context *hx;
323
    av_freep(&h->intra4x4_pred_mode);
324
    av_freep(&h->chroma_pred_mode_table);
325
    av_freep(&h->cbp_table);
326
    av_freep(&h->mvd_table[0]);
327
    av_freep(&h->mvd_table[1]);
328
    av_freep(&h->direct_table);
329
    av_freep(&h->non_zero_count);
330
    av_freep(&h->slice_table_base);
331
    h->slice_table= NULL;
332
    av_freep(&h->list_counts);
333

    
334
    av_freep(&h->mb2b_xy);
335
    av_freep(&h->mb2br_xy);
336

    
337
    for(i = 0; i < MAX_THREADS; i++) {
338
        hx = h->thread_context[i];
339
        if(!hx) continue;
340
        av_freep(&hx->top_borders[1]);
341
        av_freep(&hx->top_borders[0]);
342
        av_freep(&hx->s.obmc_scratchpad);
343
        if (free_rbsp){
344
            av_freep(&hx->rbsp_buffer[1]);
345
            av_freep(&hx->rbsp_buffer[0]);
346
            hx->rbsp_buffer_size[0] = 0;
347
            hx->rbsp_buffer_size[1] = 0;
348
        }
349
        if (i) av_freep(&h->thread_context[i]);
350
    }
351
}
352

    
353
static void init_dequant8_coeff_table(H264Context *h){
354
    int i,q,x;
355
    const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
356
    h->dequant8_coeff[0] = h->dequant8_buffer[0];
357
    h->dequant8_coeff[1] = h->dequant8_buffer[1];
358

    
359
    for(i=0; i<2; i++ ){
360
        if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
361
            h->dequant8_coeff[1] = h->dequant8_buffer[0];
362
            break;
363
        }
364

    
365
        for(q=0; q<max_qp+1; q++){
366
            int shift = div6[q];
367
            int idx = rem6[q];
368
            for(x=0; x<64; x++)
369
                h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
370
                    ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
371
                    h->pps.scaling_matrix8[i][x]) << shift;
372
        }
373
    }
374
}
375

    
376
static void init_dequant4_coeff_table(H264Context *h){
377
    int i,j,q,x;
378
    const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
379
    for(i=0; i<6; i++ ){
380
        h->dequant4_coeff[i] = h->dequant4_buffer[i];
381
        for(j=0; j<i; j++){
382
            if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
383
                h->dequant4_coeff[i] = h->dequant4_buffer[j];
384
                break;
385
            }
386
        }
387
        if(j<i)
388
            continue;
389

    
390
        for(q=0; q<max_qp+1; q++){
391
            int shift = div6[q] + 2;
392
            int idx = rem6[q];
393
            for(x=0; x<16; x++)
394
                h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
395
                    ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
396
                    h->pps.scaling_matrix4[i][x]) << shift;
397
        }
398
    }
399
}
400

    
401
static void init_dequant_tables(H264Context *h){
402
    int i,x;
403
    init_dequant4_coeff_table(h);
404
    if(h->pps.transform_8x8_mode)
405
        init_dequant8_coeff_table(h);
406
    if(h->sps.transform_bypass){
407
        for(i=0; i<6; i++)
408
            for(x=0; x<16; x++)
409
                h->dequant4_coeff[i][0][x] = 1<<6;
410
        if(h->pps.transform_8x8_mode)
411
            for(i=0; i<2; i++)
412
                for(x=0; x<64; x++)
413
                    h->dequant8_coeff[i][0][x] = 1<<6;
414
    }
415
}
416

    
417

    
418
int ff_h264_alloc_tables(H264Context *h){
419
    MpegEncContext * const s = &h->s;
420
    const int big_mb_num= s->mb_stride * (s->mb_height+1);
421
    const int row_mb_num= 2*s->mb_stride*s->avctx->thread_count;
422
    int x,y;
423

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

    
426
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count    , big_mb_num * 32 * sizeof(uint8_t), fail)
427
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
428
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
429

    
430
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
431
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
432
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
433
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
434
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
435

    
436
    memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(*h->slice_table_base));
437
    h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
438

    
439
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy  , big_mb_num * sizeof(uint32_t), fail);
440
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy , big_mb_num * sizeof(uint32_t), fail);
441
    for(y=0; y<s->mb_height; y++){
442
        for(x=0; x<s->mb_width; x++){
443
            const int mb_xy= x + y*s->mb_stride;
444
            const int b_xy = 4*x + 4*y*h->b_stride;
445

    
446
            h->mb2b_xy [mb_xy]= b_xy;
447
            h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
448
        }
449
    }
450

    
451
    s->obmc_scratchpad = NULL;
452

    
453
    if(!h->dequant4_coeff[0])
454
        init_dequant_tables(h);
455

    
456
    return 0;
457
fail:
458
    free_tables(h, 1);
459
    return -1;
460
}
461

    
462
/**
463
 * Mimic alloc_tables(), but for every context thread.
464
 */
465
static void clone_tables(H264Context *dst, H264Context *src, int i){
466
    MpegEncContext * const s = &src->s;
467
    dst->intra4x4_pred_mode       = src->intra4x4_pred_mode + i*8*2*s->mb_stride;
468
    dst->non_zero_count           = src->non_zero_count;
469
    dst->slice_table              = src->slice_table;
470
    dst->cbp_table                = src->cbp_table;
471
    dst->mb2b_xy                  = src->mb2b_xy;
472
    dst->mb2br_xy                 = src->mb2br_xy;
473
    dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;
474
    dst->mvd_table[0]             = src->mvd_table[0] + i*8*2*s->mb_stride;
475
    dst->mvd_table[1]             = src->mvd_table[1] + i*8*2*s->mb_stride;
476
    dst->direct_table             = src->direct_table;
477
    dst->list_counts              = src->list_counts;
478

    
479
    dst->s.obmc_scratchpad = NULL;
480
    ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma);
481
}
482

    
483
/**
484
 * Init context
485
 * Allocate buffers which are not shared amongst multiple threads.
486
 */
487
static int context_init(H264Context *h){
488
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t)*2, fail)
489
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t)*2, fail)
490

    
491
    h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
492
    h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
493

    
494
    return 0;
495
fail:
496
    return -1; // free_tables will clean up for us
497
}
498

    
499
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
500

    
501
static av_cold void common_init(H264Context *h){
502
    MpegEncContext * const s = &h->s;
503

    
504
    s->width = s->avctx->width;
505
    s->height = s->avctx->height;
506
    s->codec_id= s->avctx->codec->id;
507

    
508
    ff_h264dsp_init(&h->h264dsp, 8);
509
    ff_h264_pred_init(&h->hpc, s->codec_id, 8);
510

    
511
    h->dequant_coeff_pps= -1;
512
    s->unrestricted_mv=1;
513
    s->decode=1; //FIXME
514

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

    
517
    memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
518
    memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
519
}
520

    
521
int ff_h264_decode_extradata(H264Context *h)
522
{
523
    AVCodecContext *avctx = h->s.avctx;
524

    
525
    if(*(char *)avctx->extradata == 1){
526
        int i, cnt, nalsize;
527
        unsigned char *p = avctx->extradata;
528

    
529
        h->is_avc = 1;
530

    
531
        if(avctx->extradata_size < 7) {
532
            av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
533
            return -1;
534
        }
535
        /* sps and pps in the avcC always have length coded with 2 bytes,
536
           so put a fake nal_length_size = 2 while parsing them */
537
        h->nal_length_size = 2;
538
        // Decode sps from avcC
539
        cnt = *(p+5) & 0x1f; // Number of sps
540
        p += 6;
541
        for (i = 0; i < cnt; i++) {
542
            nalsize = AV_RB16(p) + 2;
543
            if(decode_nal_units(h, p, nalsize) < 0) {
544
                av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
545
                return -1;
546
            }
547
            p += nalsize;
548
        }
549
        // Decode pps from avcC
550
        cnt = *(p++); // Number of pps
551
        for (i = 0; i < cnt; i++) {
552
            nalsize = AV_RB16(p) + 2;
553
            if(decode_nal_units(h, p, nalsize) < 0) {
554
                av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
555
                return -1;
556
            }
557
            p += nalsize;
558
        }
559
        // Now store right nal length size, that will be use to parse all other nals
560
        h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
561
    } else {
562
        h->is_avc = 0;
563
        if(decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
564
            return -1;
565
    }
566
    return 0;
567
}
568

    
569
av_cold int ff_h264_decode_init(AVCodecContext *avctx){
570
    H264Context *h= avctx->priv_data;
571
    MpegEncContext * const s = &h->s;
572

    
573
    MPV_decode_defaults(s);
574

    
575
    s->avctx = avctx;
576
    common_init(h);
577

    
578
    s->out_format = FMT_H264;
579
    s->workaround_bugs= avctx->workaround_bugs;
580

    
581
    // set defaults
582
//    s->decode_mb= ff_h263_decode_mb;
583
    s->quarter_sample = 1;
584
    if(!avctx->has_b_frames)
585
    s->low_delay= 1;
586

    
587
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
588

    
589
    ff_h264_decode_init_vlc();
590

    
591
    h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
592
    h->pixel_shift = 0;
593

    
594
    h->thread_context[0] = h;
595
    h->outputed_poc = h->next_outputed_poc = INT_MIN;
596
    h->prev_poc_msb= 1<<16;
597
    h->x264_build = -1;
598
    ff_h264_reset_sei(h);
599
    if(avctx->codec_id == CODEC_ID_H264){
600
        if(avctx->ticks_per_frame == 1){
601
            s->avctx->time_base.den *=2;
602
        }
603
        avctx->ticks_per_frame = 2;
604
    }
605

    
606
    if(avctx->extradata_size > 0 && avctx->extradata &&
607
        ff_h264_decode_extradata(h))
608
        return -1;
609

    
610
    if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
611
        s->avctx->has_b_frames = h->sps.num_reorder_frames;
612
        s->low_delay = 0;
613
    }
614

    
615
    return 0;
616
}
617

    
618
static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
619
{
620
    int i;
621

    
622
    for (i=0; i<count; i++){
623
        to[i] = REBASE_PICTURE(from[i], new_base, old_base);
624
    }
625
}
626

    
627
static void copy_parameter_set(void **to, void **from, int count, int size)
628
{
629
    int i;
630

    
631
    for (i=0; i<count; i++){
632
        if (to[i] && !from[i]) av_freep(&to[i]);
633
        else if (from[i] && !to[i]) to[i] = av_malloc(size);
634

    
635
        if (from[i]) memcpy(to[i], from[i], size);
636
    }
637
}
638

    
639
static int decode_init_thread_copy(AVCodecContext *avctx){
640
    H264Context *h= avctx->priv_data;
641

    
642
    if (!avctx->is_copy) return 0;
643
    memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
644
    memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
645

    
646
    return 0;
647
}
648

    
649
#define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
650
static int decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src){
651
    H264Context *h= dst->priv_data, *h1= src->priv_data;
652
    MpegEncContext * const s = &h->s, * const s1 = &h1->s;
653
    int inited = s->context_initialized, err;
654
    int i;
655

    
656
    if(dst == src || !s1->context_initialized) return 0;
657

    
658
    err = ff_mpeg_update_thread_context(dst, src);
659
    if(err) return err;
660

    
661
    //FIXME handle width/height changing
662
    if(!inited){
663
        for(i = 0; i < MAX_SPS_COUNT; i++)
664
            av_freep(h->sps_buffers + i);
665

    
666
        for(i = 0; i < MAX_PPS_COUNT; i++)
667
            av_freep(h->pps_buffers + i);
668

    
669
        memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
670
        memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
671
        memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
672
        ff_h264_alloc_tables(h);
673
        context_init(h);
674

    
675
        for(i=0; i<2; i++){
676
            h->rbsp_buffer[i] = NULL;
677
            h->rbsp_buffer_size[i] = 0;
678
        }
679

    
680
        h->thread_context[0] = h;
681

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

    
686
        s->dsp.clear_blocks(h->mb);
687
    }
688

    
689
    //extradata/NAL handling
690
    h->is_avc          = h1->is_avc;
691

    
692
    //SPS/PPS
693
    copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
694
    h->sps             = h1->sps;
695
    copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
696
    h->pps             = h1->pps;
697

    
698
    //Dequantization matrices
699
    //FIXME these are big - can they be only copied when PPS changes?
700
    copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
701

    
702
    for(i=0; i<6; i++)
703
        h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
704

    
705
    for(i=0; i<2; i++)
706
        h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
707

    
708
    h->dequant_coeff_pps = h1->dequant_coeff_pps;
709

    
710
    //POC timing
711
    copy_fields(h, h1, poc_lsb, redundant_pic_count);
712

    
713
    //reference lists
714
    copy_fields(h, h1, ref_count, intra_gb);
715
    copy_fields(h, h1, short_ref, cabac_init_idc);
716

    
717
    copy_picture_range(h->short_ref,   h1->short_ref,   32, s, s1);
718
    copy_picture_range(h->long_ref,    h1->long_ref,    32, s, s1);
719
    copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
720

    
721
    h->last_slice_type = h1->last_slice_type;
722

    
723
    if(!s->current_picture_ptr) return 0;
724

    
725
    if(!s->dropable) {
726
        ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
727
        h->prev_poc_msb     = h->poc_msb;
728
        h->prev_poc_lsb     = h->poc_lsb;
729
    }
730
    h->prev_frame_num_offset= h->frame_num_offset;
731
    h->prev_frame_num       = h->frame_num;
732
    h->outputed_poc         = h->next_outputed_poc;
733

    
734
    return 0;
735
}
736

    
737
int ff_h264_frame_start(H264Context *h){
738
    MpegEncContext * const s = &h->s;
739
    int i;
740

    
741
    if(MPV_frame_start(s, s->avctx) < 0)
742
        return -1;
743
    ff_er_frame_start(s);
744
    /*
745
     * MPV_frame_start uses pict_type to derive key_frame.
746
     * This is incorrect for H.264; IDR markings must be used.
747
     * Zero here; IDR markings per slice in frame or fields are ORed in later.
748
     * See decode_nal_units().
749
     */
750
    s->current_picture_ptr->key_frame= 0;
751
    s->current_picture_ptr->mmco_reset= 0;
752

    
753
    assert(s->linesize && s->uvlinesize);
754

    
755
    for(i=0; i<16; i++){
756
        h->block_offset[i]= (4*((scan8[i] - scan8[0])&7)<<h->pixel_shift) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
757
        h->block_offset[24+i]= (4*((scan8[i] - scan8[0])&7)<<h->pixel_shift) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
758
    }
759
    for(i=0; i<4; i++){
760
        h->block_offset[16+i]=
761
        h->block_offset[20+i]= (4*((scan8[i] - scan8[0])&7)<<h->pixel_shift) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
762
        h->block_offset[24+16+i]=
763
        h->block_offset[24+20+i]= (4*((scan8[i] - scan8[0])&7)<<h->pixel_shift) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
764
    }
765

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

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

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

    
777
    // We mark the current picture as non-reference after allocating it, so
778
    // that if we break out due to an error it can be released automatically
779
    // in the next MPV_frame_start().
780
    // SVQ3 as well as most other codecs have only last/next/current and thus
781
    // get released even with set reference, besides SVQ3 and others do not
782
    // mark frames as reference later "naturally".
783
    if(s->codec_id != CODEC_ID_SVQ3)
784
        s->current_picture_ptr->reference= 0;
785

    
786
    s->current_picture_ptr->field_poc[0]=
787
    s->current_picture_ptr->field_poc[1]= INT_MAX;
788

    
789
    h->next_output_pic = NULL;
790

    
791
    assert(s->current_picture_ptr->long_ref==0);
792

    
793
    return 0;
794
}
795

    
796
/**
797
  * Run setup operations that must be run after slice header decoding.
798
  * This includes finding the next displayed frame.
799
  *
800
  * @param h h264 master context
801
  */
802
static void decode_postinit(H264Context *h){
803
    MpegEncContext * const s = &h->s;
804
    Picture *out = s->current_picture_ptr;
805
    Picture *cur = s->current_picture_ptr;
806
    int i, pics, out_of_order, out_idx;
807

    
808
    s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
809
    s->current_picture_ptr->pict_type= s->pict_type;
810

    
811
    if (h->next_output_pic) return;
812

    
813
    if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
814
        //FIXME this allows the next thread to start once we encounter the first field of a PAFF packet
815
        //This works if the next packet contains the second field. It does not work if both fields are
816
        //in the same packet.
817
        //ff_thread_finish_setup(s->avctx);
818
        return;
819
    }
820

    
821
    cur->interlaced_frame = 0;
822
    cur->repeat_pict = 0;
823

    
824
    /* Signal interlacing information externally. */
825
    /* Prioritize picture timing SEI information over used decoding process if it exists. */
826

    
827
    if(h->sps.pic_struct_present_flag){
828
        switch (h->sei_pic_struct)
829
        {
830
        case SEI_PIC_STRUCT_FRAME:
831
            break;
832
        case SEI_PIC_STRUCT_TOP_FIELD:
833
        case SEI_PIC_STRUCT_BOTTOM_FIELD:
834
            cur->interlaced_frame = 1;
835
            break;
836
        case SEI_PIC_STRUCT_TOP_BOTTOM:
837
        case SEI_PIC_STRUCT_BOTTOM_TOP:
838
            if (FIELD_OR_MBAFF_PICTURE)
839
                cur->interlaced_frame = 1;
840
            else
841
                // try to flag soft telecine progressive
842
                cur->interlaced_frame = h->prev_interlaced_frame;
843
            break;
844
        case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
845
        case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
846
            // Signal the possibility of telecined film externally (pic_struct 5,6)
847
            // From these hints, let the applications decide if they apply deinterlacing.
848
            cur->repeat_pict = 1;
849
            break;
850
        case SEI_PIC_STRUCT_FRAME_DOUBLING:
851
            // Force progressive here, as doubling interlaced frame is a bad idea.
852
            cur->repeat_pict = 2;
853
            break;
854
        case SEI_PIC_STRUCT_FRAME_TRIPLING:
855
            cur->repeat_pict = 4;
856
            break;
857
        }
858

    
859
        if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
860
            cur->interlaced_frame = (h->sei_ct_type & (1<<1)) != 0;
861
    }else{
862
        /* Derive interlacing flag from used decoding process. */
863
        cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
864
    }
865
    h->prev_interlaced_frame = cur->interlaced_frame;
866

    
867
    if (cur->field_poc[0] != cur->field_poc[1]){
868
        /* Derive top_field_first from field pocs. */
869
        cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
870
    }else{
871
        if(cur->interlaced_frame || h->sps.pic_struct_present_flag){
872
            /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
873
            if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
874
              || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
875
                cur->top_field_first = 1;
876
            else
877
                cur->top_field_first = 0;
878
        }else{
879
            /* Most likely progressive */
880
            cur->top_field_first = 0;
881
        }
882
    }
883

    
884
    //FIXME do something with unavailable reference frames
885

    
886
    /* Sort B-frames into display order */
887

    
888
    if(h->sps.bitstream_restriction_flag
889
       && s->avctx->has_b_frames < h->sps.num_reorder_frames){
890
        s->avctx->has_b_frames = h->sps.num_reorder_frames;
891
        s->low_delay = 0;
892
    }
893

    
894
    if(   s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
895
       && !h->sps.bitstream_restriction_flag){
896
        s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;
897
        s->low_delay= 0;
898
    }
899

    
900
    pics = 0;
901
    while(h->delayed_pic[pics]) pics++;
902

    
903
    assert(pics <= MAX_DELAYED_PIC_COUNT);
904

    
905
    h->delayed_pic[pics++] = cur;
906
    if(cur->reference == 0)
907
        cur->reference = DELAYED_PIC_REF;
908

    
909
    out = h->delayed_pic[0];
910
    out_idx = 0;
911
    for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
912
        if(h->delayed_pic[i]->poc < out->poc){
913
            out = h->delayed_pic[i];
914
            out_idx = i;
915
        }
916
    if(s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset))
917
        h->next_outputed_poc= INT_MIN;
918
    out_of_order = out->poc < h->next_outputed_poc;
919

    
920
    if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
921
        { }
922
    else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)
923
       || (s->low_delay &&
924
        ((h->next_outputed_poc != INT_MIN && out->poc > h->next_outputed_poc + 2)
925
         || cur->pict_type == FF_B_TYPE)))
926
    {
927
        s->low_delay = 0;
928
        s->avctx->has_b_frames++;
929
    }
930

    
931
    if(out_of_order || pics > s->avctx->has_b_frames){
932
        out->reference &= ~DELAYED_PIC_REF;
933
        out->owner2 = s; // for frame threading, the owner must be the second field's thread
934
                         // or else the first thread can release the picture and reuse it unsafely
935
        for(i=out_idx; h->delayed_pic[i]; i++)
936
            h->delayed_pic[i] = h->delayed_pic[i+1];
937
    }
938
    if(!out_of_order && pics > s->avctx->has_b_frames){
939
        h->next_output_pic = out;
940
        if(out_idx==0 && h->delayed_pic[0] && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset)) {
941
            h->next_outputed_poc = INT_MIN;
942
        } else
943
            h->next_outputed_poc = out->poc;
944
    }else{
945
        av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
946
    }
947

    
948
    ff_thread_finish_setup(s->avctx);
949
}
950

    
951
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){
952
    MpegEncContext * const s = &h->s;
953
    uint8_t *top_border;
954
    int top_idx = 1;
955

    
956
    src_y  -=   linesize;
957
    src_cb -= uvlinesize;
958
    src_cr -= uvlinesize;
959

    
960
    if(!simple && FRAME_MBAFF){
961
        if(s->mb_y&1){
962
            if(!MB_MBAFF){
963
                top_border = h->top_borders[0][s->mb_x];
964
                AV_COPY128(top_border, src_y + 15*linesize);
965
                if (h->pixel_shift)
966
                    AV_COPY128(top_border+16, src_y+15*linesize+16);
967
                if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
968
                    if (h->pixel_shift) {
969
                        AV_COPY128(top_border+32, src_cb+7*uvlinesize);
970
                        AV_COPY128(top_border+48, src_cr+7*uvlinesize);
971
                    } else {
972
                    AV_COPY64(top_border+16, src_cb+7*uvlinesize);
973
                    AV_COPY64(top_border+24, src_cr+7*uvlinesize);
974
                    }
975
                }
976
            }
977
        }else if(MB_MBAFF){
978
            top_idx = 0;
979
        }else
980
            return;
981
    }
982

    
983
    top_border = h->top_borders[top_idx][s->mb_x];
984
    // There are two lines saved, the line above the the top macroblock of a pair,
985
    // and the line above the bottom macroblock
986
    AV_COPY128(top_border, src_y + 16*linesize);
987
    if (h->pixel_shift)
988
        AV_COPY128(top_border+16, src_y+16*linesize+16);
989

    
990
    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
991
        if (h->pixel_shift) {
992
            AV_COPY128(top_border+32, src_cb+8*uvlinesize);
993
            AV_COPY128(top_border+48, src_cr+8*uvlinesize);
994
        } else {
995
        AV_COPY64(top_border+16, src_cb+8*uvlinesize);
996
        AV_COPY64(top_border+24, src_cr+8*uvlinesize);
997
        }
998
    }
999
}
1000

    
1001
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, int pixel_shift){
1002
    MpegEncContext * const s = &h->s;
1003
    int deblock_left;
1004
    int deblock_top;
1005
    int top_idx = 1;
1006
    uint8_t *top_border_m1;
1007
    uint8_t *top_border;
1008

    
1009
    if(!simple && FRAME_MBAFF){
1010
        if(s->mb_y&1){
1011
            if(!MB_MBAFF)
1012
                return;
1013
        }else{
1014
            top_idx = MB_MBAFF ? 0 : 1;
1015
        }
1016
    }
1017

    
1018
    if(h->deblocking_filter == 2) {
1019
        deblock_left = h->left_type[0];
1020
        deblock_top  = h->top_type;
1021
    } else {
1022
        deblock_left = (s->mb_x > 0);
1023
        deblock_top =  (s->mb_y > !!MB_FIELD);
1024
    }
1025

    
1026
    src_y  -=   linesize + 1 + pixel_shift;
1027
    src_cb -= uvlinesize + 1 + pixel_shift;
1028
    src_cr -= uvlinesize + 1 + pixel_shift;
1029

    
1030
    top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1031
    top_border    = h->top_borders[top_idx][s->mb_x];
1032

    
1033
#define XCHG(a,b,xchg)\
1034
    if (pixel_shift) {\
1035
        if (xchg) {\
1036
            AV_SWAP64(b+0,a+0);\
1037
            AV_SWAP64(b+8,a+8);\
1038
        } else {\
1039
            AV_COPY128(b,a); \
1040
        }\
1041
    } else \
1042
if (xchg) AV_SWAP64(b,a);\
1043
else      AV_COPY64(b,a);
1044

    
1045
    if(deblock_top){
1046
        if(deblock_left){
1047
            XCHG(top_border_m1+(8<<pixel_shift), src_y -(7<<h->pixel_shift), 1);
1048
        }
1049
        XCHG(top_border+(0<<pixel_shift), src_y +(1<<pixel_shift), xchg);
1050
        XCHG(top_border+(8<<pixel_shift), src_y +(9<<pixel_shift), 1);
1051
        if(s->mb_x+1 < s->mb_width){
1052
            XCHG(h->top_borders[top_idx][s->mb_x+1], src_y +(17<<pixel_shift), 1);
1053
        }
1054
    }
1055
    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1056
        if(deblock_top){
1057
            if(deblock_left){
1058
                XCHG(top_border_m1+(16<<pixel_shift), src_cb -(7<<pixel_shift), 1);
1059
                XCHG(top_border_m1+(24<<pixel_shift), src_cr -(7<<pixel_shift), 1);
1060
            }
1061
            XCHG(top_border+(16<<pixel_shift), src_cb+1+pixel_shift, 1);
1062
            XCHG(top_border+(24<<pixel_shift), src_cr+1+pixel_shift, 1);
1063
        }
1064
    }
1065
}
1066

    
1067
static av_always_inline int dctcoef_get(H264Context *h, DCTELEM *mb, int index, int pixel_shift) {
1068
    if (!pixel_shift)
1069
        return mb[index];
1070
    else
1071
        return ((int32_t*)mb)[index];
1072
}
1073

    
1074
static av_always_inline void dctcoef_set(H264Context *h, DCTELEM *mb, int index, int value, int pixel_shift) {
1075
    if (!pixel_shift)
1076
        mb[index] = value;
1077
    else
1078
        ((int32_t*)mb)[index] = value;
1079
}
1080

    
1081
static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple, int pixel_shift){
1082
    MpegEncContext * const s = &h->s;
1083
    const int mb_x= s->mb_x;
1084
    const int mb_y= s->mb_y;
1085
    const int mb_xy= h->mb_xy;
1086
    const int mb_type= s->current_picture.mb_type[mb_xy];
1087
    uint8_t  *dest_y, *dest_cb, *dest_cr;
1088
    int linesize, uvlinesize /*dct_offset*/;
1089
    int i;
1090
    int *block_offset = &h->block_offset[0];
1091
    const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
1092
    /* is_h264 should always be true if SVQ3 is disabled. */
1093
    const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
1094
    void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1095
    void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1096

    
1097
    dest_y  = s->current_picture.data[0] + ((mb_x<<pixel_shift) + mb_y * s->linesize  ) * 16;
1098
    dest_cb = s->current_picture.data[1] + ((mb_x<<pixel_shift) + mb_y * s->uvlinesize) * 8;
1099
    dest_cr = s->current_picture.data[2] + ((mb_x<<pixel_shift) + mb_y * s->uvlinesize) * 8;
1100

    
1101
    s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + (64<<pixel_shift), s->linesize, 4);
1102
    s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + (64<<pixel_shift), dest_cr - dest_cb, 2);
1103

    
1104
    h->list_counts[mb_xy]= h->list_count;
1105

    
1106
    if (!simple && MB_FIELD) {
1107
        linesize   = h->mb_linesize   = s->linesize * 2;
1108
        uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
1109
        block_offset = &h->block_offset[24];
1110
        if(mb_y&1){ //FIXME move out of this function?
1111
            dest_y -= s->linesize*15;
1112
            dest_cb-= s->uvlinesize*7;
1113
            dest_cr-= s->uvlinesize*7;
1114
        }
1115
        if(FRAME_MBAFF) {
1116
            int list;
1117
            for(list=0; list<h->list_count; list++){
1118
                if(!USES_LIST(mb_type, list))
1119
                    continue;
1120
                if(IS_16X16(mb_type)){
1121
                    int8_t *ref = &h->ref_cache[list][scan8[0]];
1122
                    fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
1123
                }else{
1124
                    for(i=0; i<16; i+=4){
1125
                        int ref = h->ref_cache[list][scan8[i]];
1126
                        if(ref >= 0)
1127
                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
1128
                    }
1129
                }
1130
            }
1131
        }
1132
    } else {
1133
        linesize   = h->mb_linesize   = s->linesize;
1134
        uvlinesize = h->mb_uvlinesize = s->uvlinesize;
1135
//        dct_offset = s->linesize * 16;
1136
    }
1137

    
1138
    if (!simple && IS_INTRA_PCM(mb_type)) {
1139
        if (pixel_shift) {
1140
            const int bit_depth = h->sps.bit_depth_luma;
1141
            int j;
1142
            GetBitContext gb;
1143
            init_get_bits(&gb, (uint8_t*)h->mb, 384*bit_depth);
1144

    
1145
            for (i = 0; i < 16; i++) {
1146
                uint16_t *tmp_y  = (uint16_t*)(dest_y  + i*linesize);
1147
                for (j = 0; j < 16; j++)
1148
                    tmp_y[j] = get_bits(&gb, bit_depth);
1149
            }
1150
            for (i = 0; i < 8; i++) {
1151
                uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
1152
                for (j = 0; j < 8; j++)
1153
                    tmp_cb[j] = get_bits(&gb, bit_depth);
1154
            }
1155
            for (i = 0; i < 8; i++) {
1156
                uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
1157
                for (j = 0; j < 8; j++)
1158
                    tmp_cr[j] = get_bits(&gb, bit_depth);
1159
            }
1160
        } else {
1161
        for (i=0; i<16; i++) {
1162
            memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
1163
        }
1164
        for (i=0; i<8; i++) {
1165
            memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4,  8);
1166
            memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4,  8);
1167
        }
1168
        }
1169
    } else {
1170
        if(IS_INTRA(mb_type)){
1171
            if(h->deblocking_filter)
1172
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple, pixel_shift);
1173

    
1174
            if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1175
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
1176
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
1177
            }
1178

    
1179
            if(IS_INTRA4x4(mb_type)){
1180
                if(simple || !s->encoding){
1181
                    if(IS_8x8DCT(mb_type)){
1182
                        if(transform_bypass){
1183
                            idct_dc_add =
1184
                            idct_add    = s->dsp.add_pixels8;
1185
                        }else{
1186
                            idct_dc_add = h->h264dsp.h264_idct8_dc_add;
1187
                            idct_add    = h->h264dsp.h264_idct8_add;
1188
                        }
1189
                        for(i=0; i<16; i+=4){
1190
                            uint8_t * const ptr= dest_y + block_offset[i];
1191
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1192
                            if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1193
                                h->hpc.pred8x8l_add[dir](ptr, h->mb + (i*16<<pixel_shift), linesize);
1194
                            }else{
1195
                                const int nnz = h->non_zero_count_cache[ scan8[i] ];
1196
                                h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
1197
                                                            (h->topright_samples_available<<i)&0x4000, linesize);
1198
                                if(nnz){
1199
                                    if(nnz == 1 && dctcoef_get(h, h->mb, i*16, pixel_shift))
1200
                                        idct_dc_add(ptr, h->mb + (i*16<<pixel_shift), linesize);
1201
                                    else
1202
                                        idct_add   (ptr, h->mb + (i*16<<pixel_shift), linesize);
1203
                                }
1204
                            }
1205
                        }
1206
                    }else{
1207
                        if(transform_bypass){
1208
                            idct_dc_add =
1209
                            idct_add    = s->dsp.add_pixels4;
1210
                        }else{
1211
                            idct_dc_add = h->h264dsp.h264_idct_dc_add;
1212
                            idct_add    = h->h264dsp.h264_idct_add;
1213
                        }
1214
                        for(i=0; i<16; i++){
1215
                            uint8_t * const ptr= dest_y + block_offset[i];
1216
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1217

    
1218
                            if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1219
                                h->hpc.pred4x4_add[dir](ptr, h->mb + (i*16<<pixel_shift), linesize);
1220
                            }else{
1221
                                uint8_t *topright;
1222
                                int nnz, tr;
1223
                                uint64_t tr_high;
1224
                                if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
1225
                                    const int topright_avail= (h->topright_samples_available<<i)&0x8000;
1226
                                    assert(mb_y || linesize <= block_offset[i]);
1227
                                    if(!topright_avail){
1228
                                        if (pixel_shift) {
1229
                                            tr_high= ((uint16_t*)ptr)[3 - linesize/2]*0x0001000100010001ULL;
1230
                                            topright= (uint8_t*) &tr_high;
1231
                                        } else {
1232
                                        tr= ptr[3 - linesize]*0x01010101;
1233
                                        topright= (uint8_t*) &tr;
1234
                                        }
1235
                                    }else
1236
                                        topright= ptr + (4<<pixel_shift) - linesize;
1237
                                }else
1238
                                    topright= NULL;
1239

    
1240
                                h->hpc.pred4x4[ dir ](ptr, topright, linesize);
1241
                                nnz = h->non_zero_count_cache[ scan8[i] ];
1242
                                if(nnz){
1243
                                    if(is_h264){
1244
                                        if(nnz == 1 && dctcoef_get(h, h->mb, i*16, pixel_shift))
1245
                                            idct_dc_add(ptr, h->mb + (i*16<<pixel_shift), linesize);
1246
                                        else
1247
                                            idct_add   (ptr, h->mb + (i*16<<pixel_shift), linesize);
1248
                                    }
1249
#if CONFIG_SVQ3_DECODER
1250
                                    else
1251
                                        ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
1252
#endif
1253
                                }
1254
                            }
1255
                        }
1256
                    }
1257
                }
1258
            }else{
1259
                h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
1260
                if(is_h264){
1261
                    if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX] ]){
1262
                        if(!transform_bypass)
1263
                            h->h264dsp.h264_luma_dc_dequant_idct(h->mb, h->mb_luma_dc, h->dequant4_coeff[0][s->qscale][0]);
1264
                        else{
1265
                            static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
1266
                                                                    8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
1267
                            for(i = 0; i < 16; i++)
1268
                                dctcoef_set(h, h->mb, dc_mapping[i], dctcoef_get(h, h->mb_luma_dc, i,pixel_shift),pixel_shift);
1269
                        }
1270
                    }
1271
                }
1272
#if CONFIG_SVQ3_DECODER
1273
                else
1274
                    ff_svq3_luma_dc_dequant_idct_c(h->mb, h->mb_luma_dc, s->qscale);
1275
#endif
1276
            }
1277
            if(h->deblocking_filter)
1278
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple, pixel_shift);
1279
        }else if(is_h264){
1280
            ff_hl_motion(h, dest_y, dest_cb, dest_cr,
1281
                      s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
1282
                      s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
1283
                      h->h264dsp.weight_h264_pixels_tab, h->h264dsp.biweight_h264_pixels_tab);
1284
        }
1285

    
1286

    
1287
        if(!IS_INTRA4x4(mb_type)){
1288
            if(is_h264){
1289
                if(IS_INTRA16x16(mb_type)){
1290
                    if(transform_bypass){
1291
                        if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
1292
                            h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb, linesize);
1293
                        }else{
1294
                            for(i=0; i<16; i++){
1295
                                if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h, h->mb, i*16,pixel_shift))
1296
                                    s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + (i*16<<pixel_shift), linesize);
1297
                            }
1298
                        }
1299
                    }else{
1300
                         h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1301
                    }
1302
                }else if(h->cbp&15){
1303
                    if(transform_bypass){
1304
                        const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1305
                        idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
1306
                        for(i=0; i<16; i+=di){
1307
                            if(h->non_zero_count_cache[ scan8[i] ]){
1308
                                idct_add(dest_y + block_offset[i], h->mb + (i*16<<pixel_shift), linesize);
1309
                            }
1310
                        }
1311
                    }else{
1312
                        if(IS_8x8DCT(mb_type)){
1313
                            h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1314
                        }else{
1315
                            h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1316
                        }
1317
                    }
1318
                }
1319
            }
1320
#if CONFIG_SVQ3_DECODER
1321
            else{
1322
                for(i=0; i<16; i++){
1323
                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
1324
                        uint8_t * const ptr= dest_y + block_offset[i];
1325
                        ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
1326
                    }
1327
                }
1328
            }
1329
#endif
1330
        }
1331

    
1332
        if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
1333
            uint8_t *dest[2] = {dest_cb, dest_cr};
1334
            if(transform_bypass){
1335
                if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
1336
                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + (16*16<<pixel_shift), uvlinesize);
1337
                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 20, h->mb + (20*16<<pixel_shift), uvlinesize);
1338
                }else{
1339
                    idct_add = s->dsp.add_pixels4;
1340
                    for(i=16; i<16+8; i++){
1341
                        if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h, h->mb, i*16,pixel_shift))
1342
                            idct_add   (dest[(i&4)>>2] + block_offset[i], h->mb + (i*16<<pixel_shift), uvlinesize);
1343
                    }
1344
                }
1345
            }else{
1346
                if(is_h264){
1347
                    if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
1348
                        h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16*16<<pixel_shift)       , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
1349
                    if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
1350
                        h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + ((16*16+4*16)<<pixel_shift), h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
1351
                    h->h264dsp.h264_idct_add8(dest, block_offset,
1352
                                              h->mb, uvlinesize,
1353
                                              h->non_zero_count_cache);
1354
                }
1355
#if CONFIG_SVQ3_DECODER
1356
                else{
1357
                    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]);
1358
                    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]);
1359
                    for(i=16; i<16+8; i++){
1360
                        if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
1361
                            uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
1362
                            ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
1363
                        }
1364
                    }
1365
                }
1366
#endif
1367
            }
1368
        }
1369
    }
1370
    if(h->cbp || IS_INTRA(mb_type))
1371
        s->dsp.clear_blocks(h->mb);
1372
}
1373

    
1374
/**
1375
 * Process a macroblock; this case avoids checks for expensive uncommon cases.
1376
 */
1377
static void hl_decode_mb_simple8(H264Context *h){
1378
    hl_decode_mb_internal(h, 1, 0);
1379
}
1380

    
1381
/**
1382
 * Process a macroblock; this handles edge cases, such as interlacing.
1383
 */
1384
static void av_noinline hl_decode_mb_complex(H264Context *h){
1385
    hl_decode_mb_internal(h, 0, h->pixel_shift);
1386
}
1387

    
1388
void ff_h264_hl_decode_mb(H264Context *h){
1389
    MpegEncContext * const s = &h->s;
1390
    const int mb_xy= h->mb_xy;
1391
    const int mb_type= s->current_picture.mb_type[mb_xy];
1392
    int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
1393

    
1394
    if (is_complex || h->pixel_shift)
1395
        hl_decode_mb_complex(h);
1396
    else{
1397
        hl_decode_mb_simple8(h);
1398
    }
1399
}
1400

    
1401
static int pred_weight_table(H264Context *h){
1402
    MpegEncContext * const s = &h->s;
1403
    int list, i;
1404
    int luma_def, chroma_def;
1405

    
1406
    h->use_weight= 0;
1407
    h->use_weight_chroma= 0;
1408
    h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
1409
    if(CHROMA)
1410
        h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
1411
    luma_def = 1<<h->luma_log2_weight_denom;
1412
    chroma_def = 1<<h->chroma_log2_weight_denom;
1413

    
1414
    for(list=0; list<2; list++){
1415
        h->luma_weight_flag[list]   = 0;
1416
        h->chroma_weight_flag[list] = 0;
1417
        for(i=0; i<h->ref_count[list]; i++){
1418
            int luma_weight_flag, chroma_weight_flag;
1419

    
1420
            luma_weight_flag= get_bits1(&s->gb);
1421
            if(luma_weight_flag){
1422
                h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
1423
                h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
1424
                if(   h->luma_weight[i][list][0] != luma_def
1425
                   || h->luma_weight[i][list][1] != 0) {
1426
                    h->use_weight= 1;
1427
                    h->luma_weight_flag[list]= 1;
1428
                }
1429
            }else{
1430
                h->luma_weight[i][list][0]= luma_def;
1431
                h->luma_weight[i][list][1]= 0;
1432
            }
1433

    
1434
            if(CHROMA){
1435
                chroma_weight_flag= get_bits1(&s->gb);
1436
                if(chroma_weight_flag){
1437
                    int j;
1438
                    for(j=0; j<2; j++){
1439
                        h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
1440
                        h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
1441
                        if(   h->chroma_weight[i][list][j][0] != chroma_def
1442
                           || h->chroma_weight[i][list][j][1] != 0) {
1443
                            h->use_weight_chroma= 1;
1444
                            h->chroma_weight_flag[list]= 1;
1445
                        }
1446
                    }
1447
                }else{
1448
                    int j;
1449
                    for(j=0; j<2; j++){
1450
                        h->chroma_weight[i][list][j][0]= chroma_def;
1451
                        h->chroma_weight[i][list][j][1]= 0;
1452
                    }
1453
                }
1454
            }
1455
        }
1456
        if(h->slice_type_nos != FF_B_TYPE) break;
1457
    }
1458
    h->use_weight= h->use_weight || h->use_weight_chroma;
1459
    return 0;
1460
}
1461

    
1462
/**
1463
 * Initialize implicit_weight table.
1464
 * @param field  0/1 initialize the weight for interlaced MBAFF
1465
 *                -1 initializes the rest
1466
 */
1467
static void implicit_weight_table(H264Context *h, int field){
1468
    MpegEncContext * const s = &h->s;
1469
    int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
1470

    
1471
    for (i = 0; i < 2; i++) {
1472
        h->luma_weight_flag[i]   = 0;
1473
        h->chroma_weight_flag[i] = 0;
1474
    }
1475

    
1476
    if(field < 0){
1477
        cur_poc = s->current_picture_ptr->poc;
1478
    if(   h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
1479
       && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
1480
        h->use_weight= 0;
1481
        h->use_weight_chroma= 0;
1482
        return;
1483
    }
1484
        ref_start= 0;
1485
        ref_count0= h->ref_count[0];
1486
        ref_count1= h->ref_count[1];
1487
    }else{
1488
        cur_poc = s->current_picture_ptr->field_poc[field];
1489
        ref_start= 16;
1490
        ref_count0= 16+2*h->ref_count[0];
1491
        ref_count1= 16+2*h->ref_count[1];
1492
    }
1493

    
1494
    h->use_weight= 2;
1495
    h->use_weight_chroma= 2;
1496
    h->luma_log2_weight_denom= 5;
1497
    h->chroma_log2_weight_denom= 5;
1498

    
1499
    for(ref0=ref_start; ref0 < ref_count0; ref0++){
1500
        int poc0 = h->ref_list[0][ref0].poc;
1501
        for(ref1=ref_start; ref1 < ref_count1; ref1++){
1502
            int poc1 = h->ref_list[1][ref1].poc;
1503
            int td = av_clip(poc1 - poc0, -128, 127);
1504
            int w= 32;
1505
            if(td){
1506
                int tb = av_clip(cur_poc - poc0, -128, 127);
1507
                int tx = (16384 + (FFABS(td) >> 1)) / td;
1508
                int dist_scale_factor = (tb*tx + 32) >> 8;
1509
                if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
1510
                    w = 64 - dist_scale_factor;
1511
            }
1512
            if(field<0){
1513
                h->implicit_weight[ref0][ref1][0]=
1514
                h->implicit_weight[ref0][ref1][1]= w;
1515
            }else{
1516
                h->implicit_weight[ref0][ref1][field]=w;
1517
            }
1518
        }
1519
    }
1520
}
1521

    
1522
/**
1523
 * instantaneous decoder refresh.
1524
 */
1525
static void idr(H264Context *h){
1526
    ff_h264_remove_all_refs(h);
1527
    h->prev_frame_num= 0;
1528
    h->prev_frame_num_offset= 0;
1529
    h->prev_poc_msb=
1530
    h->prev_poc_lsb= 0;
1531
}
1532

    
1533
/* forget old pics after a seek */
1534
static void flush_dpb(AVCodecContext *avctx){
1535
    H264Context *h= avctx->priv_data;
1536
    int i;
1537
    for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
1538
        if(h->delayed_pic[i])
1539
            h->delayed_pic[i]->reference= 0;
1540
        h->delayed_pic[i]= NULL;
1541
    }
1542
    h->outputed_poc=h->next_outputed_poc= INT_MIN;
1543
    h->prev_interlaced_frame = 1;
1544
    idr(h);
1545
    if(h->s.current_picture_ptr)
1546
        h->s.current_picture_ptr->reference= 0;
1547
    h->s.first_field= 0;
1548
    ff_h264_reset_sei(h);
1549
    ff_mpeg_flush(avctx);
1550
}
1551

    
1552
static int init_poc(H264Context *h){
1553
    MpegEncContext * const s = &h->s;
1554
    const int max_frame_num= 1<<h->sps.log2_max_frame_num;
1555
    int field_poc[2];
1556
    Picture *cur = s->current_picture_ptr;
1557

    
1558
    h->frame_num_offset= h->prev_frame_num_offset;
1559
    if(h->frame_num < h->prev_frame_num)
1560
        h->frame_num_offset += max_frame_num;
1561

    
1562
    if(h->sps.poc_type==0){
1563
        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
1564

    
1565
        if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
1566
            h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1567
        else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
1568
            h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1569
        else
1570
            h->poc_msb = h->prev_poc_msb;
1571
//printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
1572
        field_poc[0] =
1573
        field_poc[1] = h->poc_msb + h->poc_lsb;
1574
        if(s->picture_structure == PICT_FRAME)
1575
            field_poc[1] += h->delta_poc_bottom;
1576
    }else if(h->sps.poc_type==1){
1577
        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1578
        int i;
1579

    
1580
        if(h->sps.poc_cycle_length != 0)
1581
            abs_frame_num = h->frame_num_offset + h->frame_num;
1582
        else
1583
            abs_frame_num = 0;
1584

    
1585
        if(h->nal_ref_idc==0 && abs_frame_num > 0)
1586
            abs_frame_num--;
1587

    
1588
        expected_delta_per_poc_cycle = 0;
1589
        for(i=0; i < h->sps.poc_cycle_length; i++)
1590
            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
1591

    
1592
        if(abs_frame_num > 0){
1593
            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1594
            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1595

    
1596
            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1597
            for(i = 0; i <= frame_num_in_poc_cycle; i++)
1598
                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
1599
        } else
1600
            expectedpoc = 0;
1601

    
1602
        if(h->nal_ref_idc == 0)
1603
            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1604

    
1605
        field_poc[0] = expectedpoc + h->delta_poc[0];
1606
        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1607

    
1608
        if(s->picture_structure == PICT_FRAME)
1609
            field_poc[1] += h->delta_poc[1];
1610
    }else{
1611
        int poc= 2*(h->frame_num_offset + h->frame_num);
1612

    
1613
        if(!h->nal_ref_idc)
1614
            poc--;
1615

    
1616
        field_poc[0]= poc;
1617
        field_poc[1]= poc;
1618
    }
1619

    
1620
    if(s->picture_structure != PICT_BOTTOM_FIELD)
1621
        s->current_picture_ptr->field_poc[0]= field_poc[0];
1622
    if(s->picture_structure != PICT_TOP_FIELD)
1623
        s->current_picture_ptr->field_poc[1]= field_poc[1];
1624
    cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
1625

    
1626
    return 0;
1627
}
1628

    
1629

    
1630
/**
1631
 * initialize scan tables
1632
 */
1633
static void init_scan_tables(H264Context *h){
1634
    int i;
1635
    for(i=0; i<16; i++){
1636
#define T(x) (x>>2) | ((x<<2) & 0xF)
1637
        h->zigzag_scan[i] = T(zigzag_scan[i]);
1638
        h-> field_scan[i] = T( field_scan[i]);
1639
#undef T
1640
    }
1641
    for(i=0; i<64; i++){
1642
#define T(x) (x>>3) | ((x&7)<<3)
1643
        h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
1644
        h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
1645
        h->field_scan8x8[i]        = T(field_scan8x8[i]);
1646
        h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
1647
#undef T
1648
    }
1649
    if(h->sps.transform_bypass){ //FIXME same ugly
1650
        h->zigzag_scan_q0          = zigzag_scan;
1651
        h->zigzag_scan8x8_q0       = ff_zigzag_direct;
1652
        h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
1653
        h->field_scan_q0           = field_scan;
1654
        h->field_scan8x8_q0        = field_scan8x8;
1655
        h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
1656
    }else{
1657
        h->zigzag_scan_q0          = h->zigzag_scan;
1658
        h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
1659
        h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
1660
        h->field_scan_q0           = h->field_scan;
1661
        h->field_scan8x8_q0        = h->field_scan8x8;
1662
        h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
1663
    }
1664
}
1665

    
1666
static void field_end(H264Context *h, int in_setup){
1667
    MpegEncContext * const s = &h->s;
1668
    AVCodecContext * const avctx= s->avctx;
1669
    s->mb_y= 0;
1670

    
1671
    if (!in_setup && !s->dropable)
1672
        ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
1673
                                 s->picture_structure==PICT_BOTTOM_FIELD);
1674

    
1675
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
1676
        ff_vdpau_h264_set_reference_frames(s);
1677

    
1678
    if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
1679
        if(!s->dropable) {
1680
            ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1681
            h->prev_poc_msb= h->poc_msb;
1682
            h->prev_poc_lsb= h->poc_lsb;
1683
        }
1684
        h->prev_frame_num_offset= h->frame_num_offset;
1685
        h->prev_frame_num= h->frame_num;
1686
        h->outputed_poc = h->next_outputed_poc;
1687
    }
1688

    
1689
    if (avctx->hwaccel) {
1690
        if (avctx->hwaccel->end_frame(avctx) < 0)
1691
            av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
1692
    }
1693

    
1694
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
1695
        ff_vdpau_h264_picture_complete(s);
1696

    
1697
    /*
1698
     * FIXME: Error handling code does not seem to support interlaced
1699
     * when slices span multiple rows
1700
     * The ff_er_add_slice calls don't work right for bottom
1701
     * fields; they cause massive erroneous error concealing
1702
     * Error marking covers both fields (top and bottom).
1703
     * This causes a mismatched s->error_count
1704
     * and a bad error table. Further, the error count goes to
1705
     * INT_MAX when called for bottom field, because mb_y is
1706
     * past end by one (callers fault) and resync_mb_y != 0
1707
     * causes problems for the first MB line, too.
1708
     */
1709
    if (!FIELD_PICTURE)
1710
        ff_er_frame_end(s);
1711

    
1712
    MPV_frame_end(s);
1713

    
1714
    h->current_slice=0;
1715
}
1716

    
1717
/**
1718
 * Replicate H264 "master" context to thread contexts.
1719
 */
1720
static void clone_slice(H264Context *dst, H264Context *src)
1721
{
1722
    memcpy(dst->block_offset,     src->block_offset, sizeof(dst->block_offset));
1723
    dst->s.current_picture_ptr  = src->s.current_picture_ptr;
1724
    dst->s.current_picture      = src->s.current_picture;
1725
    dst->s.linesize             = src->s.linesize;
1726
    dst->s.uvlinesize           = src->s.uvlinesize;
1727
    dst->s.first_field          = src->s.first_field;
1728

    
1729
    dst->prev_poc_msb           = src->prev_poc_msb;
1730
    dst->prev_poc_lsb           = src->prev_poc_lsb;
1731
    dst->prev_frame_num_offset  = src->prev_frame_num_offset;
1732
    dst->prev_frame_num         = src->prev_frame_num;
1733
    dst->short_ref_count        = src->short_ref_count;
1734

    
1735
    memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
1736
    memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
1737
    memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
1738
    memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
1739

    
1740
    memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
1741
    memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
1742
}
1743

    
1744
/**
1745
 * computes profile from profile_idc and constraint_set?_flags
1746
 *
1747
 * @param sps SPS
1748
 *
1749
 * @return profile as defined by FF_PROFILE_H264_*
1750
 */
1751
int ff_h264_get_profile(SPS *sps)
1752
{
1753
    int profile = sps->profile_idc;
1754

    
1755
    switch(sps->profile_idc) {
1756
    case FF_PROFILE_H264_BASELINE:
1757
        // constraint_set1_flag set to 1
1758
        profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1759
        break;
1760
    case FF_PROFILE_H264_HIGH_10:
1761
    case FF_PROFILE_H264_HIGH_422:
1762
    case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1763
        // constraint_set3_flag set to 1
1764
        profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
1765
        break;
1766
    }
1767

    
1768
    return profile;
1769
}
1770

    
1771
/**
1772
 * decodes a slice header.
1773
 * This will also call MPV_common_init() and frame_start() as needed.
1774
 *
1775
 * @param h h264context
1776
 * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
1777
 *
1778
 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
1779
 */
1780
static int decode_slice_header(H264Context *h, H264Context *h0){
1781
    MpegEncContext * const s = &h->s;
1782
    MpegEncContext * const s0 = &h0->s;
1783
    unsigned int first_mb_in_slice;
1784
    unsigned int pps_id;
1785
    int num_ref_idx_active_override_flag;
1786
    unsigned int slice_type, tmp, i, j;
1787
    int default_ref_list_done = 0;
1788
    int last_pic_structure;
1789

    
1790
    s->dropable= h->nal_ref_idc == 0;
1791

    
1792
    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
1793
        s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
1794
        s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
1795
    }else{
1796
        s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
1797
        s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
1798
    }
1799

    
1800
    first_mb_in_slice= get_ue_golomb(&s->gb);
1801

    
1802
    if(first_mb_in_slice == 0){ //FIXME better field boundary detection
1803
        if(h0->current_slice && FIELD_PICTURE){
1804
            field_end(h, 1);
1805
        }
1806

    
1807
        h0->current_slice = 0;
1808
        if (!s0->first_field)
1809
            s->current_picture_ptr= NULL;
1810
    }
1811

    
1812
    slice_type= get_ue_golomb_31(&s->gb);
1813
    if(slice_type > 9){
1814
        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);
1815
        return -1;
1816
    }
1817
    if(slice_type > 4){
1818
        slice_type -= 5;
1819
        h->slice_type_fixed=1;
1820
    }else
1821
        h->slice_type_fixed=0;
1822

    
1823
    slice_type= golomb_to_pict_type[ slice_type ];
1824
    if (slice_type == FF_I_TYPE
1825
        || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
1826
        default_ref_list_done = 1;
1827
    }
1828
    h->slice_type= slice_type;
1829
    h->slice_type_nos= slice_type & 3;
1830

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

    
1833
    pps_id= get_ue_golomb(&s->gb);
1834
    if(pps_id>=MAX_PPS_COUNT){
1835
        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
1836
        return -1;
1837
    }
1838
    if(!h0->pps_buffers[pps_id]) {
1839
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
1840
        return -1;
1841
    }
1842
    h->pps= *h0->pps_buffers[pps_id];
1843

    
1844
    if(!h0->sps_buffers[h->pps.sps_id]) {
1845
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
1846
        return -1;
1847
    }
1848
    h->sps = *h0->sps_buffers[h->pps.sps_id];
1849

    
1850
    s->avctx->profile = ff_h264_get_profile(&h->sps);
1851
    s->avctx->level   = h->sps.level_idc;
1852
    s->avctx->refs    = h->sps.ref_frame_count;
1853

    
1854
    if(h == h0 && h->dequant_coeff_pps != pps_id){
1855
        h->dequant_coeff_pps = pps_id;
1856
        init_dequant_tables(h);
1857
    }
1858

    
1859
    s->mb_width= h->sps.mb_width;
1860
    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
1861

    
1862
    h->b_stride=  s->mb_width*4;
1863

    
1864
    s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
1865
    if(h->sps.frame_mbs_only_flag)
1866
        s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
1867
    else
1868
        s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 7);
1869

    
1870
    if (s->context_initialized
1871
        && (   s->width != s->avctx->width || s->height != s->avctx->height
1872
            || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
1873
        if(h != h0) {
1874
            av_log_missing_feature(s->avctx, "Width/height changing with threads is", 0);
1875
            return -1;   // width / height changed during parallelized decoding
1876
        }
1877
        free_tables(h, 0);
1878
        flush_dpb(s->avctx);
1879
        MPV_common_end(s);
1880
    }
1881
    if (!s->context_initialized) {
1882
        if(h != h0){
1883
            av_log(h->s.avctx, AV_LOG_ERROR, "we cant (re-)initialize context during parallel decoding\n");
1884
            return -1;
1885
        }
1886

    
1887
        avcodec_set_dimensions(s->avctx, s->width, s->height);
1888
        s->avctx->sample_aspect_ratio= h->sps.sar;
1889
        av_assert0(s->avctx->sample_aspect_ratio.den);
1890

    
1891
        if(h->sps.video_signal_type_present_flag){
1892
            s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
1893
            if(h->sps.colour_description_present_flag){
1894
                s->avctx->color_primaries = h->sps.color_primaries;
1895
                s->avctx->color_trc       = h->sps.color_trc;
1896
                s->avctx->colorspace      = h->sps.colorspace;
1897
            }
1898
        }
1899

    
1900
        if(h->sps.timing_info_present_flag){
1901
            int64_t den= h->sps.time_scale;
1902
            if(h->x264_build < 44U)
1903
                den *= 2;
1904
            av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
1905
                      h->sps.num_units_in_tick, den, 1<<30);
1906
        }
1907

    
1908
        switch (h->sps.bit_depth_luma) {
1909
            case 9 :
1910
                s->avctx->pix_fmt = PIX_FMT_YUV420P9;
1911
                break;
1912
            case 10 :
1913
                s->avctx->pix_fmt = PIX_FMT_YUV420P10;
1914
                break;
1915
            default:
1916
        s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
1917
                                                 s->avctx->codec->pix_fmts ?
1918
                                                 s->avctx->codec->pix_fmts :
1919
                                                 s->avctx->color_range == AVCOL_RANGE_JPEG ?
1920
                                                 hwaccel_pixfmt_list_h264_jpeg_420 :
1921
                                                 ff_hwaccel_pixfmt_list_420);
1922
        }
1923

    
1924
        s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
1925

    
1926
        if (MPV_common_init(s) < 0){
1927
            av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed\n");
1928
            return -1;
1929
        }
1930
        s->first_field = 0;
1931
        h->prev_interlaced_frame = 1;
1932

    
1933
        init_scan_tables(h);
1934
        ff_h264_alloc_tables(h);
1935

    
1936
        if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
1937
            if (context_init(h) < 0){
1938
                av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
1939
                return -1;
1940
            }
1941
        } else {
1942
            for(i = 1; i < s->avctx->thread_count; i++) {
1943
                H264Context *c;
1944
                c = h->thread_context[i] = av_malloc(sizeof(H264Context));
1945
                memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
1946
                memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
1947
                c->h264dsp = h->h264dsp;
1948
                c->sps = h->sps;
1949
                c->pps = h->pps;
1950
                init_scan_tables(c);
1951
                clone_tables(c, h, i);
1952
            }
1953

    
1954
            for(i = 0; i < s->avctx->thread_count; i++)
1955
                if(context_init(h->thread_context[i]) < 0){
1956
                    av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed\n");
1957
                    return -1;
1958
                }
1959
        }
1960
    }
1961

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

    
1964
    h->mb_mbaff = 0;
1965
    h->mb_aff_frame = 0;
1966
    last_pic_structure = s0->picture_structure;
1967
    if(h->sps.frame_mbs_only_flag){
1968
        s->picture_structure= PICT_FRAME;
1969
    }else{
1970
        if(get_bits1(&s->gb)) { //field_pic_flag
1971
            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
1972
        } else {
1973
            s->picture_structure= PICT_FRAME;
1974
            h->mb_aff_frame = h->sps.mb_aff;
1975
        }
1976
    }
1977
    h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
1978

    
1979
    if(h0->current_slice == 0){
1980
        if(h->frame_num != h->prev_frame_num &&
1981
          (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num) < (h->frame_num - h->sps.ref_frame_count))
1982
            h->prev_frame_num = h->frame_num - h->sps.ref_frame_count - 1;
1983

    
1984
        while(h->frame_num !=  h->prev_frame_num &&
1985
              h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
1986
            Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
1987
            av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
1988
            if (ff_h264_frame_start(h) < 0)
1989
                return -1;
1990
            h->prev_frame_num++;
1991
            h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
1992
            s->current_picture_ptr->frame_num= h->prev_frame_num;
1993
            ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
1994
            ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
1995
            ff_generate_sliding_window_mmcos(h);
1996
            ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1997
            /* Error concealment: if a ref is missing, copy the previous ref in its place.
1998
             * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
1999
             * about there being no actual duplicates.
2000
             * FIXME: this doesn't copy padding for out-of-frame motion vectors.  Given we're
2001
             * concealing a lost frame, this probably isn't noticable by comparison, but it should
2002
             * be fixed. */
2003
            if (h->short_ref_count) {
2004
                if (prev) {
2005
                    av_image_copy(h->short_ref[0]->data, h->short_ref[0]->linesize,
2006
                                  (const uint8_t**)prev->data, prev->linesize,
2007
                                  s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
2008
                    h->short_ref[0]->poc = prev->poc+2;
2009
                }
2010
                h->short_ref[0]->frame_num = h->prev_frame_num;
2011
            }
2012
        }
2013

    
2014
        /* See if we have a decoded first field looking for a pair... */
2015
        if (s0->first_field) {
2016
            assert(s0->current_picture_ptr);
2017
            assert(s0->current_picture_ptr->data[0]);
2018
            assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
2019

    
2020
            /* figure out if we have a complementary field pair */
2021
            if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
2022
                /*
2023
                 * Previous field is unmatched. Don't display it, but let it
2024
                 * remain for reference if marked as such.
2025
                 */
2026
                s0->current_picture_ptr = NULL;
2027
                s0->first_field = FIELD_PICTURE;
2028

    
2029
            } else {
2030
                if (h->nal_ref_idc &&
2031
                        s0->current_picture_ptr->reference &&
2032
                        s0->current_picture_ptr->frame_num != h->frame_num) {
2033
                    /*
2034
                     * This and previous field were reference, but had
2035
                     * different frame_nums. Consider this field first in
2036
                     * pair. Throw away previous field except for reference
2037
                     * purposes.
2038
                     */
2039
                    s0->first_field = 1;
2040
                    s0->current_picture_ptr = NULL;
2041

    
2042
                } else {
2043
                    /* Second field in complementary pair */
2044
                    s0->first_field = 0;
2045
                }
2046
            }
2047

    
2048
        } else {
2049
            /* Frame or first field in a potentially complementary pair */
2050
            assert(!s0->current_picture_ptr);
2051
            s0->first_field = FIELD_PICTURE;
2052
        }
2053

    
2054
        if(!FIELD_PICTURE || s0->first_field) {
2055
            if (ff_h264_frame_start(h) < 0) {
2056
                s0->first_field = 0;
2057
                return -1;
2058
            }
2059
        } else {
2060
            ff_release_unused_pictures(s, 0);
2061
        }
2062
    }
2063
    if(h != h0)
2064
        clone_slice(h, h0);
2065

    
2066
    s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2067

    
2068
    assert(s->mb_num == s->mb_width * s->mb_height);
2069
    if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2070
       first_mb_in_slice                    >= s->mb_num){
2071
        av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2072
        return -1;
2073
    }
2074
    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2075
    s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2076
    if (s->picture_structure == PICT_BOTTOM_FIELD)
2077
        s->resync_mb_y = s->mb_y = s->mb_y + 1;
2078
    assert(s->mb_y < s->mb_height);
2079

    
2080
    if(s->picture_structure==PICT_FRAME){
2081
        h->curr_pic_num=   h->frame_num;
2082
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
2083
    }else{
2084
        h->curr_pic_num= 2*h->frame_num + 1;
2085
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
2086
    }
2087

    
2088
    if(h->nal_unit_type == NAL_IDR_SLICE){
2089
        get_ue_golomb(&s->gb); /* idr_pic_id */
2090
    }
2091

    
2092
    if(h->sps.poc_type==0){
2093
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2094

    
2095
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
2096
            h->delta_poc_bottom= get_se_golomb(&s->gb);
2097
        }
2098
    }
2099

    
2100
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
2101
        h->delta_poc[0]= get_se_golomb(&s->gb);
2102

    
2103
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
2104
            h->delta_poc[1]= get_se_golomb(&s->gb);
2105
    }
2106

    
2107
    init_poc(h);
2108

    
2109
    if(h->pps.redundant_pic_cnt_present){
2110
        h->redundant_pic_count= get_ue_golomb(&s->gb);
2111
    }
2112

    
2113
    //set defaults, might be overridden a few lines later
2114
    h->ref_count[0]= h->pps.ref_count[0];
2115
    h->ref_count[1]= h->pps.ref_count[1];
2116

    
2117
    if(h->slice_type_nos != FF_I_TYPE){
2118
        if(h->slice_type_nos == FF_B_TYPE){
2119
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
2120
        }
2121
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
2122

    
2123
        if(num_ref_idx_active_override_flag){
2124
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
2125
            if(h->slice_type_nos==FF_B_TYPE)
2126
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
2127

    
2128
            if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
2129
                av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
2130
                h->ref_count[0]= h->ref_count[1]= 1;
2131
                return -1;
2132
            }
2133
        }
2134
        if(h->slice_type_nos == FF_B_TYPE)
2135
            h->list_count= 2;
2136
        else
2137
            h->list_count= 1;
2138
    }else
2139
        h->list_count= 0;
2140

    
2141
    if(!default_ref_list_done){
2142
        ff_h264_fill_default_ref_list(h);
2143
    }
2144

    
2145
    if(h->slice_type_nos!=FF_I_TYPE && ff_h264_decode_ref_pic_list_reordering(h) < 0)
2146
        return -1;
2147

    
2148
    if(h->slice_type_nos!=FF_I_TYPE){
2149
        s->last_picture_ptr= &h->ref_list[0][0];
2150
        ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2151
    }
2152
    if(h->slice_type_nos==FF_B_TYPE){
2153
        s->next_picture_ptr= &h->ref_list[1][0];
2154
        ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2155
    }
2156

    
2157
    if(   (h->pps.weighted_pred          && h->slice_type_nos == FF_P_TYPE )
2158
       ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
2159
        pred_weight_table(h);
2160
    else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2161
        implicit_weight_table(h, -1);
2162
    }else {
2163
        h->use_weight = 0;
2164
        for (i = 0; i < 2; i++) {
2165
            h->luma_weight_flag[i]   = 0;
2166
            h->chroma_weight_flag[i] = 0;
2167
        }
2168
    }
2169

    
2170
    if(h->nal_ref_idc)
2171
        ff_h264_decode_ref_pic_marking(h0, &s->gb);
2172

    
2173
    if(FRAME_MBAFF){
2174
        ff_h264_fill_mbaff_ref_list(h);
2175

    
2176
        if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2177
            implicit_weight_table(h, 0);
2178
            implicit_weight_table(h, 1);
2179
        }
2180
    }
2181

    
2182
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2183
        ff_h264_direct_dist_scale_factor(h);
2184
    ff_h264_direct_ref_list_init(h);
2185

    
2186
    if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
2187
        tmp = get_ue_golomb_31(&s->gb);
2188
        if(tmp > 2){
2189
            av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2190
            return -1;
2191
        }
2192
        h->cabac_init_idc= tmp;
2193
    }
2194

    
2195
    h->last_qscale_diff = 0;
2196
    tmp = h->pps.init_qp + get_se_golomb(&s->gb);
2197
    if(tmp>51+6*(h->sps.bit_depth_luma-8)){
2198
        av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
2199
        return -1;
2200
    }
2201
    s->qscale= tmp;
2202
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2203
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2204
    //FIXME qscale / qp ... stuff
2205
    if(h->slice_type == FF_SP_TYPE){
2206
        get_bits1(&s->gb); /* sp_for_switch_flag */
2207
    }
2208
    if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
2209
        get_se_golomb(&s->gb); /* slice_qs_delta */
2210
    }
2211

    
2212
    h->deblocking_filter = 1;
2213
    h->slice_alpha_c0_offset = 52;
2214
    h->slice_beta_offset = 52;
2215
    if( h->pps.deblocking_filter_parameters_present ) {
2216
        tmp= get_ue_golomb_31(&s->gb);
2217
        if(tmp > 2){
2218
            av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
2219
            return -1;
2220
        }
2221
        h->deblocking_filter= tmp;
2222
        if(h->deblocking_filter < 2)
2223
            h->deblocking_filter^= 1; // 1<->0
2224

    
2225
        if( h->deblocking_filter ) {
2226
            h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
2227
            h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
2228
            if(   h->slice_alpha_c0_offset > 104U
2229
               || h->slice_beta_offset     > 104U){
2230
                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);
2231
                return -1;
2232
            }
2233
        }
2234
    }
2235

    
2236
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
2237
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
2238
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
2239
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
2240
        h->deblocking_filter= 0;
2241

    
2242
    if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
2243
        if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
2244
            /* Cheat slightly for speed:
2245
               Do not bother to deblock across slices. */
2246
            h->deblocking_filter = 2;
2247
        } else {
2248
            h0->max_contexts = 1;
2249
            if(!h0->single_decode_warning) {
2250
                av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
2251
                h0->single_decode_warning = 1;
2252
            }
2253
            if(h != h0){
2254
                av_log(h->s.avctx, AV_LOG_ERROR, "deblocking switched inside frame\n");
2255
                return 1;
2256
            }
2257
        }
2258
    }
2259
    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]);
2260

    
2261
#if 0 //FMO
2262
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
2263
        slice_group_change_cycle= get_bits(&s->gb, ?);
2264
#endif
2265

    
2266
    h0->last_slice_type = slice_type;
2267
    h->slice_num = ++h0->current_slice;
2268
    if(h->slice_num >= MAX_SLICES){
2269
        av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
2270
    }
2271

    
2272
    for(j=0; j<2; j++){
2273
        int id_list[16];
2274
        int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
2275
        for(i=0; i<16; i++){
2276
            id_list[i]= 60;
2277
            if(h->ref_list[j][i].data[0]){
2278
                int k;
2279
                uint8_t *base= h->ref_list[j][i].base[0];
2280
                for(k=0; k<h->short_ref_count; k++)
2281
                    if(h->short_ref[k]->base[0] == base){
2282
                        id_list[i]= k;
2283
                        break;
2284
                    }
2285
                for(k=0; k<h->long_ref_count; k++)
2286
                    if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
2287
                        id_list[i]= h->short_ref_count + k;
2288
                        break;
2289
                    }
2290
            }
2291
        }
2292

    
2293
        ref2frm[0]=
2294
        ref2frm[1]= -1;
2295
        for(i=0; i<16; i++)
2296
            ref2frm[i+2]= 4*id_list[i]
2297
                          +(h->ref_list[j][i].reference&3);
2298
        ref2frm[18+0]=
2299
        ref2frm[18+1]= -1;
2300
        for(i=16; i<48; i++)
2301
            ref2frm[i+4]= 4*id_list[(i-16)>>1]
2302
                          +(h->ref_list[j][i].reference&3);
2303
    }
2304

    
2305
    //FIXME: fix draw_edges+PAFF+frame threads
2306
    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;
2307
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
2308

    
2309
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2310
        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",
2311
               h->slice_num,
2312
               (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
2313
               first_mb_in_slice,
2314
               av_get_pict_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
2315
               pps_id, h->frame_num,
2316
               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
2317
               h->ref_count[0], h->ref_count[1],
2318
               s->qscale,
2319
               h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
2320
               h->use_weight,
2321
               h->use_weight==1 && h->use_weight_chroma ? "c" : "",
2322
               h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
2323
               );
2324
    }
2325

    
2326
    return 0;
2327
}
2328

    
2329
int ff_h264_get_slice_type(const H264Context *h)
2330
{
2331
    switch (h->slice_type) {
2332
    case FF_P_TYPE:  return 0;
2333
    case FF_B_TYPE:  return 1;
2334
    case FF_I_TYPE:  return 2;
2335
    case FF_SP_TYPE: return 3;
2336
    case FF_SI_TYPE: return 4;
2337
    default:         return -1;
2338
    }
2339
}
2340

    
2341
/**
2342
 *
2343
 * @return non zero if the loop filter can be skiped
2344
 */
2345
static int fill_filter_caches(H264Context *h, int mb_type){
2346
    MpegEncContext * const s = &h->s;
2347
    const int mb_xy= h->mb_xy;
2348
    int top_xy, left_xy[2];
2349
    int top_type, left_type[2];
2350

    
2351
    top_xy     = mb_xy  - (s->mb_stride << MB_FIELD);
2352

    
2353
    //FIXME deblocking could skip the intra and nnz parts.
2354

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

    
2358
    left_xy[1] = left_xy[0] = mb_xy-1;
2359
    if(FRAME_MBAFF){
2360
        const int left_mb_field_flag     = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);
2361
        const int curr_mb_field_flag     = IS_INTERLACED(mb_type);
2362
        if(s->mb_y&1){
2363
            if (left_mb_field_flag != curr_mb_field_flag) {
2364
                left_xy[0] -= s->mb_stride;
2365
            }
2366
        }else{
2367
            if(curr_mb_field_flag){
2368
                top_xy      += s->mb_stride & (((s->current_picture.mb_type[top_xy    ]>>7)&1)-1);
2369
            }
2370
            if (left_mb_field_flag != curr_mb_field_flag) {
2371
                left_xy[1] += s->mb_stride;
2372
            }
2373
        }
2374
    }
2375

    
2376
    h->top_mb_xy = top_xy;
2377
    h->left_mb_xy[0] = left_xy[0];
2378
    h->left_mb_xy[1] = left_xy[1];
2379
    {
2380
        //for sufficiently low qp, filtering wouldn't do anything
2381
        //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
2382
        int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
2383
        int qp = s->current_picture.qscale_table[mb_xy];
2384
        if(qp <= qp_thresh
2385
           && (left_xy[0]<0 || ((qp + s->current_picture.qscale_table[left_xy[0]] + 1)>>1) <= qp_thresh)
2386
           && (top_xy   < 0 || ((qp + s->current_picture.qscale_table[top_xy    ] + 1)>>1) <= qp_thresh)){
2387
            if(!FRAME_MBAFF)
2388
                return 1;
2389
            if(   (left_xy[0]< 0            || ((qp + s->current_picture.qscale_table[left_xy[1]             ] + 1)>>1) <= qp_thresh)
2390
               && (top_xy    < s->mb_stride || ((qp + s->current_picture.qscale_table[top_xy    -s->mb_stride] + 1)>>1) <= qp_thresh))
2391
                return 1;
2392
        }
2393
    }
2394

    
2395
    top_type     = s->current_picture.mb_type[top_xy]    ;
2396
    left_type[0] = s->current_picture.mb_type[left_xy[0]];
2397
    left_type[1] = s->current_picture.mb_type[left_xy[1]];
2398
    if(h->deblocking_filter == 2){
2399
        if(h->slice_table[top_xy     ] != h->slice_num) top_type= 0;
2400
        if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
2401
    }else{
2402
        if(h->slice_table[top_xy     ] == 0xFFFF) top_type= 0;
2403
        if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
2404
    }
2405
    h->top_type    = top_type    ;
2406
    h->left_type[0]= left_type[0];
2407
    h->left_type[1]= left_type[1];
2408

    
2409
    if(IS_INTRA(mb_type))
2410
        return 0;
2411

    
2412
    AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
2413
    AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
2414
    AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
2415
    AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
2416
    AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
2417

    
2418
    h->cbp= h->cbp_table[mb_xy];
2419

    
2420
    {
2421
        int list;
2422
        for(list=0; list<h->list_count; list++){
2423
            int8_t *ref;
2424
            int y, b_stride;
2425
            int16_t (*mv_dst)[2];
2426
            int16_t (*mv_src)[2];
2427

    
2428
            if(!USES_LIST(mb_type, list)){
2429
                fill_rectangle(  h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
2430
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2431
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2432
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2433
                AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2434
                continue;
2435
            }
2436

    
2437
            ref = &s->current_picture.ref_index[list][4*mb_xy];
2438
            {
2439
                int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2440
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2441
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2442
                ref += 2;
2443
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2444
                AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2445
            }
2446

    
2447
            b_stride = h->b_stride;
2448
            mv_dst   = &h->mv_cache[list][scan8[0]];
2449
            mv_src   = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
2450
            for(y=0; y<4; y++){
2451
                AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
2452
            }
2453

    
2454
        }
2455
    }
2456

    
2457

    
2458
/*
2459
0 . T T. T T T T
2460
1 L . .L . . . .
2461
2 L . .L . . . .
2462
3 . T TL . . . .
2463
4 L . .L . . . .
2464
5 L . .. . . . .
2465
*/
2466
//FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
2467
    if(top_type){
2468
        AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][4+3*8]);
2469
    }
2470

    
2471
    if(left_type[0]){
2472
        h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
2473
        h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
2474
        h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
2475
        h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
2476
    }
2477

    
2478
    // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
2479
    if(!CABAC && h->pps.transform_8x8_mode){
2480
        if(IS_8x8DCT(top_type)){
2481
            h->non_zero_count_cache[4+8*0]=
2482
            h->non_zero_count_cache[5+8*0]= h->cbp_table[top_xy] & 4;
2483
            h->non_zero_count_cache[6+8*0]=
2484
            h->non_zero_count_cache[7+8*0]= h->cbp_table[top_xy] & 8;
2485
        }
2486
        if(IS_8x8DCT(left_type[0])){
2487
            h->non_zero_count_cache[3+8*1]=
2488
            h->non_zero_count_cache[3+8*2]= h->cbp_table[left_xy[0]]&2; //FIXME check MBAFF
2489
        }
2490
        if(IS_8x8DCT(left_type[1])){
2491
            h->non_zero_count_cache[3+8*3]=
2492
            h->non_zero_count_cache[3+8*4]= h->cbp_table[left_xy[1]]&8; //FIXME check MBAFF
2493
        }
2494

    
2495
        if(IS_8x8DCT(mb_type)){
2496
            h->non_zero_count_cache[scan8[0   ]]= h->non_zero_count_cache[scan8[1   ]]=
2497
            h->non_zero_count_cache[scan8[2   ]]= h->non_zero_count_cache[scan8[3   ]]= h->cbp & 1;
2498

    
2499
            h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
2500
            h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
2501

    
2502
            h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
2503
            h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp & 4;
2504

    
2505
            h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
2506
            h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
2507
        }
2508
    }
2509

    
2510
    if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
2511
        int list;
2512
        for(list=0; list<h->list_count; list++){
2513
            if(USES_LIST(top_type, list)){
2514
                const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
2515
                const int b8_xy= 4*top_xy + 2;
2516
                int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2517
                AV_COPY128(h->mv_cache[list][scan8[0] + 0 - 1*8], s->current_picture.motion_val[list][b_xy + 0]);
2518
                h->ref_cache[list][scan8[0] + 0 - 1*8]=
2519
                h->ref_cache[list][scan8[0] + 1 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 0]];
2520
                h->ref_cache[list][scan8[0] + 2 - 1*8]=
2521
                h->ref_cache[list][scan8[0] + 3 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 1]];
2522
            }else{
2523
                AV_ZERO128(h->mv_cache[list][scan8[0] + 0 - 1*8]);
2524
                AV_WN32A(&h->ref_cache[list][scan8[0] + 0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2525
            }
2526

    
2527
            if(!IS_INTERLACED(mb_type^left_type[0])){
2528
                if(USES_LIST(left_type[0], list)){
2529
                    const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
2530
                    const int b8_xy= 4*left_xy[0] + 1;
2531
                    int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[0]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2532
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 0 ], s->current_picture.motion_val[list][b_xy + h->b_stride*0]);
2533
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 8 ], s->current_picture.motion_val[list][b_xy + h->b_stride*1]);
2534
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +16 ], s->current_picture.motion_val[list][b_xy + h->b_stride*2]);
2535
                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +24 ], s->current_picture.motion_val[list][b_xy + h->b_stride*3]);
2536
                    h->ref_cache[list][scan8[0] - 1 + 0 ]=
2537
                    h->ref_cache[list][scan8[0] - 1 + 8 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*0]];
2538
                    h->ref_cache[list][scan8[0] - 1 +16 ]=
2539
                    h->ref_cache[list][scan8[0] - 1 +24 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*1]];
2540
                }else{
2541
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 0 ]);
2542
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 8 ]);
2543
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +16 ]);
2544
                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +24 ]);
2545
                    h->ref_cache[list][scan8[0] - 1 + 0  ]=
2546
                    h->ref_cache[list][scan8[0] - 1 + 8  ]=
2547
                    h->ref_cache[list][scan8[0] - 1 + 16 ]=
2548
                    h->ref_cache[list][scan8[0] - 1 + 24 ]= LIST_NOT_USED;
2549
                }
2550
            }
2551
        }
2552
    }
2553

    
2554
    return 0;
2555
}
2556

    
2557
static void loop_filter(H264Context *h){
2558
    MpegEncContext * const s = &h->s;
2559
    uint8_t  *dest_y, *dest_cb, *dest_cr;
2560
    int linesize, uvlinesize, mb_x, mb_y;
2561
    const int end_mb_y= s->mb_y + FRAME_MBAFF;
2562
    const int old_slice_type= h->slice_type;
2563
    const int end_mb_x  = s->mb_x;
2564

    
2565
    if(h->deblocking_filter) {
2566
        int start_x= s->resync_mb_y == s->mb_y ? s->resync_mb_x : 0;
2567
        for(mb_x= start_x; mb_x<end_mb_x; mb_x++){
2568
            for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
2569
                int mb_xy, mb_type;
2570
                mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
2571
                h->slice_num= h->slice_table[mb_xy];
2572
                mb_type= s->current_picture.mb_type[mb_xy];
2573
                h->list_count= h->list_counts[mb_xy];
2574

    
2575
                if(FRAME_MBAFF)
2576
                    h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2577

    
2578
                s->mb_x= mb_x;
2579
                s->mb_y= mb_y;
2580
                dest_y  = s->current_picture.data[0] + ((mb_x<<h->pixel_shift) + mb_y * s->linesize  ) * 16;
2581
                dest_cb = s->current_picture.data[1] + ((mb_x<<h->pixel_shift) + mb_y * s->uvlinesize) * 8;
2582
                dest_cr = s->current_picture.data[2] + ((mb_x<<h->pixel_shift) + mb_y * s->uvlinesize) * 8;
2583
                    //FIXME simplify above
2584

    
2585
                if (MB_FIELD) {
2586
                    linesize   = h->mb_linesize   = s->linesize * 2;
2587
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2588
                    if(mb_y&1){ //FIXME move out of this function?
2589
                        dest_y -= s->linesize*15;
2590
                        dest_cb-= s->uvlinesize*7;
2591
                        dest_cr-= s->uvlinesize*7;
2592
                    }
2593
                } else {
2594
                    linesize   = h->mb_linesize   = s->linesize;
2595
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize;
2596
                }
2597
                backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
2598
                if(fill_filter_caches(h, mb_type))
2599
                    continue;
2600
                h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2601
                h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2602

    
2603
                if (FRAME_MBAFF) {
2604
                    ff_h264_filter_mb     (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2605
                } else {
2606
                    ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2607
                }
2608
            }
2609
        }
2610
    }
2611
    h->slice_type= old_slice_type;
2612
    s->mb_x= end_mb_x;
2613
    s->mb_y= end_mb_y - FRAME_MBAFF;
2614
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2615
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2616
}
2617

    
2618
static void predict_field_decoding_flag(H264Context *h){
2619
    MpegEncContext * const s = &h->s;
2620
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
2621
    int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
2622
                ? s->current_picture.mb_type[mb_xy-1]
2623
                : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
2624
                ? s->current_picture.mb_type[mb_xy-s->mb_stride]
2625
                : 0;
2626
    h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
2627
}
2628

    
2629
/**
2630
 * Draw edges and report progress for the last MB row.
2631
 */
2632
static void decode_finish_row(H264Context *h){
2633
    MpegEncContext * const s = &h->s;
2634
    int top = 16*(s->mb_y >> FIELD_PICTURE);
2635
    int height = 16 << FRAME_MBAFF;
2636
    int deblock_border = (16 + 4) << FRAME_MBAFF;
2637
    int pic_height = 16*s->mb_height >> FIELD_PICTURE;
2638

    
2639
    if (h->deblocking_filter) {
2640
        if((top + height) >= pic_height)
2641
            height += deblock_border;
2642

    
2643
        top -= deblock_border;
2644
    }
2645

    
2646
    if (top >= pic_height || (top + height) < h->emu_edge_height)
2647
        return;
2648

    
2649
    height = FFMIN(height, pic_height - top);
2650
    if (top < h->emu_edge_height) {
2651
        height = top+height;
2652
        top = 0;
2653
    }
2654

    
2655
    ff_draw_horiz_band(s, top, height);
2656

    
2657
    if (s->dropable) return;
2658

    
2659
    ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
2660
                             s->picture_structure==PICT_BOTTOM_FIELD);
2661
}
2662

    
2663
static int decode_slice(struct AVCodecContext *avctx, void *arg){
2664
    H264Context *h = *(void**)arg;
2665
    MpegEncContext * const s = &h->s;
2666
    const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
2667

    
2668
    s->mb_skip_run= -1;
2669

    
2670
    h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
2671
                    (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
2672

    
2673
    if( h->pps.cabac ) {
2674
        /* realign */
2675
        align_get_bits( &s->gb );
2676

    
2677
        /* init cabac */
2678
        ff_init_cabac_states( &h->cabac);
2679
        ff_init_cabac_decoder( &h->cabac,
2680
                               s->gb.buffer + get_bits_count(&s->gb)/8,
2681
                               (get_bits_left(&s->gb) + 7)/8);
2682

    
2683
        ff_h264_init_cabac_states(h);
2684

    
2685
        for(;;){
2686
//START_TIMER
2687
            int ret = ff_h264_decode_mb_cabac(h);
2688
            int eos;
2689
//STOP_TIMER("decode_mb_cabac")
2690

    
2691
            if(ret>=0) ff_h264_hl_decode_mb(h);
2692

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

    
2696
                ret = ff_h264_decode_mb_cabac(h);
2697

    
2698
                if(ret>=0) ff_h264_hl_decode_mb(h);
2699
                s->mb_y--;
2700
            }
2701
            eos = get_cabac_terminate( &h->cabac );
2702

    
2703
            if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
2704
                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);
2705
                return 0;
2706
            }
2707
            if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
2708
                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);
2709
                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);
2710
                return -1;
2711
            }
2712

    
2713
            if( ++s->mb_x >= s->mb_width ) {
2714
                loop_filter(h);
2715
                s->mb_x = 0;
2716
                decode_finish_row(h);
2717
                ++s->mb_y;
2718
                if(FIELD_OR_MBAFF_PICTURE) {
2719
                    ++s->mb_y;
2720
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
2721
                        predict_field_decoding_flag(h);
2722
                }
2723
            }
2724

    
2725
            if( eos || s->mb_y >= s->mb_height ) {
2726
                if(s->mb_x)
2727
                    loop_filter(h);
2728
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
2729
                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);
2730
                return 0;
2731
            }
2732
        }
2733

    
2734
    } else {
2735
        for(;;){
2736
            int ret = ff_h264_decode_mb_cavlc(h);
2737

    
2738
            if(ret>=0) ff_h264_hl_decode_mb(h);
2739

    
2740
            if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
2741
                s->mb_y++;
2742
                ret = ff_h264_decode_mb_cavlc(h);
2743

    
2744
                if(ret>=0) ff_h264_hl_decode_mb(h);
2745
                s->mb_y--;
2746
            }
2747

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

    
2752
                return -1;
2753
            }
2754

    
2755
            if(++s->mb_x >= s->mb_width){
2756
                loop_filter(h);
2757
                s->mb_x=0;
2758
                decode_finish_row(h);
2759
                ++s->mb_y;
2760
                if(FIELD_OR_MBAFF_PICTURE) {
2761
                    ++s->mb_y;
2762
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
2763
                        predict_field_decoding_flag(h);
2764
                }
2765
                if(s->mb_y >= s->mb_height){
2766
                    tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
2767

    
2768
                    if(   get_bits_count(&s->gb) == s->gb.size_in_bits
2769
                       || get_bits_count(&s->gb) <  s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
2770
                        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);
2771

    
2772
                        return 0;
2773
                    }else{
2774
                        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);
2775

    
2776
                        return -1;
2777
                    }
2778
                }
2779
            }
2780

    
2781
            if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
2782
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
2783
                if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
2784
                    if(s->mb_x)
2785
                        loop_filter(h);
2786
                    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);
2787

    
2788
                    return 0;
2789
                }else{
2790
                    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);
2791

    
2792
                    return -1;
2793
                }
2794
            }
2795
        }
2796
    }
2797

    
2798
#if 0
2799
    for(;s->mb_y < s->mb_height; s->mb_y++){
2800
        for(;s->mb_x < s->mb_width; s->mb_x++){
2801
            int ret= decode_mb(h);
2802

2803
            ff_h264_hl_decode_mb(h);
2804

2805
            if(ret<0){
2806
                av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
2807
                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);
2808

2809
                return -1;
2810
            }
2811

2812
            if(++s->mb_x >= s->mb_width){
2813
                s->mb_x=0;
2814
                if(++s->mb_y >= s->mb_height){
2815
                    if(get_bits_count(s->gb) == s->gb.size_in_bits){
2816
                        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);
2817

2818
                        return 0;
2819
                    }else{
2820
                        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);
2821

2822
                        return -1;
2823
                    }
2824
                }
2825
            }
2826

2827
            if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
2828
                if(get_bits_count(s->gb) == s->gb.size_in_bits){
2829
                    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);
2830

2831
                    return 0;
2832
                }else{
2833
                    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);
2834

2835
                    return -1;
2836
                }
2837
            }
2838
        }
2839
        s->mb_x=0;
2840
        ff_draw_horiz_band(s, 16*s->mb_y, 16);
2841
    }
2842
#endif
2843
    return -1; //not reached
2844
}
2845

    
2846
/**
2847
 * Call decode_slice() for each context.
2848
 *
2849
 * @param h h264 master context
2850
 * @param context_count number of contexts to execute
2851
 */
2852
static void execute_decode_slices(H264Context *h, int context_count){
2853
    MpegEncContext * const s = &h->s;
2854
    AVCodecContext * const avctx= s->avctx;
2855
    H264Context *hx;
2856
    int i;
2857

    
2858
    if (s->avctx->hwaccel)
2859
        return;
2860
    if(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2861
        return;
2862
    if(context_count == 1) {
2863
        decode_slice(avctx, &h);
2864
    } else {
2865
        for(i = 1; i < context_count; i++) {
2866
            hx = h->thread_context[i];
2867
            hx->s.error_recognition = avctx->error_recognition;
2868
            hx->s.error_count = 0;
2869
            hx->x264_build= h->x264_build;
2870
        }
2871

    
2872
        avctx->execute(avctx, (void *)decode_slice,
2873
                       h->thread_context, NULL, context_count, sizeof(void*));
2874

    
2875
        /* pull back stuff from slices to master context */
2876
        hx = h->thread_context[context_count - 1];
2877
        s->mb_x = hx->s.mb_x;
2878
        s->mb_y = hx->s.mb_y;
2879
        s->dropable = hx->s.dropable;
2880
        s->picture_structure = hx->s.picture_structure;
2881
        for(i = 1; i < context_count; i++)
2882
            h->s.error_count += h->thread_context[i]->s.error_count;
2883
    }
2884
}
2885

    
2886

    
2887
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
2888
    MpegEncContext * const s = &h->s;
2889
    AVCodecContext * const avctx= s->avctx;
2890
    int buf_index=0;
2891
    H264Context *hx; ///< thread context
2892
    int context_count = 0;
2893
    int next_avc= h->is_avc ? 0 : buf_size;
2894

    
2895
    h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
2896
#if 0
2897
    int i;
2898
    for(i=0; i<50; i++){
2899
        av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
2900
    }
2901
#endif
2902
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
2903
        h->current_slice = 0;
2904
        if (!s->first_field)
2905
            s->current_picture_ptr= NULL;
2906
        ff_h264_reset_sei(h);
2907
    }
2908

    
2909
    for(;;){
2910
        int consumed;
2911
        int dst_length;
2912
        int bit_length;
2913
        const uint8_t *ptr;
2914
        int i, nalsize = 0;
2915
        int err;
2916

    
2917
        if(buf_index >= next_avc) {
2918
            if(buf_index >= buf_size) break;
2919
            nalsize = 0;
2920
            for(i = 0; i < h->nal_length_size; i++)
2921
                nalsize = (nalsize << 8) | buf[buf_index++];
2922
            if(nalsize <= 0 || nalsize > buf_size - buf_index){
2923
                av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
2924
                break;
2925
            }
2926
            next_avc= buf_index + nalsize;
2927
        } else {
2928
            // start code prefix search
2929
            for(; buf_index + 3 < next_avc; buf_index++){
2930
                // This should always succeed in the first iteration.
2931
                if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
2932
                    break;
2933
            }
2934

    
2935
            if(buf_index+3 >= buf_size) break;
2936

    
2937
            buf_index+=3;
2938
            if(buf_index >= next_avc) continue;
2939
        }
2940

    
2941
        hx = h->thread_context[context_count];
2942

    
2943
        ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
2944
        if (ptr==NULL || dst_length < 0){
2945
            return -1;
2946
        }
2947
        i= buf_index + consumed;
2948
        if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
2949
           buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
2950
            s->workaround_bugs |= FF_BUG_TRUNCATED;
2951

    
2952
        if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
2953
        while(ptr[dst_length - 1] == 0 && dst_length > 0)
2954
            dst_length--;
2955
        }
2956
        bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
2957

    
2958
        if(s->avctx->debug&FF_DEBUG_STARTCODE){
2959
            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);
2960
        }
2961

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

    
2966
        buf_index += consumed;
2967

    
2968
        //FIXME do not discard SEI id
2969
        if(
2970
#if FF_API_HURRY_UP
2971
           (s->hurry_up == 1 && h->nal_ref_idc  == 0) ||
2972
#endif
2973
           (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc  == 0))
2974
            continue;
2975

    
2976
      again:
2977
        err = 0;
2978
        switch(hx->nal_unit_type){
2979
        case NAL_IDR_SLICE:
2980
            if (h->nal_unit_type != NAL_IDR_SLICE) {
2981
                av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
2982
                return -1;
2983
            }
2984
            idr(h); //FIXME ensure we don't loose some frames if there is reordering
2985
        case NAL_SLICE:
2986
            init_get_bits(&hx->s.gb, ptr, bit_length);
2987
            hx->intra_gb_ptr=
2988
            hx->inter_gb_ptr= &hx->s.gb;
2989
            hx->s.data_partitioning = 0;
2990

    
2991
            if((err = decode_slice_header(hx, h)))
2992
               break;
2993

    
2994
            s->current_picture_ptr->key_frame |=
2995
                    (hx->nal_unit_type == NAL_IDR_SLICE) ||
2996
                    (h->sei_recovery_frame_cnt >= 0);
2997

    
2998
            if (h->current_slice == 1) {
2999
                if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
3000
                    decode_postinit(h);
3001
                }
3002

    
3003
                if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
3004
                    return -1;
3005
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3006
                    ff_vdpau_h264_picture_start(s);
3007
            }
3008

    
3009
            if(hx->redundant_pic_count==0
3010
#if FF_API_HURRY_UP
3011
               && hx->s.hurry_up < 5
3012
#endif
3013
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3014
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3015
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3016
               && avctx->skip_frame < AVDISCARD_ALL){
3017
                if(avctx->hwaccel) {
3018
                    if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
3019
                        return -1;
3020
                }else
3021
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
3022
                    static const uint8_t start_code[] = {0x00, 0x00, 0x01};
3023
                    ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
3024
                    ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
3025
                }else
3026
                    context_count++;
3027
            }
3028
            break;
3029
        case NAL_DPA:
3030
            init_get_bits(&hx->s.gb, ptr, bit_length);
3031
            hx->intra_gb_ptr=
3032
            hx->inter_gb_ptr= NULL;
3033

    
3034
            if ((err = decode_slice_header(hx, h)) < 0)
3035
                break;
3036

    
3037
            hx->s.data_partitioning = 1;
3038

    
3039
            break;
3040
        case NAL_DPB:
3041
            init_get_bits(&hx->intra_gb, ptr, bit_length);
3042
            hx->intra_gb_ptr= &hx->intra_gb;
3043
            break;
3044
        case NAL_DPC:
3045
            init_get_bits(&hx->inter_gb, ptr, bit_length);
3046
            hx->inter_gb_ptr= &hx->inter_gb;
3047

    
3048
            if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
3049
               && s->context_initialized
3050
#if FF_API_HURRY_UP
3051
               && s->hurry_up < 5
3052
#endif
3053
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3054
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3055
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3056
               && avctx->skip_frame < AVDISCARD_ALL)
3057
                context_count++;
3058
            break;
3059
        case NAL_SEI:
3060
            init_get_bits(&s->gb, ptr, bit_length);
3061
            ff_h264_decode_sei(h);
3062
            break;
3063
        case NAL_SPS:
3064
            init_get_bits(&s->gb, ptr, bit_length);
3065
            ff_h264_decode_seq_parameter_set(h);
3066

    
3067
            if(s->flags& CODEC_FLAG_LOW_DELAY)
3068
                s->low_delay=1;
3069

    
3070
            if(avctx->has_b_frames < 2)
3071
                avctx->has_b_frames= !s->low_delay;
3072

    
3073
            if (avctx->bits_per_raw_sample != h->sps.bit_depth_luma) {
3074
                if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
3075
                    avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3076
                    h->pixel_shift = h->sps.bit_depth_luma/9;
3077

    
3078
                    ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma);
3079
                    ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma);
3080
                    dsputil_init(&s->dsp, s->avctx);
3081
                } else {
3082
                    av_log(avctx, AV_LOG_DEBUG, "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3083
                    return -1;
3084
                }
3085
            }
3086
            break;
3087
        case NAL_PPS:
3088
            init_get_bits(&s->gb, ptr, bit_length);
3089

    
3090
            ff_h264_decode_picture_parameter_set(h, bit_length);
3091

    
3092
            break;
3093
        case NAL_AUD:
3094
        case NAL_END_SEQUENCE:
3095
        case NAL_END_STREAM:
3096
        case NAL_FILLER_DATA:
3097
        case NAL_SPS_EXT:
3098
        case NAL_AUXILIARY_SLICE:
3099
            break;
3100
        default:
3101
            av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
3102
        }
3103

    
3104
        if(context_count == h->max_contexts) {
3105
            execute_decode_slices(h, context_count);
3106
            context_count = 0;
3107
        }
3108

    
3109
        if (err < 0)
3110
            av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
3111
        else if(err == 1) {
3112
            /* Slice could not be decoded in parallel mode, copy down
3113
             * NAL unit stuff to context 0 and restart. Note that
3114
             * rbsp_buffer is not transferred, but since we no longer
3115
             * run in parallel mode this should not be an issue. */
3116
            h->nal_unit_type = hx->nal_unit_type;
3117
            h->nal_ref_idc   = hx->nal_ref_idc;
3118
            hx = h;
3119
            goto again;
3120
        }
3121
    }
3122
    if(context_count)
3123
        execute_decode_slices(h, context_count);
3124
    return buf_index;
3125
}
3126

    
3127
/**
3128
 * returns the number of bytes consumed for building the current frame
3129
 */
3130
static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
3131
        if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
3132
        if(pos+10>buf_size) pos=buf_size; // oops ;)
3133

    
3134
        return pos;
3135
}
3136

    
3137
static int decode_frame(AVCodecContext *avctx,
3138
                             void *data, int *data_size,
3139
                             AVPacket *avpkt)
3140
{
3141
    const uint8_t *buf = avpkt->data;
3142
    int buf_size = avpkt->size;
3143
    H264Context *h = avctx->priv_data;
3144
    MpegEncContext *s = &h->s;
3145
    AVFrame *pict = data;
3146
    int buf_index;
3147

    
3148
    s->flags= avctx->flags;
3149
    s->flags2= avctx->flags2;
3150

    
3151
   /* end of stream, output what is still in the buffers */
3152
 out:
3153
    if (buf_size == 0) {
3154
        Picture *out;
3155
        int i, out_idx;
3156

    
3157
        s->current_picture_ptr = NULL;
3158

    
3159
//FIXME factorize this with the output code below
3160
        out = h->delayed_pic[0];
3161
        out_idx = 0;
3162
        for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
3163
            if(h->delayed_pic[i]->poc < out->poc){
3164
                out = h->delayed_pic[i];
3165
                out_idx = i;
3166
            }
3167

    
3168
        for(i=out_idx; h->delayed_pic[i]; i++)
3169
            h->delayed_pic[i] = h->delayed_pic[i+1];
3170

    
3171
        if(out){
3172
            *data_size = sizeof(AVFrame);
3173
            *pict= *(AVFrame*)out;
3174
        }
3175

    
3176
        return 0;
3177
    }
3178

    
3179
    buf_index=decode_nal_units(h, buf, buf_size);
3180
    if(buf_index < 0)
3181
        return -1;
3182

    
3183
    if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
3184
        buf_size = 0;
3185
        goto out;
3186
    }
3187

    
3188
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
3189
        if (avctx->skip_frame >= AVDISCARD_NONREF
3190
#if FF_API_HURRY_UP
3191
                || s->hurry_up
3192
#endif
3193
           )
3194
            return 0;
3195
        av_log(avctx, AV_LOG_ERROR, "no frame!\n");
3196
        return -1;
3197
    }
3198

    
3199
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
3200

    
3201
        if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h);
3202

    
3203
        field_end(h, 0);
3204

    
3205
        if (!h->next_output_pic) {
3206
            /* Wait for second field. */
3207
            *data_size = 0;
3208

    
3209
        } else {
3210
            *data_size = sizeof(AVFrame);
3211
            *pict = *(AVFrame*)h->next_output_pic;
3212
        }
3213
    }
3214

    
3215
    assert(pict->data[0] || !*data_size);
3216
    ff_print_debug_info(s, pict);
3217
//printf("out %d\n", (int)pict->data[0]);
3218

    
3219
    return get_consumed_bytes(s, buf_index, buf_size);
3220
}
3221
#if 0
3222
static inline void fill_mb_avail(H264Context *h){
3223
    MpegEncContext * const s = &h->s;
3224
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3225

3226
    if(s->mb_y){
3227
        h->mb_avail[0]= s->mb_x                 && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
3228
        h->mb_avail[1]=                            h->slice_table[mb_xy - s->mb_stride    ] == h->slice_num;
3229
        h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
3230
    }else{
3231
        h->mb_avail[0]=
3232
        h->mb_avail[1]=
3233
        h->mb_avail[2]= 0;
3234
    }
3235
    h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
3236
    h->mb_avail[4]= 1; //FIXME move out
3237
    h->mb_avail[5]= 0; //FIXME move out
3238
}
3239
#endif
3240

    
3241
#ifdef TEST
3242
#undef printf
3243
#undef random
3244
#define COUNT 8000
3245
#define SIZE (COUNT*40)
3246
int main(void){
3247
    int i;
3248
    uint8_t temp[SIZE];
3249
    PutBitContext pb;
3250
    GetBitContext gb;
3251
//    int int_temp[10000];
3252
    DSPContext dsp;
3253
    AVCodecContext avctx;
3254

    
3255
    dsputil_init(&dsp, &avctx);
3256

    
3257
    init_put_bits(&pb, temp, SIZE);
3258
    printf("testing unsigned exp golomb\n");
3259
    for(i=0; i<COUNT; i++){
3260
        START_TIMER
3261
        set_ue_golomb(&pb, i);
3262
        STOP_TIMER("set_ue_golomb");
3263
    }
3264
    flush_put_bits(&pb);
3265

    
3266
    init_get_bits(&gb, temp, 8*SIZE);
3267
    for(i=0; i<COUNT; i++){
3268
        int j, s;
3269

    
3270
        s= show_bits(&gb, 24);
3271

    
3272
        START_TIMER
3273
        j= get_ue_golomb(&gb);
3274
        if(j != i){
3275
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3276
//            return -1;
3277
        }
3278
        STOP_TIMER("get_ue_golomb");
3279
    }
3280

    
3281

    
3282
    init_put_bits(&pb, temp, SIZE);
3283
    printf("testing signed exp golomb\n");
3284
    for(i=0; i<COUNT; i++){
3285
        START_TIMER
3286
        set_se_golomb(&pb, i - COUNT/2);
3287
        STOP_TIMER("set_se_golomb");
3288
    }
3289
    flush_put_bits(&pb);
3290

    
3291
    init_get_bits(&gb, temp, 8*SIZE);
3292
    for(i=0; i<COUNT; i++){
3293
        int j, s;
3294

    
3295
        s= show_bits(&gb, 24);
3296

    
3297
        START_TIMER
3298
        j= get_se_golomb(&gb);
3299
        if(j != i - COUNT/2){
3300
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3301
//            return -1;
3302
        }
3303
        STOP_TIMER("get_se_golomb");
3304
    }
3305

    
3306
#if 0
3307
    printf("testing 4x4 (I)DCT\n");
3308

3309
    DCTELEM block[16];
3310
    uint8_t src[16], ref[16];
3311
    uint64_t error= 0, max_error=0;
3312

3313
    for(i=0; i<COUNT; i++){
3314
        int j;
3315
//        printf("%d %d %d\n", r1, r2, (r2-r1)*16);
3316
        for(j=0; j<16; j++){
3317
            ref[j]= random()%255;
3318
            src[j]= random()%255;
3319
        }
3320

3321
        h264_diff_dct_c(block, src, ref, 4);
3322

3323
        //normalize
3324
        for(j=0; j<16; j++){
3325
//            printf("%d ", block[j]);
3326
            block[j]= block[j]*4;
3327
            if(j&1) block[j]= (block[j]*4 + 2)/5;
3328
            if(j&4) block[j]= (block[j]*4 + 2)/5;
3329
        }
3330
//        printf("\n");
3331

3332
        h->h264dsp.h264_idct_add(ref, block, 4);
3333
/*        for(j=0; j<16; j++){
3334
            printf("%d ", ref[j]);
3335
        }
3336
        printf("\n");*/
3337

3338
        for(j=0; j<16; j++){
3339
            int diff= FFABS(src[j] - ref[j]);
3340

3341
            error+= diff*diff;
3342
            max_error= FFMAX(max_error, diff);
3343
        }
3344
    }
3345
    printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
3346
    printf("testing quantizer\n");
3347
    for(qp=0; qp<52; qp++){
3348
        for(i=0; i<16; i++)
3349
            src1_block[i]= src2_block[i]= random()%255;
3350

3351
    }
3352
    printf("Testing NAL layer\n");
3353

3354
    uint8_t bitstream[COUNT];
3355
    uint8_t nal[COUNT*2];
3356
    H264Context h;
3357
    memset(&h, 0, sizeof(H264Context));
3358

3359
    for(i=0; i<COUNT; i++){
3360
        int zeros= i;
3361
        int nal_length;
3362
        int consumed;
3363
        int out_length;
3364
        uint8_t *out;
3365
        int j;
3366

3367
        for(j=0; j<COUNT; j++){
3368
            bitstream[j]= (random() % 255) + 1;
3369
        }
3370

3371
        for(j=0; j<zeros; j++){
3372
            int pos= random() % COUNT;
3373
            while(bitstream[pos] == 0){
3374
                pos++;
3375
                pos %= COUNT;
3376
            }
3377
            bitstream[pos]=0;
3378
        }
3379

3380
        START_TIMER
3381

3382
        nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
3383
        if(nal_length<0){
3384
            printf("encoding failed\n");
3385
            return -1;
3386
        }
3387

3388
        out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
3389

3390
        STOP_TIMER("NAL")
3391

3392
        if(out_length != COUNT){
3393
            printf("incorrect length %d %d\n", out_length, COUNT);
3394
            return -1;
3395
        }
3396

3397
        if(consumed != nal_length){
3398
            printf("incorrect consumed length %d %d\n", nal_length, consumed);
3399
            return -1;
3400
        }
3401

3402
        if(memcmp(bitstream, out, COUNT)){
3403
            printf("mismatch\n");
3404
            return -1;
3405
        }
3406
    }
3407
#endif
3408

    
3409
    printf("Testing RBSP\n");
3410

    
3411

    
3412
    return 0;
3413
}
3414
#endif /* TEST */
3415

    
3416

    
3417
av_cold void ff_h264_free_context(H264Context *h)
3418
{
3419
    int i;
3420

    
3421
    free_tables(h, 1); //FIXME cleanup init stuff perhaps
3422

    
3423
    for(i = 0; i < MAX_SPS_COUNT; i++)
3424
        av_freep(h->sps_buffers + i);
3425

    
3426
    for(i = 0; i < MAX_PPS_COUNT; i++)
3427
        av_freep(h->pps_buffers + i);
3428
}
3429

    
3430
av_cold int ff_h264_decode_end(AVCodecContext *avctx)
3431
{
3432
    H264Context *h = avctx->priv_data;
3433
    MpegEncContext *s = &h->s;
3434

    
3435
    ff_h264_free_context(h);
3436

    
3437
    MPV_common_end(s);
3438

    
3439
//    memset(h, 0, sizeof(H264Context));
3440

    
3441
    return 0;
3442
}
3443

    
3444
static const AVProfile profiles[] = {
3445
    { FF_PROFILE_H264_BASELINE,             "Baseline"              },
3446
    { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
3447
    { FF_PROFILE_H264_MAIN,                 "Main"                  },
3448
    { FF_PROFILE_H264_EXTENDED,             "Extended"              },
3449
    { FF_PROFILE_H264_HIGH,                 "High"                  },
3450
    { FF_PROFILE_H264_HIGH_10,              "High 10"               },
3451
    { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
3452
    { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
3453
    { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
3454
    { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
3455
    { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
3456
    { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
3457
    { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
3458
    { FF_PROFILE_UNKNOWN },
3459
};
3460

    
3461
AVCodec ff_h264_decoder = {
3462
    "h264",
3463
    AVMEDIA_TYPE_VIDEO,
3464
    CODEC_ID_H264,
3465
    sizeof(H264Context),
3466
    ff_h264_decode_init,
3467
    NULL,
3468
    ff_h264_decode_end,
3469
    decode_frame,
3470
    /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
3471
    .flush= flush_dpb,
3472
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
3473
    .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
3474
    .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
3475
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3476
};
3477

    
3478
#if CONFIG_H264_VDPAU_DECODER
3479
AVCodec ff_h264_vdpau_decoder = {
3480
    "h264_vdpau",
3481
    AVMEDIA_TYPE_VIDEO,
3482
    CODEC_ID_H264,
3483
    sizeof(H264Context),
3484
    ff_h264_decode_init,
3485
    NULL,
3486
    ff_h264_decode_end,
3487
    decode_frame,
3488
    CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
3489
    .flush= flush_dpb,
3490
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
3491
    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
3492
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3493
};
3494
#endif