Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ 943f69a6

History | View | Annotate | Download (263 KB)

1
/*
2
 * H.26L/H.264/AVC/JVT/14496-10/... encoder/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 libavcodec/h264.c
24
 * H.264 / AVC / MPEG4 part10 codec.
25
 * @author Michael Niedermayer <michaelni@gmx.at>
26
 */
27

    
28
#include "internal.h"
29
#include "dsputil.h"
30
#include "avcodec.h"
31
#include "mpegvideo.h"
32
#include "h264.h"
33
#include "h264data.h"
34
#include "h264_parser.h"
35
#include "golomb.h"
36
#include "mathops.h"
37
#include "rectangle.h"
38
#include "vdpau_internal.h"
39

    
40
#include "cabac.h"
41
#if ARCH_X86
42
#include "x86/h264_i386.h"
43
#endif
44

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

    
48
/**
49
 * Value of Picture.reference when Picture is not a reference picture, but
50
 * is held for delayed output.
51
 */
52
#define DELAYED_PIC_REF 4
53

    
54
static VLC coeff_token_vlc[4];
55
static VLC_TYPE coeff_token_vlc_tables[520+332+280+256][2];
56
static const int coeff_token_vlc_tables_size[4]={520,332,280,256};
57

    
58
static VLC chroma_dc_coeff_token_vlc;
59
static VLC_TYPE chroma_dc_coeff_token_vlc_table[256][2];
60
static const int chroma_dc_coeff_token_vlc_table_size = 256;
61

    
62
static VLC total_zeros_vlc[15];
63
static VLC_TYPE total_zeros_vlc_tables[15][512][2];
64
static const int total_zeros_vlc_tables_size = 512;
65

    
66
static VLC chroma_dc_total_zeros_vlc[3];
67
static VLC_TYPE chroma_dc_total_zeros_vlc_tables[3][8][2];
68
static const int chroma_dc_total_zeros_vlc_tables_size = 8;
69

    
70
static VLC run_vlc[6];
71
static VLC_TYPE run_vlc_tables[6][8][2];
72
static const int run_vlc_tables_size = 8;
73

    
74
static VLC run7_vlc;
75
static VLC_TYPE run7_vlc_table[96][2];
76
static const int run7_vlc_table_size = 96;
77

    
78
static void svq3_luma_dc_dequant_idct_c(DCTELEM *block, int qp);
79
static void svq3_add_idct_c(uint8_t *dst, DCTELEM *block, int stride, int qp, int dc);
80
static Picture * remove_long(H264Context *h, int i, int ref_mask);
81

    
82
static const uint8_t rem6[52]={
83
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,
84
};
85

    
86
static const uint8_t div6[52]={
87
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,
88
};
89

    
90
static const uint8_t left_block_options[4][8]={
91
    {0,1,2,3,7,10,8,11},
92
    {2,2,3,3,8,11,8,11},
93
    {0,0,1,1,7,10,7,10},
94
    {0,2,0,2,7,10,7,10}
95
};
96

    
97
#define LEVEL_TAB_BITS 8
98
static int8_t cavlc_level_tab[7][1<<LEVEL_TAB_BITS][2];
99

    
100
static void fill_caches(H264Context *h, int mb_type, int for_deblock){
101
    MpegEncContext * const s = &h->s;
102
    const int mb_xy= h->mb_xy;
103
    int topleft_xy, top_xy, topright_xy, left_xy[2];
104
    int topleft_type, top_type, topright_type, left_type[2];
105
    const uint8_t * left_block;
106
    int topleft_partition= -1;
107
    int i;
108

    
109
    top_xy     = mb_xy  - (s->mb_stride << FIELD_PICTURE);
110

    
111
    //FIXME deblocking could skip the intra and nnz parts.
112
    if(for_deblock && (h->slice_num == 1 || h->slice_table[mb_xy] == h->slice_table[top_xy]) && !FRAME_MBAFF)
113
        return;
114

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

    
118
    topleft_xy = top_xy - 1;
119
    topright_xy= top_xy + 1;
120
    left_xy[1] = left_xy[0] = mb_xy-1;
121
    left_block = left_block_options[0];
122
    if(FRAME_MBAFF){
123
        const int pair_xy          = s->mb_x     + (s->mb_y & ~1)*s->mb_stride;
124
        const int top_pair_xy      = pair_xy     - s->mb_stride;
125
        const int topleft_pair_xy  = top_pair_xy - 1;
126
        const int topright_pair_xy = top_pair_xy + 1;
127
        const int topleft_mb_field_flag  = IS_INTERLACED(s->current_picture.mb_type[topleft_pair_xy]);
128
        const int top_mb_field_flag      = IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);
129
        const int topright_mb_field_flag = IS_INTERLACED(s->current_picture.mb_type[topright_pair_xy]);
130
        const int left_mb_field_flag     = IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);
131
        const int curr_mb_field_flag     = IS_INTERLACED(mb_type);
132
        const int bottom = (s->mb_y & 1);
133
        tprintf(s->avctx, "fill_caches: curr_mb_field_flag:%d, left_mb_field_flag:%d, topleft_mb_field_flag:%d, top_mb_field_flag:%d, topright_mb_field_flag:%d\n", curr_mb_field_flag, left_mb_field_flag, topleft_mb_field_flag, top_mb_field_flag, topright_mb_field_flag);
134

    
135
        if (curr_mb_field_flag && (bottom || top_mb_field_flag)){
136
            top_xy -= s->mb_stride;
137
        }
138
        if (curr_mb_field_flag && (bottom || topleft_mb_field_flag)){
139
            topleft_xy -= s->mb_stride;
140
        } else if(bottom && !curr_mb_field_flag && left_mb_field_flag) {
141
            topleft_xy += s->mb_stride;
142
            // take top left mv from the middle of the mb, as opposed to all other modes which use the bottom right partition
143
            topleft_partition = 0;
144
        }
145
        if (curr_mb_field_flag && (bottom || topright_mb_field_flag)){
146
            topright_xy -= s->mb_stride;
147
        }
148
        if (left_mb_field_flag != curr_mb_field_flag) {
149
            left_xy[1] = left_xy[0] = pair_xy - 1;
150
            if (curr_mb_field_flag) {
151
                left_xy[1] += s->mb_stride;
152
                left_block = left_block_options[3];
153
            } else {
154
                left_block= left_block_options[2 - bottom];
155
            }
156
        }
157
    }
158

    
159
    h->top_mb_xy = top_xy;
160
    h->left_mb_xy[0] = left_xy[0];
161
    h->left_mb_xy[1] = left_xy[1];
162
    if(for_deblock){
163
        topleft_type = 0;
164
        topright_type = 0;
165
        top_type     = h->slice_table[top_xy     ] < 0xFFFF ? s->current_picture.mb_type[top_xy]     : 0;
166
        left_type[0] = h->slice_table[left_xy[0] ] < 0xFFFF ? s->current_picture.mb_type[left_xy[0]] : 0;
167
        left_type[1] = h->slice_table[left_xy[1] ] < 0xFFFF ? s->current_picture.mb_type[left_xy[1]] : 0;
168

    
169
        if(MB_MBAFF && !IS_INTRA(mb_type)){
170
            int list;
171
            for(list=0; list<h->list_count; list++){
172
                //These values where changed for ease of performing MC, we need to change them back
173
                //FIXME maybe we can make MC and loop filter use the same values or prevent
174
                //the MC code from changing ref_cache and rather use a temporary array.
175
                if(USES_LIST(mb_type,list)){
176
                    int8_t *ref = &s->current_picture.ref_index[list][h->mb2b8_xy[mb_xy]];
177
                    *(uint32_t*)&h->ref_cache[list][scan8[ 0]] =
178
                    *(uint32_t*)&h->ref_cache[list][scan8[ 2]] = (pack16to32(ref[0],ref[1])&0x00FF00FF)*0x0101;
179
                    ref += h->b8_stride;
180
                    *(uint32_t*)&h->ref_cache[list][scan8[ 8]] =
181
                    *(uint32_t*)&h->ref_cache[list][scan8[10]] = (pack16to32(ref[0],ref[1])&0x00FF00FF)*0x0101;
182
                }
183
            }
184
        }
185
    }else{
186
        topleft_type = h->slice_table[topleft_xy ] == h->slice_num ? s->current_picture.mb_type[topleft_xy] : 0;
187
        top_type     = h->slice_table[top_xy     ] == h->slice_num ? s->current_picture.mb_type[top_xy]     : 0;
188
        topright_type= h->slice_table[topright_xy] == h->slice_num ? s->current_picture.mb_type[topright_xy]: 0;
189
        left_type[0] = h->slice_table[left_xy[0] ] == h->slice_num ? s->current_picture.mb_type[left_xy[0]] : 0;
190
        left_type[1] = h->slice_table[left_xy[1] ] == h->slice_num ? s->current_picture.mb_type[left_xy[1]] : 0;
191

    
192
    if(IS_INTRA(mb_type)){
193
        int type_mask= h->pps.constrained_intra_pred ? IS_INTRA(-1) : -1;
194
        h->topleft_samples_available=
195
        h->top_samples_available=
196
        h->left_samples_available= 0xFFFF;
197
        h->topright_samples_available= 0xEEEA;
198

    
199
        if(!(top_type & type_mask)){
200
            h->topleft_samples_available= 0xB3FF;
201
            h->top_samples_available= 0x33FF;
202
            h->topright_samples_available= 0x26EA;
203
        }
204
        if(IS_INTERLACED(mb_type) != IS_INTERLACED(left_type[0])){
205
            if(IS_INTERLACED(mb_type)){
206
                if(!(left_type[0] & type_mask)){
207
                    h->topleft_samples_available&= 0xDFFF;
208
                    h->left_samples_available&= 0x5FFF;
209
                }
210
                if(!(left_type[1] & type_mask)){
211
                    h->topleft_samples_available&= 0xFF5F;
212
                    h->left_samples_available&= 0xFF5F;
213
                }
214
            }else{
215
                int left_typei = h->slice_table[left_xy[0] + s->mb_stride ] == h->slice_num
216
                                ? s->current_picture.mb_type[left_xy[0] + s->mb_stride] : 0;
217
                assert(left_xy[0] == left_xy[1]);
218
                if(!((left_typei & type_mask) && (left_type[0] & type_mask))){
219
                    h->topleft_samples_available&= 0xDF5F;
220
                    h->left_samples_available&= 0x5F5F;
221
                }
222
            }
223
        }else{
224
            if(!(left_type[0] & type_mask)){
225
                h->topleft_samples_available&= 0xDF5F;
226
                h->left_samples_available&= 0x5F5F;
227
            }
228
        }
229

    
230
        if(!(topleft_type & type_mask))
231
            h->topleft_samples_available&= 0x7FFF;
232

    
233
        if(!(topright_type & type_mask))
234
            h->topright_samples_available&= 0xFBFF;
235

    
236
        if(IS_INTRA4x4(mb_type)){
237
            if(IS_INTRA4x4(top_type)){
238
                h->intra4x4_pred_mode_cache[4+8*0]= h->intra4x4_pred_mode[top_xy][4];
239
                h->intra4x4_pred_mode_cache[5+8*0]= h->intra4x4_pred_mode[top_xy][5];
240
                h->intra4x4_pred_mode_cache[6+8*0]= h->intra4x4_pred_mode[top_xy][6];
241
                h->intra4x4_pred_mode_cache[7+8*0]= h->intra4x4_pred_mode[top_xy][3];
242
            }else{
243
                int pred;
244
                if(!(top_type & type_mask))
245
                    pred= -1;
246
                else{
247
                    pred= 2;
248
                }
249
                h->intra4x4_pred_mode_cache[4+8*0]=
250
                h->intra4x4_pred_mode_cache[5+8*0]=
251
                h->intra4x4_pred_mode_cache[6+8*0]=
252
                h->intra4x4_pred_mode_cache[7+8*0]= pred;
253
            }
254
            for(i=0; i<2; i++){
255
                if(IS_INTRA4x4(left_type[i])){
256
                    h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[0+2*i]];
257
                    h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[1+2*i]];
258
                }else{
259
                    int pred;
260
                    if(!(left_type[i] & type_mask))
261
                        pred= -1;
262
                    else{
263
                        pred= 2;
264
                    }
265
                    h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]=
266
                    h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= pred;
267
                }
268
            }
269
        }
270
    }
271
    }
272

    
273

    
274
/*
275
0 . T T. T T T T
276
1 L . .L . . . .
277
2 L . .L . . . .
278
3 . T TL . . . .
279
4 L . .L . . . .
280
5 L . .. . . . .
281
*/
282
//FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
283
    if(top_type){
284
        h->non_zero_count_cache[4+8*0]= h->non_zero_count[top_xy][4];
285
        h->non_zero_count_cache[5+8*0]= h->non_zero_count[top_xy][5];
286
        h->non_zero_count_cache[6+8*0]= h->non_zero_count[top_xy][6];
287
        h->non_zero_count_cache[7+8*0]= h->non_zero_count[top_xy][3];
288

    
289
        h->non_zero_count_cache[1+8*0]= h->non_zero_count[top_xy][9];
290
        h->non_zero_count_cache[2+8*0]= h->non_zero_count[top_xy][8];
291

    
292
        h->non_zero_count_cache[1+8*3]= h->non_zero_count[top_xy][12];
293
        h->non_zero_count_cache[2+8*3]= h->non_zero_count[top_xy][11];
294

    
295
    }else{
296
        h->non_zero_count_cache[4+8*0]=
297
        h->non_zero_count_cache[5+8*0]=
298
        h->non_zero_count_cache[6+8*0]=
299
        h->non_zero_count_cache[7+8*0]=
300

    
301
        h->non_zero_count_cache[1+8*0]=
302
        h->non_zero_count_cache[2+8*0]=
303

    
304
        h->non_zero_count_cache[1+8*3]=
305
        h->non_zero_count_cache[2+8*3]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
306

    
307
    }
308

    
309
    for (i=0; i<2; i++) {
310
        if(left_type[i]){
311
            h->non_zero_count_cache[3+8*1 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[0+2*i]];
312
            h->non_zero_count_cache[3+8*2 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[1+2*i]];
313
            h->non_zero_count_cache[0+8*1 +   8*i]= h->non_zero_count[left_xy[i]][left_block[4+2*i]];
314
            h->non_zero_count_cache[0+8*4 +   8*i]= h->non_zero_count[left_xy[i]][left_block[5+2*i]];
315
        }else{
316
            h->non_zero_count_cache[3+8*1 + 2*8*i]=
317
            h->non_zero_count_cache[3+8*2 + 2*8*i]=
318
            h->non_zero_count_cache[0+8*1 +   8*i]=
319
            h->non_zero_count_cache[0+8*4 +   8*i]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
320
        }
321
    }
322

    
323
    if( h->pps.cabac ) {
324
        // top_cbp
325
        if(top_type) {
326
            h->top_cbp = h->cbp_table[top_xy];
327
        } else if(IS_INTRA(mb_type)) {
328
            h->top_cbp = 0x1C0;
329
        } else {
330
            h->top_cbp = 0;
331
        }
332
        // left_cbp
333
        if (left_type[0]) {
334
            h->left_cbp = h->cbp_table[left_xy[0]] & 0x1f0;
335
        } else if(IS_INTRA(mb_type)) {
336
            h->left_cbp = 0x1C0;
337
        } else {
338
            h->left_cbp = 0;
339
        }
340
        if (left_type[0]) {
341
            h->left_cbp |= ((h->cbp_table[left_xy[0]]>>((left_block[0]&(~1))+1))&0x1) << 1;
342
        }
343
        if (left_type[1]) {
344
            h->left_cbp |= ((h->cbp_table[left_xy[1]]>>((left_block[2]&(~1))+1))&0x1) << 3;
345
        }
346
    }
347

    
348
#if 1
349
    if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
350
        int list;
351
        for(list=0; list<h->list_count; list++){
352
            if(!USES_LIST(mb_type, list) && !IS_DIRECT(mb_type) && !h->deblocking_filter){
353
                /*if(!h->mv_cache_clean[list]){
354
                    memset(h->mv_cache [list],  0, 8*5*2*sizeof(int16_t)); //FIXME clean only input? clean at all?
355
                    memset(h->ref_cache[list], PART_NOT_AVAILABLE, 8*5*sizeof(int8_t));
356
                    h->mv_cache_clean[list]= 1;
357
                }*/
358
                continue;
359
            }
360
            h->mv_cache_clean[list]= 0;
361

    
362
            if(USES_LIST(top_type, list)){
363
                const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
364
                const int b8_xy= h->mb2b8_xy[top_xy] + h->b8_stride;
365
                *(uint32_t*)h->mv_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 0];
366
                *(uint32_t*)h->mv_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 1];
367
                *(uint32_t*)h->mv_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 2];
368
                *(uint32_t*)h->mv_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 3];
369
                h->ref_cache[list][scan8[0] + 0 - 1*8]=
370
                h->ref_cache[list][scan8[0] + 1 - 1*8]= s->current_picture.ref_index[list][b8_xy + 0];
371
                h->ref_cache[list][scan8[0] + 2 - 1*8]=
372
                h->ref_cache[list][scan8[0] + 3 - 1*8]= s->current_picture.ref_index[list][b8_xy + 1];
373
            }else{
374
                *(uint32_t*)h->mv_cache [list][scan8[0] + 0 - 1*8]=
375
                *(uint32_t*)h->mv_cache [list][scan8[0] + 1 - 1*8]=
376
                *(uint32_t*)h->mv_cache [list][scan8[0] + 2 - 1*8]=
377
                *(uint32_t*)h->mv_cache [list][scan8[0] + 3 - 1*8]= 0;
378
                *(uint32_t*)&h->ref_cache[list][scan8[0] + 0 - 1*8]= ((top_type ? LIST_NOT_USED : PART_NOT_AVAILABLE)&0xFF)*0x01010101;
379
            }
380

    
381
            for(i=0; i<2; i++){
382
                int cache_idx = scan8[0] - 1 + i*2*8;
383
                if(USES_LIST(left_type[i], list)){
384
                    const int b_xy= h->mb2b_xy[left_xy[i]] + 3;
385
                    const int b8_xy= h->mb2b8_xy[left_xy[i]] + 1;
386
                    *(uint32_t*)h->mv_cache[list][cache_idx  ]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[0+i*2]];
387
                    *(uint32_t*)h->mv_cache[list][cache_idx+8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[1+i*2]];
388
                    h->ref_cache[list][cache_idx  ]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[0+i*2]>>1)];
389
                    h->ref_cache[list][cache_idx+8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[1+i*2]>>1)];
390
                }else{
391
                    *(uint32_t*)h->mv_cache [list][cache_idx  ]=
392
                    *(uint32_t*)h->mv_cache [list][cache_idx+8]= 0;
393
                    h->ref_cache[list][cache_idx  ]=
394
                    h->ref_cache[list][cache_idx+8]= left_type[i] ? LIST_NOT_USED : PART_NOT_AVAILABLE;
395
                }
396
            }
397

    
398
            if(for_deblock || ((IS_DIRECT(mb_type) && !h->direct_spatial_mv_pred) && !FRAME_MBAFF))
399
                continue;
400

    
401
            if(USES_LIST(topleft_type, list)){
402
                const int b_xy = h->mb2b_xy[topleft_xy] + 3 + h->b_stride + (topleft_partition & 2*h->b_stride);
403
                const int b8_xy= h->mb2b8_xy[topleft_xy] + 1 + (topleft_partition & h->b8_stride);
404
                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
405
                h->ref_cache[list][scan8[0] - 1 - 1*8]= s->current_picture.ref_index[list][b8_xy];
406
            }else{
407
                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= 0;
408
                h->ref_cache[list][scan8[0] - 1 - 1*8]= topleft_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
409
            }
410

    
411
            if(USES_LIST(topright_type, list)){
412
                const int b_xy= h->mb2b_xy[topright_xy] + 3*h->b_stride;
413
                const int b8_xy= h->mb2b8_xy[topright_xy] + h->b8_stride;
414
                *(uint32_t*)h->mv_cache[list][scan8[0] + 4 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
415
                h->ref_cache[list][scan8[0] + 4 - 1*8]= s->current_picture.ref_index[list][b8_xy];
416
            }else{
417
                *(uint32_t*)h->mv_cache [list][scan8[0] + 4 - 1*8]= 0;
418
                h->ref_cache[list][scan8[0] + 4 - 1*8]= topright_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
419
            }
420

    
421
            if((IS_SKIP(mb_type) || IS_DIRECT(mb_type)) && !FRAME_MBAFF)
422
                continue;
423

    
424
            h->ref_cache[list][scan8[5 ]+1] =
425
            h->ref_cache[list][scan8[7 ]+1] =
426
            h->ref_cache[list][scan8[13]+1] =  //FIXME remove past 3 (init somewhere else)
427
            h->ref_cache[list][scan8[4 ]] =
428
            h->ref_cache[list][scan8[12]] = PART_NOT_AVAILABLE;
429
            *(uint32_t*)h->mv_cache [list][scan8[5 ]+1]=
430
            *(uint32_t*)h->mv_cache [list][scan8[7 ]+1]=
431
            *(uint32_t*)h->mv_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)
432
            *(uint32_t*)h->mv_cache [list][scan8[4 ]]=
433
            *(uint32_t*)h->mv_cache [list][scan8[12]]= 0;
434

    
435
            if( h->pps.cabac ) {
436
                /* XXX beurk, Load mvd */
437
                if(USES_LIST(top_type, list)){
438
                    const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
439
                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 0];
440
                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 1];
441
                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 2];
442
                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 3];
443
                }else{
444
                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 0 - 1*8]=
445
                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 1 - 1*8]=
446
                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 2 - 1*8]=
447
                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 3 - 1*8]= 0;
448
                }
449
                if(USES_LIST(left_type[0], list)){
450
                    const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
451
                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 0*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[0]];
452
                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[1]];
453
                }else{
454
                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 0*8]=
455
                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 1*8]= 0;
456
                }
457
                if(USES_LIST(left_type[1], list)){
458
                    const int b_xy= h->mb2b_xy[left_xy[1]] + 3;
459
                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 2*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[2]];
460
                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 3*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[3]];
461
                }else{
462
                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 2*8]=
463
                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 3*8]= 0;
464
                }
465
                *(uint32_t*)h->mvd_cache [list][scan8[5 ]+1]=
466
                *(uint32_t*)h->mvd_cache [list][scan8[7 ]+1]=
467
                *(uint32_t*)h->mvd_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)
468
                *(uint32_t*)h->mvd_cache [list][scan8[4 ]]=
469
                *(uint32_t*)h->mvd_cache [list][scan8[12]]= 0;
