Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ a50f0bea

History | View | Annotate | Download (125 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
        for(i=out_idx; h->delayed_pic[i]; i++)
934
            h->delayed_pic[i] = h->delayed_pic[i+1];
935
    }
936
    if(!out_of_order && pics > s->avctx->has_b_frames){
937
        h->next_output_pic = out;
938
        if(out_idx==0 && h->delayed_pic[0] && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset)) {
939
            h->next_outputed_poc = INT_MIN;
940
        } else
941
            h->next_outputed_poc = out->poc;
942
    }else{
943
        av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
944
    }
945

    
946
    ff_thread_finish_setup(s->avctx);
947
}
948

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

    
954
    src_y  -=   linesize;
955
    src_cb -= uvlinesize;
956
    src_cr -= uvlinesize;
957

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

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

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

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

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

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

    
1024
    src_y  -=   linesize + 1 + h->pixel_shift;
1025
    src_cb -= uvlinesize + 1 + h->pixel_shift;
1026
    src_cr -= uvlinesize + 1 + h->pixel_shift;
1027

    
1028
    top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1029
    top_border    = h->top_borders[top_idx][s->mb_x];
1030

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

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

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

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

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

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

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

    
1102
    h->list_counts[mb_xy]= h->list_count;
1103

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

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

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

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

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

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

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

    
1284

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

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

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

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

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

    
1392
    if (is_complex)
1393
        hl_decode_mb_complex(h);
1394
    else hl_decode_mb_simple(h);
1395
}
1396

    
1397
static int pred_weight_table(H264Context *h){
1398
    MpegEncContext * const s = &h->s;
1399
    int list, i;
1400
    int luma_def, chroma_def;
1401

    
1402
    h->use_weight= 0;
1403
    h->use_weight_chroma= 0;
1404
    h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
1405
    if(CHROMA)
1406
        h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
1407
    luma_def = 1<<h->luma_log2_weight_denom;
1408
    chroma_def = 1<<h->chroma_log2_weight_denom;
1409

    
1410
    for(list=0; list<2; list++){
1411
        h->luma_weight_flag[list]   = 0;
1412
        h->chroma_weight_flag[list] = 0;
1413
        for(i=0; i<h->ref_count[list]; i++){
1414
            int luma_weight_flag, chroma_weight_flag;
1415

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

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

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

    
1467
    for (i = 0; i < 2; i++) {
1468
        h->luma_weight_flag[i]   = 0;
1469
        h->chroma_weight_flag[i] = 0;
1470
    }
1471

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

    
1490
    h->use_weight= 2;
1491
    h->use_weight_chroma= 2;
1492
    h->luma_log2_weight_denom= 5;
1493
    h->chroma_log2_weight_denom= 5;
1494

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

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

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

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

    
1554
    h->frame_num_offset= h->prev_frame_num_offset;
1555
    if(h->frame_num < h->prev_frame_num)
1556
        h->frame_num_offset += max_frame_num;
1557

    
1558
    if(h->sps.poc_type==0){
1559
        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
1560

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

    
1576
        if(h->sps.poc_cycle_length != 0)
1577
            abs_frame_num = h->frame_num_offset + h->frame_num;
1578
        else
1579
            abs_frame_num = 0;
1580

    
1581
        if(h->nal_ref_idc==0 && abs_frame_num > 0)
1582
            abs_frame_num--;
1583

    
1584
        expected_delta_per_poc_cycle = 0;
1585
        for(i=0; i < h->sps.poc_cycle_length; i++)
1586
            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
1587

    
1588
        if(abs_frame_num > 0){
1589
            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1590
            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1591

    
1592
            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1593
            for(i = 0; i <= frame_num_in_poc_cycle; i++)
1594
                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
1595
        } else
1596
            expectedpoc = 0;
1597

    
1598
        if(h->nal_ref_idc == 0)
1599
            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1600

    
1601
        field_poc[0] = expectedpoc + h->delta_poc[0];
1602
        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1603

    
1604
        if(s->picture_structure == PICT_FRAME)
1605
            field_poc[1] += h->delta_poc[1];
1606
    }else{
1607
        int poc= 2*(h->frame_num_offset + h->frame_num);
1608

    
1609
        if(!h->nal_ref_idc)
1610
            poc--;
1611

    
1612
        field_poc[0]= poc;
1613
        field_poc[1]= poc;
1614
    }
1615

    
1616
    if(s->picture_structure != PICT_BOTTOM_FIELD)
1617
        s->current_picture_ptr->field_poc[0]= field_poc[0];
1618
    if(s->picture_structure != PICT_TOP_FIELD)
1619
        s->current_picture_ptr->field_poc[1]= field_poc[1];
1620
    cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
1621

    
1622
    return 0;
1623
}
1624

    
1625

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

    
1662
static void field_end(H264Context *h, int in_setup){
1663
    MpegEncContext * const s = &h->s;
1664
    AVCodecContext * const avctx= s->avctx;
1665
    s->mb_y= 0;
1666

    
1667
    if (!in_setup && !s->dropable)
1668
        ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
1669
                                 s->picture_structure==PICT_BOTTOM_FIELD);
1670

    
1671
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
1672
        ff_vdpau_h264_set_reference_frames(s);
1673

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

    
1685
    if (avctx->hwaccel) {
1686
        if (avctx->hwaccel->end_frame(avctx) < 0)
1687
            av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
1688
    }
1689

    
1690
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
1691
        ff_vdpau_h264_picture_complete(s);
1692

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

    
1708
    MPV_frame_end(s);
1709

    
1710
    h->current_slice=0;
1711
}
1712

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

    
1725
    dst->prev_poc_msb           = src->prev_poc_msb;
1726
    dst->prev_poc_lsb           = src->prev_poc_lsb;
1727
    dst->prev_frame_num_offset  = src->prev_frame_num_offset;
1728
    dst->prev_frame_num         = src->prev_frame_num;
1729
    dst->short_ref_count        = src->short_ref_count;
1730

    
1731
    memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
1732
    memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
1733
    memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
1734
    memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
1735

    
1736
    memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
1737
    memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
1738
}
1739

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

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

    
1764
    return profile;
1765
}
1766

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

    
1786
    s->dropable= h->nal_ref_idc == 0;
1787

    
1788
    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
1789
        s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
1790
        s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
