Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ 0e5758d1

History | View | Annotate | Download (126 KB)

1
/*
2
 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3
 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
/**
23
 * @file
24
 * H.264 / AVC / MPEG4 part10 codec.
25
 * @author Michael Niedermayer <michaelni@gmx.at>
26
 */
27

    
28
#include "libavutil/imgutils.h"
29
#include "internal.h"
30
#include "dsputil.h"
31
#include "avcodec.h"
32
#include "mpegvideo.h"
33
#include "h264.h"
34
#include "h264data.h"
35
#include "h264_mvpred.h"
36
#include "golomb.h"
37
#include "mathops.h"
38
#include "rectangle.h"
39
#include "thread.h"
40
#include "vdpau_internal.h"
41
#include "libavutil/avassert.h"
42

    
43
#include "cabac.h"
44

    
45
//#undef NDEBUG
46
#include <assert.h>
47

    
48
static const uint8_t rem6[QP_MAX_MAX+1]={
49
0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
50
};
51

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

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

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

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

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

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

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

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

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

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

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

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

    
143
    return mode;
144
}
145

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

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

    
155
    src++; length--;
156

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

    
186
    if(i>=length-1){ //no escaped 0
187
        *dst_length= length;
188
        *consumed= length+1; //+1 for the header
189
        return src;
190
    }
191

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

    
196
    if (dst == NULL){
197
        return NULL;
198
    }
199

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

    
218
        dst[di++]= src[si++];
219
    }
220
    while(si<length)
221
        dst[di++]= src[si++];
222
nsc:
223

    
224
    memset(dst+di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
225

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

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

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

    
242
    for(r=1; r<9; r++){
243
        if(v&1) return r;
244
        v>>=1;
245
    }
246
    return 0;
247
}
248

    
249
#if 0
250
/**
251
 * DCT transforms the 16 dc values.
252
 * @param qp quantization parameter ??? FIXME
253
 */
254
static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
255
//    const int qmul= dequant_coeff[qp][0];
256
    int i;
257
    int temp[16]; //FIXME check if this is a good idea
258
    static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
259
    static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
260

261
    for(i=0; i<4; i++){
262
        const int offset= y_offset[i];
263
        const int z0= block[offset+stride*0] + block[offset+stride*4];
264
        const int z1= block[offset+stride*0] - block[offset+stride*4];
265
        const int z2= block[offset+stride*1] - block[offset+stride*5];
266
        const int z3= block[offset+stride*1] + block[offset+stride*5];
267

268
        temp[4*i+0]= z0+z3;
269
        temp[4*i+1]= z1+z2;
270
        temp[4*i+2]= z1-z2;
271
        temp[4*i+3]= z0-z3;
272
    }
273

274
    for(i=0; i<4; i++){
275
        const int offset= x_offset[i];
276
        const int z0= temp[4*0+i] + temp[4*2+i];
277
        const int z1= temp[4*0+i] - temp[4*2+i];
278
        const int z2= temp[4*1+i] - temp[4*3+i];
279
        const int z3= temp[4*1+i] + temp[4*3+i];
280

281
        block[stride*0 +offset]= (z0 + z3)>>1;
282
        block[stride*2 +offset]= (z1 + z2)>>1;
283
        block[stride*8 +offset]= (z1 - z2)>>1;
284
        block[stride*10+offset]= (z0 - z3)>>1;
285
    }
286
}
287
#endif
288

    
289
#undef xStride
290
#undef stride
291

    
292
#if 0
293
static void chroma_dc_dct_c(DCTELEM *block){
294
    const int stride= 16*2;
295
    const int xStride= 16;
296
    int a,b,c,d,e;
297

298
    a= block[stride*0 + xStride*0];
299
    b= block[stride*0 + xStride*1];
300
    c= block[stride*1 + xStride*0];
301
    d= block[stride*1 + xStride*1];
302

303
    e= a-b;
304
    a= a+b;
305
    b= c-d;
306
    c= c+d;
307

308
    block[stride*0 + xStride*0]= (a+c);
309
    block[stride*0 + xStride*1]= (e+b);
310
    block[stride*1 + xStride*0]= (a-c);
311
    block[stride*1 + xStride*1]= (e-b);
312
}
313
#endif
314

    
315

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

    
330
    av_freep(&h->mb2b_xy);
331
    av_freep(&h->mb2br_xy);
332

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

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

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

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

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

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

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

    
413

    
414
int ff_h264_alloc_tables(H264Context *h){
415
    MpegEncContext * const s = &h->s;
416
    const int big_mb_num= s->mb_stride * (s->mb_height+1);
417
    const int row_mb_num= 2*s->mb_stride*s->avctx->thread_count;
418
    int x,y;
419

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

    
422
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count    , big_mb_num * 32 * sizeof(uint8_t), fail)
423
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
424
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
425

    
426
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
427
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
428
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
429
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
430
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
431

    
432
    memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(*h->slice_table_base));