470

    
471
                if(h->slice_type_nos == FF_B_TYPE){
472
                    fill_rectangle(&h->direct_cache[scan8[0]], 4, 4, 8, 0, 1);
473

    
474
                    if(IS_DIRECT(top_type)){
475
                        *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0x01010101;
476
                    }else if(IS_8X8(top_type)){
477
                        int b8_xy = h->mb2b8_xy[top_xy] + h->b8_stride;
478
                        h->direct_cache[scan8[0] + 0 - 1*8]= h->direct_table[b8_xy];
479
                        h->direct_cache[scan8[0] + 2 - 1*8]= h->direct_table[b8_xy + 1];
480
                    }else{
481
                        *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0;
482
                    }
483

    
484
                    if(IS_DIRECT(left_type[0]))
485
                        h->direct_cache[scan8[0] - 1 + 0*8]= 1;
486
                    else if(IS_8X8(left_type[0]))
487
                        h->direct_cache[scan8[0] - 1 + 0*8]= h->direct_table[h->mb2b8_xy[left_xy[0]] + 1 + h->b8_stride*(left_block[0]>>1)];
488
                    else
489
                        h->direct_cache[scan8[0] - 1 + 0*8]= 0;
490

    
491
                    if(IS_DIRECT(left_type[1]))
492
                        h->direct_cache[scan8[0] - 1 + 2*8]= 1;
493
                    else if(IS_8X8(left_type[1]))
494
                        h->direct_cache[scan8[0] - 1 + 2*8]= h->direct_table[h->mb2b8_xy[left_xy[1]] + 1 + h->b8_stride*(left_block[2]>>1)];
495
                    else
496
                        h->direct_cache[scan8[0] - 1 + 2*8]= 0;
497
                }
498
            }
499

    
500
            if(FRAME_MBAFF){
501
#define MAP_MVS\
502
                    MAP_F2F(scan8[0] - 1 - 1*8, topleft_type)\
503
                    MAP_F2F(scan8[0] + 0 - 1*8, top_type)\
504
                    MAP_F2F(scan8[0] + 1 - 1*8, top_type)\
505
                    MAP_F2F(scan8[0] + 2 - 1*8, top_type)\
506
                    MAP_F2F(scan8[0] + 3 - 1*8, top_type)\
507
                    MAP_F2F(scan8[0] + 4 - 1*8, topright_type)\
508
                    MAP_F2F(scan8[0] - 1 + 0*8, left_type[0])\
509
                    MAP_F2F(scan8[0] - 1 + 1*8, left_type[0])\
510
                    MAP_F2F(scan8[0] - 1 + 2*8, left_type[1])\
511
                    MAP_F2F(scan8[0] - 1 + 3*8, left_type[1])
512
                if(MB_FIELD){
513
#define MAP_F2F(idx, mb_type)\
514
                    if(!IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\
515
                        h->ref_cache[list][idx] <<= 1;\
516
                        h->mv_cache[list][idx][1] /= 2;\
517
                        h->mvd_cache[list][idx][1] /= 2;\
518
                    }
519
                    MAP_MVS
520
#undef MAP_F2F
521
                }else{
522
#define MAP_F2F(idx, mb_type)\
523
                    if(IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\
524
                        h->ref_cache[list][idx] >>= 1;\
525
                        h->mv_cache[list][idx][1] <<= 1;\
526
                        h->mvd_cache[list][idx][1] <<= 1;\
527
                    }
528
                    MAP_MVS
529
#undef MAP_F2F
530
                }
531
            }
532
        }
533
    }
534
#endif
535

    
536
    h->neighbor_transform_size= !!IS_8x8DCT(top_type) + !!IS_8x8DCT(left_type[0]);
537
}
538

    
539
void ff_h264_write_back_intra_pred_mode(H264Context *h){
540
    const int mb_xy= h->mb_xy;
541

    
542
    h->intra4x4_pred_mode[mb_xy][0]= h->intra4x4_pred_mode_cache[7+8*1];
543
    h->intra4x4_pred_mode[mb_xy][1]= h->intra4x4_pred_mode_cache[7+8*2];
544
    h->intra4x4_pred_mode[mb_xy][2]= h->intra4x4_pred_mode_cache[7+8*3];
545
    h->intra4x4_pred_mode[mb_xy][3]= h->intra4x4_pred_mode_cache[7+8*4];
546
    h->intra4x4_pred_mode[mb_xy][4]= h->intra4x4_pred_mode_cache[4+8*4];
547
    h->intra4x4_pred_mode[mb_xy][5]= h->intra4x4_pred_mode_cache[5+8*4];
548
    h->intra4x4_pred_mode[mb_xy][6]= h->intra4x4_pred_mode_cache[6+8*4];
549
}
550

    
551
/**
552
 * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
553
 */
554
int ff_h264_check_intra_pred_mode(H264Context *h, int mode){
555
    MpegEncContext * const s = &h->s;
556
    static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
557
    static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
558

    
559
    if(mode > 6U) {
560
        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);
561
        return -1;
562
    }
563

    
564
    if(!(h->top_samples_available&0x8000)){
565
        mode= top[ mode ];
566
        if(mode<0){
567
            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);
568
            return -1;
569
        }
570
    }
571

    
572
    if((h->left_samples_available&0x8080) != 0x8080){
573
        mode= left[ mode ];
574
        if(h->left_samples_available&0x8080){ //mad cow disease mode, aka MBAFF + constrained_intra_pred
575
            mode= ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available&0x8000)) + 2*(mode == DC_128_PRED8x8);
576
        }
577
        if(mode<0){
578
            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);
579
            return -1;
580
        }
581
    }
582

    
583
    return mode;
584
}
585

    
586
/**
587
 * gets the predicted intra4x4 prediction mode.
588
 */
589
static inline int pred_intra_mode(H264Context *h, int n){
590
    const int index8= scan8[n];
591
    const int left= h->intra4x4_pred_mode_cache[index8 - 1];
592
    const int top = h->intra4x4_pred_mode_cache[index8 - 8];
593
    const int min= FFMIN(left, top);
594

    
595
    tprintf(h->s.avctx, "mode:%d %d min:%d\n", left ,top, min);
596

    
597
    if(min<0) return DC_PRED;
598
    else      return min;
599
}
600

    
601
static inline void write_back_non_zero_count(H264Context *h){
602
    const int mb_xy= h->mb_xy;
603

    
604
    h->non_zero_count[mb_xy][0]= h->non_zero_count_cache[7+8*1];
605
    h->non_zero_count[mb_xy][1]= h->non_zero_count_cache[7+8*2];
606
    h->non_zero_count[mb_xy][2]= h->non_zero_count_cache[7+8*3];
607
    h->non_zero_count[mb_xy][3]= h->non_zero_count_cache[7+8*4];
608
    h->non_zero_count[mb_xy][4]= h->non_zero_count_cache[4+8*4];
609
    h->non_zero_count[mb_xy][5]= h->non_zero_count_cache[5+8*4];
610
    h->non_zero_count[mb_xy][6]= h->non_zero_count_cache[6+8*4];
611

    
612
    h->non_zero_count[mb_xy][9]= h->non_zero_count_cache[1+8*2];
613
    h->non_zero_count[mb_xy][8]= h->non_zero_count_cache[2+8*2];
614
    h->non_zero_count[mb_xy][7]= h->non_zero_count_cache[2+8*1];
615

    
616
    h->non_zero_count[mb_xy][12]=h->non_zero_count_cache[1+8*5];
617
    h->non_zero_count[mb_xy][11]=h->non_zero_count_cache[2+8*5];
618
    h->non_zero_count[mb_xy][10]=h->non_zero_count_cache[2+8*4];
619
}
620

    
621
/**
622
 * gets the predicted number of non-zero coefficients.
623
 * @param n block index
624
 */
625
static inline int pred_non_zero_count(H264Context *h, int n){
626
    const int index8= scan8[n];
627
    const int left= h->non_zero_count_cache[index8 - 1];
628
    const int top = h->non_zero_count_cache[index8 - 8];
629
    int i= left + top;
630

    
631
    if(i<64) i= (i+1)>>1;
632

    
633
    tprintf(h->s.avctx, "pred_nnz L%X T%X n%d s%d P%X\n", left, top, n, scan8[n], i&31);
634

    
635
    return i&31;
636
}
637

    
638
/**
639
 * gets the directionally predicted 16x8 MV.
640
 * @param n the block index
641
 * @param mx the x component of the predicted motion vector
642
 * @param my the y component of the predicted motion vector
643
 */
644
static inline void pred_16x8_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
645
    if(n==0){
646
        const int top_ref=      h->ref_cache[list][ scan8[0] - 8 ];
647
        const int16_t * const B= h->mv_cache[list][ scan8[0] - 8 ];
648

    
649
        tprintf(h->s.avctx, "pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d\n", top_ref, B[0], B[1], h->s.mb_x, h->s.mb_y, n, list);
650

    
651
        if(top_ref == ref){
652
            *mx= B[0];
653
            *my= B[1];
654
            return;
655
        }
656
    }else{
657
        const int left_ref=     h->ref_cache[list][ scan8[8] - 1 ];
658
        const int16_t * const A= h->mv_cache[list][ scan8[8] - 1 ];
659

    
660
        tprintf(h->s.avctx, "pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d\n", left_ref, A[0], A[1], h->s.mb_x, h->s.mb_y, n, list);
661

    
662
        if(left_ref == ref){
663
            *mx= A[0];
664
            *my= A[1];
665
            return;
666
        }
667
    }
668

    
669
    //RARE
670
    pred_motion(h, n, 4, list, ref, mx, my);
671
}
672

    
673
/**
674
 * gets the directionally predicted 8x16 MV.
675
 * @param n the block index
676
 * @param mx the x component of the predicted motion vector
677
 * @param my the y component of the predicted motion vector
678
 */
679
static inline void pred_8x16_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
680
    if(n==0){
681
        const int left_ref=      h->ref_cache[list][ scan8[0] - 1 ];
682
        const int16_t * const A=  h->mv_cache[list][ scan8[0] - 1 ];
683

    
684
        tprintf(h->s.avctx, "pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d\n", left_ref, A[0], A[1], h->s.mb_x, h->s.mb_y, n, list);
685

    
686
        if(left_ref == ref){
687
            *mx= A[0];
688
            *my= A[1];
689
            return;
690
        }
691
    }else{
692
        const int16_t * C;
693
        int diagonal_ref;
694

    
695
        diagonal_ref= fetch_diagonal_mv(h, &C, scan8[4], list, 2);
696

    
697
        tprintf(h->s.avctx, "pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d\n", diagonal_ref, C[0], C[1], h->s.mb_x, h->s.mb_y, n, list);
698

    
699
        if(diagonal_ref == ref){
700
            *mx= C[0];
701
            *my= C[1];
702
            return;
703
        }
704
    }
705

    
706
    //RARE
707
    pred_motion(h, n, 2, list, ref, mx, my);
708
}
709

    
710
static inline void pred_pskip_motion(H264Context * const h, int * const mx, int * const my){
711
    const int top_ref = h->ref_cache[0][ scan8[0] - 8 ];
712
    const int left_ref= h->ref_cache[0][ scan8[0] - 1 ];
713

    
714
    tprintf(h->s.avctx, "pred_pskip: (%d) (%d) at %2d %2d\n", top_ref, left_ref, h->s.mb_x, h->s.mb_y);
715

    
716
    if(top_ref == PART_NOT_AVAILABLE || left_ref == PART_NOT_AVAILABLE
717
       || !( top_ref | *(uint32_t*)h->mv_cache[0][ scan8[0] - 8 ])
718
       || !(left_ref | *(uint32_t*)h->mv_cache[0][ scan8[0] - 1 ])){
719

    
720
        *mx = *my = 0;
721
        return;
722
    }
723

    
724
    pred_motion(h, 0, 4, 0, 0, mx, my);
725

    
726
    return;
727
}
728

    
729
static inline void write_back_motion(H264Context *h, int mb_type){
730
    MpegEncContext * const s = &h->s;
731
    const int b_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
732
    const int b8_xy= 2*s->mb_x + 2*s->mb_y*h->b8_stride;
733
    int list;
734

    
735
    if(!USES_LIST(mb_type, 0))
736
        fill_rectangle(&s->current_picture.ref_index[0][b8_xy], 2, 2, h->b8_stride, (uint8_t)LIST_NOT_USED, 1);
737

    
738
    for(list=0; list<h->list_count; list++){
739
        int y;
740
        if(!USES_LIST(mb_type, list))
741
            continue;
742

    
743
        for(y=0; y<4; y++){
744
            *(uint64_t*)s->current_picture.motion_val[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mv_cache[list][scan8[0]+0 + 8*y];
745
            *(uint64_t*)s->current_picture.motion_val[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mv_cache[list][scan8[0]+2 + 8*y];
746
        }
747
        if( h->pps.cabac ) {
748
            if(IS_SKIP(mb_type))
749
                fill_rectangle(h->mvd_table[list][b_xy], 4, 4, h->b_stride, 0, 4);
750
            else
751
            for(y=0; y<4; y++){
752
                *(uint64_t*)h->mvd_table[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+0 + 8*y];
753
                *(uint64_t*)h->mvd_table[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+2 + 8*y];
754
            }
755
        }
756

    
757
        {
758
            int8_t *ref_index = &s->current_picture.ref_index[list][b8_xy];
759
            ref_index[0+0*h->b8_stride]= h->ref_cache[list][scan8[0]];
760
            ref_index[1+0*h->b8_stride]= h->ref_cache[list][scan8[4]];
761
            ref_index[0+1*h->b8_stride]= h->ref_cache[list][scan8[8]];
762
            ref_index[1+1*h->b8_stride]= h->ref_cache[list][scan8[12]];
763
        }
764
    }
765

    
766
    if(h->slice_type_nos == FF_B_TYPE && h->pps.cabac){
767
        if(IS_8X8(mb_type)){
768
            uint8_t *direct_table = &h->direct_table[b8_xy];
769
            direct_table[1+0*h->b8_stride] = IS_DIRECT(h->sub_mb_type[1]) ? 1 : 0;
770
            direct_table[0+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[2]) ? 1 : 0;
771
            direct_table[1+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[3]) ? 1 : 0;
772
        }
773
    }
774
}
775

    
776
const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
777
    int i, si, di;
778
    uint8_t *dst;
779
    int bufidx;
780

    
781
//    src[0]&0x80;                //forbidden bit
782
    h->nal_ref_idc= src[0]>>5;
783
    h->nal_unit_type= src[0]&0x1F;
784

    
785
    src++; length--;
786
#if 0
787
    for(i=0; i<length; i++)
788
        printf("%2X ", src[i]);
789
#endif
790

    
791
#if HAVE_FAST_UNALIGNED
792
# if HAVE_FAST_64BIT
793
#   define RS 7
794
    for(i=0; i+1<length; i+=9){
795
        if(!((~*(const uint64_t*)(src+i) & (*(const uint64_t*)(src+i) - 0x0100010001000101ULL)) & 0x8000800080008080ULL))
796
# else
797
#   define RS 3
798
    for(i=0; i+1<length; i+=5){
799
        if(!((~*(const uint32_t*)(src+i) & (*(const uint32_t*)(src+i) - 0x01000101U)) & 0x80008080U))
800
# endif
801
            continue;
802
        if(i>0 && !src[i]) i--;
803
        while(src[i]) i++;
804
#else
805
#   define RS 0
806
    for(i=0; i+1<length; i+=2){
807
        if(src[i]) continue;
808
        if(i>0 && src[i-1]==0) i--;
809
#endif
810
        if(i+2<length && src[i+1]==0 && src[i+2]<=3){
811
            if(src[i+2]!=3){
812
                /* startcode, so we must be past the end */
813
                length=i;
814
            }
815
            break;
816
        }
817
        i-= RS;
818
    }
819

    
820
    if(i>=length-1){ //no escaped 0
821
        *dst_length= length;
822
        *consumed= length+1; //+1 for the header
823
        return src;
824
    }
825

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

    
830
    if (dst == NULL){
831
        return NULL;
832
    }
833

    
834
//printf("decoding esc\n");
835
    memcpy(dst, src, i);
836
    si=di=i;
837
    while(si+2<length){
838
        //remove escapes (very rare 1:2^22)
839
        if(src[si+2]>3){
840
            dst[di++]= src[si++];
841
            dst[di++]= src[si++];
842
        }else if(src[si]==0 && src[si+1]==0){
843
            if(src[si+2]==3){ //escape
844
                dst[di++]= 0;
845
                dst[di++]= 0;
846
                si+=3;
847
                continue;
848
            }else //next start code
849
                goto nsc;
850
        }
851

    
852
        dst[di++]= src[si++];
853
    }
854
    while(si<length)
855
        dst[di++]= src[si++];
856
nsc:
857

    
858
    memset(dst+di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
859

    
860
    *dst_length= di;
861
    *consumed= si + 1;//+1 for the header
862
//FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
863
    return dst;
864
}
865

    
866
int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
867
    int v= *src;
868
    int r;
869

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

    
872
    for(r=1; r<9; r++){
873
        if(v&1) return r;
874
        v>>=1;
875
    }
876
    return 0;
877
}
878

    
879
/**
880
 * IDCT transforms the 16 dc values and dequantizes them.
881
 * @param qp quantization parameter
882
 */
883
static void h264_luma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
884
#define stride 16
885
    int i;
886
    int temp[16]; //FIXME check if this is a good idea
887
    static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
888
    static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
889

    
890
//memset(block, 64, 2*256);
891
//return;
892
    for(i=0; i<4; i++){
893
        const int offset= y_offset[i];
894
        const int z0= block[offset+stride*0] + block[offset+stride*4];
895
        const int z1= block[offset+stride*0] - block[offset+stride*4];
896
        const int z2= block[offset+stride*1] - block[offset+stride*5];
897
        const int z3= block[offset+stride*1] + block[offset+stride*5];
898

    
899
        temp[4*i+0]= z0+z3;
900
        temp[4*i+1]= z1+z2;
901
        temp[4*i+2]= z1-z2;
902
        temp[4*i+3]= z0-z3;
903
    }
904

    
905
    for(i=0; i<4; i++){
906
        const int offset= x_offset[i];
907
        const int z0= temp[4*0+i] + temp[4*2+i];
908
        const int z1= temp[4*0+i] - temp[4*2+i];
909
        const int z2= temp[4*1+i] - temp[4*3+i];
910
        const int z3= temp[4*1+i] + temp[4*3+i];
911

    
912
        block[stride*0 +offset]= ((((z0 + z3)*qmul + 128 ) >> 8)); //FIXME think about merging this into decode_residual
913
        block[stride*2 +offset]= ((((z1 + z2)*qmul + 128 ) >> 8));
914
        block[stride*8 +offset]= ((((z1 - z2)*qmul + 128 ) >> 8));
915
        block[stride*10+offset]= ((((z0 - z3)*qmul + 128 ) >> 8));
916
    }
917
}
918

    
919
#if 0
920
/**
921
 * DCT transforms the 16 dc values.
922
 * @param qp quantization parameter ??? FIXME
923
 */
924
static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
925
//    const int qmul= dequant_coeff[qp][0];
926
    int i;
927
    int temp[16]; //FIXME check if this is a good idea
928
    static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
929
    static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
930

931
    for(i=0; i<4; i++){
932
        const int offset= y_offset[i];
933
        const int z0= block[offset+stride*0] + block[offset+stride*4];
934
        const int z1= block[offset+stride*0] - block[offset+stride*4];
935
        const int z2= block[offset+stride*1] - block[offset+stride*5];
936
        const int z3= block[offset+stride*1] + block[offset+stride*5];
937

938
        temp[4*i+0]= z0+z3;
939
        temp[4*i+1]= z1+z2;
940
        temp[4*i+2]= z1-z2;
941
        temp[4*i+3]= z0-z3;
942
    }
943

944
    for(i=0; i<4; i++){
945
        const int offset= x_offset[i];
946
        const int z0= temp[4*0+i] + temp[4*2+i];
947
        const int z1= temp[4*0+i] - temp[4*2+i];
948
        const int z2= temp[4*1+i] - temp[4*3+i];
949
        const int z3= temp[4*1+i] + temp[4*3+i];
950

951
        block[stride*0 +offset]= (z0 + z3)>>1;
952
        block[stride*2 +offset]= (z1 + z2)>>1;
953
        block[stride*8 +offset]= (z1 - z2)>>1;
954
        block[stride*10+offset]= (z0 - z3)>>1;
955
    }
956
}
957
#endif
958

    
959
#undef xStride
960
#undef stride
961

    
962
static void chroma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
963
    const int stride= 16*2;
964
    const int xStride= 16;
965
    int a,b,c,d,e;
966

    
967
    a= block[stride*0 + xStride*0];
968
    b= block[stride*0 + xStride*1];
969
    c= block[stride*1 + xStride*0];
970
    d= block[stride*1 + xStride*1];
971

    
972
    e= a-b;
973
    a= a+b;
974
    b= c-d;
975
    c= c+d;
976

    
977
    block[stride*0 + xStride*0]= ((a+c)*qmul) >> 7;
978
    block[stride*0 + xStride*1]= ((e+b)*qmul) >> 7;
979
    block[stride*1 + xStride*0]= ((a-c)*qmul) >> 7;
980
    block[stride*1 + xStride*1]= ((e-b)*qmul) >> 7;
981
}
982

    
983
#if 0
984
static void chroma_dc_dct_c(DCTELEM *block){
985
    const int stride= 16*2;
986
    const int xStride= 16;
987
    int a,b,c,d,e;
988

989
    a= block[stride*0 + xStride*0];
990
    b= block[stride*0 + xStride*1];
991
    c= block[stride*1 + xStride*0];
992
    d= block[stride*1 + xStride*1];
993

994
    e= a-b;
995
    a= a+b;
996
    b= c-d;
997
    c= c+d;
998

999
    block[stride*0 + xStride*0]= (a+c);
1000
    block[stride*0 + xStride*1]= (e+b);
1001
    block[stride*1 + xStride*0]= (a-c);
1002
    block[stride*1 + xStride*1]= (e-b);
1003
}
1004
#endif
1005

    
1006
static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
1007
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1008
                           int src_x_offset, int src_y_offset,
1009
                           qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
1010
    MpegEncContext * const s = &h->s;
1011
    const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
1012
    int my=       h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
1013
    const int luma_xy= (mx&3) + ((my&3)<<2);
1014
    uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*h->mb_linesize;
1015
    uint8_t * src_cb, * src_cr;
1016
    int extra_width= h->emu_edge_width;
1017
    int extra_height= h->emu_edge_height;
1018
    int emu=0;
1019
    const int full_mx= mx>>2;
1020
    const int full_my= my>>2;
1021
    const int pic_width  = 16*s->mb_width;
1022
    const int pic_height = 16*s->mb_height >> MB_FIELD;
1023

    
1024
    if(mx&7) extra_width -= 3;
1025
    if(my&7) extra_height -= 3;
1026

    
1027
    if(   full_mx < 0-extra_width
1028
       || full_my < 0-extra_height
1029
       || full_mx + 16/*FIXME*/ > pic_width + extra_width
1030
       || full_my + 16/*FIXME*/ > pic_height + extra_height){
1031
        ff_emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*h->mb_linesize, h->mb_linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
1032
            src_y= s->edge_emu_buffer + 2 + 2*h->mb_linesize;
1033
        emu=1;
1034
    }
1035

    
1036
    qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
1037
    if(!square){
1038
        qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
1039
    }
1040

    
1041
    if(CONFIG_GRAY && s->flags&CODEC_FLAG_GRAY) return;