1791
    }else{
1792
        s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
1793
        s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
1794
    }
1795

    
1796
    first_mb_in_slice= get_ue_golomb(&s->gb);
1797

    
1798
    if(first_mb_in_slice == 0){ //FIXME better field boundary detection
1799
        if(h0->current_slice && FIELD_PICTURE){
1800
            field_end(h, 1);
1801
        }
1802

    
1803
        h0->current_slice = 0;
1804
        if (!s0->first_field)
1805
            s->current_picture_ptr= NULL;
1806
    }
1807

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

    
1819
    slice_type= golomb_to_pict_type[ slice_type ];
1820
    if (slice_type == FF_I_TYPE
1821
        || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
1822
        default_ref_list_done = 1;
1823
    }
1824
    h->slice_type= slice_type;
1825
    h->slice_type_nos= slice_type & 3;
1826

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

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

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

    
1846
    s->avctx->profile = ff_h264_get_profile(&h->sps);
1847
    s->avctx->level   = h->sps.level_idc;
1848
    s->avctx->refs    = h->sps.ref_frame_count;
1849

    
1850
    if(h == h0 && h->dequant_coeff_pps != pps_id){
1851
        h->dequant_coeff_pps = pps_id;
1852
        init_dequant_tables(h);
1853
    }
1854

    
1855
    s->mb_width= h->sps.mb_width;
1856
    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
1857

    
1858
    h->b_stride=  s->mb_width*4;
1859

    
1860
    s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
1861
    if(h->sps.frame_mbs_only_flag)
1862
        s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
1863
    else
1864
        s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 7);
1865

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

    
1883
        avcodec_set_dimensions(s->avctx, s->width, s->height);
1884
        s->avctx->sample_aspect_ratio= h->sps.sar;
1885
        av_assert0(s->avctx->sample_aspect_ratio.den);
1886

    
1887
        if(h->sps.video_signal_type_present_flag){
1888
            s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
1889
            if(h->sps.colour_description_present_flag){
1890
                s->avctx->color_primaries = h->sps.color_primaries;
1891
                s->avctx->color_trc       = h->sps.color_trc;
1892
                s->avctx->colorspace      = h->sps.colorspace;
1893
            }
1894
        }
1895

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

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

    
1920
        s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
1921

    
1922
        if (MPV_common_init(s) < 0){
1923
            av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed\n");
1924
            return -1;
1925
        }
1926
        s->first_field = 0;
1927
        h->prev_interlaced_frame = 1;
1928

    
1929
        init_scan_tables(h);
1930
        ff_h264_alloc_tables(h);
1931

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

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

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

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

    
1975
    if(h0->current_slice == 0){
1976
        if(h->frame_num != h->prev_frame_num &&
1977
          (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num) < (h->frame_num - h->sps.ref_frame_count))
1978
            h->prev_frame_num = h->frame_num - h->sps.ref_frame_count - 1;
1979

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

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

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

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

    
2038
                } else {
2039
                    /* Second field in complementary pair */
2040
                    s0->first_field = 0;
2041
                }
2042
            }
2043

    
2044
        } else {
2045
            /* Frame or first field in a potentially complementary pair */
2046
            assert(!s0->current_picture_ptr);
2047
            s0->first_field = FIELD_PICTURE;
2048
        }
2049

    
2050
        if((!FIELD_PICTURE || s0->first_field) && ff_h264_frame_start(h) < 0) {
2051
            s0->first_field = 0;
2052
            return -1;
2053
        }
2054
    }
2055
    if(h != h0)
2056
        clone_slice(h, h0);
2057

    
2058
    s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2059

    
2060
    assert(s->mb_num == s->mb_width * s->mb_height);
2061
    if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
2062
       first_mb_in_slice                    >= s->mb_num){
2063
        av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
2064
        return -1;
2065
    }
2066
    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
2067
    s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
2068
    if (s->picture_structure == PICT_BOTTOM_FIELD)
2069
        s->resync_mb_y = s->mb_y = s->mb_y + 1;
2070
    assert(s->mb_y < s->mb_height);
2071

    
2072
    if(s->picture_structure==PICT_FRAME){
2073
        h->curr_pic_num=   h->frame_num;
2074
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
2075
    }else{
2076
        h->curr_pic_num= 2*h->frame_num + 1;
2077
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
2078
    }
2079

    
2080
    if(h->nal_unit_type == NAL_IDR_SLICE){
2081
        get_ue_golomb(&s->gb); /* idr_pic_id */
2082
    }
2083

    
2084
    if(h->sps.poc_type==0){
2085
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2086

    
2087
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
2088
            h->delta_poc_bottom= get_se_golomb(&s->gb);
2089
        }
2090
    }
2091

    
2092
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
2093
        h->delta_poc[0]= get_se_golomb(&s->gb);
2094

    
2095
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
2096
            h->delta_poc[1]= get_se_golomb(&s->gb);
2097
    }
2098

    
2099
    init_poc(h);
2100

    
2101
    if(h->pps.redundant_pic_cnt_present){
2102
        h->redundant_pic_count= get_ue_golomb(&s->gb);
2103
    }
2104

    
2105
    //set defaults, might be overridden a few lines later
2106
    h->ref_count[0]= h->pps.ref_count[0];
2107
    h->ref_count[1]= h->pps.ref_count[1];
2108

    
2109
    if(h->slice_type_nos != FF_I_TYPE){
2110
        if(h->slice_type_nos == FF_B_TYPE){
2111
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
2112
        }
2113
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
2114

    
2115
        if(num_ref_idx_active_override_flag){
2116
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
2117
            if(h->slice_type_nos==FF_B_TYPE)
2118
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
2119

    
2120
            if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
2121
                av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
2122
                h->ref_count[0]= h->ref_count[1]= 1;
2123
                return -1;
2124
            }
2125
        }
2126
        if(h->slice_type_nos == FF_B_TYPE)
2127
            h->list_count= 2;
2128
        else
2129
            h->list_count= 1;
2130
    }else
2131
        h->list_count= 0;
2132

    
2133
    if(!default_ref_list_done){
2134
        ff_h264_fill_default_ref_list(h);
2135
    }
2136

    
2137
    if(h->slice_type_nos!=FF_I_TYPE && ff_h264_decode_ref_pic_list_reordering(h) < 0)
2138
        return -1;