433
    h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
434

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

    
442
            h->mb2b_xy [mb_xy]= b_xy;
443
            h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
444
        }
445
    }
446

    
447
    s->obmc_scratchpad = NULL;
448

    
449
    if(!h->dequant4_coeff[0])
450
        init_dequant_tables(h);
451

    
452
    return 0;
453
fail:
454
    free_tables(h, 1);
455
    return -1;
456
}
457

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

    
475
    dst->s.obmc_scratchpad = NULL;
476
    ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma);
477
}
478

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

    
487
    h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
488
    h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
489

    
490
    return 0;
491
fail:
492
    return -1; // free_tables will clean up for us
493
}
494

    
495
static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
496

    
497
static av_cold void common_init(H264Context *h){
498
    MpegEncContext * const s = &h->s;
499

    
500
    s->width = s->avctx->width;
501
    s->height = s->avctx->height;
502
    s->codec_id= s->avctx->codec->id;
503

    
504
    ff_h264dsp_init(&h->h264dsp, 8);
505
    ff_h264_pred_init(&h->hpc, s->codec_id, 8);
506

    
507
    h->dequant_coeff_pps= -1;
508
    s->unrestricted_mv=1;
509
    s->decode=1; //FIXME
510

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

    
513
    memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
514
    memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
515
}
516

    
517
int ff_h264_decode_extradata(H264Context *h)
518
{
519
    AVCodecContext *avctx = h->s.avctx;
520

    
521
    if(*(char *)avctx->extradata == 1){
522
        int i, cnt, nalsize;
523
        unsigned char *p = avctx->extradata;
524

    
525
        h->is_avc = 1;
526

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

    
565
av_cold int ff_h264_decode_init(AVCodecContext *avctx){
566
    H264Context *h= avctx->priv_data;
567
    MpegEncContext * const s = &h->s;
568

    
569
    MPV_decode_defaults(s);
570

    
571
    s->avctx = avctx;
572
    common_init(h);
573

    
574
    s->out_format = FMT_H264;
575
    s->workaround_bugs= avctx->workaround_bugs;
576

    
577
    // set defaults
578
//    s->decode_mb= ff_h263_decode_mb;
579
    s->quarter_sample = 1;
580
    if(!avctx->has_b_frames)
581
    s->low_delay= 1;
582

    
583
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
584

    
585
    ff_h264_decode_init_vlc();
586

    
587
    h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
588
    h->pixel_shift = 0;
589

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

    
602
    if(avctx->extradata_size > 0 && avctx->extradata &&
603
        ff_h264_decode_extradata(h))
604
        return -1;
605

    
606
    if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
607
        s->avctx->has_b_frames = h->sps.num_reorder_frames;
608
        s->low_delay = 0;
609
    }
610

    
611
    return 0;
612
}
613

    
614
static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
615
{
616
    int i;
617

    
618
    for (i=0; i<count; i++){
619
        to[i] = REBASE_PICTURE(from[i], new_base, old_base);
620
    }
621
}
622

    
623
static void copy_parameter_set(void **to, void **from, int count, int size)
624
{
625
    int i;
626

    
627
    for (i=0; i<count; i++){
628
        if (to[i] && !from[i]) av_freep(&to[i]);
629
        else if (from[i] && !to[i]) to[i] = av_malloc(size);
630

    
631
        if (from[i]) memcpy(to[i], from[i], size);
632
    }
633
}
634

    
635
static int decode_init_thread_copy(AVCodecContext *avctx){
636
    H264Context *h= avctx->priv_data;
637

    
638
    if (!avctx->is_copy) return 0;
639
    memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
640
    memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
641

    
642
    return 0;
643
}
644

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

    
652
    if(dst == src || !s1->context_initialized) return 0;
653

    
654
    err = ff_mpeg_update_thread_context(dst, src);
655
    if(err) return err;
656

    
657
    //FIXME handle width/height changing
658
    if(!inited){
659
        for(i = 0; i < MAX_SPS_COUNT; i++)
660
            av_freep(h->sps_buffers + i);
661

    
662
        for(i = 0; i < MAX_PPS_COUNT; i++)
663
            av_freep(h->pps_buffers + i);
664

    
665
        memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
666
        memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
667
        memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
668
        ff_h264_alloc_tables(h);
669
        context_init(h);
670

    
671
        for(i=0; i<2; i++){
672
            h->rbsp_buffer[i] = NULL;
673
            h->rbsp_buffer_size[i] = 0;
674
        }
675

    
676
        h->thread_context[0] = h;
677

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

    
682
        s->dsp.clear_blocks(h->mb);
683
    }
684

    
685
    //extradata/NAL handling
686
    h->is_avc          = h1->is_avc;
687

    
688
    //SPS/PPS
689
    copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
690
    h->sps             = h1->sps;
691
    copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
692
    h->pps             = h1->pps;
693

    
694
    //Dequantization matrices
695
    //FIXME these are big - can they be only copied when PPS changes?
696
    copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
697

    
698
    for(i=0; i<6; i++)
699
        h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
700

    
701
    for(i=0; i<2; i++)
702
        h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
703

    
704
    h->dequant_coeff_pps = h1->dequant_coeff_pps;
705

    
706
    //POC timing
707
    copy_fields(h, h1, poc_lsb, redundant_pic_count);
708

    
709
    //reference lists
710
    copy_fields(h, h1, ref_count, intra_gb);
711
    copy_fields(h, h1, short_ref, cabac_init_idc);
712

    
713
    copy_picture_range(h->short_ref,   h1->short_ref,   32, s, s1);
714
    copy_picture_range(h->long_ref,    h1->long_ref,    32, s, s1);
715
    copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
716

    
717
    h->last_slice_type = h1->last_slice_type;
718

    
719
    if(!s->current_picture_ptr) return 0;
720

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

    
730
    return 0;
731
}
732

    
733
int ff_h264_frame_start(H264Context *h){
734
    MpegEncContext * const s = &h->s;
735
    int i;
736

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

    
749
    assert(s->linesize && s->uvlinesize);
750

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

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

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

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

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

    
782
    s->current_picture_ptr->field_poc[0]=
783
    s->current_picture_ptr->field_poc[1]= INT_MAX;
784

    
785
    h->next_output_pic = NULL;
786

    
787
    assert(s->current_picture_ptr->long_ref==0);
788

    
789
    return 0;
790
}
791

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

    
804
    s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