1042

    
1043
    if(MB_FIELD){
1044
        // chroma offset when predicting from a field of opposite parity
1045
        my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
1046
        emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
1047
    }
1048
    src_cb= pic->data[1] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
1049
    src_cr= pic->data[2] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
1050

    
1051
    if(emu){
1052
        ff_emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
1053
            src_cb= s->edge_emu_buffer;
1054
    }
1055
    chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
1056

    
1057
    if(emu){
1058
        ff_emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
1059
            src_cr= s->edge_emu_buffer;
1060
    }
1061
    chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
1062
}
1063

    
1064
static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
1065
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1066
                           int x_offset, int y_offset,
1067
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1068
                           qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
1069
                           int list0, int list1){
1070
    MpegEncContext * const s = &h->s;
1071
    qpel_mc_func *qpix_op=  qpix_put;
1072
    h264_chroma_mc_func chroma_op= chroma_put;
1073

    
1074
    dest_y  += 2*x_offset + 2*y_offset*h->  mb_linesize;
1075
    dest_cb +=   x_offset +   y_offset*h->mb_uvlinesize;
1076
    dest_cr +=   x_offset +   y_offset*h->mb_uvlinesize;
1077
    x_offset += 8*s->mb_x;
1078
    y_offset += 8*(s->mb_y >> MB_FIELD);
1079

    
1080
    if(list0){
1081
        Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
1082
        mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
1083
                           dest_y, dest_cb, dest_cr, x_offset, y_offset,
1084
                           qpix_op, chroma_op);
1085

    
1086
        qpix_op=  qpix_avg;
1087
        chroma_op= chroma_avg;
1088
    }
1089

    
1090
    if(list1){
1091
        Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
1092
        mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
1093
                           dest_y, dest_cb, dest_cr, x_offset, y_offset,
1094
                           qpix_op, chroma_op);
1095
    }
1096
}
1097

    
1098
static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
1099
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1100
                           int x_offset, int y_offset,
1101
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1102
                           h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
1103
                           h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
1104
                           int list0, int list1){
1105
    MpegEncContext * const s = &h->s;
1106

    
1107
    dest_y  += 2*x_offset + 2*y_offset*h->  mb_linesize;
1108
    dest_cb +=   x_offset +   y_offset*h->mb_uvlinesize;
1109
    dest_cr +=   x_offset +   y_offset*h->mb_uvlinesize;
1110
    x_offset += 8*s->mb_x;
1111
    y_offset += 8*(s->mb_y >> MB_FIELD);
1112

    
1113
    if(list0 && list1){
1114
        /* don't optimize for luma-only case, since B-frames usually
1115
         * use implicit weights => chroma too. */
1116
        uint8_t *tmp_cb = s->obmc_scratchpad;
1117
        uint8_t *tmp_cr = s->obmc_scratchpad + 8;
1118
        uint8_t *tmp_y  = s->obmc_scratchpad + 8*h->mb_uvlinesize;
1119
        int refn0 = h->ref_cache[0][ scan8[n] ];
1120
        int refn1 = h->ref_cache[1][ scan8[n] ];
1121

    
1122
        mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
1123
                    dest_y, dest_cb, dest_cr,
1124
                    x_offset, y_offset, qpix_put, chroma_put);
1125
        mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
1126
                    tmp_y, tmp_cb, tmp_cr,
1127
                    x_offset, y_offset, qpix_put, chroma_put);
1128

    
1129
        if(h->use_weight == 2){
1130
            int weight0 = h->implicit_weight[refn0][refn1];
1131
            int weight1 = 64 - weight0;
1132
            luma_weight_avg(  dest_y,  tmp_y,  h->  mb_linesize, 5, weight0, weight1, 0);
1133
            chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
1134
            chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
1135
        }else{
1136
            luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
1137
                            h->luma_weight[0][refn0], h->luma_weight[1][refn1],
1138
                            h->luma_offset[0][refn0] + h->luma_offset[1][refn1]);
1139
            chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1140
                            h->chroma_weight[0][refn0][0], h->chroma_weight[1][refn1][0],
1141
                            h->chroma_offset[0][refn0][0] + h->chroma_offset[1][refn1][0]);
1142
            chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1143
                            h->chroma_weight[0][refn0][1], h->chroma_weight[1][refn1][1],
1144
                            h->chroma_offset[0][refn0][1] + h->chroma_offset[1][refn1][1]);
1145
        }
1146
    }else{
1147
        int list = list1 ? 1 : 0;
1148
        int refn = h->ref_cache[list][ scan8[n] ];
1149
        Picture *ref= &h->ref_list[list][refn];
1150
        mc_dir_part(h, ref, n, square, chroma_height, delta, list,
1151
                    dest_y, dest_cb, dest_cr, x_offset, y_offset,
1152
                    qpix_put, chroma_put);
1153

    
1154
        luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
1155
                       h->luma_weight[list][refn], h->luma_offset[list][refn]);
1156
        if(h->use_weight_chroma){
1157
            chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1158
                             h->chroma_weight[list][refn][0], h->chroma_offset[list][refn][0]);
1159
            chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1160
                             h->chroma_weight[list][refn][1], h->chroma_offset[list][refn][1]);
1161
        }
1162
    }
1163
}
1164

    
1165
static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
1166
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1167
                           int x_offset, int y_offset,
1168
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1169
                           qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
1170
                           h264_weight_func *weight_op, h264_biweight_func *weight_avg,
1171
                           int list0, int list1){
1172
    if((h->use_weight==2 && list0 && list1
1173
        && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ] != 32))
1174
       || h->use_weight==1)
1175
        mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
1176
                         x_offset, y_offset, qpix_put, chroma_put,
1177
                         weight_op[0], weight_op[3], weight_avg[0], weight_avg[3], list0, list1);
1178
    else
1179
        mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
1180
                    x_offset, y_offset, qpix_put, chroma_put, qpix_avg, chroma_avg, list0, list1);
1181
}
1182

    
1183
static inline void prefetch_motion(H264Context *h, int list){
1184
    /* fetch pixels for estimated mv 4 macroblocks ahead
1185
     * optimized for 64byte cache lines */
1186
    MpegEncContext * const s = &h->s;
1187
    const int refn = h->ref_cache[list][scan8[0]];
1188
    if(refn >= 0){
1189
        const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
1190
        const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
1191
        uint8_t **src= h->ref_list[list][refn].data;
1192
        int off= mx + (my + (s->mb_x&3)*4)*h->mb_linesize + 64;
1193
        s->dsp.prefetch(src[0]+off, s->linesize, 4);
1194
        off= (mx>>1) + ((my>>1) + (s->mb_x&7))*s->uvlinesize + 64;
1195
        s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
1196
    }
1197
}
1198

    
1199
static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1200
                      qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
1201
                      qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
1202
                      h264_weight_func *weight_op, h264_biweight_func *weight_avg){
1203
    MpegEncContext * const s = &h->s;
1204
    const int mb_xy= h->mb_xy;
1205
    const int mb_type= s->current_picture.mb_type[mb_xy];
1206

    
1207
    assert(IS_INTER(mb_type));
1208

    
1209
    prefetch_motion(h, 0);
1210

    
1211
    if(IS_16X16(mb_type)){
1212
        mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
1213
                qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
1214
                &weight_op[0], &weight_avg[0],
1215
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1216
    }else if(IS_16X8(mb_type)){
1217
        mc_part(h, 0, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 0,
1218
                qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
1219
                &weight_op[1], &weight_avg[1],
1220
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1221
        mc_part(h, 8, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 4,
1222
                qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
1223
                &weight_op[1], &weight_avg[1],
1224
                IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
1225
    }else if(IS_8X16(mb_type)){
1226
        mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
1227
                qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1228
                &weight_op[2], &weight_avg[2],
1229
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1230
        mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
1231
                qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1232
                &weight_op[2], &weight_avg[2],
1233
                IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
1234
    }else{
1235
        int i;
1236

    
1237
        assert(IS_8X8(mb_type));
1238

    
1239
        for(i=0; i<4; i++){
1240
            const int sub_mb_type= h->sub_mb_type[i];
1241
            const int n= 4*i;
1242
            int x_offset= (i&1)<<2;
1243
            int y_offset= (i&2)<<1;
1244

    
1245
            if(IS_SUB_8X8(sub_mb_type)){
1246
                mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1247
                    qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1248
                    &weight_op[3], &weight_avg[3],
1249
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1250
            }else if(IS_SUB_8X4(sub_mb_type)){
1251
                mc_part(h, n  , 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1252
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
1253
                    &weight_op[4], &weight_avg[4],
1254
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1255
                mc_part(h, n+2, 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
1256
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
1257
                    &weight_op[4], &weight_avg[4],
1258
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1259
            }else if(IS_SUB_4X8(sub_mb_type)){
1260
                mc_part(h, n  , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1261
                    qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1262
                    &weight_op[5], &weight_avg[5],
1263
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1264
                mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
1265
                    qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1266
                    &weight_op[5], &weight_avg[5],
1267
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1268
            }else{
1269
                int j;
1270
                assert(IS_SUB_4X4(sub_mb_type));
1271
                for(j=0; j<4; j++){
1272
                    int sub_x_offset= x_offset + 2*(j&1);
1273
                    int sub_y_offset= y_offset +   (j&2);
1274
                    mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
1275
                        qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1276
                        &weight_op[6], &weight_avg[6],
1277
                        IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1278
                }
1279
            }
1280
        }
1281
    }
1282

    
1283
    prefetch_motion(h, 1);
1284
}
1285

    
1286
static av_cold void init_cavlc_level_tab(void){
1287
    int suffix_length, mask;
1288
    unsigned int i;
1289

    
1290
    for(suffix_length=0; suffix_length<7; suffix_length++){
1291
        for(i=0; i<(1<<LEVEL_TAB_BITS); i++){
1292
            int prefix= LEVEL_TAB_BITS - av_log2(2*i);
1293
            int level_code= (prefix<<suffix_length) + (i>>(LEVEL_TAB_BITS-prefix-1-suffix_length)) - (1<<suffix_length);
1294

    
1295
            mask= -(level_code&1);
1296
            level_code= (((2+level_code)>>1) ^ mask) - mask;
1297
            if(prefix + 1 + suffix_length <= LEVEL_TAB_BITS){
1298
                cavlc_level_tab[suffix_length][i][0]= level_code;
1299
                cavlc_level_tab[suffix_length][i][1]= prefix + 1 + suffix_length;
1300
            }else if(prefix + 1 <= LEVEL_TAB_BITS){
1301
                cavlc_level_tab[suffix_length][i][0]= prefix+100;
1302
                cavlc_level_tab[suffix_length][i][1]= prefix + 1;
1303
            }else{
1304
                cavlc_level_tab[suffix_length][i][0]= LEVEL_TAB_BITS+100;
1305
                cavlc_level_tab[suffix_length][i][1]= LEVEL_TAB_BITS;
1306
            }
1307
        }
1308
    }
1309
}
1310

    
1311
static av_cold void decode_init_vlc(void){
1312
    static int done = 0;
1313

    
1314
    if (!done) {
1315
        int i;
1316
        int offset;
1317
        done = 1;
1318

    
1319
        chroma_dc_coeff_token_vlc.table = chroma_dc_coeff_token_vlc_table;
1320
        chroma_dc_coeff_token_vlc.table_allocated = chroma_dc_coeff_token_vlc_table_size;
1321
        init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5,
1322
                 &chroma_dc_coeff_token_len [0], 1, 1,
1323
                 &chroma_dc_coeff_token_bits[0], 1, 1,
1324
                 INIT_VLC_USE_NEW_STATIC);
1325

    
1326
        offset = 0;
1327
        for(i=0; i<4; i++){
1328
            coeff_token_vlc[i].table = coeff_token_vlc_tables+offset;
1329
            coeff_token_vlc[i].table_allocated = coeff_token_vlc_tables_size[i];
1330
            init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17,
1331
                     &coeff_token_len [i][0], 1, 1,
1332
                     &coeff_token_bits[i][0], 1, 1,
1333
                     INIT_VLC_USE_NEW_STATIC);
1334
            offset += coeff_token_vlc_tables_size[i];
1335
        }
1336
        /*
1337
         * This is a one time safety check to make sure that
1338
         * the packed static coeff_token_vlc table sizes
1339
         * were initialized correctly.
1340
         */
1341
        assert(offset == FF_ARRAY_ELEMS(coeff_token_vlc_tables));
1342

    
1343
        for(i=0; i<3; i++){
1344
            chroma_dc_total_zeros_vlc[i].table = chroma_dc_total_zeros_vlc_tables[i];
1345
            chroma_dc_total_zeros_vlc[i].table_allocated = chroma_dc_total_zeros_vlc_tables_size;
1346
            init_vlc(&chroma_dc_total_zeros_vlc[i],
1347
                     CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,
1348
                     &chroma_dc_total_zeros_len [i][0], 1, 1,
1349
                     &chroma_dc_total_zeros_bits[i][0], 1, 1,
1350
                     INIT_VLC_USE_NEW_STATIC);
1351
        }
1352
        for(i=0; i<15; i++){
1353
            total_zeros_vlc[i].table = total_zeros_vlc_tables[i];
1354
            total_zeros_vlc[i].table_allocated = total_zeros_vlc_tables_size;
1355
            init_vlc(&total_zeros_vlc[i],
1356
                     TOTAL_ZEROS_VLC_BITS, 16,
1357
                     &total_zeros_len [i][0], 1, 1,
1358
                     &total_zeros_bits[i][0], 1, 1,
1359
                     INIT_VLC_USE_NEW_STATIC);
1360
        }
1361

    
1362
        for(i=0; i<6; i++){
1363
            run_vlc[i].table = run_vlc_tables[i];
1364
            run_vlc[i].table_allocated = run_vlc_tables_size;
1365
            init_vlc(&run_vlc[i],
1366
                     RUN_VLC_BITS, 7,
1367
                     &run_len [i][0], 1, 1,
1368
                     &run_bits[i][0], 1, 1,
1369
                     INIT_VLC_USE_NEW_STATIC);
1370
        }
1371
        run7_vlc.table = run7_vlc_table,
1372
        run7_vlc.table_allocated = run7_vlc_table_size;
1373
        init_vlc(&run7_vlc, RUN7_VLC_BITS, 16,
1374
                 &run_len [6][0], 1, 1,
1375
                 &run_bits[6][0], 1, 1,
1376
                 INIT_VLC_USE_NEW_STATIC);
1377

    
1378
        init_cavlc_level_tab();
1379
    }
1380
}
1381

    
1382
static void free_tables(H264Context *h){
1383
    int i;
1384
    H264Context *hx;
1385
    av_freep(&h->intra4x4_pred_mode);
1386
    av_freep(&h->chroma_pred_mode_table);
1387
    av_freep(&h->cbp_table);
1388
    av_freep(&h->mvd_table[0]);
1389
    av_freep(&h->mvd_table[1]);
1390
    av_freep(&h->direct_table);
1391
    av_freep(&h->non_zero_count);
1392
    av_freep(&h->slice_table_base);
1393
    h->slice_table= NULL;
1394

    
1395
    av_freep(&h->mb2b_xy);
1396
    av_freep(&h->mb2b8_xy);
1397

    
1398
    for(i = 0; i < MAX_THREADS; i++) {
1399
        hx = h->thread_context[i];
1400
        if(!hx) continue;
1401
        av_freep(&hx->top_borders[1]);
1402
        av_freep(&hx->top_borders[0]);
1403
        av_freep(&hx->s.obmc_scratchpad);
1404
        av_freep(&hx->rbsp_buffer[1]);
1405
        av_freep(&hx->rbsp_buffer[0]);
1406
        hx->rbsp_buffer_size[0] = 0;
1407
        hx->rbsp_buffer_size[1] = 0;
1408
        if (i) av_freep(&h->thread_context[i]);
1409
    }
1410
}
1411

    
1412
static void init_dequant8_coeff_table(H264Context *h){
1413
    int i,q,x;
1414
    const int transpose = (h->s.dsp.h264_idct8_add != ff_h264_idct8_add_c); //FIXME ugly
1415
    h->dequant8_coeff[0] = h->dequant8_buffer[0];
1416
    h->dequant8_coeff[1] = h->dequant8_buffer[1];
1417

    
1418
    for(i=0; i<2; i++ ){
1419
        if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
1420
            h->dequant8_coeff[1] = h->dequant8_buffer[0];
1421
            break;
1422
        }
1423

    
1424
        for(q=0; q<52; q++){
1425
            int shift = div6[q];
1426
            int idx = rem6[q];
1427
            for(x=0; x<64; x++)
1428
                h->dequant8_coeff[i][q][transpose ? (x>>3)|((x&7)<<3) : x] =
1429
                    ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
1430
                    h->pps.scaling_matrix8[i][x]) << shift;
1431
        }
1432
    }
1433
}
1434

    
1435
static void init_dequant4_coeff_table(H264Context *h){
1436
    int i,j,q,x;
1437
    const int transpose = (h->s.dsp.h264_idct_add != ff_h264_idct_add_c); //FIXME ugly
1438
    for(i=0; i<6; i++ ){
1439
        h->dequant4_coeff[i] = h->dequant4_buffer[i];
1440
        for(j=0; j<i; j++){
1441
            if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
1442
                h->dequant4_coeff[i] = h->dequant4_buffer[j];
1443
                break;
1444
            }
1445
        }
1446
        if(j<i)
1447
            continue;
1448

    
1449
        for(q=0; q<52; q++){
1450
            int shift = div6[q] + 2;
1451
            int idx = rem6[q];
1452
            for(x=0; x<16; x++)
1453
                h->dequant4_coeff[i][q][transpose ? (x>>2)|((x<<2)&0xF) : x] =
1454
                    ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
1455
                    h->pps.scaling_matrix4[i][x]) << shift;
1456
        }
1457
    }
1458
}
1459

    
1460
static void init_dequant_tables(H264Context *h){
1461
    int i,x;
1462
    init_dequant4_coeff_table(h);
1463
    if(h->pps.transform_8x8_mode)
1464
        init_dequant8_coeff_table(h);
1465
    if(h->sps.transform_bypass){
1466
        for(i=0; i<6; i++)
1467
            for(x=0; x<16; x++)
1468
                h->dequant4_coeff[i][0][x] = 1<<6;
1469
        if(h->pps.transform_8x8_mode)
1470
            for(i=0; i<2; i++)
1471
                for(x=0; x<64; x++)
1472
                    h->dequant8_coeff[i][0][x] = 1<<6;
1473
    }
1474
}
1475

    
1476

    
1477
int ff_h264_alloc_tables(H264Context *h){
1478
    MpegEncContext * const s = &h->s;
1479
    const int big_mb_num= s->mb_stride * (s->mb_height+1);
1480
    int x,y;
1481

    
1482
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode, big_mb_num * 8  * sizeof(uint8_t), fail)
1483

    
1484
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count    , big_mb_num * 16 * sizeof(uint8_t), fail)
1485
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
1486
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
1487

    
1488
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
1489
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 32*big_mb_num * sizeof(uint16_t), fail);
1490
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 32*big_mb_num * sizeof(uint16_t), fail);
1491
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 32*big_mb_num * sizeof(uint8_t) , fail);
1492

    
1493
    memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(*h->slice_table_base));
1494
    h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
1495

    
1496
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy  , big_mb_num * sizeof(uint32_t), fail);
1497
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b8_xy , big_mb_num * sizeof(uint32_t), fail);
1498
    for(y=0; y<s->mb_height; y++){
1499
        for(x=0; x<s->mb_width; x++){
1500
            const int mb_xy= x + y*s->mb_stride;
1501
            const int b_xy = 4*x + 4*y*h->b_stride;
1502
            const int b8_xy= 2*x + 2*y*h->b8_stride;
1503

    
1504
            h->mb2b_xy [mb_xy]= b_xy;
1505
            h->mb2b8_xy[mb_xy]= b8_xy;
1506
        }
1507
    }
1508

    
1509
    s->obmc_scratchpad = NULL;
1510

    
1511
    if(!h->dequant4_coeff[0])
1512
        init_dequant_tables(h);
1513

    
1514
    return 0;
1515
fail:
1516
    free_tables(h);
1517
    return -1;
1518
}
1519

    
1520
/**
1521
 * Mimic alloc_tables(), but for every context thread.
1522
 */
1523
static void clone_tables(H264Context *dst, H264Context *src){
1524
    dst->intra4x4_pred_mode       = src->intra4x4_pred_mode;
1525
    dst->non_zero_count           = src->non_zero_count;
1526
    dst->slice_table              = src->slice_table;
1527
    dst->cbp_table                = src->cbp_table;
1528
    dst->mb2b_xy                  = src->mb2b_xy;
1529
    dst->mb2b8_xy                 = src->mb2b8_xy;
1530
    dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;
1531
    dst->mvd_table[0]             = src->mvd_table[0];
1532
    dst->mvd_table[1]             = src->mvd_table[1];
1533
    dst->direct_table             = src->direct_table;
1534

    
1535
    dst->s.obmc_scratchpad = NULL;
1536
    ff_h264_pred_init(&dst->hpc, src->s.codec_id);
1537
}
1538

    
1539
/**
1540
 * Init context
1541
 * Allocate buffers which are not shared amongst multiple threads.
1542
 */
1543
static int context_init(H264Context *h){
1544
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t), fail)
1545
    FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t), fail)
1546

    
1547
    return 0;
1548
fail:
1549
    return -1; // free_tables will clean up for us
1550
}
1551

    
1552
static av_cold void common_init(H264Context *h){
1553
    MpegEncContext * const s = &h->s;
1554

    
1555
    s->width = s->avctx->width;
1556
    s->height = s->avctx->height;
1557
    s->codec_id= s->avctx->codec->id;
1558

    
1559
    ff_h264_pred_init(&h->hpc, s->codec_id);
1560

    
1561
    h->dequant_coeff_pps= -1;
1562
    s->unrestricted_mv=1;
1563
    s->decode=1; //FIXME
1564

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

    
1567
    memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
1568
    memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
1569
}
1570

    
1571
/**
1572
 * Reset SEI values at the beginning of the frame.
1573
 *
1574
 * @param h H.264 context.
1575
 */