2139

    
2140
    if(h->slice_type_nos!=FF_I_TYPE){
2141
        s->last_picture_ptr= &h->ref_list[0][0];
2142
        ff_copy_picture(&s->last_picture, s->last_picture_ptr);
2143
    }
2144
    if(h->slice_type_nos==FF_B_TYPE){
2145
        s->next_picture_ptr= &h->ref_list[1][0];
2146
        ff_copy_picture(&s->next_picture, s->next_picture_ptr);
2147
    }
2148

    
2149
    if(   (h->pps.weighted_pred          && h->slice_type_nos == FF_P_TYPE )
2150
       ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
2151
        pred_weight_table(h);
2152
    else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2153
        implicit_weight_table(h, -1);
2154
    }else {
2155
        h->use_weight = 0;
2156
        for (i = 0; i < 2; i++) {
2157
            h->luma_weight_flag[i]   = 0;
2158
            h->chroma_weight_flag[i] = 0;
2159
        }
2160
    }
2161

    
2162
    if(h->nal_ref_idc)
2163
        ff_h264_decode_ref_pic_marking(h0, &s->gb);
2164

    
2165
    if(FRAME_MBAFF){
2166
        ff_h264_fill_mbaff_ref_list(h);
2167

    
2168
        if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2169
            implicit_weight_table(h, 0);
2170
            implicit_weight_table(h, 1);
2171
        }
2172
    }
2173

    
2174
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2175
        ff_h264_direct_dist_scale_factor(h);
2176
    ff_h264_direct_ref_list_init(h);
2177

    
2178
    if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
2179
        tmp = get_ue_golomb_31(&s->gb);
2180
        if(tmp > 2){
2181
            av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
2182
            return -1;
2183
        }
2184
        h->cabac_init_idc= tmp;
2185
    }
2186

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

    
2204
    h->deblocking_filter = 1;
2205
    h->slice_alpha_c0_offset = 52;
2206
    h->slice_beta_offset = 52;
2207
    if( h->pps.deblocking_filter_parameters_present ) {
2208
        tmp= get_ue_golomb_31(&s->gb);
2209
        if(tmp > 2){
2210
            av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
2211
            return -1;
2212
        }
2213
        h->deblocking_filter= tmp;
2214
        if(h->deblocking_filter < 2)
2215
            h->deblocking_filter^= 1; // 1<->0
2216

    
2217
        if( h->deblocking_filter ) {
2218
            h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
2219
            h->slice_beta_offset     += get_se_golomb(&s->gb) << 1;
2220
            if(   h->slice_alpha_c0_offset > 104U
2221
               || h->slice_beta_offset     > 104U){
2222
                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);
2223
                return -1;
2224
            }
2225
        }
2226
    }
2227

    
2228
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
2229
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
2230
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
2231
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
2232
        h->deblocking_filter= 0;
2233

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

    
2253
#if 0 //FMO
2254
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
2255
        slice_group_change_cycle= get_bits(&s->gb, ?);
2256
#endif
2257

    
2258
    h0->last_slice_type = slice_type;
2259
    h->slice_num = ++h0->current_slice;
2260
    if(h->slice_num >= MAX_SLICES){
2261
        av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
2262
    }
2263

    
2264
    for(j=0; j<2; j++){
2265
        int id_list[16];
2266
        int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
2267
        for(i=0; i<16; i++){
2268
            id_list[i]= 60;
2269
            if(h->ref_list[j][i].data[0]){
2270
                int k;
2271
                uint8_t *base= h->ref_list[j][i].base[0];
2272
                for(k=0; k<h->short_ref_count; k++)
2273
                    if(h->short_ref[k]->base[0] == base){
2274
                        id_list[i]= k;
2275
                        break;
2276
                    }
2277
                for(k=0; k<h->long_ref_count; k++)
2278
                    if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
2279
                        id_list[i]= h->short_ref_count + k;
2280
                        break;
2281
                    }
2282
            }
2283
        }
2284

    
2285
        ref2frm[0]=
2286
        ref2frm[1]= -1;
2287
        for(i=0; i<16; i++)
2288
            ref2frm[i+2]= 4*id_list[i]
2289
                          +(h->ref_list[j][i].reference&3);
2290
        ref2frm[18+0]=
2291
        ref2frm[18+1]= -1;
2292
        for(i=16; i<48; i++)
2293
            ref2frm[i+4]= 4*id_list[(i-16)>>1]
2294
                          +(h->ref_list[j][i].reference&3);
2295
    }
2296

    
2297
    //FIXME: fix draw_edges+PAFF+frame threads
2298
    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;
2299
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
2300

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

    
2318
    return 0;
2319
}
2320

    
2321
int ff_h264_get_slice_type(const H264Context *h)
2322
{
2323
    switch (h->slice_type) {
2324
    case FF_P_TYPE:  return 0;
2325
    case FF_B_TYPE:  return 1;
2326
    case FF_I_TYPE:  return 2;
2327
    case FF_SP_TYPE: return 3;
2328
    case FF_SI_TYPE: return 4;
2329
    default:         return -1;
2330
    }
2331
}
2332

    
2333
/**
2334
 *
2335
 * @return non zero if the loop filter can be skiped
2336
 */
2337
static int fill_filter_caches(H264Context *h, int mb_type){
2338
    MpegEncContext * const s = &h->s;
2339
    const int mb_xy= h->mb_xy;
2340
    int top_xy, left_xy[2];
2341
    int top_type, left_type[2];
2342

    
2343
    top_xy     = mb_xy  - (s->mb_stride << MB_FIELD);
2344

    
2345
    //FIXME deblocking could skip the intra and nnz parts.
2346

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

    
2350
    left_xy[1] = left_xy[0] = mb_xy-1;
2351
    if(FRAME_MBAFF){
2352
        const int left_mb_field_flag     = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);
2353
        const int curr_mb_field_flag     = IS_INTERLACED(mb_type);
2354
        if(s->mb_y&1){
2355
            if (left_mb_field_flag != curr_mb_field_flag) {
2356
                left_xy[0] -= s->mb_stride;
2357
            }
2358
        }else{
2359
            if(curr_mb_field_flag){
2360
                top_xy      += s->mb_stride & (((s->current_picture.mb_type[top_xy    ]>>7)&1)-1);
2361
            }
2362
            if (left_mb_field_flag != curr_mb_field_flag) {
2363
                left_xy[1] += s->mb_stride;
2364
            }
2365
        }
2366
    }