805
    s->current_picture_ptr->pict_type= s->pict_type;
806

    
807
    if (h->next_output_pic) return;
808

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

    
817
    cur->interlaced_frame = 0;
818
    cur->repeat_pict = 0;
819

    
820
    /* Signal interlacing information externally. */
821
    /* Prioritize picture timing SEI information over used decoding process if it exists. */
822

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

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

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

    
880
    //FIXME do something with unavailable reference frames
881

    
882
    /* Sort B-frames into display order */
883

    
884
    if(h->sps.bitstream_restriction_flag
885
       && s->avctx->has_b_frames < h->sps.num_reorder_frames){
886
        s->avctx->has_b_frames = h->sps.num_reorder_frames;
887
        s->low_delay = 0;
888
    }
889

    
890
    if(   s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
891
       && !h->sps.bitstream_restriction_flag){
892
        s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;
893
        s->low_delay= 0;
894
    }
895

    
896
    pics = 0;
897
    while(h->delayed_pic[pics]) pics++;
898

    
899
    assert(pics <= MAX_DELAYED_PIC_COUNT);
900

    
901
    h->delayed_pic[pics++] = cur;
902
    if(cur->reference == 0)
903
        cur->reference = DELAYED_PIC_REF;
904

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

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

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

    
944
    ff_thread_finish_setup(s->avctx);
945
}
946

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

    
952
    src_y  -=   linesize;
953
    src_cb -= uvlinesize;
954
    src_cr -= uvlinesize;
955

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

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

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

    
997
static inline void xchg_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg, int simple, int pixel_shift){
998
    MpegEncContext * const s = &h->s;
999
    int deblock_left;
1000
    int deblock_top;
1001
    int top_idx = 1;
1002
    uint8_t *top_border_m1;
1003
    uint8_t *top_border;
1004

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

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

    
1022
    src_y  -=   linesize + 1 + pixel_shift;
1023
    src_cb -= uvlinesize + 1 + pixel_shift;
1024
    src_cr -= uvlinesize + 1 + pixel_shift;
1025

    
1026
    top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
1027
    top_border    = h->top_borders[top_idx][s->mb_x];
1028

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

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

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

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

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

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

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

    
1100
    h->list_counts[mb_xy]= h->list_count;
1101

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

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

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

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

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

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

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

    
1282

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

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

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

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

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

    
1390
    if (is_complex || h->pixel_shift)
1391
        hl_decode_mb_complex(h);
1392
    else{
1393
        hl_decode_mb_simple8(h);
1394
    }
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) {
2051
            if (ff_h264_frame_start(h) < 0) {
2052
                s0->first_field = 0;
2053
                return -1;
2054
            }
2055
        } else {
2056
            ff_release_unused_pictures(s, 0);
2057
        }
2058
    }
2059
    if(h != h0)
2060
        clone_slice(h, h0);
2061

    
2062
    s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