1576
static void reset_sei(H264Context *h) {
1577
    h->sei_recovery_frame_cnt       = -1;
1578
    h->sei_dpb_output_delay         =  0;
1579
    h->sei_cpb_removal_delay        = -1;
1580
    h->sei_buffering_period_present =  0;
1581
}
1582

    
1583
av_cold int ff_h264_decode_init(AVCodecContext *avctx){
1584
    H264Context *h= avctx->priv_data;
1585
    MpegEncContext * const s = &h->s;
1586

    
1587
    MPV_decode_defaults(s);
1588

    
1589
    s->avctx = avctx;
1590
    common_init(h);
1591

    
1592
    s->out_format = FMT_H264;
1593
    s->workaround_bugs= avctx->workaround_bugs;
1594

    
1595
    // set defaults
1596
//    s->decode_mb= ff_h263_decode_mb;
1597
    s->quarter_sample = 1;
1598
    if(!avctx->has_b_frames)
1599
    s->low_delay= 1;
1600

    
1601
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1602

    
1603
    decode_init_vlc();
1604

    
1605
    if(avctx->extradata_size > 0 && avctx->extradata &&
1606
       *(char *)avctx->extradata == 1){
1607
        h->is_avc = 1;
1608
        h->got_avcC = 0;
1609
    } else {
1610
        h->is_avc = 0;
1611
    }
1612

    
1613
    h->thread_context[0] = h;
1614
    h->outputed_poc = INT_MIN;
1615
    h->prev_poc_msb= 1<<16;
1616
    reset_sei(h);
1617
    if(avctx->codec_id == CODEC_ID_H264){
1618
        if(avctx->ticks_per_frame == 1){
1619
            s->avctx->time_base.den *=2;
1620
        }
1621
        avctx->ticks_per_frame = 2;
1622
    }
1623
    return 0;
1624
}
1625

    
1626
int ff_h264_frame_start(H264Context *h){
1627
    MpegEncContext * const s = &h->s;
1628
    int i;
1629

    
1630
    if(MPV_frame_start(s, s->avctx) < 0)
1631
        return -1;
1632
    ff_er_frame_start(s);
1633
    /*
1634
     * MPV_frame_start uses pict_type to derive key_frame.
1635
     * This is incorrect for H.264; IDR markings must be used.
1636
     * Zero here; IDR markings per slice in frame or fields are ORed in later.
1637
     * See decode_nal_units().
1638
     */
1639
    s->current_picture_ptr->key_frame= 0;
1640
    s->current_picture_ptr->mmco_reset= 0;
1641

    
1642
    assert(s->linesize && s->uvlinesize);
1643

    
1644
    for(i=0; i<16; i++){
1645
        h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
1646
        h->block_offset[24+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
1647
    }
1648
    for(i=0; i<4; i++){
1649
        h->block_offset[16+i]=
1650
        h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1651
        h->block_offset[24+16+i]=
1652
        h->block_offset[24+20+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
1653
    }
1654

    
1655
    /* can't be in alloc_tables because linesize isn't known there.
1656
     * FIXME: redo bipred weight to not require extra buffer? */
1657
    for(i = 0; i < s->avctx->thread_count; i++)
1658
        if(!h->thread_context[i]->s.obmc_scratchpad)
1659
            h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
1660

    
1661
    /* some macroblocks will be accessed before they're available */
1662
    if(FRAME_MBAFF || s->avctx->thread_count > 1)
1663
        memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(*h->slice_table));
1664

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

    
1667
    // We mark the current picture as non-reference after allocating it, so
1668
    // that if we break out due to an error it can be released automatically
1669
    // in the next MPV_frame_start().
1670
    // SVQ3 as well as most other codecs have only last/next/current and thus
1671
    // get released even with set reference, besides SVQ3 and others do not
1672
    // mark frames as reference later "naturally".
1673
    if(s->codec_id != CODEC_ID_SVQ3)
1674
        s->current_picture_ptr->reference= 0;
1675

    
1676
    s->current_picture_ptr->field_poc[0]=
1677
    s->current_picture_ptr->field_poc[1]= INT_MAX;
1678
    assert(s->current_picture_ptr->long_ref==0);
1679

    
1680
    return 0;
1681
}
1682

    
1683
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){
1684
    MpegEncContext * const s = &h->s;
1685
    int i;
1686
    int step    = 1;
1687
    int offset  = 1;
1688
    int uvoffset= 1;
1689
    int top_idx = 1;
1690
    int skiplast= 0;
1691

    
1692
    src_y  -=   linesize;
1693
    src_cb -= uvlinesize;
1694
    src_cr -= uvlinesize;
1695

    
1696
    if(!simple && FRAME_MBAFF){
1697
        if(s->mb_y&1){
1698
            offset  = MB_MBAFF ? 1 : 17;
1699
            uvoffset= MB_MBAFF ? 1 : 9;
1700
            if(!MB_MBAFF){
1701
                *(uint64_t*)(h->top_borders[0][s->mb_x]+ 0)= *(uint64_t*)(src_y +  15*linesize);
1702
                *(uint64_t*)(h->top_borders[0][s->mb_x]+ 8)= *(uint64_t*)(src_y +8+15*linesize);
1703
                if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1704
                    *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+7*uvlinesize);
1705
                    *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+7*uvlinesize);
1706
                }
1707
            }
1708
        }else{
1709
            if(!MB_MBAFF){
1710
                h->left_border[0]= h->top_borders[0][s->mb_x][15];
1711
                if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1712
                    h->left_border[34   ]= h->top_borders[0][s->mb_x][16+7  ];
1713
                    h->left_border[34+18]= h->top_borders[0][s->mb_x][16+8+7];
1714
                }
1715
                skiplast= 1;
1716
            }
1717
            offset  =
1718
            uvoffset=
1719
            top_idx = MB_MBAFF ? 0 : 1;
1720
        }
1721
        step= MB_MBAFF ? 2 : 1;
1722
    }
1723

    
1724
    // There are two lines saved, the line above the the top macroblock of a pair,
1725
    // and the line above the bottom macroblock
1726
    h->left_border[offset]= h->top_borders[top_idx][s->mb_x][15];
1727
    for(i=1; i<17 - skiplast; i++){
1728
        h->left_border[offset+i*step]= src_y[15+i*  linesize];
1729
    }
1730

    
1731
    *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+0)= *(uint64_t*)(src_y +  16*linesize);
1732
    *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+8)= *(uint64_t*)(src_y +8+16*linesize);
1733

    
1734
    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1735
        h->left_border[uvoffset+34   ]= h->top_borders[top_idx][s->mb_x][16+7];
1736
        h->left_border[uvoffset+34+18]= h->top_borders[top_idx][s->mb_x][24+7];
1737
        for(i=1; i<9 - skiplast; i++){
1738
            h->left_border[uvoffset+34   +i*step]= src_cb[7+i*uvlinesize];
1739
            h->left_border[uvoffset+34+18+i*step]= src_cr[7+i*uvlinesize];
1740
        }
1741
        *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+16)= *(uint64_t*)(src_cb+8*uvlinesize);
1742
        *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+24)= *(uint64_t*)(src_cr+8*uvlinesize);
1743
    }
1744
}
1745

    
1746
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){
1747
    MpegEncContext * const s = &h->s;
1748
    int temp8, i;
1749
    uint64_t temp64;
1750
    int deblock_left;
1751
    int deblock_top;
1752
    int mb_xy;
1753
    int step    = 1;
1754
    int offset  = 1;
1755
    int uvoffset= 1;
1756
    int top_idx = 1;
1757

    
1758
    if(!simple && FRAME_MBAFF){
1759
        if(s->mb_y&1){
1760
            offset  = MB_MBAFF ? 1 : 17;
1761
            uvoffset= MB_MBAFF ? 1 : 9;
1762
        }else{
1763
            offset  =
1764
            uvoffset=
1765
            top_idx = MB_MBAFF ? 0 : 1;
1766
        }
1767
        step= MB_MBAFF ? 2 : 1;
1768
    }
1769

    
1770
    if(h->deblocking_filter == 2) {
1771
        mb_xy = h->mb_xy;
1772
        deblock_left = h->slice_table[mb_xy] == h->slice_table[mb_xy - 1];
1773
        deblock_top  = h->slice_table[mb_xy] == h->slice_table[h->top_mb_xy];
1774
    } else {
1775
        deblock_left = (s->mb_x > 0);
1776
        deblock_top =  (s->mb_y > !!MB_FIELD);
1777
    }
1778

    
1779
    src_y  -=   linesize + 1;
1780
    src_cb -= uvlinesize + 1;
1781
    src_cr -= uvlinesize + 1;
1782

    
1783
#define XCHG(a,b,t,xchg)\
1784
t= a;\
1785
if(xchg)\
1786
    a= b;\
1787
b= t;
1788

    
1789
    if(deblock_left){
1790
        for(i = !deblock_top; i<16; i++){
1791
            XCHG(h->left_border[offset+i*step], src_y [i*  linesize], temp8, xchg);
1792
        }
1793
        XCHG(h->left_border[offset+i*step], src_y [i*  linesize], temp8, 1);
1794
    }
1795

    
1796
    if(deblock_top){
1797
        XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
1798
        XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
1799
        if(s->mb_x+1 < s->mb_width){
1800
            XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
1801
        }
1802
    }
1803

    
1804
    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1805
        if(deblock_left){
1806
            for(i = !deblock_top; i<8; i++){
1807
                XCHG(h->left_border[uvoffset+34   +i*step], src_cb[i*uvlinesize], temp8, xchg);
1808
                XCHG(h->left_border[uvoffset+34+18+i*step], src_cr[i*uvlinesize], temp8, xchg);
1809
            }
1810
            XCHG(h->left_border[uvoffset+34   +i*step], src_cb[i*uvlinesize], temp8, 1);
1811
            XCHG(h->left_border[uvoffset+34+18+i*step], src_cr[i*uvlinesize], temp8, 1);
1812
        }
1813
        if(deblock_top){
1814
            XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
1815
            XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
1816
        }
1817
    }
1818
}
1819

    
1820
static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
1821
    MpegEncContext * const s = &h->s;
1822
    const int mb_x= s->mb_x;
1823
    const int mb_y= s->mb_y;
1824
    const int mb_xy= h->mb_xy;
1825
    const int mb_type= s->current_picture.mb_type[mb_xy];
1826
    uint8_t  *dest_y, *dest_cb, *dest_cr;
1827
    int linesize, uvlinesize /*dct_offset*/;
1828
    int i;
1829
    int *block_offset = &h->block_offset[0];
1830
    const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
1831
    /* is_h264 should always be true if SVQ3 is disabled. */
1832
    const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
1833
    void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
1834
    void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
1835

    
1836
    dest_y  = s->current_picture.data[0] + (mb_x + mb_y * s->linesize  ) * 16;
1837
    dest_cb = s->current_picture.data[1] + (mb_x + mb_y * s->uvlinesize) * 8;
1838
    dest_cr = s->current_picture.data[2] + (mb_x + mb_y * s->uvlinesize) * 8;
1839

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

    
1843
    if (!simple && MB_FIELD) {
1844
        linesize   = h->mb_linesize   = s->linesize * 2;
1845
        uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
1846
        block_offset = &h->block_offset[24];
1847
        if(mb_y&1){ //FIXME move out of this function?
1848
            dest_y -= s->linesize*15;
1849
            dest_cb-= s->uvlinesize*7;
1850
            dest_cr-= s->uvlinesize*7;
1851
        }
1852
        if(FRAME_MBAFF) {
1853
            int list;
1854
            for(list=0; list<h->list_count; list++){
1855
                if(!USES_LIST(mb_type, list))
1856
                    continue;
1857
                if(IS_16X16(mb_type)){
1858
                    int8_t *ref = &h->ref_cache[list][scan8[0]];
1859
                    fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
1860
                }else{
1861
                    for(i=0; i<16; i+=4){
1862
                        int ref = h->ref_cache[list][scan8[i]];
1863
                        if(ref >= 0)
1864
                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
1865
                    }
1866
                }
1867
            }
1868
        }
1869
    } else {
1870
        linesize   = h->mb_linesize   = s->linesize;
1871
        uvlinesize = h->mb_uvlinesize = s->uvlinesize;
1872
//        dct_offset = s->linesize * 16;
1873
    }
1874

    
1875
    if (!simple && IS_INTRA_PCM(mb_type)) {
1876
        for (i=0; i<16; i++) {
1877
            memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
1878
        }
1879
        for (i=0; i<8; i++) {
1880
            memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4,  8);
1881
            memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4,  8);
1882
        }
1883
    } else {
1884
        if(IS_INTRA(mb_type)){
1885
            if(h->deblocking_filter)
1886
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
1887

    
1888
            if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
1889
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
1890
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
1891
            }
1892

    
1893
            if(IS_INTRA4x4(mb_type)){
1894
                if(simple || !s->encoding){
1895
                    if(IS_8x8DCT(mb_type)){
1896
                        if(transform_bypass){
1897
                            idct_dc_add =
1898
                            idct_add    = s->dsp.add_pixels8;
1899
                        }else{
1900
                            idct_dc_add = s->dsp.h264_idct8_dc_add;
1901
                            idct_add    = s->dsp.h264_idct8_add;
1902
                        }
1903
                        for(i=0; i<16; i+=4){
1904
                            uint8_t * const ptr= dest_y + block_offset[i];
1905
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1906
                            if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1907
                                h->hpc.pred8x8l_add[dir](ptr, h->mb + i*16, linesize);
1908
                            }else{
1909
                                const int nnz = h->non_zero_count_cache[ scan8[i] ];
1910
                                h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
1911
                                                            (h->topright_samples_available<<i)&0x4000, linesize);
1912
                                if(nnz){
1913
                                    if(nnz == 1 && h->mb[i*16])
1914
                                        idct_dc_add(ptr, h->mb + i*16, linesize);
1915
                                    else
1916
                                        idct_add   (ptr, h->mb + i*16, linesize);
1917
                                }
1918
                            }
1919
                        }
1920
                    }else{
1921
                        if(transform_bypass){
1922
                            idct_dc_add =
1923
                            idct_add    = s->dsp.add_pixels4;
1924
                        }else{
1925
                            idct_dc_add = s->dsp.h264_idct_dc_add;
1926
                            idct_add    = s->dsp.h264_idct_add;
1927
                        }
1928
                        for(i=0; i<16; i++){
1929
                            uint8_t * const ptr= dest_y + block_offset[i];
1930
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
1931

    
1932
                            if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
1933
                                h->hpc.pred4x4_add[dir](ptr, h->mb + i*16, linesize);
1934
                            }else{
1935
                                uint8_t *topright;
1936
                                int nnz, tr;
1937
                                if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
1938
                                    const int topright_avail= (h->topright_samples_available<<i)&0x8000;
1939
                                    assert(mb_y || linesize <= block_offset[i]);
1940
                                    if(!topright_avail){
1941
                                        tr= ptr[3 - linesize]*0x01010101;
1942
                                        topright= (uint8_t*) &tr;
1943
                                    }else
1944
                                        topright= ptr + 4 - linesize;
1945
                                }else
1946
                                    topright= NULL;
1947

    
1948
                                h->hpc.pred4x4[ dir ](ptr, topright, linesize);
1949
                                nnz = h->non_zero_count_cache[ scan8[i] ];
1950
                                if(nnz){
1951
                                    if(is_h264){
1952
                                        if(nnz == 1 && h->mb[i*16])
1953
                                            idct_dc_add(ptr, h->mb + i*16, linesize);
1954
                                        else
1955
                                            idct_add   (ptr, h->mb + i*16, linesize);
1956
                                    }else
1957
                                        svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
1958
                                }
1959
                            }
1960
                        }
1961
                    }
1962
                }
1963
            }else{
1964
                h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
1965
                if(is_h264){
1966
                    if(!transform_bypass)
1967
                        h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[0][s->qscale][0]);
1968
                }else
1969
                    svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
1970
            }
1971
            if(h->deblocking_filter)
1972
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
1973
        }else if(is_h264){
1974
            hl_motion(h, dest_y, dest_cb, dest_cr,
1975
                      s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
1976
                      s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
1977
                      s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);
1978
        }
1979

    
1980

    
1981
        if(!IS_INTRA4x4(mb_type)){
1982
            if(is_h264){
1983
                if(IS_INTRA16x16(mb_type)){
1984
                    if(transform_bypass){
1985
                        if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
1986
                            h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb, linesize);
1987
                        }else{
1988
                            for(i=0; i<16; i++){
1989
                                if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16])
1990
                                    s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + i*16, linesize);
1991
                            }
1992
                        }
1993
                    }else{
1994
                         s->dsp.h264_idct_add16intra(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
1995
                    }
1996
                }else if(h->cbp&15){
1997
                    if(transform_bypass){
1998
                        const int di = IS_8x8DCT(mb_type) ? 4 : 1;
1999
                        idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
2000
                        for(i=0; i<16; i+=di){
2001
                            if(h->non_zero_count_cache[ scan8[i] ]){
2002
                                idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2003
                            }
2004
                        }
2005
                    }else{
2006
                        if(IS_8x8DCT(mb_type)){
2007
                            s->dsp.h264_idct8_add4(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
2008
                        }else{
2009
                            s->dsp.h264_idct_add16(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
2010
                        }
2011
                    }
2012
                }
2013
            }else{
2014
                for(i=0; i<16; i++){
2015
                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
2016
                        uint8_t * const ptr= dest_y + block_offset[i];
2017
                        svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
2018
                    }
2019
                }
2020
            }
2021
        }
2022

    
2023
        if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
2024
            uint8_t *dest[2] = {dest_cb, dest_cr};
2025
            if(transform_bypass){
2026
                if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
2027
                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + 16*16, uvlinesize);
2028
                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 20, h->mb + 20*16, uvlinesize);
2029
                }else{
2030
                    idct_add = s->dsp.add_pixels4;
2031
                    for(i=16; i<16+8; i++){
2032
                        if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16])
2033
                            idct_add   (dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2034
                    }
2035
                }
2036
            }else{
2037
                chroma_dc_dequant_idct_c(h->mb + 16*16, h->chroma_qp[0], h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
2038
                chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->chroma_qp[1], h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
2039
                if(is_h264){
2040
                    idct_add = s->dsp.h264_idct_add;
2041
                    idct_dc_add = s->dsp.h264_idct_dc_add;
2042
                    for(i=16; i<16+8; i++){
2043
                        if(h->non_zero_count_cache[ scan8[i] ])
2044
                            idct_add   (dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2045
                        else if(h->mb[i*16])
2046
                            idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2047
                    }
2048
                }else{
2049
                    for(i=16; i<16+8; i++){
2050
                        if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2051
                            uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
2052
                            svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
2053
                        }
2054
                    }
2055
                }
2056
            }
2057
        }
2058
    }
2059
    if(h->cbp || IS_INTRA(mb_type))
2060
        s->dsp.clear_blocks(h->mb);
2061

    
2062
    if(h->deblocking_filter) {
2063
        backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, simple);
2064
        fill_caches(h, mb_type, 1); //FIXME don't fill stuff which isn't used by filter_mb
2065
        h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2066
        h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2067
        if (!simple && FRAME_MBAFF) {
2068
            ff_h264_filter_mb     (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2069
        } else {
2070
            ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2071
        }
2072
    }
2073
}
2074

    
2075
/**
2076
 * Process a macroblock; this case avoids checks for expensive uncommon cases.
2077
 */
2078
static void hl_decode_mb_simple(H264Context *h){
2079
    hl_decode_mb_internal(h, 1);
2080
}
2081

    
2082
/**
2083
 * Process a macroblock; this handles edge cases, such as interlacing.
2084
 */
2085
static void av_noinline hl_decode_mb_complex(H264Context *h){
2086
    hl_decode_mb_internal(h, 0);
2087
}
2088

    
2089
void ff_h264_hl_decode_mb(H264Context *h){
2090
    MpegEncContext * const s = &h->s;
2091
    const int mb_xy= h->mb_xy;
2092
    const int mb_type= s->current_picture.mb_type[mb_xy];
2093
    int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
2094

    
2095
    if (is_complex)
2096
        hl_decode_mb_complex(h);
2097
    else hl_decode_mb_simple(h);
2098
}
2099

    
2100
static void pic_as_field(Picture *pic, const int parity){
2101
    int i;
2102
    for (i = 0; i < 4; ++i) {
2103
        if (parity == PICT_BOTTOM_FIELD)
2104
            pic->data[i] += pic->linesize[i];
2105
        pic->reference = parity;
2106
        pic->linesize[i] *= 2;
2107
    }
2108
    pic->poc= pic->field_poc[parity == PICT_BOTTOM_FIELD];
2109
}
2110

    
2111
static int split_field_copy(Picture *dest, Picture *src,
2112
                            int parity, int id_add){
2113
    int match = !!(src->reference & parity);
2114

    
2115
    if (match) {
2116
        *dest = *src;
2117
        if(parity != PICT_FRAME){
2118
            pic_as_field(dest, parity);
2119
            dest->pic_id *= 2;
2120
            dest->pic_id += id_add;
2121
        }
2122
    }
2123

    
2124
    return match;
2125
}
2126

    
2127
static int build_def_list(Picture *def, Picture **in, int len, int is_long, int sel){
2128
    int i[2]={0};
2129
    int index=0;
2130

    
2131
    while(i[0]<len || i[1]<len){
2132
        while(i[0]<len && !(in[ i[0] ] && (in[ i[0] ]->reference & sel)))
2133
            i[0]++;
2134
        while(i[1]<len && !(in[ i[1] ] && (in[ i[1] ]->reference & (sel^3))))
2135
            i[1]++;
2136
        if(i[0] < len){
2137
            in[ i[0] ]->pic_id= is_long ? i[0] : in[ i[0] ]->frame_num;
2138
            split_field_copy(&def[index++], in[ i[0]++ ], sel  , 1);
2139
        }
2140
        if(i[1] < len){
2141
            in[ i[1] ]->pic_id= is_long ? i[1] : in[ i[1] ]->frame_num;
2142
            split_field_copy(&def[index++], in[ i[1]++ ], sel^3, 0);
2143
        }
2144
    }
2145

    
2146
    return index;
2147
}
2148

    
2149
static int add_sorted(Picture **sorted, Picture **src, int len, int limit, int dir){
2150
    int i, best_poc;
2151
    int out_i= 0;
2152

    
2153
    for(;;){
2154
        best_poc= dir ? INT_MIN : INT_MAX;
2155

    
2156
        for(i=0; i<len; i++){
2157
            const int poc= src[i]->poc;
2158
            if(((poc > limit) ^ dir) && ((poc < best_poc) ^ dir)){
2159
                best_poc= poc;
2160
                sorted[out_i]= src[i];
2161
            }
2162
        }
2163
        if(best_poc == (dir ? INT_MIN : INT_MAX))
2164
            break;
2165
        limit= sorted[out_i++]->poc - dir;
2166
    }
2167
    return out_i;
2168
}
2169

    
2170
/**
2171
 * fills the default_ref_list.
2172
 */