2367

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

    
2387
    top_type     = s->current_picture.mb_type[top_xy]    ;
2388
    left_type[0] = s->current_picture.mb_type[left_xy[0]];
2389
    left_type[1] = s->current_picture.mb_type[left_xy[1]];
2390
    if(h->deblocking_filter == 2){
2391
        if(h->slice_table[top_xy     ] != h->slice_num) top_type= 0;
2392
        if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
2393
    }else{
2394
        if(h->slice_table[top_xy     ] == 0xFFFF) top_type= 0;
2395
        if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
2396
    }
2397
    h->top_type    = top_type    ;
2398
    h->left_type[0]= left_type[0];
2399
    h->left_type[1]= left_type[1];
2400

    
2401
    if(IS_INTRA(mb_type))
2402
        return 0;
2403

    
2404
    AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
2405
    AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
2406
    AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
2407
    AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
2408
    AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
2409

    
2410
    h->cbp= h->cbp_table[mb_xy];
2411

    
2412
    {
2413
        int list;
2414
        for(list=0; list<h->list_count; list++){
2415
            int8_t *ref;
2416
            int y, b_stride;
2417
            int16_t (*mv_dst)[2];
2418
            int16_t (*mv_src)[2];
2419

    
2420
            if(!USES_LIST(mb_type, list)){
2421
                fill_rectangle(  h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
2422
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2423
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2424
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2425
                AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
2426
                continue;
2427
            }
2428

    
2429
            ref = &s->current_picture.ref_index[list][4*mb_xy];
2430
            {
2431
                int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
2432
                AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2433
                AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2434
                ref += 2;
2435
                AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2436
                AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
2437
            }
2438

    
2439
            b_stride = h->b_stride;
2440
            mv_dst   = &h->mv_cache[list][scan8[0]];
2441
            mv_src   = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
2442
            for(y=0; y<4; y++){
2443
                AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
2444
            }
2445

    
2446
        }
2447
    }
2448

    
2449

    
2450
/*
2451
0 . T T. T T T T
2452
1 L . .L . . . .
2453
2 L . .L . . . .
2454
3 . T TL . . . .
2455
4 L . .L . . . .
2456
5 L . .. . . . .
2457
*/
2458
//FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
2459
    if(top_type){
2460
        AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][4+3*8]);
2461
    }
2462

    
2463
    if(left_type[0]){
2464
        h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
2465
        h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
2466
        h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
2467
        h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
2468
    }
2469

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

    
2487
        if(IS_8x8DCT(mb_type)){
2488
            h->non_zero_count_cache[scan8[0   ]]= h->non_zero_count_cache[scan8[1   ]]=
2489
            h->non_zero_count_cache[scan8[2   ]]= h->non_zero_count_cache[scan8[3   ]]= h->cbp & 1;
2490

    
2491
            h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
2492
            h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
2493

    
2494
            h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
2495
            h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp & 4;
2496

    
2497
            h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
2498
            h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
2499
        }
2500
    }
2501

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

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

    
2546
    return 0;
2547
}
2548

    
2549
static void loop_filter(H264Context *h){
2550
    MpegEncContext * const s = &h->s;
2551
    uint8_t  *dest_y, *dest_cb, *dest_cr;
2552
    int linesize, uvlinesize, mb_x, mb_y;
2553
    const int end_mb_y= s->mb_y + FRAME_MBAFF;
2554
    const int old_slice_type= h->slice_type;
2555
    const int end_mb_x  = s->mb_x;
2556

    
2557
    if(h->deblocking_filter) {
2558
        int start_x= s->resync_mb_y == s->mb_y ? s->resync_mb_x : 0;
2559
        for(mb_x= start_x; mb_x<end_mb_x; mb_x++){
2560
            for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
2561
                int mb_xy, mb_type;
2562
                mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
2563
                h->slice_num= h->slice_table[mb_xy];
2564
                mb_type= s->current_picture.mb_type[mb_xy];
2565
                h->list_count= h->list_counts[mb_xy];
2566

    
2567
                if(FRAME_MBAFF)
2568
                    h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2569

    
2570
                s->mb_x= mb_x;
2571
                s->mb_y= mb_y;
2572
                dest_y  = s->current_picture.data[0] + ((mb_x<<h->pixel_shift) + mb_y * s->linesize  ) * 16;
2573
                dest_cb = s->current_picture.data[1] + ((mb_x<<h->pixel_shift) + mb_y * s->uvlinesize) * 8;
2574
                dest_cr = s->current_picture.data[2] + ((mb_x<<h->pixel_shift) + mb_y * s->uvlinesize) * 8;
2575
                    //FIXME simplify above
2576

    
2577
                if (MB_FIELD) {
2578
                    linesize   = h->mb_linesize   = s->linesize * 2;
2579
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2580
                    if(mb_y&1){ //FIXME move out of this function?
2581
                        dest_y -= s->linesize*15;
2582
                        dest_cb-= s->uvlinesize*7;
2583
                        dest_cr-= s->uvlinesize*7;
2584
                    }
2585
                } else {
2586
                    linesize   = h->mb_linesize   = s->linesize;
2587
                    uvlinesize = h->mb_uvlinesize = s->uvlinesize;
2588
                }
2589
                backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
2590
                if(fill_filter_caches(h, mb_type))
2591
                    continue;
2592
                h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2593
                h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2594

    
2595
                if (FRAME_MBAFF) {
2596
                    ff_h264_filter_mb     (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2597
                } else {
2598
                    ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2599
                }
2600
            }
2601
        }
2602
    }
2603
    h->slice_type= old_slice_type;
2604
    s->mb_x= end_mb_x;
2605
    s->mb_y= end_mb_y - FRAME_MBAFF;
2606
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
2607
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
2608
}
2609

    
2610
static void predict_field_decoding_flag(H264Context *h){
2611
    MpegEncContext * const s = &h->s;
2612
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
2613
    int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
2614
                ? s->current_picture.mb_type[mb_xy-1]
2615
                : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
2616
                ? s->current_picture.mb_type[mb_xy-s->mb_stride]
2617
                : 0;
2618
    h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
2619
}
2620

    
2621
/**
2622
 * Draw edges and report progress for the last MB row.
2623
 */