2063

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

    
2076
    if(s->picture_structure==PICT_FRAME){
2077
        h->curr_pic_num=   h->frame_num;
2078
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
2079
    }else{
2080
        h->curr_pic_num= 2*h->frame_num + 1;
2081
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
2082
    }
2083

    
2084
    if(h->nal_unit_type == NAL_IDR_SLICE){
2085
        get_ue_golomb(&s->gb); /* idr_pic_id */
2086
    }
2087

    
2088
    if(h->sps.poc_type==0){
2089
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2090

    
2091
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
2092
            h->delta_poc_bottom= get_se_golomb(&s->gb);
2093
        }
2094
    }
2095

    
2096
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
2097
        h->delta_poc[0]= get_se_golomb(&s->gb);
2098

    
2099
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
2100
            h->delta_poc[1]= get_se_golomb(&s->gb);
2101
    }
2102

    
2103
    init_poc(h);
2104

    
2105
    if(h->pps.redundant_pic_cnt_present){
2106
        h->redundant_pic_count= get_ue_golomb(&s->gb);
2107
    }
2108

    
2109
    //set defaults, might be overridden a few lines later
2110
    h->ref_count[0]= h->pps.ref_count[0];
2111
    h->ref_count[1]= h->pps.ref_count[1];
2112

    
2113
    if(h->slice_type_nos != FF_I_TYPE){
2114
        if(h->slice_type_nos == FF_B_TYPE){
2115
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
2116
        }
2117
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
2118

    
2119
        if(num_ref_idx_active_override_flag){
2120
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
2121
            if(h->slice_type_nos==FF_B_TYPE)
2122
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
2123

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

    
2137
    if(!default_ref_list_done){
2138
        ff_h264_fill_default_ref_list(h);
2139
    }
2140

    
2141
    if(h->slice_type_nos!=FF_I_TYPE && ff_h264_decode_ref_pic_list_reordering(h) < 0)
2142
        return -1;
2143

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

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

    
2166
    if(h->nal_ref_idc)
2167
        ff_h264_decode_ref_pic_marking(h0, &s->gb);
2168

    
2169
    if(FRAME_MBAFF){
2170
        ff_h264_fill_mbaff_ref_list(h);
2171

    
2172
        if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
2173
            implicit_weight_table(h, 0);
2174
            implicit_weight_table(h, 1);
2175
        }
2176
    }
2177

    
2178
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2179
        ff_h264_direct_dist_scale_factor(h);
2180
    ff_h264_direct_ref_list_init(h);
2181

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

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

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

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

    
2232
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
2233
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
2234
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
2235
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
2236
        h->deblocking_filter= 0;
2237

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

    
2257
#if 0 //FMO
2258
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
2259
        slice_group_change_cycle= get_bits(&s->gb, ?);
2260
#endif
2261

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

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

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

    
2301
    //FIXME: fix draw_edges+PAFF+frame threads
2302
    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;
2303
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
2304

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

    
2322
    return 0;
2323
}
2324

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

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

    
2347
    top_xy     = mb_xy  - (s->mb_stride << MB_FIELD);
2348

    
2349
    //FIXME deblocking could skip the intra and nnz parts.
2350

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

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

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

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

    
2405
    if(IS_INTRA(mb_type))
2406
        return 0;
2407

    
2408
    AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
2409
    AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
2410
    AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
2411
    AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
2412
    AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
2413

    
2414
    h->cbp= h->cbp_table[mb_xy];
2415

    
2416
    {
2417
        int list;
2418
        for(list=0; list<h->list_count; list++){
2419
            int8_t *ref;
2420
            int y, b_stride;
2421
            int16_t (*mv_dst)[2];
2422
            int16_t (*mv_src)[2];
2423

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

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

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

    
2450
        }
2451
    }
2452

    
2453

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

    
2467
    if(left_type[0]){
2468
        h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
2469
        h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
2470
        h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
2471
        h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
2472
    }
2473

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

    
2491
        if(IS_8x8DCT(mb_type)){
2492
            h->non_zero_count_cache[scan8[0   ]]= h->non_zero_count_cache[scan8[1   ]]=
2493
            h->non_zero_count_cache[scan8[2   ]]= h->non_zero_count_cache[scan8[3   ]]= h->cbp & 1;
2494

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

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

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

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

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

    
2550
    return 0;
2551
}
2552

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

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

    
2571
                if(FRAME_MBAFF)
2572
                    h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2573

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

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

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

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

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

    
2635
    if (h->deblocking_filter) {
2636
        if((top + height) >= pic_height)
2637
            height += deblock_border;
2638

    
2639
        top -= deblock_border;
2640
    }
2641

    
2642
    if (top >= pic_height || (top + height) < h->emu_edge_height)
2643
        return;
2644

    
2645
    height = FFMIN(height, pic_height - top);