2173
static int fill_default_ref_list(H264Context *h){
2174
    MpegEncContext * const s = &h->s;
2175
    int i, len;
2176

    
2177
    if(h->slice_type_nos==FF_B_TYPE){
2178
        Picture *sorted[32];
2179
        int cur_poc, list;
2180
        int lens[2];
2181

    
2182
        if(FIELD_PICTURE)
2183
            cur_poc= s->current_picture_ptr->field_poc[ s->picture_structure == PICT_BOTTOM_FIELD ];
2184
        else
2185
            cur_poc= s->current_picture_ptr->poc;
2186

    
2187
        for(list= 0; list<2; list++){
2188
            len= add_sorted(sorted    , h->short_ref, h->short_ref_count, cur_poc, 1^list);
2189
            len+=add_sorted(sorted+len, h->short_ref, h->short_ref_count, cur_poc, 0^list);
2190
            assert(len<=32);
2191
            len= build_def_list(h->default_ref_list[list]    , sorted     , len, 0, s->picture_structure);
2192
            len+=build_def_list(h->default_ref_list[list]+len, h->long_ref, 16 , 1, s->picture_structure);
2193
            assert(len<=32);
2194

    
2195
            if(len < h->ref_count[list])
2196
                memset(&h->default_ref_list[list][len], 0, sizeof(Picture)*(h->ref_count[list] - len));
2197
            lens[list]= len;
2198
        }
2199

    
2200
        if(lens[0] == lens[1] && lens[1] > 1){
2201
            for(i=0; h->default_ref_list[0][i].data[0] == h->default_ref_list[1][i].data[0] && i<lens[0]; i++);
2202
            if(i == lens[0])
2203
                FFSWAP(Picture, h->default_ref_list[1][0], h->default_ref_list[1][1]);
2204
        }
2205
    }else{
2206
        len = build_def_list(h->default_ref_list[0]    , h->short_ref, h->short_ref_count, 0, s->picture_structure);
2207
        len+= build_def_list(h->default_ref_list[0]+len, h-> long_ref, 16                , 1, s->picture_structure);
2208
        assert(len <= 32);
2209
        if(len < h->ref_count[0])
2210
            memset(&h->default_ref_list[0][len], 0, sizeof(Picture)*(h->ref_count[0] - len));
2211
    }
2212
#ifdef TRACE
2213
    for (i=0; i<h->ref_count[0]; i++) {
2214
        tprintf(h->s.avctx, "List0: %s fn:%d 0x%p\n", (h->default_ref_list[0][i].long_ref ? "LT" : "ST"), h->default_ref_list[0][i].pic_id, h->default_ref_list[0][i].data[0]);
2215
    }
2216
    if(h->slice_type_nos==FF_B_TYPE){
2217
        for (i=0; i<h->ref_count[1]; i++) {
2218
            tprintf(h->s.avctx, "List1: %s fn:%d 0x%p\n", (h->default_ref_list[1][i].long_ref ? "LT" : "ST"), h->default_ref_list[1][i].pic_id, h->default_ref_list[1][i].data[0]);
2219
        }
2220
    }
2221
#endif
2222
    return 0;
2223
}
2224

    
2225
static void print_short_term(H264Context *h);
2226
static void print_long_term(H264Context *h);
2227

    
2228
/**
2229
 * Extract structure information about the picture described by pic_num in
2230
 * the current decoding context (frame or field). Note that pic_num is
2231
 * picture number without wrapping (so, 0<=pic_num<max_pic_num).
2232
 * @param pic_num picture number for which to extract structure information
2233
 * @param structure one of PICT_XXX describing structure of picture
2234
 *                      with pic_num
2235
 * @return frame number (short term) or long term index of picture
2236
 *         described by pic_num
2237
 */
2238
static int pic_num_extract(H264Context *h, int pic_num, int *structure){
2239
    MpegEncContext * const s = &h->s;
2240

    
2241
    *structure = s->picture_structure;
2242
    if(FIELD_PICTURE){
2243
        if (!(pic_num & 1))
2244
            /* opposite field */
2245
            *structure ^= PICT_FRAME;
2246
        pic_num >>= 1;
2247
    }
2248

    
2249
    return pic_num;
2250
}
2251

    
2252
static int decode_ref_pic_list_reordering(H264Context *h){
2253
    MpegEncContext * const s = &h->s;
2254
    int list, index, pic_structure;
2255

    
2256
    print_short_term(h);
2257
    print_long_term(h);
2258

    
2259
    for(list=0; list<h->list_count; list++){
2260
        memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);
2261

    
2262
        if(get_bits1(&s->gb)){
2263
            int pred= h->curr_pic_num;
2264

    
2265
            for(index=0; ; index++){
2266
                unsigned int reordering_of_pic_nums_idc= get_ue_golomb_31(&s->gb);
2267
                unsigned int pic_id;
2268
                int i;
2269
                Picture *ref = NULL;
2270

    
2271
                if(reordering_of_pic_nums_idc==3)
2272
                    break;
2273

    
2274
                if(index >= h->ref_count[list]){
2275
                    av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
2276
                    return -1;
2277
                }
2278

    
2279
                if(reordering_of_pic_nums_idc<3){
2280
                    if(reordering_of_pic_nums_idc<2){
2281
                        const unsigned int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
2282
                        int frame_num;
2283

    
2284
                        if(abs_diff_pic_num > h->max_pic_num){
2285
                            av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
2286
                            return -1;
2287
                        }
2288

    
2289
                        if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
2290
                        else                                pred+= abs_diff_pic_num;
2291
                        pred &= h->max_pic_num - 1;
2292

    
2293
                        frame_num = pic_num_extract(h, pred, &pic_structure);
2294

    
2295
                        for(i= h->short_ref_count-1; i>=0; i--){
2296
                            ref = h->short_ref[i];
2297
                            assert(ref->reference);
2298
                            assert(!ref->long_ref);
2299
                            if(
2300
                                   ref->frame_num == frame_num &&
2301
                                   (ref->reference & pic_structure)
2302
                              )
2303
                                break;
2304
                        }
2305
                        if(i>=0)
2306
                            ref->pic_id= pred;
2307
                    }else{
2308
                        int long_idx;
2309
                        pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
2310

    
2311
                        long_idx= pic_num_extract(h, pic_id, &pic_structure);
2312

    
2313
                        if(long_idx>31){
2314
                            av_log(h->s.avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
2315
                            return -1;
2316
                        }
2317
                        ref = h->long_ref[long_idx];
2318
                        assert(!(ref && !ref->reference));
2319
                        if(ref && (ref->reference & pic_structure)){
2320
                            ref->pic_id= pic_id;
2321
                            assert(ref->long_ref);
2322
                            i=0;
2323
                        }else{
2324
                            i=-1;
2325
                        }
2326
                    }
2327

    
2328
                    if (i < 0) {
2329
                        av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
2330
                        memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
2331
                    } else {
2332
                        for(i=index; i+1<h->ref_count[list]; i++){
2333
                            if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)
2334
                                break;
2335
                        }
2336
                        for(; i > index; i--){
2337
                            h->ref_list[list][i]= h->ref_list[list][i-1];
2338
                        }
2339
                        h->ref_list[list][index]= *ref;
2340
                        if (FIELD_PICTURE){
2341
                            pic_as_field(&h->ref_list[list][index], pic_structure);
2342
                        }
2343
                    }
2344
                }else{
2345
                    av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
2346
                    return -1;
2347
                }
2348
            }
2349
        }
2350
    }
2351
    for(list=0; list<h->list_count; list++){
2352
        for(index= 0; index < h->ref_count[list]; index++){
2353
            if(!h->ref_list[list][index].data[0]){
2354
                av_log(h->s.avctx, AV_LOG_ERROR, "Missing reference picture\n");
2355
                if(h->default_ref_list[list][0].data[0])
2356
                    h->ref_list[list][index]= h->default_ref_list[list][0];
2357
                else
2358
                    return -1;
2359
            }
2360
        }
2361
    }
2362

    
2363
    return 0;
2364
}
2365

    
2366
static void fill_mbaff_ref_list(H264Context *h){
2367
    int list, i, j;
2368
    for(list=0; list<2; list++){ //FIXME try list_count
2369
        for(i=0; i<h->ref_count[list]; i++){
2370
            Picture *frame = &h->ref_list[list][i];
2371
            Picture *field = &h->ref_list[list][16+2*i];
2372
            field[0] = *frame;
2373
            for(j=0; j<3; j++)
2374
                field[0].linesize[j] <<= 1;
2375
            field[0].reference = PICT_TOP_FIELD;
2376
            field[0].poc= field[0].field_poc[0];
2377
            field[1] = field[0];
2378
            for(j=0; j<3; j++)
2379
                field[1].data[j] += frame->linesize[j];
2380
            field[1].reference = PICT_BOTTOM_FIELD;
2381
            field[1].poc= field[1].field_poc[1];
2382

    
2383
            h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i];
2384
            h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i];
2385
            for(j=0; j<2; j++){
2386
                h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j];
2387
                h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j];
2388
            }
2389
        }
2390
    }
2391
    for(j=0; j<h->ref_count[1]; j++){
2392
        for(i=0; i<h->ref_count[0]; i++)
2393
            h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i];
2394
        memcpy(h->implicit_weight[16+2*j],   h->implicit_weight[j], sizeof(*h->implicit_weight));
2395
        memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight));
2396
    }
2397
}
2398

    
2399
static int pred_weight_table(H264Context *h){
2400
    MpegEncContext * const s = &h->s;
2401
    int list, i;
2402
    int luma_def, chroma_def;
2403

    
2404
    h->use_weight= 0;
2405
    h->use_weight_chroma= 0;
2406
    h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
2407
    h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
2408
    luma_def = 1<<h->luma_log2_weight_denom;
2409
    chroma_def = 1<<h->chroma_log2_weight_denom;
2410

    
2411
    for(list=0; list<2; list++){
2412
        h->luma_weight_flag[list]   = 0;
2413
        h->chroma_weight_flag[list] = 0;
2414
        for(i=0; i<h->ref_count[list]; i++){
2415
            int luma_weight_flag, chroma_weight_flag;
2416

    
2417
            luma_weight_flag= get_bits1(&s->gb);
2418
            if(luma_weight_flag){
2419
                h->luma_weight[list][i]= get_se_golomb(&s->gb);
2420
                h->luma_offset[list][i]= get_se_golomb(&s->gb);
2421
                if(   h->luma_weight[list][i] != luma_def
2422
                   || h->luma_offset[list][i] != 0) {
2423
                    h->use_weight= 1;
2424
                    h->luma_weight_flag[list]= 1;
2425
                }
2426
            }else{
2427
                h->luma_weight[list][i]= luma_def;
2428
                h->luma_offset[list][i]= 0;
2429
            }
2430

    
2431
            if(CHROMA){
2432
                chroma_weight_flag= get_bits1(&s->gb);
2433
                if(chroma_weight_flag){
2434
                    int j;
2435
                    for(j=0; j<2; j++){
2436
                        h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
2437
                        h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
2438
                        if(   h->chroma_weight[list][i][j] != chroma_def
2439
                           || h->chroma_offset[list][i][j] != 0) {
2440
                            h->use_weight_chroma= 1;
2441
                            h->chroma_weight_flag[list]= 1;
2442
                        }
2443
                    }
2444
                }else{
2445
                    int j;
2446
                    for(j=0; j<2; j++){
2447
                        h->chroma_weight[list][i][j]= chroma_def;
2448
                        h->chroma_offset[list][i][j]= 0;
2449
                    }
2450
                }
2451
            }
2452
        }
2453
        if(h->slice_type_nos != FF_B_TYPE) break;
2454
    }
2455
    h->use_weight= h->use_weight || h->use_weight_chroma;
2456
    return 0;
2457
}
2458

    
2459
static void implicit_weight_table(H264Context *h){
2460
    MpegEncContext * const s = &h->s;
2461
    int ref0, ref1, i;
2462
    int cur_poc = s->current_picture_ptr->poc;
2463

    
2464
    for (i = 0; i < 2; i++) {
2465
        h->luma_weight_flag[i]   = 0;
2466
        h->chroma_weight_flag[i] = 0;
2467
    }
2468

    
2469
    if(   h->ref_count[0] == 1 && h->ref_count[1] == 1
2470
       && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
2471
        h->use_weight= 0;
2472
        h->use_weight_chroma= 0;
2473
        return;
2474
    }
2475

    
2476
    h->use_weight= 2;
2477
    h->use_weight_chroma= 2;
2478
    h->luma_log2_weight_denom= 5;
2479
    h->chroma_log2_weight_denom= 5;
2480

    
2481
    for(ref0=0; ref0 < h->ref_count[0]; ref0++){
2482
        int poc0 = h->ref_list[0][ref0].poc;
2483
        for(ref1=0; ref1 < h->ref_count[1]; ref1++){
2484
            int poc1 = h->ref_list[1][ref1].poc;
2485
            int td = av_clip(poc1 - poc0, -128, 127);
2486
            if(td){
2487
                int tb = av_clip(cur_poc - poc0, -128, 127);
2488
                int tx = (16384 + (FFABS(td) >> 1)) / td;
2489
                int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
2490
                if(dist_scale_factor < -64 || dist_scale_factor > 128)
2491
                    h->implicit_weight[ref0][ref1] = 32;
2492
                else
2493
                    h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
2494
            }else
2495
                h->implicit_weight[ref0][ref1] = 32;
2496
        }
2497
    }
2498
}
2499

    
2500
/**
2501
 * Mark a picture as no longer needed for reference. The refmask
2502
 * argument allows unreferencing of individual fields or the whole frame.
2503
 * If the picture becomes entirely unreferenced, but is being held for
2504
 * display purposes, it is marked as such.
2505
 * @param refmask mask of fields to unreference; the mask is bitwise
2506
 *                anded with the reference marking of pic
2507
 * @return non-zero if pic becomes entirely unreferenced (except possibly
2508
 *         for display purposes) zero if one of the fields remains in
2509
 *         reference
2510
 */
2511
static inline int unreference_pic(H264Context *h, Picture *pic, int refmask){
2512
    int i;
2513
    if (pic->reference &= refmask) {
2514
        return 0;
2515
    } else {
2516
        for(i = 0; h->delayed_pic[i]; i++)
2517
            if(pic == h->delayed_pic[i]){
2518
                pic->reference=DELAYED_PIC_REF;
2519
                break;
2520
            }
2521
        return 1;
2522
    }
2523
}
2524

    
2525
/**
2526
 * instantaneous decoder refresh.
2527
 */
2528
static void idr(H264Context *h){
2529
    int i;
2530

    
2531
    for(i=0; i<16; i++){
2532
        remove_long(h, i, 0);
2533
    }
2534
    assert(h->long_ref_count==0);
2535

    
2536
    for(i=0; i<h->short_ref_count; i++){
2537
        unreference_pic(h, h->short_ref[i], 0);
2538
        h->short_ref[i]= NULL;
2539
    }
2540
    h->short_ref_count=0;
2541
    h->prev_frame_num= 0;
2542
    h->prev_frame_num_offset= 0;
2543
    h->prev_poc_msb=
2544
    h->prev_poc_lsb= 0;
2545
}
2546

    
2547
/* forget old pics after a seek */
2548
static void flush_dpb(AVCodecContext *avctx){
2549
    H264Context *h= avctx->priv_data;
2550
    int i;
2551
    for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
2552
        if(h->delayed_pic[i])
2553
            h->delayed_pic[i]->reference= 0;
2554
        h->delayed_pic[i]= NULL;
2555
    }
2556
    h->outputed_poc= INT_MIN;
2557
    h->prev_interlaced_frame = 1;
2558
    idr(h);
2559
    if(h->s.current_picture_ptr)
2560
        h->s.current_picture_ptr->reference= 0;
2561
    h->s.first_field= 0;
2562
    reset_sei(h);
2563
    ff_mpeg_flush(avctx);
2564
}
2565

    
2566
/**
2567
 * Find a Picture in the short term reference list by frame number.
2568
 * @param frame_num frame number to search for
2569
 * @param idx the index into h->short_ref where returned picture is found
2570
 *            undefined if no picture found.
2571
 * @return pointer to the found picture, or NULL if no pic with the provided
2572
 *                 frame number is found
2573
 */
2574
static Picture * find_short(H264Context *h, int frame_num, int *idx){
2575
    MpegEncContext * const s = &h->s;
2576
    int i;
2577

    
2578
    for(i=0; i<h->short_ref_count; i++){
2579
        Picture *pic= h->short_ref[i];
2580
        if(s->avctx->debug&FF_DEBUG_MMCO)
2581
            av_log(h->s.avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
2582
        if(pic->frame_num == frame_num) {
2583
            *idx = i;
2584
            return pic;
2585
        }
2586
    }
2587
    return NULL;
2588
}
2589

    
2590
/**
2591
 * Remove a picture from the short term reference list by its index in
2592
 * that list.  This does no checking on the provided index; it is assumed
2593
 * to be valid. Other list entries are shifted down.
2594
 * @param i index into h->short_ref of picture to remove.
2595
 */
2596
static void remove_short_at_index(H264Context *h, int i){
2597
    assert(i >= 0 && i < h->short_ref_count);
2598
    h->short_ref[i]= NULL;
2599
    if (--h->short_ref_count)
2600
        memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i)*sizeof(Picture*));
2601
}
2602

    
2603
/**
2604
 *
2605
 * @return the removed picture or NULL if an error occurs
2606
 */
2607
static Picture * remove_short(H264Context *h, int frame_num, int ref_mask){
2608
    MpegEncContext * const s = &h->s;
2609
    Picture *pic;
2610
    int i;
2611

    
2612
    if(s->avctx->debug&FF_DEBUG_MMCO)
2613
        av_log(h->s.avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
2614

    
2615
    pic = find_short(h, frame_num, &i);
2616
    if (pic){
2617
        if(unreference_pic(h, pic, ref_mask))
2618
        remove_short_at_index(h, i);
2619
    }
2620

    
2621
    return pic;
2622
}
2623

    
2624
/**
2625
 * Remove a picture from the long term reference list by its index in
2626
 * that list.
2627
 * @return the removed picture or NULL if an error occurs
2628
 */
2629
static Picture * remove_long(H264Context *h, int i, int ref_mask){
2630
    Picture *pic;
2631

    
2632
    pic= h->long_ref[i];
2633
    if (pic){
2634
        if(unreference_pic(h, pic, ref_mask)){
2635
            assert(h->long_ref[i]->long_ref == 1);
2636
            h->long_ref[i]->long_ref= 0;
2637
            h->long_ref[i]= NULL;
2638
            h->long_ref_count--;
2639
        }
2640
    }
2641

    
2642
    return pic;
2643
}
2644

    
2645
/**
2646
 * print short term list
2647
 */
2648
static void print_short_term(H264Context *h) {
2649
    uint32_t i;
2650
    if(h->s.avctx->debug&FF_DEBUG_MMCO) {
2651
        av_log(h->s.avctx, AV_LOG_DEBUG, "short term list:\n");
2652
        for(i=0; i<h->short_ref_count; i++){
2653
            Picture *pic= h->short_ref[i];
2654
            av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
2655
        }
2656
    }
2657
}
2658

    
2659
/**
2660
 * print long term list
2661
 */
2662
static void print_long_term(H264Context *h) {
2663
    uint32_t i;
2664
    if(h->s.avctx->debug&FF_DEBUG_MMCO) {
2665
        av_log(h->s.avctx, AV_LOG_DEBUG, "long term list:\n");
2666
        for(i = 0; i < 16; i++){
2667
            Picture *pic= h->long_ref[i];
2668
            if (pic) {
2669
                av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
2670
            }
2671
        }
2672
    }
2673
}
2674

    
2675
/**
2676
 * Executes the reference picture marking (memory management control operations).
2677
 */
2678
static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
2679
    MpegEncContext * const s = &h->s;
2680
    int i, av_uninit(j);
2681
    int current_ref_assigned=0;
2682
    Picture *av_uninit(pic);
2683

    
2684
    if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)
2685
        av_log(h->s.avctx, AV_LOG_DEBUG, "no mmco here\n");
2686

    
2687
    for(i=0; i<mmco_count; i++){
2688
        int av_uninit(structure), av_uninit(frame_num);
2689
        if(s->avctx->debug&FF_DEBUG_MMCO)
2690
            av_log(h->s.avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode, h->mmco[i].short_pic_num, h->mmco[i].long_arg);
2691

    
2692
        if(   mmco[i].opcode == MMCO_SHORT2UNUSED
2693
           || mmco[i].opcode == MMCO_SHORT2LONG){
2694
            frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
2695
            pic = find_short(h, frame_num, &j);
2696
            if(!pic){
2697
                if(mmco[i].opcode != MMCO_SHORT2LONG || !h->long_ref[mmco[i].long_arg]
2698
                   || h->long_ref[mmco[i].long_arg]->frame_num != frame_num)
2699
                av_log(h->s.avctx, AV_LOG_ERROR, "mmco: unref short failure\n");
2700
                continue;
2701
            }
2702
        }
2703

    
2704
        switch(mmco[i].opcode){
2705
        case MMCO_SHORT2UNUSED:
2706
            if(s->avctx->debug&FF_DEBUG_MMCO)
2707
                av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref short %d count %d\n", h->mmco[i].short_pic_num, h->short_ref_count);
2708
            remove_short(h, frame_num, structure ^ PICT_FRAME);
2709
            break;
2710
        case MMCO_SHORT2LONG:
2711
                if (h->long_ref[mmco[i].long_arg] != pic)
2712
                    remove_long(h, mmco[i].long_arg, 0);
2713

    
2714
                remove_short_at_index(h, j);
2715
                h->long_ref[ mmco[i].long_arg ]= pic;
2716
                if (h->long_ref[ mmco[i].long_arg ]){
2717
                    h->long_ref[ mmco[i].long_arg ]->long_ref=1;
2718
                    h->long_ref_count++;
2719
                }
2720
            break;
2721
        case MMCO_LONG2UNUSED:
2722
            j = pic_num_extract(h, mmco[i].long_arg, &structure);
2723
            pic = h->long_ref[j];
2724
            if (pic) {
2725
                remove_long(h, j, structure ^ PICT_FRAME);
2726
            } else if(s->avctx->debug&FF_DEBUG_MMCO)
2727
                av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
2728
            break;
2729
        case MMCO_LONG:
2730
                    // Comment below left from previous code as it is an interresting note.
2731
                    /* First field in pair is in short term list or
2732
                     * at a different long term index.
2733
                     * This is not allowed; see 7.4.3.3, notes 2 and 3.
2734
                     * Report the problem and keep the pair where it is,
2735
                     * and mark this field valid.
2736
                     */
2737

    
2738
            if (h->long_ref[mmco[i].long_arg] != s->current_picture_ptr) {
2739
                remove_long(h, mmco[i].long_arg, 0);
2740

    
2741
                h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;
2742
                h->long_ref[ mmco[i].long_arg ]->long_ref=1;
2743
                h->long_ref_count++;
2744
            }
2745

    
2746
            s->current_picture_ptr->reference |= s->picture_structure;
2747
            current_ref_assigned=1;
2748
            break;
2749
        case MMCO_SET_MAX_LONG:
2750
            assert(mmco[i].long_arg <= 16);
2751
            // just remove the long term which index is greater than new max
2752
            for(j = mmco[i].long_arg; j<16; j++){
2753
                remove_long(h, j, 0);
2754
            }
2755
            break;
2756
        case MMCO_RESET:
2757
            while(h->short_ref_count){
2758
                remove_short(h, h->short_ref[0]->frame_num, 0);
2759
            }
2760
            for(j = 0; j < 16; j++) {
2761
                remove_long(h, j, 0);
2762
            }
2763
            s->current_picture_ptr->poc=
2764
            s->current_picture_ptr->field_poc[0]=
2765
            s->current_picture_ptr->field_poc[1]=
2766
            h->poc_lsb=
2767
            h->poc_msb=
2768
            h->frame_num=
2769
            s->current_picture_ptr->frame_num= 0;
2770
            s->current_picture_ptr->mmco_reset=1;
2771
            break;
2772
        default: assert(0);
2773
        }
2774
    }