2624
static void decode_finish_row(H264Context *h){
2625
    MpegEncContext * const s = &h->s;
2626
    int top = 16*(s->mb_y >> FIELD_PICTURE);
2627
    int height = 16 << FRAME_MBAFF;
2628
    int deblock_border = (16 + 4) << FRAME_MBAFF;
2629
    int pic_height = 16*s->mb_height >> FIELD_PICTURE;
2630

    
2631
    if (h->deblocking_filter) {
2632
        if((top + height) >= pic_height)
2633
            height += deblock_border;
2634

    
2635
        top -= deblock_border;
2636
    }
2637

    
2638
    if (top >= pic_height || (top + height) < h->emu_edge_height)
2639
        return;
2640

    
2641
    height = FFMIN(height, pic_height - top);
2642
    if (top < h->emu_edge_height) {
2643
        height = top+height;
2644
        top = 0;
2645
    }
2646

    
2647
    ff_draw_horiz_band(s, top, height);
2648

    
2649
    if (s->dropable) return;
2650

    
2651
    ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
2652
                             s->picture_structure==PICT_BOTTOM_FIELD);
2653
}
2654

    
2655
static int decode_slice(struct AVCodecContext *avctx, void *arg){
2656
    H264Context *h = *(void**)arg;
2657
    MpegEncContext * const s = &h->s;
2658
    const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
2659

    
2660
    s->mb_skip_run= -1;
2661

    
2662
    h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
2663
                    (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
2664

    
2665
    if( h->pps.cabac ) {
2666
        /* realign */
2667
        align_get_bits( &s->gb );
2668

    
2669
        /* init cabac */
2670
        ff_init_cabac_states( &h->cabac);
2671
        ff_init_cabac_decoder( &h->cabac,
2672
                               s->gb.buffer + get_bits_count(&s->gb)/8,
2673
                               (get_bits_left(&s->gb) + 7)/8);
2674

    
2675
        ff_h264_init_cabac_states(h);
2676

    
2677
        for(;;){
2678
//START_TIMER
2679
            int ret = ff_h264_decode_mb_cabac(h);
2680
            int eos;
2681
//STOP_TIMER("decode_mb_cabac")
2682

    
2683
            if(ret>=0) ff_h264_hl_decode_mb(h);
2684

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

    
2688
                ret = ff_h264_decode_mb_cabac(h);
2689

    
2690
                if(ret>=0) ff_h264_hl_decode_mb(h);
2691
                s->mb_y--;
2692
            }
2693
            eos = get_cabac_terminate( &h->cabac );
2694

    
2695
            if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
2696
                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);
2697
                return 0;
2698
            }
2699
            if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
2700
                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);
2701
                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);
2702
                return -1;
2703
            }
2704

    
2705
            if( ++s->mb_x >= s->mb_width ) {
2706
                loop_filter(h);
2707
                s->mb_x = 0;
2708
                decode_finish_row(h);
2709
                ++s->mb_y;
2710
                if(FIELD_OR_MBAFF_PICTURE) {
2711
                    ++s->mb_y;
2712
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
2713
                        predict_field_decoding_flag(h);
2714
                }
2715
            }
2716

    
2717
            if( eos || s->mb_y >= s->mb_height ) {
2718
                if(s->mb_x)
2719
                    loop_filter(h);
2720
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
2721
                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);
2722
                return 0;
2723
            }
2724
        }
2725

    
2726
    } else {
2727
        for(;;){
2728
            int ret = ff_h264_decode_mb_cavlc(h);
2729

    
2730
            if(ret>=0) ff_h264_hl_decode_mb(h);
2731

    
2732
            if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
2733
                s->mb_y++;
2734
                ret = ff_h264_decode_mb_cavlc(h);
2735

    
2736
                if(ret>=0) ff_h264_hl_decode_mb(h);
2737
                s->mb_y--;
2738
            }
2739

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

    
2744
                return -1;
2745
            }
2746

    
2747
            if(++s->mb_x >= s->mb_width){
2748
                loop_filter(h);
2749
                s->mb_x=0;
2750
                decode_finish_row(h);
2751
                ++s->mb_y;
2752
                if(FIELD_OR_MBAFF_PICTURE) {
2753
                    ++s->mb_y;
2754
                    if(FRAME_MBAFF && s->mb_y < s->mb_height)
2755
                        predict_field_decoding_flag(h);
2756
                }
2757
                if(s->mb_y >= s->mb_height){
2758
                    tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
2759

    
2760
                    if(   get_bits_count(&s->gb) == s->gb.size_in_bits
2761
                       || get_bits_count(&s->gb) <  s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
2762
                        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);
2763

    
2764
                        return 0;
2765
                    }else{
2766
                        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);
2767

    
2768
                        return -1;
2769
                    }
2770
                }
2771
            }
2772

    
2773
            if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
2774
                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
2775
                if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
2776
                    if(s->mb_x)
2777
                        loop_filter(h);
2778
                    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);
2779

    
2780
                    return 0;
2781
                }else{
2782
                    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);
2783

    
2784
                    return -1;
2785
                }
2786
            }
2787
        }
2788
    }
2789

    
2790
#if 0
2791
    for(;s->mb_y < s->mb_height; s->mb_y++){
2792
        for(;s->mb_x < s->mb_width; s->mb_x++){
2793
            int ret= decode_mb(h);
2794

2795
            ff_h264_hl_decode_mb(h);
2796

2797
            if(ret<0){
2798
                av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
2799
                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);
2800

2801
                return -1;
2802
            }
2803

2804
            if(++s->mb_x >= s->mb_width){
2805
                s->mb_x=0;
2806
                if(++s->mb_y >= s->mb_height){
2807
                    if(get_bits_count(s->gb) == s->gb.size_in_bits){
2808
                        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);
2809

2810
                        return 0;
2811
                    }else{
2812
                        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);
2813

2814
                        return -1;
2815
                    }
2816
                }
2817
            }
2818

2819
            if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
2820
                if(get_bits_count(s->gb) == s->gb.size_in_bits){
2821
                    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);
2822

2823
                    return 0;
2824
                }else{
2825
                    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);
2826

2827
                    return -1;
2828
                }
2829
            }
2830
        }
2831
        s->mb_x=0;
2832
        ff_draw_horiz_band(s, 16*s->mb_y, 16);
2833
    }