2646
    if (top < h->emu_edge_height) {
2647
        height = top+height;
2648
        top = 0;
2649
    }
2650

    
2651
    ff_draw_horiz_band(s, top, height);
2652

    
2653
    if (s->dropable) return;
2654

    
2655
    ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
2656
                             s->picture_structure==PICT_BOTTOM_FIELD);
2657
}
2658

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

    
2664
    s->mb_skip_run= -1;
2665

    
2666
    h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
2667
                    (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
2668

    
2669
    if( h->pps.cabac ) {
2670
        /* realign */
2671
        align_get_bits( &s->gb );
2672

    
2673
        /* init cabac */
2674
        ff_init_cabac_states( &h->cabac);
2675
        ff_init_cabac_decoder( &h->cabac,
2676
                               s->gb.buffer + get_bits_count(&s->gb)/8,
2677
                               (get_bits_left(&s->gb) + 7)/8);
2678

    
2679
        ff_h264_init_cabac_states(h);
2680

    
2681
        for(;;){
2682
//START_TIMER
2683
            int ret = ff_h264_decode_mb_cabac(h);
2684
            int eos;
2685
//STOP_TIMER("decode_mb_cabac")
2686

    
2687
            if(ret>=0) ff_h264_hl_decode_mb(h);
2688

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

    
2692
                ret = ff_h264_decode_mb_cabac(h);
2693

    
2694
                if(ret>=0) ff_h264_hl_decode_mb(h);
2695
                s->mb_y--;
2696
            }
2697
            eos = get_cabac_terminate( &h->cabac );
2698

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

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

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

    
2730
    } else {
2731
        for(;;){
2732
            int ret = ff_h264_decode_mb_cavlc(h);
2733

    
2734
            if(ret>=0) ff_h264_hl_decode_mb(h);
2735

    
2736
            if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
2737
                s->mb_y++;
2738
                ret = ff_h264_decode_mb_cavlc(h);
2739

    
2740
                if(ret>=0) ff_h264_hl_decode_mb(h);
2741
                s->mb_y--;
2742
            }
2743

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

    
2748
                return -1;
2749
            }
2750

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

    
2764
                    if(   get_bits_count(&s->gb) == s->gb.size_in_bits
2765
                       || get_bits_count(&s->gb) <  s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
2766
                        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);
2767

    
2768
                        return 0;
2769
                    }else{
2770
                        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);
2771

    
2772
                        return -1;
2773
                    }
2774
                }
2775
            }
2776

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

    
2784
                    return 0;
2785
                }else{
2786
                    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);
2787

    
2788
                    return -1;
2789
                }
2790
            }
2791
        }
2792
    }
2793

    
2794
#if 0
2795
    for(;s->mb_y < s->mb_height; s->mb_y++){
2796
        for(;s->mb_x < s->mb_width; s->mb_x++){
2797
            int ret= decode_mb(h);
2798

2799
            ff_h264_hl_decode_mb(h);
2800

2801
            if(ret<0){
2802
                av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
2803
                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);
2804

2805
                return -1;
2806
            }
2807

2808
            if(++s->mb_x >= s->mb_width){
2809
                s->mb_x=0;
2810
                if(++s->mb_y >= s->mb_height){
2811
                    if(get_bits_count(s->gb) == s->gb.size_in_bits){
2812
                        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);
2813

2814
                        return 0;
2815
                    }else{
2816
                        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);
2817

2818
                        return -1;
2819
                    }
2820
                }
2821
            }
2822

2823
            if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
2824
                if(get_bits_count(s->gb) == s->gb.size_in_bits){
2825
                    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);
2826

2827
                    return 0;
2828
                }else{
2829
                    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);
2830

2831
                    return -1;
2832
                }
2833
            }
2834
        }
2835
        s->mb_x=0;
2836
        ff_draw_horiz_band(s, 16*s->mb_y, 16);
2837
    }
2838
#endif
2839
    return -1; //not reached
2840
}
2841

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

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

    
2868
        avctx->execute(avctx, (void *)decode_slice,
2869
                       h->thread_context, NULL, context_count, sizeof(void*));
2870

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

    
2882

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

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

    
2905
    for(;;){
2906
        int consumed;
2907
        int dst_length;
2908
        int bit_length;
2909
        const uint8_t *ptr;
2910
        int i, nalsize = 0;
2911
        int err;
2912

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

    
2931
            if(buf_index+3 >= buf_size) break;
2932

    
2933
            buf_index+=3;
2934
            if(buf_index >= next_avc) continue;
2935
        }
2936

    
2937
        hx = h->thread_context[context_count];
2938

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

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

    
2954
        if(s->avctx->debug&FF_DEBUG_STARTCODE){
2955
            av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d/%d at %d/%d length %d\n", hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length);
2956
        }
2957

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

    
2962
        buf_index += consumed;