2775

    
2776
    if (!current_ref_assigned) {
2777
        /* Second field of complementary field pair; the first field of
2778
         * which is already referenced. If short referenced, it
2779
         * should be first entry in short_ref. If not, it must exist
2780
         * in long_ref; trying to put it on the short list here is an
2781
         * error in the encoded bit stream (ref: 7.4.3.3, NOTE 2 and 3).
2782
         */
2783
        if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {
2784
            /* Just mark the second field valid */
2785
            s->current_picture_ptr->reference = PICT_FRAME;
2786
        } else if (s->current_picture_ptr->long_ref) {
2787
            av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "
2788
                                             "assignment for second field "
2789
                                             "in complementary field pair "
2790
                                             "(first field is long term)\n");
2791
        } else {
2792
            pic= remove_short(h, s->current_picture_ptr->frame_num, 0);
2793
            if(pic){
2794
                av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
2795
            }
2796

    
2797
            if(h->short_ref_count)
2798
                memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
2799

    
2800
            h->short_ref[0]= s->current_picture_ptr;
2801
            h->short_ref_count++;
2802
            s->current_picture_ptr->reference |= s->picture_structure;
2803
        }
2804
    }
2805

    
2806
    if (h->long_ref_count + h->short_ref_count > h->sps.ref_frame_count){
2807

    
2808
        /* We have too many reference frames, probably due to corrupted
2809
         * stream. Need to discard one frame. Prevents overrun of the
2810
         * short_ref and long_ref buffers.
2811
         */
2812
        av_log(h->s.avctx, AV_LOG_ERROR,
2813
               "number of reference frames exceeds max (probably "
2814
               "corrupt input), discarding one\n");
2815

    
2816
        if (h->long_ref_count && !h->short_ref_count) {
2817
            for (i = 0; i < 16; ++i)
2818
                if (h->long_ref[i])
2819
                    break;
2820

    
2821
            assert(i < 16);
2822
            remove_long(h, i, 0);
2823
        } else {
2824
            pic = h->short_ref[h->short_ref_count - 1];
2825
            remove_short(h, pic->frame_num, 0);
2826
        }
2827
    }
2828

    
2829
    print_short_term(h);
2830
    print_long_term(h);
2831
    return 0;
2832
}
2833

    
2834
static int decode_ref_pic_marking(H264Context *h, GetBitContext *gb){
2835
    MpegEncContext * const s = &h->s;
2836
    int i;
2837

    
2838
    h->mmco_index= 0;
2839
    if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields
2840
        s->broken_link= get_bits1(gb) -1;
2841
        if(get_bits1(gb)){
2842
            h->mmco[0].opcode= MMCO_LONG;
2843
            h->mmco[0].long_arg= 0;
2844
            h->mmco_index= 1;
2845
        }
2846
    }else{
2847
        if(get_bits1(gb)){ // adaptive_ref_pic_marking_mode_flag
2848
            for(i= 0; i<MAX_MMCO_COUNT; i++) {
2849
                MMCOOpcode opcode= get_ue_golomb_31(gb);
2850

    
2851
                h->mmco[i].opcode= opcode;
2852
                if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){
2853
                    h->mmco[i].short_pic_num= (h->curr_pic_num - get_ue_golomb(gb) - 1) & (h->max_pic_num - 1);
2854
/*                    if(h->mmco[i].short_pic_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_pic_num ] == NULL){
2855
                        av_log(s->avctx, AV_LOG_ERROR, "illegal short ref in memory management control operation %d\n", mmco);
2856
                        return -1;
2857
                    }*/
2858
                }
2859
                if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){
2860
                    unsigned int long_arg= get_ue_golomb_31(gb);
2861
                    if(long_arg >= 32 || (long_arg >= 16 && !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){
2862
                        av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);
2863
                        return -1;
2864
                    }
2865
                    h->mmco[i].long_arg= long_arg;
2866
                }
2867

    
2868
                if(opcode > (unsigned)MMCO_LONG){
2869
                    av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);
2870
                    return -1;
2871
                }
2872
                if(opcode == MMCO_END)
2873
                    break;
2874
            }
2875
            h->mmco_index= i;
2876
        }else{
2877
            assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
2878

    
2879
            if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
2880
                    !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {
2881
                h->mmco[0].opcode= MMCO_SHORT2UNUSED;
2882
                h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
2883
                h->mmco_index= 1;
2884
                if (FIELD_PICTURE) {
2885
                    h->mmco[0].short_pic_num *= 2;
2886
                    h->mmco[1].opcode= MMCO_SHORT2UNUSED;
2887
                    h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;
2888
                    h->mmco_index= 2;
2889
                }
2890
            }
2891
        }
2892
    }
2893

    
2894
    return 0;
2895
}
2896

    
2897
static int init_poc(H264Context *h){
2898
    MpegEncContext * const s = &h->s;
2899
    const int max_frame_num= 1<<h->sps.log2_max_frame_num;
2900
    int field_poc[2];
2901
    Picture *cur = s->current_picture_ptr;
2902

    
2903
    h->frame_num_offset= h->prev_frame_num_offset;
2904
    if(h->frame_num < h->prev_frame_num)
2905
        h->frame_num_offset += max_frame_num;
2906

    
2907
    if(h->sps.poc_type==0){
2908
        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
2909

    
2910
        if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
2911
            h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2912
        else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
2913
            h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2914
        else
2915
            h->poc_msb = h->prev_poc_msb;
2916
//printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2917
        field_poc[0] =
2918
        field_poc[1] = h->poc_msb + h->poc_lsb;
2919
        if(s->picture_structure == PICT_FRAME)
2920
            field_poc[1] += h->delta_poc_bottom;
2921
    }else if(h->sps.poc_type==1){
2922
        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2923
        int i;
2924

    
2925
        if(h->sps.poc_cycle_length != 0)
2926
            abs_frame_num = h->frame_num_offset + h->frame_num;
2927
        else
2928
            abs_frame_num = 0;
2929

    
2930
        if(h->nal_ref_idc==0 && abs_frame_num > 0)
2931
            abs_frame_num--;
2932

    
2933
        expected_delta_per_poc_cycle = 0;
2934
        for(i=0; i < h->sps.poc_cycle_length; i++)
2935
            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
2936

    
2937
        if(abs_frame_num > 0){
2938
            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2939
            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2940

    
2941
            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2942
            for(i = 0; i <= frame_num_in_poc_cycle; i++)
2943
                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
2944
        } else
2945
            expectedpoc = 0;
2946

    
2947
        if(h->nal_ref_idc == 0)
2948
            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2949

    
2950
        field_poc[0] = expectedpoc + h->delta_poc[0];
2951
        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2952

    
2953
        if(s->picture_structure == PICT_FRAME)
2954
            field_poc[1] += h->delta_poc[1];
2955
    }else{
2956
        int poc= 2*(h->frame_num_offset + h->frame_num);
2957

    
2958
        if(!h->nal_ref_idc)
2959
            poc--;
2960

    
2961
        field_poc[0]= poc;
2962
        field_poc[1]= poc;
2963
    }
2964

    
2965
    if(s->picture_structure != PICT_BOTTOM_FIELD)
2966
        s->current_picture_ptr->field_poc[0]= field_poc[0];
2967
    if(s->picture_structure != PICT_TOP_FIELD)
2968
        s->current_picture_ptr->field_poc[1]= field_poc[1];
2969
    cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
2970

    
2971
    return 0;
2972
}
2973

    
2974

    
2975
/**
2976
 * initialize scan tables
2977
 */
2978
static void init_scan_tables(H264Context *h){
2979
    MpegEncContext * const s = &h->s;
2980
    int i;
2981
    if(s->dsp.h264_idct_add == ff_h264_idct_add_c){ //FIXME little ugly
2982
        memcpy(h->zigzag_scan, zigzag_scan, 16*sizeof(uint8_t));
2983
        memcpy(h-> field_scan,  field_scan, 16*sizeof(uint8_t));
2984
    }else{
2985
        for(i=0; i<16; i++){
2986
#define T(x) (x>>2) | ((x<<2) & 0xF)
2987
            h->zigzag_scan[i] = T(zigzag_scan[i]);
2988
            h-> field_scan[i] = T( field_scan[i]);
2989
#undef T
2990
        }
2991
    }
2992
    if(s->dsp.h264_idct8_add == ff_h264_idct8_add_c){
2993
        memcpy(h->zigzag_scan8x8,       ff_zigzag_direct,     64*sizeof(uint8_t));
2994
        memcpy(h->zigzag_scan8x8_cavlc, zigzag_scan8x8_cavlc, 64*sizeof(uint8_t));
2995
        memcpy(h->field_scan8x8,        field_scan8x8,        64*sizeof(uint8_t));
2996
        memcpy(h->field_scan8x8_cavlc,  field_scan8x8_cavlc,  64*sizeof(uint8_t));
2997
    }else{
2998
        for(i=0; i<64; i++){
2999
#define T(x) (x>>3) | ((x&7)<<3)
3000
            h->zigzag_scan8x8[i]       = T(ff_zigzag_direct[i]);
3001
            h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
3002
            h->field_scan8x8[i]        = T(field_scan8x8[i]);
3003
            h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
3004
#undef T
3005
        }
3006
    }
3007
    if(h->sps.transform_bypass){ //FIXME same ugly
3008
        h->zigzag_scan_q0          = zigzag_scan;
3009
        h->zigzag_scan8x8_q0       = ff_zigzag_direct;
3010
        h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
3011
        h->field_scan_q0           = field_scan;
3012
        h->field_scan8x8_q0        = field_scan8x8;
3013
        h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
3014
    }else{
3015
        h->zigzag_scan_q0          = h->zigzag_scan;
3016
        h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
3017
        h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
3018
        h->field_scan_q0           = h->field_scan;
3019
        h->field_scan8x8_q0        = h->field_scan8x8;
3020
        h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
3021
    }
3022
}
3023

    
3024
static void field_end(H264Context *h){
3025
    MpegEncContext * const s = &h->s;
3026
    AVCodecContext * const avctx= s->avctx;
3027
    s->mb_y= 0;
3028

    
3029
    s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
3030
    s->current_picture_ptr->pict_type= s->pict_type;
3031

    
3032
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3033
        ff_vdpau_h264_set_reference_frames(s);
3034

    
3035
    if(!s->dropable) {
3036
        execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3037
        h->prev_poc_msb= h->poc_msb;
3038
        h->prev_poc_lsb= h->poc_lsb;
3039
    }
3040
    h->prev_frame_num_offset= h->frame_num_offset;
3041
    h->prev_frame_num= h->frame_num;
3042

    
3043
    if (avctx->hwaccel) {
3044
        if (avctx->hwaccel->end_frame(avctx) < 0)
3045
            av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
3046
    }
3047

    
3048
    if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
3049
        ff_vdpau_h264_picture_complete(s);
3050

    
3051
    /*
3052
     * FIXME: Error handling code does not seem to support interlaced
3053
     * when slices span multiple rows
3054
     * The ff_er_add_slice calls don't work right for bottom
3055
     * fields; they cause massive erroneous error concealing
3056
     * Error marking covers both fields (top and bottom).
3057
     * This causes a mismatched s->error_count
3058
     * and a bad error table. Further, the error count goes to
3059
     * INT_MAX when called for bottom field, because mb_y is
3060
     * past end by one (callers fault) and resync_mb_y != 0
3061
     * causes problems for the first MB line, too.
3062
     */
3063
    if (!FIELD_PICTURE)
3064
        ff_er_frame_end(s);
3065

    
3066
    MPV_frame_end(s);
3067

    
3068
    h->current_slice=0;
3069
}
3070

    
3071
/**
3072
 * Replicates H264 "master" context to thread contexts.
3073
 */
3074
static void clone_slice(H264Context *dst, H264Context *src)
3075
{
3076
    memcpy(dst->block_offset,     src->block_offset, sizeof(dst->block_offset));
3077
    dst->s.current_picture_ptr  = src->s.current_picture_ptr;
3078
    dst->s.current_picture      = src->s.current_picture;
3079
    dst->s.linesize             = src->s.linesize;
3080
    dst->s.uvlinesize           = src->s.uvlinesize;
3081
    dst->s.first_field          = src->s.first_field;
3082

    
3083
    dst->prev_poc_msb           = src->prev_poc_msb;
3084
    dst->prev_poc_lsb           = src->prev_poc_lsb;
3085
    dst->prev_frame_num_offset  = src->prev_frame_num_offset;
3086
    dst->prev_frame_num         = src->prev_frame_num;
3087
    dst->short_ref_count        = src->short_ref_count;
3088

    
3089
    memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
3090
    memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
3091
    memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3092
    memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
3093

    
3094
    memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
3095
    memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
3096
}
3097

    
3098
/**
3099
 * decodes a slice header.
3100
 * This will also call MPV_common_init() and frame_start() as needed.
3101
 *
3102
 * @param h h264context
3103
 * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
3104
 *
3105
 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3106
 */
3107
static int decode_slice_header(H264Context *h, H264Context *h0){
3108
    MpegEncContext * const s = &h->s;
3109
    MpegEncContext * const s0 = &h0->s;
3110
    unsigned int first_mb_in_slice;
3111
    unsigned int pps_id;
3112
    int num_ref_idx_active_override_flag;
3113
    unsigned int slice_type, tmp, i, j;
3114
    int default_ref_list_done = 0;
3115
    int last_pic_structure;
3116

    
3117
    s->dropable= h->nal_ref_idc == 0;
3118

    
3119
    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
3120
        s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
3121
        s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
3122
    }else{
3123
        s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
3124
        s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
3125
    }
3126

    
3127
    first_mb_in_slice= get_ue_golomb(&s->gb);
3128

    
3129
    if(first_mb_in_slice == 0){ //FIXME better field boundary detection
3130
        if(h0->current_slice && FIELD_PICTURE){
3131
            field_end(h);
3132
        }
3133

    
3134
        h0->current_slice = 0;
3135
        if (!s0->first_field)
3136
            s->current_picture_ptr= NULL;
3137
    }
3138

    
3139
    slice_type= get_ue_golomb_31(&s->gb);
3140
    if(slice_type > 9){
3141
        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);
3142
        return -1;
3143
    }
3144
    if(slice_type > 4){
3145
        slice_type -= 5;
3146
        h->slice_type_fixed=1;
3147
    }else
3148
        h->slice_type_fixed=0;
3149

    
3150
    slice_type= golomb_to_pict_type[ slice_type ];
3151
    if (slice_type == FF_I_TYPE
3152
        || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
3153
        default_ref_list_done = 1;
3154
    }
3155
    h->slice_type= slice_type;
3156
    h->slice_type_nos= slice_type & 3;
3157

    
3158
    s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
3159
    if (s->pict_type == FF_B_TYPE && s0->last_picture_ptr == NULL) {
3160
        av_log(h->s.avctx, AV_LOG_ERROR,
3161
               "B picture before any references, skipping\n");
3162
        return -1;
3163
    }
3164

    
3165
    pps_id= get_ue_golomb(&s->gb);
3166
    if(pps_id>=MAX_PPS_COUNT){
3167
        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
3168
        return -1;
3169
    }
3170
    if(!h0->pps_buffers[pps_id]) {
3171
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
3172
        return -1;
3173
    }
3174
    h->pps= *h0->pps_buffers[pps_id];
3175

    
3176
    if(!h0->sps_buffers[h->pps.sps_id]) {
3177
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
3178
        return -1;
3179
    }
3180
    h->sps = *h0->sps_buffers[h->pps.sps_id];
3181

    
3182
    if(h == h0 && h->dequant_coeff_pps != pps_id){
3183
        h->dequant_coeff_pps = pps_id;
3184
        init_dequant_tables(h);
3185
    }
3186

    
3187
    s->mb_width= h->sps.mb_width;
3188
    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3189

    
3190
    h->b_stride=  s->mb_width*4;
3191
    h->b8_stride= s->mb_width*2;
3192

    
3193
    s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
3194
    if(h->sps.frame_mbs_only_flag)
3195
        s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
3196
    else
3197
        s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 3);
3198

    
3199
    if (s->context_initialized
3200
        && (   s->width != s->avctx->width || s->height != s->avctx->height)) {
3201
        if(h != h0)
3202
            return -1;   // width / height changed during parallelized decoding
3203
        free_tables(h);
3204
        flush_dpb(s->avctx);
3205
        MPV_common_end(s);
3206
    }
3207
    if (!s->context_initialized) {
3208
        if(h != h0)
3209
            return -1;  // we cant (re-)initialize context during parallel decoding
3210

    
3211
        avcodec_set_dimensions(s->avctx, s->width, s->height);
3212
        s->avctx->sample_aspect_ratio= h->sps.sar;
3213
        if(!s->avctx->sample_aspect_ratio.den)
3214
            s->avctx->sample_aspect_ratio.den = 1;
3215

    
3216
        if(h->sps.video_signal_type_present_flag){
3217
            s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
3218
            if(h->sps.colour_description_present_flag){
3219
                s->avctx->color_primaries = h->sps.color_primaries;
3220
                s->avctx->color_trc       = h->sps.color_trc;
3221
                s->avctx->colorspace      = h->sps.colorspace;
3222
            }
3223
        }
3224

    
3225
        if(h->sps.timing_info_present_flag){
3226
            s->avctx->time_base= (AVRational){h->sps.num_units_in_tick, h->sps.time_scale};
3227
            if(h->x264_build > 0 && h->x264_build < 44)
3228
                s->avctx->time_base.den *= 2;
3229
            av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
3230
                      s->avctx->time_base.num, s->avctx->time_base.den, 1<<30);
3231
        }
3232
        s->avctx->pix_fmt = s->avctx->get_format(s->avctx, s->avctx->codec->pix_fmts);
3233
        s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
3234

    
3235
        if (MPV_common_init(s) < 0)
3236
            return -1;
3237
        s->first_field = 0;
3238
        h->prev_interlaced_frame = 1;
3239

    
3240
        init_scan_tables(h);
3241
        ff_h264_alloc_tables(h);
3242

    
3243
        for(i = 1; i < s->avctx->thread_count; i++) {
3244
            H264Context *c;
3245
            c = h->thread_context[i] = av_malloc(sizeof(H264Context));
3246
            memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
3247
            memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
3248
            c->sps = h->sps;
3249
            c->pps = h->pps;
3250
            init_scan_tables(c);
3251
            clone_tables(c, h);
3252
        }
3253

    
3254
        for(i = 0; i < s->avctx->thread_count; i++)
3255
            if(context_init(h->thread_context[i]) < 0)
3256
                return -1;
3257
    }
3258

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

    
3261
    h->mb_mbaff = 0;
3262
    h->mb_aff_frame = 0;
3263
    last_pic_structure = s0->picture_structure;
3264
    if(h->sps.frame_mbs_only_flag){
3265
        s->picture_structure= PICT_FRAME;
3266
    }else{
3267
        if(get_bits1(&s->gb)) { //field_pic_flag
3268
            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
3269
        } else {
3270
            s->picture_structure= PICT_FRAME;
3271
            h->mb_aff_frame = h->sps.mb_aff;
3272
        }
3273
    }
3274
    h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
3275

    
3276
    if(h0->current_slice == 0){
3277
        while(h->frame_num !=  h->prev_frame_num &&
3278
              h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
3279
            av_log(NULL, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
3280
            if (ff_h264_frame_start(h) < 0)
3281
                return -1;
3282
            h->prev_frame_num++;
3283
            h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
3284
            s->current_picture_ptr->frame_num= h->prev_frame_num;
3285
            execute_ref_pic_marking(h, NULL, 0);
3286
        }
3287

    
3288
        /* See if we have a decoded first field looking for a pair... */
3289
        if (s0->first_field) {
3290
            assert(s0->current_picture_ptr);
3291
            assert(s0->current_picture_ptr->data[0]);
3292
            assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
3293

    
3294
            /* figure out if we have a complementary field pair */
3295
            if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
3296
                /*
3297
                 * Previous field is unmatched. Don't display it, but let it
3298
                 * remain for reference if marked as such.
3299
                 */
3300
                s0->current_picture_ptr = NULL;
3301
                s0->first_field = FIELD_PICTURE;
3302

    
3303
            } else {
3304
                if (h->nal_ref_idc &&
3305
                        s0->current_picture_ptr->reference &&
3306
                        s0->current_picture_ptr->frame_num != h->frame_num) {
3307
                    /*
3308
                     * This and previous field were reference, but had
3309
                     * different frame_nums. Consider this field first in
3310
                     * pair. Throw away previous field except for reference
3311
                     * purposes.
3312
                     */
3313
                    s0->first_field = 1;
3314
                    s0->current_picture_ptr = NULL;
3315

    
3316
                } else {
3317
                    /* Second field in complementary pair */
3318
                    s0->first_field = 0;
3319
                }
3320
            }
3321

    
3322
        } else {
3323
            /* Frame or first field in a potentially complementary pair */
3324
            assert(!s0->current_picture_ptr);
3325
            s0->first_field = FIELD_PICTURE;
3326
        }
3327

    
3328
        if((!FIELD_PICTURE || s0->first_field) && ff_h264_frame_start(h) < 0) {
3329
            s0->first_field = 0;
3330
            return -1;
3331
        }
3332
    }
3333
    if(h != h0)
3334
        clone_slice(h, h0);
3335

    
3336
    s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
3337

    
3338
    assert(s->mb_num == s->mb_width * s->mb_height);
3339
    if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
3340
       first_mb_in_slice                    >= s->mb_num){
3341
        av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3342
        return -1;
3343
    }
3344
    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
3345
    s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
3346
    if (s->picture_structure == PICT_BOTTOM_FIELD)
3347
        s->resync_mb_y = s->mb_y = s->mb_y + 1;
3348
    assert(s->mb_y < s->mb_height);
3349

    
3350
    if(s->picture_structure==PICT_FRAME){
3351
        h->curr_pic_num=   h->frame_num;
3352
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
3353
    }else{
3354
        h->curr_pic_num= 2*h->frame_num + 1;
3355
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
3356
    }
3357

    
3358
    if(h->nal_unit_type == NAL_IDR_SLICE){
3359
        get_ue_golomb(&s->gb); /* idr_pic_id */
3360
    }
3361

    
3362
    if(h->sps.poc_type==0){
3363
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3364

    
3365
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
3366
            h->delta_poc_bottom= get_se_golomb(&s->gb);
3367
        }
3368
    }
3369

    
3370
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
3371
        h->delta_poc[0]= get_se_golomb(&s->gb);
3372

    
3373
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
3374
            h->delta_poc[1]= get_se_golomb(&s->gb);
3375
    }
3376

    
3377
    init_poc(h);
3378

    
3379
    if(h->pps.redundant_pic_cnt_present){
3380
        h->redundant_pic_count= get_ue_golomb(&s->gb);
3381
    }
3382

    
3383
    //set defaults, might be overridden a few lines later
3384
    h->ref_count[0]= h->pps.ref_count[0];
3385
    h->ref_count[1]= h->pps.ref_count[1];