2834
#endif
2835
    return -1; //not reached
2836
}
2837

    
2838
/**
2839
 * Call decode_slice() for each context.
2840
 *
2841
 * @param h h264 master context
2842
 * @param context_count number of contexts to execute
2843
 */
2844
static void execute_decode_slices(H264Context *h, int context_count){
2845
    MpegEncContext * const s = &h->s;
2846
    AVCodecContext * const avctx= s->avctx;
2847
    H264Context *hx;
2848
    int i;
2849

    
2850
    if (s->avctx->hwaccel)
2851
        return;
2852
    if(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2853
        return;
2854
    if(context_count == 1) {
2855
        decode_slice(avctx, &h);
2856
    } else {
2857
        for(i = 1; i < context_count; i++) {
2858
            hx = h->thread_context[i];
2859
            hx->s.error_recognition = avctx->error_recognition;
2860
            hx->s.error_count = 0;
2861
            hx->x264_build= h->x264_build;
2862
        }
2863

    
2864
        avctx->execute(avctx, (void *)decode_slice,
2865
                       h->thread_context, NULL, context_count, sizeof(void*));
2866

    
2867
        /* pull back stuff from slices to master context */
2868
        hx = h->thread_context[context_count - 1];
2869
        s->mb_x = hx->s.mb_x;
2870
        s->mb_y = hx->s.mb_y;
2871
        s->dropable = hx->s.dropable;
2872
        s->picture_structure = hx->s.picture_structure;
2873
        for(i = 1; i < context_count; i++)
2874
            h->s.error_count += h->thread_context[i]->s.error_count;
2875
    }
2876
}
2877

    
2878

    
2879
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
2880
    MpegEncContext * const s = &h->s;
2881
    AVCodecContext * const avctx= s->avctx;
2882
    int buf_index=0;
2883
    H264Context *hx; ///< thread context
2884
    int context_count = 0;
2885
    int next_avc= h->is_avc ? 0 : buf_size;
2886

    
2887
    h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
2888
#if 0
2889
    int i;
2890
    for(i=0; i<50; i++){
2891
        av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
2892
    }
2893
#endif
2894
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
2895
        h->current_slice = 0;
2896
        if (!s->first_field)
2897
            s->current_picture_ptr= NULL;
2898
        ff_h264_reset_sei(h);
2899
    }
2900

    
2901
    for(;;){
2902
        int consumed;
2903
        int dst_length;
2904
        int bit_length;
2905
        const uint8_t *ptr;
2906
        int i, nalsize = 0;
2907
        int err;
2908

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

    
2927
            if(buf_index+3 >= buf_size) break;
2928

    
2929
            buf_index+=3;
2930
            if(buf_index >= next_avc) continue;
2931
        }
2932

    
2933
        hx = h->thread_context[context_count];
2934

    
2935
        ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
2936
        if (ptr==NULL || dst_length < 0){
2937
            return -1;
2938
        }
2939
        i= buf_index + consumed;
2940
        if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
2941
           buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
2942
            s->workaround_bugs |= FF_BUG_TRUNCATED;
2943

    
2944
        if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
2945
        while(ptr[dst_length - 1] == 0 && dst_length > 0)
2946
            dst_length--;
2947
        }
2948
        bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
2949

    
2950
        if(s->avctx->debug&FF_DEBUG_STARTCODE){
2951
            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);
2952
        }
2953

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

    
2958
        buf_index += consumed;
2959

    
2960
        //FIXME do not discard SEI id
2961
        if(
2962
#if FF_API_HURRY_UP
2963
           (s->hurry_up == 1 && h->nal_ref_idc  == 0) ||
2964
#endif
2965
           (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc  == 0))
2966
            continue;
2967

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

    
2983
            if((err = decode_slice_header(hx, h)))
2984
               break;
2985

    
2986
            s->current_picture_ptr->key_frame |=
2987
                    (hx->nal_unit_type == NAL_IDR_SLICE) ||
2988
                    (h->sei_recovery_frame_cnt >= 0);
2989

    
2990
            if (h->current_slice == 1) {
2991
                if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
2992
                    decode_postinit(h);
2993
                }
2994

    
2995
                if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
2996
                    return -1;
2997
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
2998
                    ff_vdpau_h264_picture_start(s);
2999
            }
3000

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

    
3026
            if ((err = decode_slice_header(hx, h)) < 0)
3027
                break;
3028

    
3029
            hx->s.data_partitioning = 1;
3030

    
3031
            break;
3032
        case NAL_DPB:
3033
            init_get_bits(&hx->intra_gb, ptr, bit_length);
3034
            hx->intra_gb_ptr= &hx->intra_gb;
3035
            break;
3036
        case NAL_DPC:
3037
            init_get_bits(&hx->inter_gb, ptr, bit_length);
3038
            hx->inter_gb_ptr= &hx->inter_gb;
3039

    
3040
            if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
3041
               && s->context_initialized
3042
#if FF_API_HURRY_UP
3043
               && s->hurry_up < 5
3044
#endif
3045
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3046
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3047
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3048
               && avctx->skip_frame < AVDISCARD_ALL)
3049
                context_count++;
3050
            break;
3051
        case NAL_SEI:
3052
            init_get_bits(&s->gb, ptr, bit_length);
3053
            ff_h264_decode_sei(h);
3054
            break;
3055
        case NAL_SPS:
3056
            init_get_bits(&s->gb, ptr, bit_length);
3057
            ff_h264_decode_seq_parameter_set(h);
3058

    
3059
            if(s->flags& CODEC_FLAG_LOW_DELAY)
3060
                s->low_delay=1;
3061

    
3062
            if(avctx->has_b_frames < 2)
3063
                avctx->has_b_frames= !s->low_delay;
3064

    
3065
            if (avctx->bits_per_raw_sample != h->sps.bit_depth_luma) {
3066
                if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
3067
                    avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3068
                    h->pixel_shift = h->sps.bit_depth_luma/9;
3069

    
3070
                    ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma);
3071
                    ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma);
3072
                    dsputil_init(&s->dsp, s->avctx);
3073
                } else {
3074
                    av_log(avctx, AV_LOG_DEBUG, "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3075
                    return -1;
3076
                }
3077
            }
3078
            break;
3079
        case NAL_PPS:
3080
            init_get_bits(&s->gb, ptr, bit_length);