2963

    
2964
        //FIXME do not discard SEI id
2965
        if(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
               && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
3003
               && (avctx->skip_frame < AVDISCARD_BIDIR  || hx->slice_type_nos!=FF_B_TYPE)
3004
               && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
3005
               && avctx->skip_frame < AVDISCARD_ALL){
3006
                if(avctx->hwaccel) {
3007
                    if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
3008
                        return -1;
3009
                }else
3010
                if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
3011
                    static const uint8_t start_code[] = {0x00, 0x00, 0x01};
3012
                    ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
3013
                    ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
3014
                }else
3015
                    context_count++;
3016
            }
3017
            break;
3018
        case NAL_DPA:
3019
            init_get_bits(&hx->s.gb, ptr, bit_length);
3020
            hx->intra_gb_ptr=
3021
            hx->inter_gb_ptr= NULL;
3022

    
3023
            if ((err = decode_slice_header(hx, h)) < 0)
3024
                break;
3025

    
3026
            hx->s.data_partitioning = 1;
3027

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

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

    
3053
            if(s->flags& CODEC_FLAG_LOW_DELAY ||
3054
              (h->sps.bitstream_restriction_flag && !h->sps.num_reorder_frames))
3055
                s->low_delay=1;
3056

    
3057
            if(avctx->has_b_frames < 2)
3058
                avctx->has_b_frames= !s->low_delay;
3059

    
3060
            if (avctx->bits_per_raw_sample != h->sps.bit_depth_luma) {
3061
                if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
3062
                    avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3063
                    h->pixel_shift = h->sps.bit_depth_luma/9;
3064

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

    
3077
            ff_h264_decode_picture_parameter_set(h, bit_length);
3078

    
3079
            break;
3080
        case NAL_AUD:
3081
        case NAL_END_SEQUENCE:
3082
        case NAL_END_STREAM:
3083
        case NAL_FILLER_DATA:
3084
        case NAL_SPS_EXT:
3085
        case NAL_AUXILIARY_SLICE:
3086
            break;
3087
        default:
3088
            av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
3089
        }
3090

    
3091
        if(context_count == h->max_contexts) {
3092
            execute_decode_slices(h, context_count);
3093
            context_count = 0;
3094
        }
3095

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

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

    
3121
        return pos;
3122
}
3123

    
3124
static int decode_frame(AVCodecContext *avctx,
3125
                             void *data, int *data_size,
3126
                             AVPacket *avpkt)
3127
{
3128
    const uint8_t *buf = avpkt->data;
3129
    int buf_size = avpkt->size;
3130
    H264Context *h = avctx->priv_data;
3131
    MpegEncContext *s = &h->s;
3132
    AVFrame *pict = data;
3133
    int buf_index;
3134

    
3135
    s->flags= avctx->flags;
3136
    s->flags2= avctx->flags2;
3137

    
3138
   /* end of stream, output what is still in the buffers */
3139
 out:
3140
    if (buf_size == 0) {
3141
        Picture *out;
3142
        int i, out_idx;
3143

    
3144
        s->current_picture_ptr = NULL;
3145

    
3146
//FIXME factorize this with the output code below
3147
        out = h->delayed_pic[0];
3148
        out_idx = 0;
3149
        for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
3150
            if(h->delayed_pic[i]->poc < out->poc){
3151
                out = h->delayed_pic[i];
3152
                out_idx = i;
3153
            }
3154

    
3155
        for(i=out_idx; h->delayed_pic[i]; i++)
3156
            h->delayed_pic[i] = h->delayed_pic[i+1];
3157

    
3158
        if(out){
3159
            *data_size = sizeof(AVFrame);
3160
            *pict= *(AVFrame*)out;
3161
        }
3162

    
3163
        return 0;
3164
    }
3165

    
3166
    buf_index=decode_nal_units(h, buf, buf_size);
3167
    if(buf_index < 0)
3168
        return -1;
3169

    
3170
    if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
3171
        buf_size = 0;
3172
        goto out;
3173
    }
3174

    
3175
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
3176
        if (avctx->skip_frame >= AVDISCARD_NONREF)
3177
            return 0;
3178
        av_log(avctx, AV_LOG_ERROR, "no frame!\n");
3179
        return -1;
3180
    }
3181

    
3182
    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
3183

    
3184
        if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h);
3185

    
3186
        field_end(h, 0);
3187

    
3188
        if (!h->next_output_pic) {
3189
            /* Wait for second field. */
3190
            *data_size = 0;
3191

    
3192
        } else {
3193
            *data_size = sizeof(AVFrame);
3194
            *pict = *(AVFrame*)h->next_output_pic;
3195
        }
3196
    }
3197

    
3198
    assert(pict->data[0] || !*data_size);
3199
    ff_print_debug_info(s, pict);