3386

    
3387
    if(h->slice_type_nos != FF_I_TYPE){
3388
        if(h->slice_type_nos == FF_B_TYPE){
3389
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
3390
        }
3391
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
3392

    
3393
        if(num_ref_idx_active_override_flag){
3394
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
3395
            if(h->slice_type_nos==FF_B_TYPE)
3396
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
3397

    
3398
            if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
3399
                av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3400
                h->ref_count[0]= h->ref_count[1]= 1;
3401
                return -1;
3402
            }
3403
        }
3404
        if(h->slice_type_nos == FF_B_TYPE)
3405
            h->list_count= 2;
3406
        else
3407
            h->list_count= 1;
3408
    }else
3409
        h->list_count= 0;
3410

    
3411
    if(!default_ref_list_done){
3412
        fill_default_ref_list(h);
3413
    }
3414

    
3415
    if(h->slice_type_nos!=FF_I_TYPE && decode_ref_pic_list_reordering(h) < 0)
3416
        return -1;
3417

    
3418
    if(h->slice_type_nos!=FF_I_TYPE){
3419
        s->last_picture_ptr= &h->ref_list[0][0];
3420
        ff_copy_picture(&s->last_picture, s->last_picture_ptr);
3421
    }
3422
    if(h->slice_type_nos==FF_B_TYPE){
3423
        s->next_picture_ptr= &h->ref_list[1][0];
3424
        ff_copy_picture(&s->next_picture, s->next_picture_ptr);
3425
    }
3426

    
3427
    if(   (h->pps.weighted_pred          && h->slice_type_nos == FF_P_TYPE )
3428
       ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
3429
        pred_weight_table(h);
3430
    else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE)
3431
        implicit_weight_table(h);
3432
    else {
3433
        h->use_weight = 0;
3434
        for (i = 0; i < 2; i++) {
3435
            h->luma_weight_flag[i]   = 0;
3436
            h->chroma_weight_flag[i] = 0;
3437
        }
3438
    }
3439

    
3440
    if(h->nal_ref_idc)
3441
        decode_ref_pic_marking(h0, &s->gb);
3442

    
3443
    if(FRAME_MBAFF)
3444
        fill_mbaff_ref_list(h);
3445

    
3446
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
3447
        ff_h264_direct_dist_scale_factor(h);
3448
    ff_h264_direct_ref_list_init(h);
3449

    
3450
    if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
3451
        tmp = get_ue_golomb_31(&s->gb);
3452
        if(tmp > 2){
3453
            av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3454
            return -1;
3455
        }
3456
        h->cabac_init_idc= tmp;
3457
    }
3458

    
3459
    h->last_qscale_diff = 0;
3460
    tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3461
    if(tmp>51){
3462
        av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3463
        return -1;
3464
    }
3465
    s->qscale= tmp;
3466
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3467
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3468
    //FIXME qscale / qp ... stuff
3469
    if(h->slice_type == FF_SP_TYPE){
3470
        get_bits1(&s->gb); /* sp_for_switch_flag */
3471
    }
3472
    if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
3473
        get_se_golomb(&s->gb); /* slice_qs_delta */
3474
    }
3475

    
3476
    h->deblocking_filter = 1;
3477
    h->slice_alpha_c0_offset = 0;
3478
    h->slice_beta_offset = 0;
3479
    if( h->pps.deblocking_filter_parameters_present ) {
3480
        tmp= get_ue_golomb_31(&s->gb);
3481
        if(tmp > 2){
3482
            av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
3483
            return -1;
3484
        }
3485
        h->deblocking_filter= tmp;
3486
        if(h->deblocking_filter < 2)
3487
            h->deblocking_filter^= 1; // 1<->0
3488

    
3489
        if( h->deblocking_filter ) {
3490
            h->slice_alpha_c0_offset = get_se_golomb(&s->gb) << 1;
3491
            h->slice_beta_offset = get_se_golomb(&s->gb) << 1;
3492
        }
3493
    }
3494

    
3495
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
3496
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
3497
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
3498
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
3499
        h->deblocking_filter= 0;
3500

    
3501
    if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
3502
        if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
3503
            /* Cheat slightly for speed:
3504
               Do not bother to deblock across slices. */
3505
            h->deblocking_filter = 2;
3506
        } else {
3507
            h0->max_contexts = 1;
3508
            if(!h0->single_decode_warning) {
3509
                av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3510
                h0->single_decode_warning = 1;
3511
            }
3512
            if(h != h0)
3513
                return 1; // deblocking switched inside frame
3514
        }
3515
    }
3516

    
3517
#if 0 //FMO
3518
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
3519
        slice_group_change_cycle= get_bits(&s->gb, ?);
3520
#endif
3521

    
3522
    h0->last_slice_type = slice_type;
3523
    h->slice_num = ++h0->current_slice;
3524
    if(h->slice_num >= MAX_SLICES){
3525
        av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
3526
    }
3527

    
3528
    for(j=0; j<2; j++){
3529
        int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
3530
        ref2frm[0]=
3531
        ref2frm[1]= -1;
3532
        for(i=0; i<16; i++)
3533
            ref2frm[i+2]= 4*h->ref_list[j][i].frame_num
3534
                          +(h->ref_list[j][i].reference&3);
3535
        ref2frm[18+0]=
3536
        ref2frm[18+1]= -1;
3537
        for(i=16; i<48; i++)
3538
            ref2frm[i+4]= 4*h->ref_list[j][i].frame_num
3539
                          +(h->ref_list[j][i].reference&3);
3540
    }
3541

    
3542
    h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16;
3543
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3544

    
3545
    s->avctx->refs= h->sps.ref_frame_count;
3546

    
3547
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
3548
        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",
3549
               h->slice_num,
3550
               (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
3551
               first_mb_in_slice,
3552
               av_get_pict_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3553
               pps_id, h->frame_num,
3554
               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
3555
               h->ref_count[0], h->ref_count[1],
3556
               s->qscale,
3557
               h->deblocking_filter, h->slice_alpha_c0_offset/2, h->slice_beta_offset/2,
3558
               h->use_weight,
3559
               h->use_weight==1 && h->use_weight_chroma ? "c" : "",
3560
               h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
3561
               );
3562
    }
3563

    
3564
    return 0;
3565
}
3566

    
3567
int ff_h264_get_slice_type(H264Context *h)
3568
{
3569
    switch (h->slice_type) {
3570
    case FF_P_TYPE:  return 0;
3571
    case FF_B_TYPE:  return 1;
3572
    case FF_I_TYPE:  return 2;
3573
    case FF_SP_TYPE: return 3;
3574
    case FF_SI_TYPE: return 4;
3575
    default:         return -1;
3576
    }
3577
}
3578

    
3579
/**
3580
 *
3581
 */
3582
static inline int get_level_prefix(GetBitContext *gb){
3583
    unsigned int buf;
3584
    int log;
3585

    
3586
    OPEN_READER(re, gb);
3587
    UPDATE_CACHE(re, gb);
3588
    buf=GET_CACHE(re, gb);
3589

    
3590
    log= 32 - av_log2(buf);
3591
#ifdef TRACE
3592
    print_bin(buf>>(32-log), log);
3593
    av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d lpr @%5d in %s get_level_prefix\n", buf>>(32-log), log, log-1, get_bits_count(gb), __FILE__);
3594
#endif
3595

    
3596
    LAST_SKIP_BITS(re, gb, log);
3597
    CLOSE_READER(re, gb);
3598

    
3599
    return log-1;
3600
}
3601

    
3602
static inline int get_dct8x8_allowed(H264Context *h){
3603
    if(h->sps.direct_8x8_inference_flag)
3604
        return !(*(uint64_t*)h->sub_mb_type & ((MB_TYPE_16x8|MB_TYPE_8x16|MB_TYPE_8x8                )*0x0001000100010001ULL));
3605
    else
3606
        return !(*(uint64_t*)h->sub_mb_type & ((MB_TYPE_16x8|MB_TYPE_8x16|MB_TYPE_8x8|MB_TYPE_DIRECT2)*0x0001000100010001ULL));
3607
}
3608

    
3609
/**
3610
 * decodes a residual block.
3611
 * @param n block index
3612
 * @param scantable scantable
3613
 * @param max_coeff number of coefficients in the block
3614
 * @return <0 if an error occurred
3615
 */
3616
static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff){
3617
    MpegEncContext * const s = &h->s;
3618
    static const int coeff_token_table_index[17]= {0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3};
3619
    int level[16];
3620
    int zeros_left, coeff_num, coeff_token, total_coeff, i, j, trailing_ones, run_before;
3621

    
3622
    //FIXME put trailing_onex into the context
3623

    
3624
    if(n == CHROMA_DC_BLOCK_INDEX){
3625
        coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
3626
        total_coeff= coeff_token>>2;
3627
    }else{
3628
        if(n == LUMA_DC_BLOCK_INDEX){
3629
            total_coeff= pred_non_zero_count(h, 0);
3630
            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
3631
            total_coeff= coeff_token>>2;
3632
        }else{
3633
            total_coeff= pred_non_zero_count(h, n);
3634
            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
3635
            total_coeff= coeff_token>>2;
3636
            h->non_zero_count_cache[ scan8[n] ]= total_coeff;
3637
        }
3638
    }
3639

    
3640
    //FIXME set last_non_zero?
3641

    
3642
    if(total_coeff==0)
3643
        return 0;
3644
    if(total_coeff > (unsigned)max_coeff) {
3645
        av_log(h->s.avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", s->mb_x, s->mb_y, total_coeff);
3646
        return -1;
3647
    }
3648

    
3649
    trailing_ones= coeff_token&3;
3650
    tprintf(h->s.avctx, "trailing:%d, total:%d\n", trailing_ones, total_coeff);
3651
    assert(total_coeff<=16);
3652

    
3653
    i = show_bits(gb, 3);
3654
    skip_bits(gb, trailing_ones);
3655
    level[0] = 1-((i&4)>>1);
3656
    level[1] = 1-((i&2)   );
3657
    level[2] = 1-((i&1)<<1);
3658

    
3659
    if(trailing_ones<total_coeff) {
3660
        int mask, prefix;
3661
        int suffix_length = total_coeff > 10 && trailing_ones < 3;
3662
        int bitsi= show_bits(gb, LEVEL_TAB_BITS);
3663
        int level_code= cavlc_level_tab[suffix_length][bitsi][0];
3664

    
3665
        skip_bits(gb, cavlc_level_tab[suffix_length][bitsi][1]);
3666
        if(level_code >= 100){
3667
            prefix= level_code - 100;
3668
            if(prefix == LEVEL_TAB_BITS)
3669
                prefix += get_level_prefix(gb);
3670

    
3671
            //first coefficient has suffix_length equal to 0 or 1
3672
            if(prefix<14){ //FIXME try to build a large unified VLC table for all this
3673
                if(suffix_length)
3674
                    level_code= (prefix<<1) + get_bits1(gb); //part
3675
                else
3676
                    level_code= prefix; //part
3677
            }else if(prefix==14){
3678
                if(suffix_length)
3679
                    level_code= (prefix<<1) + get_bits1(gb); //part
3680
                else
3681
                    level_code= prefix + get_bits(gb, 4); //part
3682
            }else{
3683
                level_code= 30 + get_bits(gb, prefix-3); //part
3684
                if(prefix>=16)
3685
                    level_code += (1<<(prefix-3))-4096;
3686
            }
3687

    
3688
            if(trailing_ones < 3) level_code += 2;
3689

    
3690
            suffix_length = 2;
3691
            mask= -(level_code&1);
3692
            level[trailing_ones]= (((2+level_code)>>1) ^ mask) - mask;
3693
        }else{
3694
            if(trailing_ones < 3) level_code += (level_code>>31)|1;
3695

    
3696
            suffix_length = 1;
3697
            if(level_code + 3U > 6U)
3698
                suffix_length++;
3699
            level[trailing_ones]= level_code;
3700
        }
3701

    
3702
        //remaining coefficients have suffix_length > 0
3703
        for(i=trailing_ones+1;i<total_coeff;i++) {
3704
            static const unsigned int suffix_limit[7] = {0,3,6,12,24,48,INT_MAX };
3705
            int bitsi= show_bits(gb, LEVEL_TAB_BITS);
3706
            level_code= cavlc_level_tab[suffix_length][bitsi][0];
3707

    
3708
            skip_bits(gb, cavlc_level_tab[suffix_length][bitsi][1]);
3709
            if(level_code >= 100){
3710
                prefix= level_code - 100;
3711
                if(prefix == LEVEL_TAB_BITS){
3712
                    prefix += get_level_prefix(gb);
3713
                }
3714
                if(prefix<15){
3715
                    level_code = (prefix<<suffix_length) + get_bits(gb, suffix_length);
3716
                }else{
3717
                    level_code = (15<<suffix_length) + get_bits(gb, prefix-3);
3718
                    if(prefix>=16)
3719
                        level_code += (1<<(prefix-3))-4096;
3720
                }
3721
                mask= -(level_code&1);
3722
                level_code= (((2+level_code)>>1) ^ mask) - mask;
3723
            }
3724
            level[i]= level_code;
3725

    
3726
            if(suffix_limit[suffix_length] + level_code > 2U*suffix_limit[suffix_length])
3727
                suffix_length++;
3728
        }
3729
    }
3730

    
3731
    if(total_coeff == max_coeff)
3732
        zeros_left=0;
3733
    else{
3734
        if(n == CHROMA_DC_BLOCK_INDEX)
3735
            zeros_left= get_vlc2(gb, chroma_dc_total_zeros_vlc[ total_coeff-1 ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
3736
        else
3737
            zeros_left= get_vlc2(gb, total_zeros_vlc[ total_coeff-1 ].table, TOTAL_ZEROS_VLC_BITS, 1);
3738
    }
3739

    
3740
    coeff_num = zeros_left + total_coeff - 1;
3741
    j = scantable[coeff_num];
3742
    if(n > 24){
3743
        block[j] = level[0];
3744
        for(i=1;i<total_coeff;i++) {
3745
            if(zeros_left <= 0)
3746
                run_before = 0;
3747
            else if(zeros_left < 7){
3748
                run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
3749
            }else{
3750
                run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
3751
            }
3752
            zeros_left -= run_before;
3753
            coeff_num -= 1 + run_before;
3754
            j= scantable[ coeff_num ];
3755

    
3756
            block[j]= level[i];
3757
        }
3758
    }else{
3759
        block[j] = (level[0] * qmul[j] + 32)>>6;
3760
        for(i=1;i<total_coeff;i++) {
3761
            if(zeros_left <= 0)
3762
                run_before = 0;
3763
            else if(zeros_left < 7){
3764
                run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
3765
            }else{
3766
                run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
3767
            }
3768
            zeros_left -= run_before;
3769
            coeff_num -= 1 + run_before;
3770
            j= scantable[ coeff_num ];
3771

    
3772
            block[j]= (level[i] * qmul[j] + 32)>>6;
3773
        }
3774
    }
3775

    
3776
    if(zeros_left<0){
3777
        av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);
3778
        return -1;
3779
    }
3780

    
3781
    return 0;
3782
}
3783

    
3784
static void predict_field_decoding_flag(H264Context *h){
3785
    MpegEncContext * const s = &h->s;
3786
    const int mb_xy= h->mb_xy;
3787
    int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
3788
                ? s->current_picture.mb_type[mb_xy-1]
3789
                : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
3790
                ? s->current_picture.mb_type[mb_xy-s->mb_stride]
3791
                : 0;
3792
    h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
3793
}
3794

    
3795
/**
3796
 * decodes a P_SKIP or B_SKIP macroblock
3797
 */
3798
static void decode_mb_skip(H264Context *h){
3799
    MpegEncContext * const s = &h->s;
3800
    const int mb_xy= h->mb_xy;
3801
    int mb_type=0;
3802

    
3803
    memset(h->non_zero_count[mb_xy], 0, 16);
3804
    memset(h->non_zero_count_cache + 8, 0, 8*5); //FIXME ugly, remove pfui
3805

    
3806
    if(MB_FIELD)
3807
        mb_type|= MB_TYPE_INTERLACED;
3808

    
3809
    if( h->slice_type_nos == FF_B_TYPE )
3810
    {
3811
        // just for fill_caches. pred_direct_motion will set the real mb_type
3812
        mb_type|= MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_SKIP;
3813

    
3814
        fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
3815
        ff_h264_pred_direct_motion(h, &mb_type);
3816
        mb_type|= MB_TYPE_SKIP;
3817
    }
3818
    else
3819
    {
3820
        int mx, my;
3821
        mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P1L0|MB_TYPE_SKIP;
3822

    
3823
        fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
3824
        pred_pskip_motion(h, &mx, &my);
3825
        fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
3826
        fill_rectangle(  h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx,my), 4);
3827
    }
3828

    
3829
    write_back_motion(h, mb_type);
3830
    s->current_picture.mb_type[mb_xy]= mb_type;
3831
    s->current_picture.qscale_table[mb_xy]= s->qscale;
3832
    h->slice_table[ mb_xy ]= h->slice_num;
3833
    h->prev_mb_skipped= 1;
3834
}
3835

    
3836
/**
3837
 * decodes a macroblock
3838
 * @returns 0 if OK, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
3839
 */
3840
static int decode_mb_cavlc(H264Context *h){
3841
    MpegEncContext * const s = &h->s;
3842
    int mb_xy;
3843
    int partition_count;
3844
    unsigned int mb_type, cbp;
3845
    int dct8x8_allowed= h->pps.transform_8x8_mode;
3846

    
3847
    mb_xy = h->mb_xy = s->mb_x + s->mb_y*s->mb_stride;
3848

    
3849
    tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
3850
    cbp = 0; /* avoid warning. FIXME: find a solution without slowing
3851
                down the code */
3852
    if(h->slice_type_nos != FF_I_TYPE){
3853
        if(s->mb_skip_run==-1)
3854
            s->mb_skip_run= get_ue_golomb(&s->gb);
3855

    
3856
        if (s->mb_skip_run--) {
3857
            if(FRAME_MBAFF && (s->mb_y&1) == 0){
3858
                if(s->mb_skip_run==0)
3859
                    h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
3860
                else
3861
                    predict_field_decoding_flag(h);
3862
            }
3863
            decode_mb_skip(h);
3864
            return 0;
3865
        }
3866
    }
3867
    if(FRAME_MBAFF){
3868
        if( (s->mb_y&1) == 0 )
3869
            h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
3870
    }
3871

    
3872
    h->prev_mb_skipped= 0;
3873

    
3874
    mb_type= get_ue_golomb(&s->gb);
3875
    if(h->slice_type_nos == FF_B_TYPE){
3876
        if(mb_type < 23){
3877
            partition_count= b_mb_type_info[mb_type].partition_count;
3878
            mb_type=         b_mb_type_info[mb_type].type;
3879
        }else{
3880
            mb_type -= 23;
3881
            goto decode_intra_mb;
3882
        }
3883
    }else if(h->slice_type_nos == FF_P_TYPE){
3884
        if(mb_type < 5){
3885
            partition_count= p_mb_type_info[mb_type].partition_count;
3886
            mb_type=         p_mb_type_info[mb_type].type;
3887
        }else{
3888
            mb_type -= 5;
3889
            goto decode_intra_mb;
3890
        }
3891
    }else{
3892
       assert(h->slice_type_nos == FF_I_TYPE);
3893
        if(h->slice_type == FF_SI_TYPE && mb_type)
3894
            mb_type--;
3895
decode_intra_mb:
3896
        if(mb_type > 25){
3897
            av_log(h->s.avctx, AV_LOG_ERROR, "mb_type %d in %c slice too large at %d %d\n", mb_type, av_get_pict_type_char(h->slice_type), s->mb_x, s->mb_y);
3898
            return -1;
3899
        }
3900
        partition_count=0;
3901
        cbp= i_mb_type_info[mb_type].cbp;
3902
        h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
3903
        mb_type= i_mb_type_info[mb_type].type;
3904
    }
3905

    
3906
    if(MB_FIELD)
3907
        mb_type |= MB_TYPE_INTERLACED;
3908

    
3909
    h->slice_table[ mb_xy ]= h->slice_num;
3910

    
3911
    if(IS_INTRA_PCM(mb_type)){
3912
        unsigned int x;
3913

    
3914
        // We assume these blocks are very rare so we do not optimize it.
3915
        align_get_bits(&s->gb);
3916

    
3917
        // The pixels are stored in the same order as levels in h->mb array.
3918
        for(x=0; x < (CHROMA ? 384 : 256); x++){
3919
            ((uint8_t*)h->mb)[x]= get_bits(&s->gb, 8);
3920
        }
3921

    
3922
        // In deblocking, the quantizer is 0
3923
        s->current_picture.qscale_table[mb_xy]= 0;
3924
        // All coeffs are present
3925
        memset(h->non_zero_count[mb_xy], 16, 16);
3926

    
3927
        s->current_picture.mb_type[mb_xy]= mb_type;
3928
        return 0;
3929
    }
3930

    
3931
    if(MB_MBAFF){
3932
        h->ref_count[0] <<= 1;
3933
        h->ref_count[1] <<= 1;
3934
    }
3935

    
3936
    fill_caches(h, mb_type, 0);
3937

    
3938
    //mb_pred
3939
    if(IS_INTRA(mb_type)){
3940
        int pred_mode;
3941
//            init_top_left_availability(h);
3942
        if(IS_INTRA4x4(mb_type)){
3943
            int i;
3944
            int di = 1;
3945
            if(dct8x8_allowed && get_bits1(&s->gb)){
3946
                mb_type |= MB_TYPE_8x8DCT;
3947
                di = 4;
3948
            }
3949

    
3950
//                fill_intra4x4_pred_table(h);
3951
            for(i=0; i<16; i+=di){
3952
                int mode= pred_intra_mode(h, i);
3953

    
3954
                if(!get_bits1(&s->gb)){
3955
                    const int rem_mode= get_bits(&s->gb, 3);
3956
                    mode = rem_mode + (rem_mode >= mode);
3957
                }
3958

    
3959
                if(di==4)
3960
                    fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
3961
                else
3962
                    h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;
3963
            }
3964
            ff_h264_write_back_intra_pred_mode(h);
3965
            if( check_intra4x4_pred_mode(h) < 0)
3966
                return -1;
3967
        }else{
3968
            h->intra16x16_pred_mode= ff_h264_check_intra_pred_mode(h, h->intra16x16_pred_mode);
3969
            if(h->intra16x16_pred_mode < 0)
3970
                return -1;
3971
        }
3972
        if(CHROMA){
3973
            pred_mode= ff_h264_check_intra_pred_mode(h, get_ue_golomb_31(&s->gb));
3974
            if(pred_mode < 0)
3975
                return -1;
3976
            h->chroma_pred_mode= pred_mode;
3977
        }
3978
    }else if(partition_count==4){
3979
        int i, j, sub_partition_count[4], list, ref[2][4];
3980

    
3981
        if(h->slice_type_nos == FF_B_TYPE){
3982
            for(i=0; i<4; i++){
3983
                h->sub_mb_type[i]= get_ue_golomb_31(&s->gb);
3984
                if(h->sub_mb_type[i] >=13){
3985
                    av_log(h->s.avctx, AV_LOG_ERROR, "B sub_mb_type %u out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);
3986
                    return -1;
3987
                }
3988
                sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
3989
                h->sub_mb_type[i]=      b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
3990
            }
3991
            if(   IS_DIRECT(h->sub_mb_type[0]) || IS_DIRECT(h->sub_mb_type[1])
3992
               || IS_DIRECT(h->sub_mb_type[2]) || IS_DIRECT(h->sub_mb_type[3])) {
3993
                ff_h264_pred_direct_motion(h, &mb_type);
3994
                h->ref_cache[0][scan8[4]] =
3995
                h->ref_cache[1][scan8[4]] =
3996
                h->ref_cache[0][scan8[12]] =
3997
                h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
3998
            }
3999
        }else{
4000
            assert(h->slice_type_nos == FF_P_TYPE); //FIXME SP correct ?
4001
            for(i=0; i<4; i++){
4002
                h->sub_mb_type[i]= get_ue_golomb_31(&s->gb);
4003
                if(h->sub_mb_type[i] >=4){
4004
                    av_log(h->s.avctx, AV_LOG_ERROR, "P sub_mb_type %u out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);
4005
                    return -1;
4006
                }
4007
                sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
4008
                h->sub_mb_type[i]=      p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
4009
            }
4010
        }
4011

    
4012
        for(list=0; list<h->list_count; list++){
4013
            int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
4014
            for(i=0; i<4; i++){
4015
                if(IS_DIRECT(h->sub_mb_type[i])) continue;
4016
                if(IS_DIR(h->sub_mb_type[i], 0, list)){
4017
                    unsigned int tmp;
4018
                    if(ref_count == 1){
4019
                        tmp= 0;
4020
                    }else if(ref_count == 2){
4021
                        tmp= get_bits1(&s->gb)^1;
4022
                    }else{
4023
                        tmp= get_ue_golomb_31(&s->gb);
4024
                        if(tmp>=ref_count){
4025
                            av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", tmp);
4026
                            return -1;
4027
                        }
4028
                    }
4029
                    ref[list][i]= tmp;
4030
                }else{
4031
                 //FIXME
4032
                    ref[list][i] = -1;
4033
                }
4034
            }
4035
        }
4036

    
4037
        if(dct8x8_allowed)
4038
            dct8x8_allowed = get_dct8x8_allowed(h);
4039

    
4040
        for(list=0; list<h->list_count; list++){
4041
            for(i=0; i<4; i++){
4042
                if(IS_DIRECT(h->sub_mb_type[i])) {
4043
                    h->ref_cache[list][ scan8[4*i] ] = h->ref_cache[list][ scan8[4*i]+1 ];
4044
                    continue;
4045
                }
4046
                h->ref_cache[list][ scan8[4*i]   ]=h->ref_cache[list][ scan8[4*i]+1 ]=
4047
                h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
4048

    
4049
                if(IS_DIR(h->sub_mb_type[i], 0, list)){
4050
                    const int sub_mb_type= h->sub_mb_type[i];
4051
                    const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
4052
                    for(j=0; j<sub_partition_count[i]; j++){
4053
                        int mx, my;
4054
                        const int index= 4*i + block_width*j;
4055
                        int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
4056
                        pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);
4057
                        mx += get_se_golomb(&s->gb);
4058
                        my += get_se_golomb(&s->gb);
4059
                        tprintf(s->avctx, "final mv:%d %d\n", mx, my);
4060

    
4061
                        if(IS_SUB_8X8(sub_mb_type)){
4062
                            mv_cache[ 1 ][0]=
4063
                            mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
4064
                            mv_cache[ 1 ][1]=
4065
                            mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
4066
                        }else if(IS_SUB_8X4(sub_mb_type)){
4067
                            mv_cache[ 1 ][0]= mx;
4068
                            mv_cache[ 1 ][1]= my;
4069
                        }else if(IS_SUB_4X8(sub_mb_type)){
4070
                            mv_cache[ 8 ][0]= mx;
4071
                            mv_cache[ 8 ][1]= my;
4072
                        }
4073
                        mv_cache[ 0 ][0]= mx;
4074
                        mv_cache[ 0 ][1]= my;
4075
                    }
4076
                }else{
4077
                    uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
4078
                    p[0] = p[1]=
4079
                    p[8] = p[9]= 0;
4080
                }
4081
            }
4082
        }
4083
    }else if(IS_DIRECT(mb_type)){
4084
        ff_h264_pred_direct_motion(h, &mb_type);
4085
        dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
4086
    }else{
4087
        int list, mx, my, i;
4088
         //FIXME we should set ref_idx_l? to 0 if we use that later ...
4089
        if(IS_16X16(mb_type)){
4090
            for(list=0; list<h->list_count; list++){
4091
                    unsigned int val;
4092
                    if(IS_DIR(mb_type, 0, list)){
4093
                        if(h->ref_count[list]==1){
4094
                            val= 0;
4095
                        }else if(h->ref_count[list]==2){
4096
                            val= get_bits1(&s->gb)^1;
4097
                        }else{
4098
                            val= get_ue_golomb_31(&s->gb);
4099
                            if(val >= h->ref_count[list]){
4100
                                av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
4101
                                return -1;
4102
                            }
4103
                        }
4104
                    }else
4105
                        val= LIST_NOT_USED&0xFF;
4106
                    fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);
4107
            }
4108
            for(list=0; list<h->list_count; list++){
4109
                unsigned int val;
4110
                if(IS_DIR(mb_type, 0, list)){
4111
                    pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);
4112
                    mx += get_se_golomb(&s->gb);
4113
                    my += get_se_golomb(&s->gb);
4114
                    tprintf(s->avctx, "final mv:%d %d\n", mx, my);
4115

    
4116
                    val= pack16to32(mx,my);
4117
                }else
4118
                    val=0;
4119
                fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, val, 4);
4120
            }
4121
        }
4122
        else if(IS_16X8(mb_type)){
4123
            for(list=0; list<h->list_count; list++){
4124
                    for(i=0; i<2; i++){
4125
                        unsigned int val;
4126
                        if(IS_DIR(mb_type, i, list)){
4127
                            if(h->ref_count[list] == 1){
4128
                                val= 0;
4129
                            }else if(h->ref_count[list] == 2){
4130
                                val= get_bits1(&s->gb)^1;
4131
                            }else{
4132
                                val= get_ue_golomb_31(&s->gb);
4133
                                if(val >= h->ref_count[list]){
4134
                                    av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
4135
                                    return -1;
4136
                                }
4137
                            }
4138
                        }else
4139
                            val= LIST_NOT_USED&0xFF;
4140
                        fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);
4141
                    }
4142
            }
4143
            for(list=0; list<h->list_count; list++){
4144
                for(i=0; i<2; i++){
4145
                    unsigned int val;
4146
                    if(IS_DIR(mb_type, i, list)){
4147
                        pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);
4148
                        mx += get_se_golomb(&s->gb);
4149
                        my += get_se_golomb(&s->gb);
4150
                        tprintf(s->avctx, "final mv:%d %d\n", mx, my);
4151

    
4152
                        val= pack16to32(mx,my);
4153
                    }else
4154
                        val=0;
4155
                    fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 4);
4156
                }