3081

    
3082
            ff_h264_decode_picture_parameter_set(h, bit_length);
3083

    
3084
            break;
3085
        case NAL_AUD:
3086
        case NAL_END_SEQUENCE:
3087
        case NAL_END_STREAM:
3088
        case NAL_FILLER_DATA:
3089
        case NAL_SPS_EXT:
3090
        case NAL_AUXILIARY_SLICE:
3091
            break;
3092
        default:
3093
            av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
3094
        }
3095

    
3096
        if(context_count == h->max_contexts) {
3097
            execute_decode_slices(h, context_count);
3098
            context_count = 0;
3099
        }
3100

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

    
3119
/**
3120
 * returns the number of bytes consumed for building the current frame
3121
 */
3122
static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
3123
        if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
3124
        if(pos+10>buf_size) pos=buf_size; // oops ;)
3125

    
3126
        return pos;
3127
}
3128

    
3129
static int decode_frame(AVCodecContext *avctx,
3130
                             void *data, int *data_size,
3131
                             AVPacket *avpkt)
3132
{
3133
    const uint8_t *buf = avpkt->data;
3134
    int buf_size = avpkt->size;
3135
    H264Context *h = avctx->priv_data;
3136
    MpegEncContext *s = &h->s;
3137
    AVFrame *pict = data;
3138
    int buf_index;
3139

    
3140
    s->flags= avctx->flags;
3141
    s->flags2= avctx->flags2;
3142

    
3143
   /* end of stream, output what is still in the buffers */
3144
 out:
3145
    if (buf_size == 0) {
3146
        Picture *out;
3147
        int i, out_idx;
3148

    
3149
        s->current_picture_ptr = NULL;
3150

    
3151
//FIXME factorize this with the output code below
3152
        out = h->delayed_pic[0];
3153
        out_idx = 0;
3154
        for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
3155
            if(h->delayed_pic[i]->poc < out->poc){
3156
                out = h->delayed_pic[i];
3157
                out_idx = i;
3158
            }
3159

    
3160
        for(i=out_idx; h->delayed_pic[i]; i++)
3161
            h->delayed_pic[i] = h->delayed_pic[i+1];
3162

    
3163
        if(out){
3164
            *data_size = sizeof(AVFrame);
3165
            *pict= *(AVFrame*)out;
3166
        }
3167

    
3168
        return 0;
3169
    }
3170

    
3171
    buf_index=decode_nal_units(h, buf, buf_size);
3172
    if(buf_index < 0)
3173
        return -1;
3174

    
3175
    if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
3176
        buf_size = 0;
3177
        goto out;
3178
    }
3179

    
3180
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
3181
        if (avctx->skip_frame >= AVDISCARD_NONREF
3182
#if FF_API_HURRY_UP
3183
                || s->hurry_up
3184
#endif
3185
           )
3186
            return 0;
3187
        av_log(avctx, AV_LOG_ERROR, "no frame!\n");
3188
        return -1;
3189
    }
3190

    
3191
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
3192

    
3193
        if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h);
3194

    
3195
        field_end(h, 0);
3196

    
3197
        if (!h->next_output_pic) {
3198
            /* Wait for second field. */
3199
            *data_size = 0;
3200

    
3201
        } else {
3202
            *data_size = sizeof(AVFrame);
3203
            *pict = *(AVFrame*)h->next_output_pic;
3204
        }
3205
    }
3206

    
3207
    assert(pict->data[0] || !*data_size);
3208
    ff_print_debug_info(s, pict);
3209
//printf("out %d\n", (int)pict->data[0]);
3210

    
3211
    return get_consumed_bytes(s, buf_index, buf_size);