3200
//printf("out %d\n", (int)pict->data[0]);
3201

    
3202
    return get_consumed_bytes(s, buf_index, buf_size);
3203
}
3204
#if 0
3205
static inline void fill_mb_avail(H264Context *h){
3206
    MpegEncContext * const s = &h->s;
3207
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3208

3209
    if(s->mb_y){
3210
        h->mb_avail[0]= s->mb_x                 && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
3211
        h->mb_avail[1]=                            h->slice_table[mb_xy - s->mb_stride    ] == h->slice_num;
3212
        h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
3213
    }else{
3214
        h->mb_avail[0]=
3215
        h->mb_avail[1]=
3216
        h->mb_avail[2]= 0;
3217
    }
3218
    h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
3219
    h->mb_avail[4]= 1; //FIXME move out
3220
    h->mb_avail[5]= 0; //FIXME move out
3221
}
3222
#endif
3223

    
3224
#ifdef TEST
3225
#undef printf
3226
#undef random
3227
#define COUNT 8000
3228
#define SIZE (COUNT*40)
3229
int main(void){
3230
    int i;
3231
    uint8_t temp[SIZE];
3232
    PutBitContext pb;
3233
    GetBitContext gb;
3234
//    int int_temp[10000];
3235
    DSPContext dsp;
3236
    AVCodecContext avctx;
3237

    
3238
    dsputil_init(&dsp, &avctx);
3239

    
3240
    init_put_bits(&pb, temp, SIZE);
3241
    printf("testing unsigned exp golomb\n");
3242
    for(i=0; i<COUNT; i++){
3243
        START_TIMER
3244
        set_ue_golomb(&pb, i);
3245
        STOP_TIMER("set_ue_golomb");
3246
    }
3247
    flush_put_bits(&pb);
3248

    
3249
    init_get_bits(&gb, temp, 8*SIZE);
3250
    for(i=0; i<COUNT; i++){
3251
        int j, s;
3252

    
3253
        s= show_bits(&gb, 24);
3254

    
3255
        START_TIMER
3256
        j= get_ue_golomb(&gb);
3257
        if(j != i){
3258
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3259
//            return -1;
3260
        }
3261
        STOP_TIMER("get_ue_golomb");
3262
    }
3263

    
3264

    
3265
    init_put_bits(&pb, temp, SIZE);
3266
    printf("testing signed exp golomb\n");
3267
    for(i=0; i<COUNT; i++){
3268
        START_TIMER
3269
        set_se_golomb(&pb, i - COUNT/2);
3270
        STOP_TIMER("set_se_golomb");
3271
    }
3272
    flush_put_bits(&pb);
3273

    
3274
    init_get_bits(&gb, temp, 8*SIZE);
3275
    for(i=0; i<COUNT; i++){
3276
        int j, s;
3277

    
3278
        s= show_bits(&gb, 24);
3279

    
3280
        START_TIMER
3281
        j= get_se_golomb(&gb);
3282
        if(j != i - COUNT/2){
3283
            printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
3284
//            return -1;
3285
        }
3286
        STOP_TIMER("get_se_golomb");
3287
    }
3288

    
3289
#if 0
3290
    printf("testing 4x4 (I)DCT\n");
3291

3292
    DCTELEM block[16];
3293
    uint8_t src[16], ref[16];
3294
    uint64_t error= 0, max_error=0;
3295

3296
    for(i=0; i<COUNT; i++){
3297
        int j;
3298
//        printf("%d %d %d\n", r1, r2, (r2-r1)*16);
3299
        for(j=0; j<16; j++){
3300
            ref[j]= random()%255;
3301
            src[j]= random()%255;
3302
        }
3303

3304
        h264_diff_dct_c(block, src, ref, 4);
3305

3306
        //normalize
3307
        for(j=0; j<16; j++){
3308
//            printf("%d ", block[j]);
3309
            block[j]= block[j]*4;
3310
            if(j&1) block[j]= (block[j]*4 + 2)/5;
3311
            if(j&4) block[j]= (block[j]*4 + 2)/5;
3312
        }
3313
//        printf("\n");
3314

3315
        h->h264dsp.h264_idct_add(ref, block, 4);
3316
/*        for(j=0; j<16; j++){
3317
            printf("%d ", ref[j]);
3318
        }
3319
        printf("\n");*/
3320

3321
        for(j=0; j<16; j++){
3322
            int diff= FFABS(src[j] - ref[j]);
3323

3324
            error+= diff*diff;
3325
            max_error= FFMAX(max_error, diff);
3326
        }
3327
    }
3328
    printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
3329
    printf("testing quantizer\n");
3330
    for(qp=0; qp<52; qp++){
3331
        for(i=0; i<16; i++)
3332
            src1_block[i]= src2_block[i]= random()%255;
3333

3334
    }
3335
    printf("Testing NAL layer\n");
3336

3337
    uint8_t bitstream[COUNT];
3338
    uint8_t nal[COUNT*2];
3339
    H264Context h;
3340
    memset(&h, 0, sizeof(H264Context));
3341

3342
    for(i=0; i<COUNT; i++){
3343
        int zeros= i;
3344
        int nal_length;
3345
        int consumed;
3346
        int out_length;
3347
        uint8_t *out;
3348
        int j;
3349

3350
        for(j=0; j<COUNT; j++){
3351
            bitstream[j]= (random() % 255) + 1;
3352
        }
3353

3354
        for(j=0; j<zeros; j++){
3355
            int pos= random() % COUNT;
3356
            while(bitstream[pos] == 0){
3357
                pos++;
3358
                pos %= COUNT;
3359
            }
3360
            bitstream[pos]=0;
3361
        }
3362

3363
        START_TIMER
3364

3365
        nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
3366
        if(nal_length<0){
3367
            printf("encoding failed\n");
3368
            return -1;
3369
        }
3370

3371
        out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
3372

3373
        STOP_TIMER("NAL")
3374

3375
        if(out_length != COUNT){
3376
            printf("incorrect length %d %d\n", out_length, COUNT);
3377
            return -1;
3378
        }
3379

3380
        if(consumed != nal_length){
3381
            printf("incorrect consumed length %d %d\n", nal_length, consumed);
3382
            return -1;
3383
        }
3384

3385
        if(memcmp(bitstream, out, COUNT)){
3386
            printf("mismatch\n");
3387
            return -1;
3388
        }
3389
    }
3390
#endif
3391

    
3392
    printf("Testing RBSP\n");
3393

    
3394

    
3395
    return 0;
3396
}
3397
#endif /* TEST */
3398

    
3399

    
3400
av_cold void ff_h264_free_context(H264Context *h)
3401
{
3402
    int i;
3403

    
3404
    free_tables(h, 1); //FIXME cleanup init stuff perhaps
3405

    
3406
    for(i = 0; i < MAX_SPS_COUNT; i++)
3407
        av_freep(h->sps_buffers + i);
3408

    
3409
    for(i = 0; i < MAX_PPS_COUNT; i++)
3410
        av_freep(h->pps_buffers + i);
3411
}
3412

    
3413
av_cold int ff_h264_decode_end(AVCodecContext *avctx)
3414
{
3415
    H264Context *h = avctx->priv_data;
3416
    MpegEncContext *s = &h->s;
3417

    
3418
    ff_h264_free_context(h);
3419

    
3420
    MPV_common_end(s);
3421

    
3422
//    memset(h, 0, sizeof(H264Context));
3423

    
3424
    return 0;
3425
}
3426

    
3427
static const AVProfile profiles[] = {
3428
    { FF_PROFILE_H264_BASELINE,             "Baseline"              },
3429
    { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline"  },
3430
    { FF_PROFILE_H264_MAIN,                 "Main"                  },
3431
    { FF_PROFILE_H264_EXTENDED,             "Extended"              },
3432
    { FF_PROFILE_H264_HIGH,                 "High"                  },
3433
    { FF_PROFILE_H264_HIGH_10,              "High 10"               },
3434
    { FF_PROFILE_H264_HIGH_10_INTRA,        "High 10 Intra"         },
3435
    { FF_PROFILE_H264_HIGH_422,             "High 4:2:2"            },
3436
    { FF_PROFILE_H264_HIGH_422_INTRA,       "High 4:2:2 Intra"      },
3437
    { FF_PROFILE_H264_HIGH_444,             "High 4:4:4"            },
3438
    { FF_PROFILE_H264_HIGH_444_PREDICTIVE,  "High 4:4:4 Predictive" },
3439
    { FF_PROFILE_H264_HIGH_444_INTRA,       "High 4:4:4 Intra"      },
3440
    { FF_PROFILE_H264_CAVLC_444,            "CAVLC 4:4:4"           },
3441
    { FF_PROFILE_UNKNOWN },
3442
};
3443

    
3444
AVCodec ff_h264_decoder = {
3445
    "h264",
3446
    AVMEDIA_TYPE_VIDEO,
3447
    CODEC_ID_H264,
3448
    sizeof(H264Context),
3449
    ff_h264_decode_init,
3450
    NULL,
3451
    ff_h264_decode_end,
3452
    decode_frame,
3453
    /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY |
3454
        CODEC_CAP_FRAME_THREADS |
3455
        CODEC_CAP_SLICE_THREADS,
3456
    .flush= flush_dpb,
3457
    .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
3458
    .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
3459
    .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
3460
    .profiles = NULL_IF_CONFIG_SMALL(profiles),
3461
};
3462

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