4157
            }
4158
        }else{
4159
            assert(IS_8X16(mb_type));
4160
            for(list=0; list<h->list_count; list++){
4161
                    for(i=0; i<2; i++){
4162
                        unsigned int val;
4163
                        if(IS_DIR(mb_type, i, list)){ //FIXME optimize
4164
                            if(h->ref_count[list]==1){
4165
                                val= 0;
4166
                            }else if(h->ref_count[list]==2){
4167
                                val= get_bits1(&s->gb)^1;
4168
                            }else{
4169
                                val= get_ue_golomb_31(&s->gb);
4170
                                if(val >= h->ref_count[list]){
4171
                                    av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
4172
                                    return -1;
4173
                                }
4174
                            }
4175
                        }else
4176
                            val= LIST_NOT_USED&0xFF;
4177
                        fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);
4178
                    }
4179
            }
4180
            for(list=0; list<h->list_count; list++){
4181
                for(i=0; i<2; i++){
4182
                    unsigned int val;
4183
                    if(IS_DIR(mb_type, i, list)){
4184
                        pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
4185
                        mx += get_se_golomb(&s->gb);
4186
                        my += get_se_golomb(&s->gb);
4187
                        tprintf(s->avctx, "final mv:%d %d\n", mx, my);
4188

    
4189
                        val= pack16to32(mx,my);
4190
                    }else
4191
                        val=0;
4192
                    fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 4);
4193
                }
4194
            }
4195
        }
4196
    }
4197

    
4198
    if(IS_INTER(mb_type))
4199
        write_back_motion(h, mb_type);
4200

    
4201
    if(!IS_INTRA16x16(mb_type)){
4202
        cbp= get_ue_golomb(&s->gb);
4203
        if(cbp > 47){
4204
            av_log(h->s.avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, s->mb_x, s->mb_y);
4205
            return -1;
4206
        }
4207

    
4208
        if(CHROMA){
4209
            if(IS_INTRA4x4(mb_type)) cbp= golomb_to_intra4x4_cbp[cbp];
4210
            else                     cbp= golomb_to_inter_cbp   [cbp];
4211
        }else{
4212
            if(IS_INTRA4x4(mb_type)) cbp= golomb_to_intra4x4_cbp_gray[cbp];
4213
            else                     cbp= golomb_to_inter_cbp_gray[cbp];
4214
        }
4215
    }
4216
    h->cbp = cbp;
4217

    
4218
    if(dct8x8_allowed && (cbp&15) && !IS_INTRA(mb_type)){
4219
        if(get_bits1(&s->gb)){
4220
            mb_type |= MB_TYPE_8x8DCT;
4221
            h->cbp_table[mb_xy]= cbp;
4222
        }
4223
    }
4224
    s->current_picture.mb_type[mb_xy]= mb_type;
4225

    
4226
    if(cbp || IS_INTRA16x16(mb_type)){
4227
        int i8x8, i4x4, chroma_idx;
4228
        int dquant;
4229
        GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;
4230
        const uint8_t *scan, *scan8x8, *dc_scan;
4231

    
4232
//        fill_non_zero_count_cache(h);
4233

    
4234
        if(IS_INTERLACED(mb_type)){
4235
            scan8x8= s->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;
4236
            scan= s->qscale ? h->field_scan : h->field_scan_q0;
4237
            dc_scan= luma_dc_field_scan;
4238
        }else{
4239
            scan8x8= s->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;
4240
            scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
4241
            dc_scan= luma_dc_zigzag_scan;
4242
        }
4243

    
4244
        dquant= get_se_golomb(&s->gb);
4245

    
4246
        if( dquant > 25 || dquant < -26 ){
4247
            av_log(h->s.avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, s->mb_x, s->mb_y);
4248
            return -1;
4249
        }
4250

    
4251
        s->qscale += dquant;
4252
        if(((unsigned)s->qscale) > 51){
4253
            if(s->qscale<0) s->qscale+= 52;
4254
            else            s->qscale-= 52;
4255
        }
4256

    
4257
        h->chroma_qp[0]= get_chroma_qp(h, 0, s->qscale);
4258
        h->chroma_qp[1]= get_chroma_qp(h, 1, s->qscale);
4259
        if(IS_INTRA16x16(mb_type)){
4260
            if( decode_residual(h, h->intra_gb_ptr, h->mb, LUMA_DC_BLOCK_INDEX, dc_scan, h->dequant4_coeff[0][s->qscale], 16) < 0){
4261
                return -1; //FIXME continue if partitioned and other return -1 too
4262
            }
4263

    
4264
            assert((cbp&15) == 0 || (cbp&15) == 15);
4265

    
4266
            if(cbp&15){
4267
                for(i8x8=0; i8x8<4; i8x8++){
4268
                    for(i4x4=0; i4x4<4; i4x4++){
4269
                        const int index= i4x4 + 4*i8x8;
4270
                        if( decode_residual(h, h->intra_gb_ptr, h->mb + 16*index, index, scan + 1, h->dequant4_coeff[0][s->qscale], 15) < 0 ){
4271
                            return -1;
4272
                        }
4273
                    }
4274
                }
4275
            }else{
4276
                fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
4277
            }
4278
        }else{
4279
            for(i8x8=0; i8x8<4; i8x8++){
4280
                if(cbp & (1<<i8x8)){
4281
                    if(IS_8x8DCT(mb_type)){
4282
                        DCTELEM *buf = &h->mb[64*i8x8];
4283
                        uint8_t *nnz;
4284
                        for(i4x4=0; i4x4<4; i4x4++){
4285
                            if( decode_residual(h, gb, buf, i4x4+4*i8x8, scan8x8+16*i4x4,
4286
                                                h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 16) <0 )
4287
                                return -1;
4288
                        }
4289
                        nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
4290
                        nnz[0] += nnz[1] + nnz[8] + nnz[9];
4291
                    }else{
4292
                        for(i4x4=0; i4x4<4; i4x4++){
4293
                            const int index= i4x4 + 4*i8x8;
4294

    
4295
                            if( decode_residual(h, gb, h->mb + 16*index, index, scan, h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale], 16) <0 ){
4296
                                return -1;
4297
                            }
4298
                        }
4299
                    }
4300
                }else{
4301
                    uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
4302
                    nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
4303
                }
4304
            }
4305
        }
4306

    
4307
        if(cbp&0x30){
4308
            for(chroma_idx=0; chroma_idx<2; chroma_idx++)
4309
                if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX, chroma_dc_scan, NULL, 4) < 0){
4310
                    return -1;
4311
                }
4312
        }
4313

    
4314
        if(cbp&0x20){
4315
            for(chroma_idx=0; chroma_idx<2; chroma_idx++){
4316
                const uint32_t *qmul = h->dequant4_coeff[chroma_idx+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[chroma_idx]];
4317
                for(i4x4=0; i4x4<4; i4x4++){
4318
                    const int index= 16 + 4*chroma_idx + i4x4;
4319
                    if( decode_residual(h, gb, h->mb + 16*index, index, scan + 1, qmul, 15) < 0){
4320
                        return -1;
4321
                    }
4322
                }
4323
            }
4324
        }else{
4325
            uint8_t * const nnz= &h->non_zero_count_cache[0];
4326
            nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
4327
            nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
4328
        }
4329
    }else{
4330
        uint8_t * const nnz= &h->non_zero_count_cache[0];
4331
        fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
4332
        nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
4333
        nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
4334
    }
4335
    s->current_picture.qscale_table[mb_xy]= s->qscale;
4336
    write_back_non_zero_count(h);
4337

    
4338
    if(MB_MBAFF){
4339
        h->ref_count[0] >>= 1;
4340
        h->ref_count[1] >>= 1;
4341
    }
4342

    
4343
    return 0;
4344
}
4345

    
4346
static int decode_cabac_field_decoding_flag(H264Context *h) {
4347
    MpegEncContext * const s = &h->s;
4348
    const int mb_x = s->mb_x;
4349
    const int mb_y = s->mb_y & ~1;
4350
    const int mba_xy = mb_x - 1 +  mb_y   *s->mb_stride;
4351
    const int mbb_xy = mb_x     + (mb_y-2)*s->mb_stride;
4352

    
4353
    unsigned int ctx = 0;
4354

    
4355
    if( h->slice_table[mba_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) ) {
4356
        ctx += 1;
4357
    }
4358
    if( h->slice_table[mbb_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) ) {
4359
        ctx += 1;
4360
    }
4361

    
4362
    return get_cabac_noinline( &h->cabac, &h->cabac_state[70 + ctx] );
4363
}
4364

    
4365
static int decode_cabac_intra_mb_type(H264Context *h, int ctx_base, int intra_slice) {
4366
    uint8_t *state= &h->cabac_state[ctx_base];
4367
    int mb_type;
4368

    
4369
    if(intra_slice){
4370
        MpegEncContext * const s = &h->s;
4371
        const int mba_xy = h->left_mb_xy[0];
4372
        const int mbb_xy = h->top_mb_xy;
4373
        int ctx=0;
4374
        if( h->slice_table[mba_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mba_xy] ) )
4375
            ctx++;
4376
        if( h->slice_table[mbb_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mbb_xy] ) )
4377
            ctx++;
4378
        if( get_cabac_noinline( &h->cabac, &state[ctx] ) == 0 )
4379
            return 0;   /* I4x4 */
4380
        state += 2;
4381
    }else{
4382
        if( get_cabac_noinline( &h->cabac, &state[0] ) == 0 )
4383
            return 0;   /* I4x4 */
4384
    }
4385

    
4386
    if( get_cabac_terminate( &h->cabac ) )
4387
        return 25;  /* PCM */
4388

    
4389
    mb_type = 1; /* I16x16 */
4390
    mb_type += 12 * get_cabac_noinline( &h->cabac, &state[1] ); /* cbp_luma != 0 */
4391
    if( get_cabac_noinline( &h->cabac, &state[2] ) ) /* cbp_chroma */
4392
        mb_type += 4 + 4 * get_cabac_noinline( &h->cabac, &state[2+intra_slice] );
4393
    mb_type += 2 * get_cabac_noinline( &h->cabac, &state[3+intra_slice] );
4394
    mb_type += 1 * get_cabac_noinline( &h->cabac, &state[3+2*intra_slice] );
4395
    return mb_type;
4396
}
4397

    
4398
static int decode_cabac_mb_type_b( H264Context *h ) {
4399
    MpegEncContext * const s = &h->s;
4400

    
4401
        const int mba_xy = h->left_mb_xy[0];
4402
        const int mbb_xy = h->top_mb_xy;
4403
        int ctx = 0;
4404
        int bits;
4405
        assert(h->slice_type_nos == FF_B_TYPE);
4406

    
4407
        if( h->slice_table[mba_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mba_xy] ) )
4408
            ctx++;
4409
        if( h->slice_table[mbb_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mbb_xy] ) )
4410
            ctx++;
4411

    
4412
        if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+ctx] ) )
4413
            return 0; /* B_Direct_16x16 */
4414

    
4415
        if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+3] ) ) {
4416
            return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ); /* B_L[01]_16x16 */
4417
        }
4418

    
4419
        bits = get_cabac_noinline( &h->cabac, &h->cabac_state[27+4] ) << 3;
4420
        bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 2;
4421
        bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 1;
4422
        bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
4423
        if( bits < 8 )
4424
            return bits + 3; /* B_Bi_16x16 through B_L1_L0_16x8 */
4425
        else if( bits == 13 ) {
4426
            return decode_cabac_intra_mb_type(h, 32, 0) + 23;
4427
        } else if( bits == 14 )
4428
            return 11; /* B_L1_L0_8x16 */
4429
        else if( bits == 15 )
4430
            return 22; /* B_8x8 */
4431

    
4432
        bits= ( bits<<1 ) | get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
4433
        return bits - 4; /* B_L0_Bi_* through B_Bi_Bi_* */
4434
}
4435

    
4436
static int decode_cabac_mb_skip( H264Context *h, int mb_x, int mb_y ) {
4437
    MpegEncContext * const s = &h->s;
4438
    int mba_xy, mbb_xy;
4439
    int ctx = 0;
4440

    
4441
    if(FRAME_MBAFF){ //FIXME merge with the stuff in fill_caches?
4442
        int mb_xy = mb_x + (mb_y&~1)*s->mb_stride;
4443
        mba_xy = mb_xy - 1;
4444
        if( (mb_y&1)
4445
            && h->slice_table[mba_xy] == h->slice_num
4446
            && MB_FIELD == !!IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) )
4447
            mba_xy += s->mb_stride;
4448
        if( MB_FIELD ){
4449
            mbb_xy = mb_xy - s->mb_stride;
4450
            if( !(mb_y&1)
4451
                && h->slice_table[mbb_xy] == h->slice_num
4452
                && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) )
4453
                mbb_xy -= s->mb_stride;
4454
        }else
4455
            mbb_xy = mb_x + (mb_y-1)*s->mb_stride;
4456
    }else{
4457
        int mb_xy = h->mb_xy;
4458
        mba_xy = mb_xy - 1;
4459
        mbb_xy = mb_xy - (s->mb_stride << FIELD_PICTURE);
4460
    }
4461

    
4462
    if( h->slice_table[mba_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mba_xy] ))
4463
        ctx++;
4464
    if( h->slice_table[mbb_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mbb_xy] ))
4465
        ctx++;
4466

    
4467
    if( h->slice_type_nos == FF_B_TYPE )
4468
        ctx += 13;
4469
    return get_cabac_noinline( &h->cabac, &h->cabac_state[11+ctx] );
4470
}
4471

    
4472
static int decode_cabac_mb_intra4x4_pred_mode( H264Context *h, int pred_mode ) {
4473
    int mode = 0;
4474

    
4475
    if( get_cabac( &h->cabac, &h->cabac_state[68] ) )
4476
        return pred_mode;
4477

    
4478
    mode += 1 * get_cabac( &h->cabac, &h->cabac_state[69] );
4479
    mode += 2 * get_cabac( &h->cabac, &h->cabac_state[69] );
4480
    mode += 4 * get_cabac( &h->cabac, &h->cabac_state[69] );
4481

    
4482
    if( mode >= pred_mode )
4483
        return mode + 1;
4484
    else
4485
        return mode;
4486
}
4487

    
4488
static int decode_cabac_mb_chroma_pre_mode( H264Context *h) {
4489
    const int mba_xy = h->left_mb_xy[0];
4490
    const int mbb_xy = h->top_mb_xy;
4491

    
4492
    int ctx = 0;
4493

    
4494
    /* No need to test for IS_INTRA4x4 and IS_INTRA16x16, as we set chroma_pred_mode_table to 0 */
4495
    if( h->slice_table[mba_xy] == h->slice_num && h->chroma_pred_mode_table[mba_xy] != 0 )
4496
        ctx++;
4497

    
4498
    if( h->slice_table[mbb_xy] == h->slice_num && h->chroma_pred_mode_table[mbb_xy] != 0 )
4499
        ctx++;
4500

    
4501
    if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+ctx] ) == 0 )
4502
        return 0;
4503

    
4504
    if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
4505
        return 1;
4506
    if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
4507
        return 2;
4508
    else
4509
        return 3;
4510
}
4511

    
4512
static int decode_cabac_mb_cbp_luma( H264Context *h) {
4513
    int cbp_b, cbp_a, ctx, cbp = 0;
4514

    
4515
    cbp_a = h->slice_table[h->left_mb_xy[0]] == h->slice_num ? h->left_cbp : -1;
4516
    cbp_b = h->slice_table[h->top_mb_xy]     == h->slice_num ? h->top_cbp  : -1;
4517

    
4518
    ctx = !(cbp_a & 0x02) + 2 * !(cbp_b & 0x04);
4519
    cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]);
4520
    ctx = !(cbp   & 0x01) + 2 * !(cbp_b & 0x08);
4521
    cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 1;
4522
    ctx = !(cbp_a & 0x08) + 2 * !(cbp   & 0x01);
4523
    cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 2;
4524
    ctx = !(cbp   & 0x04) + 2 * !(cbp   & 0x02);
4525
    cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 3;
4526
    return cbp;