3212
}
3213
#if 0
3214
static inline void fill_mb_avail(H264Context *h){
3215
    MpegEncContext * const s = &h->s;
3216
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3217

3218
    if(s->mb_y){
3219
        h->mb_avail[0]= s->mb_x                 && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
3220
        h->mb_avail[1]=                            h->slice_table[mb_xy - s->mb_stride    ] == h->slice_num;
3221
        h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
3222
    }else{
3223
        h->mb_avail[0]=
3224
        h->mb_avail[1]=
3225
        h->mb_avail[2]= 0;
3226
    }
3227
    h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
3228
    h->mb_avail[4]= 1; //FIXME move out
3229
    h->mb_avail[5]= 0; //FIXME move out
3230
}
3231
#endif
3232

    
3233
#ifdef TEST
3234
#undef printf
3235
#undef random
3236
#define COUNT 8000
3237
#define SIZE (COUNT*40)
3238
int main(void){
3239
    int i;
3240
    uint8_t temp[SIZE];
3241
    PutBitContext pb;
3242
    GetBitContext gb;
3243
//    int int_temp[10000];
3244
    DSPContext dsp;
3245
    AVCodecContext avctx;
3246

    
3247
    dsputil_init(&dsp, &avctx);
3248

    
3249
    init_put_bits(&pb, temp, SIZE);
3250
    printf("testing unsigned exp golomb\n");
3251
    for(i=0; i<COUNT; i++){
3252
        START_TIMER
3253
        set_ue_golomb(&pb, i);
3254
        STOP_TIMER("set_ue_golomb");
3255
    }
3256
    flush_put_bits(&pb);
3257

    
3258
    init_get_bits(&gb, temp, 8*SIZE);
3259
    for(i=0; i<COUNT; i++){
3260
        int j, s;
3261

    
3262
        s= show_bits(&gb, 24);
3263

    
3264
        START_TIMER
3265
        j= get_ue_golomb(&gb);
3266
        if(j != i){
3267
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3268
//            return -1;
3269
        }
3270
        STOP_TIMER("get_ue_golomb");
3271
    }
3272

    
3273

    
3274
    init_put_bits(&pb, temp, SIZE);
3275
    printf("testing signed exp golomb\n");
3276
    for(i=0; i<COUNT; i++){
3277
        START_TIMER
3278
        set_se_golomb(&pb, i - COUNT/2);
3279
        STOP_TIMER("set_se_golomb");
3280
    }
3281
    flush_put_bits(&pb);
3282

    
3283
    init_get_bits(&gb, temp, 8*SIZE);
3284
    for(i=0; i<COUNT; i++){
3285
        int j, s;
3286

    
3287
        s= show_bits(&gb, 24);
3288

    
3289
        START_TIMER
3290
        j= get_se_golomb(&gb);
3291
        if(j != i - COUNT/2){
3292
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3293
//            return -1;
3294
        }
3295
        STOP_TIMER("get_se_golomb");
3296
    }
3297

    
3298
#if 0
3299
    printf("testing 4x4 (I)DCT\n");
3300

3301
    DCTELEM block[16];
3302
    uint8_t src[16], ref[16];
3303
    uint64_t error= 0, max_error=0;
3304

3305
    for(i=0; i<COUNT; i++){
3306
        int j;
3307
//        printf("%d %d %d\n", r1, r2, (r2-r1)*16);
3308
        for(j=0; j<16; j++){
3309
            ref[j]= random()%255;
3310
            src[j]= random()%255;
3311
        }
3312

3313
        h264_diff_dct_c(block, src, ref, 4);
3314

3315
        //normalize
3316
        for(j=0; j<16; j++){
3317
//            printf("%d ", block[j]);
3318
            block[j]= block[j]*4;
3319
            if(j&1) block[j]= (block[j]*4 + 2)/5;
3320
            if(j&4) block[j]= (block[j]*4 + 2)/5;
3321
        }
3322
//        printf("\n");
3323

3324
        h->h264dsp.h264_idct_add(ref, block, 4);
3325
/*        for(j=0; j<16; j++){
3326
            printf("%d ", ref[j]);
3327
        }
3328
        printf("\n");*/
3329

3330
        for(j=0; j<16; j++){
3331
            int diff= FFABS(src[j] - ref[j]);
3332

3333
            error+= diff*diff;
3334
            max_error= FFMAX(max_error, diff);
3335
        }
3336
    }
3337
    printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
3338
    printf("testing quantizer\n");
3339
    for(qp=0; qp<52; qp++){
3340
        for(i=0; i<16; i++)
3341
            src1_block[i]= src2_block[i]= random()%255;
3342

3343
    }
3344
    printf("Testing NAL layer\n");
3345

3346
    uint8_t bitstream[COUNT];
3347
    uint8_t nal[COUNT*2];
3348
    H264Context h;
3349
    memset(&h, 0, sizeof(H264Context));
3350

3351
    for(i=0; i<COUNT; i++){
3352
        int zeros= i;
3353
        int nal_length;
3354
        int consumed;
3355
        int out_length;
3356
        uint8_t *out;
3357
        int j;
3358

3359
        for(j=0; j<COUNT; j++){
3360
            bitstream[j]= (random() % 255) + 1;
3361
        }
3362

3363
        for(j=0; j<zeros; j++){
3364
            int pos= random() % COUNT;
3365
            while(bitstream[pos] == 0){
3366
                pos++;
3367
                pos %= COUNT;
3368
            }
3369
            bitstream[pos]=0;
3370
        }
3371

3372
        START_TIMER
3373

3374
        nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
3375
        if(nal_length<0){
3376
            printf("encoding failed\n");
3377
            return -1;
3378
        }
3379

3380
        out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
3381

3382
        STOP_TIMER("NAL")
3383

3384
        if(out_length != COUNT){
3385
            printf("incorrect length %d %d\n", out_length, COUNT);
3386
            return -1;
3387
        }
3388

3389
        if(consumed != nal_length){
3390
            printf("incorrect consumed length %d %d\n", nal_length, consumed);
3391
            return -1;
3392
        }
3393

3394
        if(memcmp(bitstream, out, COUNT)){
3395
            printf("mismatch\n");
3396
            return -1;
3397
        }
3398
    }
3399
#endif
3400

    
3401
    printf("Testing RBSP\n");
3402

    
3403

    
3404
    return 0;
3405
}
3406
#endif /* TEST */
3407

    
3408

    
3409
av_cold void ff_h264_free_context(H264Context *h)
3410
{
3411
    int i;
3412

    
3413
    free_tables(h, 1); //FIXME cleanup init stuff perhaps
3414

    
3415
    for(i = 0; i < MAX_SPS_COUNT; i++)
3416
        av_freep(h->sps_buffers + i);
3417

    
3418
    for(i = 0; i < MAX_PPS_COUNT; i++)
3419
        av_freep(h->pps_buffers + i);
3420
}
3421

    
3422
av_cold int ff_h264_decode_end(AVCodecContext *avctx)
3423
{
3424
    H264Context *h = avctx->priv_data;
3425
    MpegEncContext *s = &h->s;
3426

    
3427
    ff_h264_free_context(h);
3428

    
3429
    MPV_common_end(s);
3430

    
3431
//    memset(h, 0, sizeof(H264Context));
3432

    
3433
    return 0;
3434
}
3435

    
3436
static const AVProfile profiles[] = {
3437
    { FF_PROFILE_H264_BASELINE,             "Baseline"              },
3438
    { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
3439
    { FF_PROFILE_H264_MAIN,                 "Main"                  },
3440
    { FF_PROFILE_H264_EXTENDED,             "Extended"              },
3441
    { FF_PROFILE_H264_HIGH,                 "High"                  },
3442
    { FF_PROFILE_H264_HIGH_10,              "High 10"               },
3443
    { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
3444
    { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
3445
    { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
3446
    { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
3447
    { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
3448
    { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
3449
    { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
3450
    { FF_PROFILE_UNKNOWN },
3451
};
3452

    
3453
AVCodec ff_h264_decoder = {
3454
    "h264",
3455
    AVMEDIA_TYPE_VIDEO,
3456
    CODEC_ID_H264,
3457
    sizeof(H264Context),
3458
    ff_h264_decode_init,
3459
    NULL,
3460
    ff_h264_decode_end,
3461
    decode_frame,
3462
    /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
3463
    .flush= flush_dpb,
3464
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
3465
    .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
3466
    .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
3467
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3468
};
3469

    
3470
#if CONFIG_H264_VDPAU_DECODER
3471
AVCodec ff_h264_vdpau_decoder = {
3472
    "h264_vdpau",
3473
    AVMEDIA_TYPE_VIDEO,
3474
    CODEC_ID_H264,
3475
    sizeof(H264Context),
3476
    ff_h264_decode_init,
3477
    NULL,
3478
    ff_h264_decode_end,
3479
    decode_frame,
3480
    CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
3481
    .flush= flush_dpb,
3482
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
3483
    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
3484
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3485
};
3486
#endif