Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ aa6a89aa

History | View | Annotate | Download (309 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 h264.c
24
 * H.264 / AVC / MPEG4 part10 codec.
25
 * @author Michael Niedermayer <michaelni@gmx.at>
26
 */
27

    
28
#include "dsputil.h"
29
#include "avcodec.h"
30
#include "mpegvideo.h"
31
#include "h264.h"
32
#include "h264data.h"
33
#include "h264_parser.h"
34
#include "golomb.h"
35
#include "rectangle.h"
36

    
37
#include "cabac.h"
38
#ifdef ARCH_X86
39
#include "i386/h264_i386.h"
40
#endif
41

    
42
//#undef NDEBUG
43
#include <assert.h>
44

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

    
51
static VLC coeff_token_vlc[4];
52
static VLC chroma_dc_coeff_token_vlc;
53

    
54
static VLC total_zeros_vlc[15];
55
static VLC chroma_dc_total_zeros_vlc[3];
56

    
57
static VLC run_vlc[6];
58
static VLC run7_vlc;
59

    
60
static void svq3_luma_dc_dequant_idct_c(DCTELEM *block, int qp);
61
static void svq3_add_idct_c(uint8_t *dst, DCTELEM *block, int stride, int qp, int dc);
62
static void filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize);
63
static void filter_mb_fast( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize);
64
static Picture * remove_long(H264Context *h, int i, int ref_mask);
65

    
66
static av_always_inline uint32_t pack16to32(int a, int b){
67
#ifdef WORDS_BIGENDIAN
68
   return (b&0xFFFF) + (a<<16);
69
#else
70
   return (a&0xFFFF) + (b<<16);
71
#endif
72
}
73

    
74
const uint8_t ff_rem6[52]={
75
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,
76
};
77

    
78
const uint8_t ff_div6[52]={
79
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,
80
};
81

    
82
static const int left_block_options[4][8]={
83
    {0,1,2,3,7,10,8,11},
84
    {2,2,3,3,8,11,8,11},
85
    {0,0,1,1,7,10,7,10},
86
    {0,2,0,2,7,10,7,10}
87
};
88

    
89
static void fill_caches(H264Context *h, int mb_type, int for_deblock){
90
    MpegEncContext * const s = &h->s;
91
    const int mb_xy= h->mb_xy;
92
    int topleft_xy, top_xy, topright_xy, left_xy[2];
93
    int topleft_type, top_type, topright_type, left_type[2];
94
    int * left_block;
95
    int topleft_partition= -1;
96
    int i;
97

    
98
    top_xy     = mb_xy  - (s->mb_stride << FIELD_PICTURE);
99

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

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

    
107
    topleft_xy = top_xy - 1;
108
    topright_xy= top_xy + 1;
109
    left_xy[1] = left_xy[0] = mb_xy-1;
110
    left_block = left_block_options[0];
111
    if(FRAME_MBAFF){
112
        const int pair_xy          = s->mb_x     + (s->mb_y & ~1)*s->mb_stride;
113
        const int top_pair_xy      = pair_xy     - s->mb_stride;
114
        const int topleft_pair_xy  = top_pair_xy - 1;
115
        const int topright_pair_xy = top_pair_xy + 1;
116
        const int topleft_mb_frame_flag  = !IS_INTERLACED(s->current_picture.mb_type[topleft_pair_xy]);
117
        const int top_mb_frame_flag      = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);
118
        const int topright_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[topright_pair_xy]);
119
        const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);
120
        const int curr_mb_frame_flag = !IS_INTERLACED(mb_type);
121
        const int bottom = (s->mb_y & 1);
122
        tprintf(s->avctx, "fill_caches: curr_mb_frame_flag:%d, left_mb_frame_flag:%d, topleft_mb_frame_flag:%d, top_mb_frame_flag:%d, topright_mb_frame_flag:%d\n", curr_mb_frame_flag, left_mb_frame_flag, topleft_mb_frame_flag, top_mb_frame_flag, topright_mb_frame_flag);
123
        if (bottom
124
                ? !curr_mb_frame_flag // bottom macroblock
125
                : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock
126
                ) {
127
            top_xy -= s->mb_stride;
128
        }
129
        if (bottom
130
                ? !curr_mb_frame_flag // bottom macroblock
131
                : (!curr_mb_frame_flag && !topleft_mb_frame_flag) // top macroblock
132
                ) {
133
            topleft_xy -= s->mb_stride;
134
        } else if(bottom && curr_mb_frame_flag && !left_mb_frame_flag) {
135
            topleft_xy += s->mb_stride;
136
            // take top left mv from the middle of the mb, as opposed to all other modes which use the bottom right partition
137
            topleft_partition = 0;
138
        }
139
        if (bottom
140
                ? !curr_mb_frame_flag // bottom macroblock
141
                : (!curr_mb_frame_flag && !topright_mb_frame_flag) // top macroblock
142
                ) {
143
            topright_xy -= s->mb_stride;
144
        }
145
        if (left_mb_frame_flag != curr_mb_frame_flag) {
146
            left_xy[1] = left_xy[0] = pair_xy - 1;
147
            if (curr_mb_frame_flag) {
148
                if (bottom) {
149
                    left_block = left_block_options[1];
150
                } else {
151
                    left_block= left_block_options[2];
152
                }
153
            } else {
154
                left_xy[1] += s->mb_stride;
155
                left_block = left_block_options[3];
156
            }
157
        }
158
    }
159

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

    
170
        if(FRAME_MBAFF && !IS_INTRA(mb_type)){
171
            int list;
172
            int v = *(uint16_t*)&h->non_zero_count[mb_xy][14];
173
            for(i=0; i<16; i++)
174
                h->non_zero_count_cache[scan8[i]] = (v>>i)&1;
175
            for(list=0; list<h->list_count; list++){
176
                if(USES_LIST(mb_type,list)){
177
                    uint32_t *src = (uint32_t*)s->current_picture.motion_val[list][h->mb2b_xy[mb_xy]];
178
                    uint32_t *dst = (uint32_t*)h->mv_cache[list][scan8[0]];
179
                    int8_t *ref = &s->current_picture.ref_index[list][h->mb2b8_xy[mb_xy]];
180
                    for(i=0; i<4; i++, dst+=8, src+=h->b_stride){
181
                        dst[0] = src[0];
182
                        dst[1] = src[1];
183
                        dst[2] = src[2];
184
                        dst[3] = src[3];
185
                    }
186
                    *(uint32_t*)&h->ref_cache[list][scan8[ 0]] =
187
                    *(uint32_t*)&h->ref_cache[list][scan8[ 2]] = pack16to32(ref[0],ref[1])*0x0101;
188
                    ref += h->b8_stride;
189
                    *(uint32_t*)&h->ref_cache[list][scan8[ 8]] =
190
                    *(uint32_t*)&h->ref_cache[list][scan8[10]] = pack16to32(ref[0],ref[1])*0x0101;
191
                }else{
192
                    fill_rectangle(&h-> mv_cache[list][scan8[ 0]], 4, 4, 8, 0, 4);
193
                    fill_rectangle(&h->ref_cache[list][scan8[ 0]], 4, 4, 8, (uint8_t)LIST_NOT_USED, 1);
194
                }
195
            }
196
        }
197
    }else{
198
        topleft_type = h->slice_table[topleft_xy ] == h->slice_num ? s->current_picture.mb_type[topleft_xy] : 0;
199
        top_type     = h->slice_table[top_xy     ] == h->slice_num ? s->current_picture.mb_type[top_xy]     : 0;
200
        topright_type= h->slice_table[topright_xy] == h->slice_num ? s->current_picture.mb_type[topright_xy]: 0;
201
        left_type[0] = h->slice_table[left_xy[0] ] == h->slice_num ? s->current_picture.mb_type[left_xy[0]] : 0;
202
        left_type[1] = h->slice_table[left_xy[1] ] == h->slice_num ? s->current_picture.mb_type[left_xy[1]] : 0;
203
    }
204

    
205
    if(IS_INTRA(mb_type)){
206
        h->topleft_samples_available=
207
        h->top_samples_available=
208
        h->left_samples_available= 0xFFFF;
209
        h->topright_samples_available= 0xEEEA;
210

    
211
        if(!IS_INTRA(top_type) && (top_type==0 || h->pps.constrained_intra_pred)){
212
            h->topleft_samples_available= 0xB3FF;
213
            h->top_samples_available= 0x33FF;
214
            h->topright_samples_available= 0x26EA;
215
        }
216
        for(i=0; i<2; i++){
217
            if(!IS_INTRA(left_type[i]) && (left_type[i]==0 || h->pps.constrained_intra_pred)){
218
                h->topleft_samples_available&= 0xDF5F;
219
                h->left_samples_available&= 0x5F5F;
220
            }
221
        }
222

    
223
        if(!IS_INTRA(topleft_type) && (topleft_type==0 || h->pps.constrained_intra_pred))
224
            h->topleft_samples_available&= 0x7FFF;
225

    
226
        if(!IS_INTRA(topright_type) && (topright_type==0 || h->pps.constrained_intra_pred))
227
            h->topright_samples_available&= 0xFBFF;
228

    
229
        if(IS_INTRA4x4(mb_type)){
230
            if(IS_INTRA4x4(top_type)){
231
                h->intra4x4_pred_mode_cache[4+8*0]= h->intra4x4_pred_mode[top_xy][4];
232
                h->intra4x4_pred_mode_cache[5+8*0]= h->intra4x4_pred_mode[top_xy][5];
233
                h->intra4x4_pred_mode_cache[6+8*0]= h->intra4x4_pred_mode[top_xy][6];
234
                h->intra4x4_pred_mode_cache[7+8*0]= h->intra4x4_pred_mode[top_xy][3];
235
            }else{
236
                int pred;
237
                if(!top_type || (IS_INTER(top_type) && h->pps.constrained_intra_pred))
238
                    pred= -1;
239
                else{
240
                    pred= 2;
241
                }
242
                h->intra4x4_pred_mode_cache[4+8*0]=
243
                h->intra4x4_pred_mode_cache[5+8*0]=
244
                h->intra4x4_pred_mode_cache[6+8*0]=
245
                h->intra4x4_pred_mode_cache[7+8*0]= pred;
246
            }
247
            for(i=0; i<2; i++){
248
                if(IS_INTRA4x4(left_type[i])){
249
                    h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[0+2*i]];
250
                    h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[1+2*i]];
251
                }else{
252
                    int pred;
253
                    if(!left_type[i] || (IS_INTER(left_type[i]) && h->pps.constrained_intra_pred))
254
                        pred= -1;
255
                    else{
256
                        pred= 2;
257
                    }
258
                    h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]=
259
                    h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= pred;
260
                }
261
            }
262
        }
263
    }
264

    
265

    
266
/*
267
0 . T T. T T T T
268
1 L . .L . . . .
269
2 L . .L . . . .
270
3 . T TL . . . .
271
4 L . .L . . . .
272
5 L . .. . . . .
273
*/
274
//FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
275
    if(top_type){
276
        h->non_zero_count_cache[4+8*0]= h->non_zero_count[top_xy][4];
277
        h->non_zero_count_cache[5+8*0]= h->non_zero_count[top_xy][5];
278
        h->non_zero_count_cache[6+8*0]= h->non_zero_count[top_xy][6];
279
        h->non_zero_count_cache[7+8*0]= h->non_zero_count[top_xy][3];
280

    
281
        h->non_zero_count_cache[1+8*0]= h->non_zero_count[top_xy][9];
282
        h->non_zero_count_cache[2+8*0]= h->non_zero_count[top_xy][8];
283

    
284
        h->non_zero_count_cache[1+8*3]= h->non_zero_count[top_xy][12];
285
        h->non_zero_count_cache[2+8*3]= h->non_zero_count[top_xy][11];
286

    
287
    }else{
288
        h->non_zero_count_cache[4+8*0]=
289
        h->non_zero_count_cache[5+8*0]=
290
        h->non_zero_count_cache[6+8*0]=
291
        h->non_zero_count_cache[7+8*0]=
292

    
293
        h->non_zero_count_cache[1+8*0]=
294
        h->non_zero_count_cache[2+8*0]=
295

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

    
299
    }
300

    
301
    for (i=0; i<2; i++) {
302
        if(left_type[i]){
303
            h->non_zero_count_cache[3+8*1 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[0+2*i]];
304
            h->non_zero_count_cache[3+8*2 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[1+2*i]];
305
            h->non_zero_count_cache[0+8*1 +   8*i]= h->non_zero_count[left_xy[i]][left_block[4+2*i]];
306
            h->non_zero_count_cache[0+8*4 +   8*i]= h->non_zero_count[left_xy[i]][left_block[5+2*i]];
307
        }else{
308
            h->non_zero_count_cache[3+8*1 + 2*8*i]=
309
            h->non_zero_count_cache[3+8*2 + 2*8*i]=
310
            h->non_zero_count_cache[0+8*1 +   8*i]=
311
            h->non_zero_count_cache[0+8*4 +   8*i]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
312
        }
313
    }
314

    
315
    if( h->pps.cabac ) {
316
        // top_cbp
317
        if(top_type) {
318
            h->top_cbp = h->cbp_table[top_xy];
319
        } else if(IS_INTRA(mb_type)) {
320
            h->top_cbp = 0x1C0;
321
        } else {
322
            h->top_cbp = 0;
323
        }
324
        // left_cbp
325
        if (left_type[0]) {
326
            h->left_cbp = h->cbp_table[left_xy[0]] & 0x1f0;
327
        } else if(IS_INTRA(mb_type)) {
328
            h->left_cbp = 0x1C0;
329
        } else {
330
            h->left_cbp = 0;
331
        }
332
        if (left_type[0]) {
333
            h->left_cbp |= ((h->cbp_table[left_xy[0]]>>((left_block[0]&(~1))+1))&0x1) << 1;
334
        }
335
        if (left_type[1]) {
336
            h->left_cbp |= ((h->cbp_table[left_xy[1]]>>((left_block[2]&(~1))+1))&0x1) << 3;
337
        }
338
    }
339

    
340
#if 1
341
    if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
342
        int list;
343
        for(list=0; list<h->list_count; list++){
344
            if(!USES_LIST(mb_type, list) && !IS_DIRECT(mb_type) && !h->deblocking_filter){
345
                /*if(!h->mv_cache_clean[list]){
346
                    memset(h->mv_cache [list],  0, 8*5*2*sizeof(int16_t)); //FIXME clean only input? clean at all?
347
                    memset(h->ref_cache[list], PART_NOT_AVAILABLE, 8*5*sizeof(int8_t));
348
                    h->mv_cache_clean[list]= 1;
349
                }*/
350
                continue;
351
            }
352
            h->mv_cache_clean[list]= 0;
353

    
354
            if(USES_LIST(top_type, list)){
355
                const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
356
                const int b8_xy= h->mb2b8_xy[top_xy] + h->b8_stride;
357
                *(uint32_t*)h->mv_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 0];
358
                *(uint32_t*)h->mv_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 1];
359
                *(uint32_t*)h->mv_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 2];
360
                *(uint32_t*)h->mv_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 3];
361
                h->ref_cache[list][scan8[0] + 0 - 1*8]=
362
                h->ref_cache[list][scan8[0] + 1 - 1*8]= s->current_picture.ref_index[list][b8_xy + 0];
363
                h->ref_cache[list][scan8[0] + 2 - 1*8]=
364
                h->ref_cache[list][scan8[0] + 3 - 1*8]= s->current_picture.ref_index[list][b8_xy + 1];
365
            }else{
366
                *(uint32_t*)h->mv_cache [list][scan8[0] + 0 - 1*8]=
367
                *(uint32_t*)h->mv_cache [list][scan8[0] + 1 - 1*8]=
368
                *(uint32_t*)h->mv_cache [list][scan8[0] + 2 - 1*8]=
369
                *(uint32_t*)h->mv_cache [list][scan8[0] + 3 - 1*8]= 0;
370
                *(uint32_t*)&h->ref_cache[list][scan8[0] + 0 - 1*8]= ((top_type ? LIST_NOT_USED : PART_NOT_AVAILABLE)&0xFF)*0x01010101;
371
            }
372

    
373
            for(i=0; i<2; i++){
374
                int cache_idx = scan8[0] - 1 + i*2*8;
375
                if(USES_LIST(left_type[i], list)){
376
                    const int b_xy= h->mb2b_xy[left_xy[i]] + 3;
377
                    const int b8_xy= h->mb2b8_xy[left_xy[i]] + 1;
378
                    *(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]];
379
                    *(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]];
380
                    h->ref_cache[list][cache_idx  ]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[0+i*2]>>1)];
381
                    h->ref_cache[list][cache_idx+8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[1+i*2]>>1)];
382
                }else{
383
                    *(uint32_t*)h->mv_cache [list][cache_idx  ]=
384
                    *(uint32_t*)h->mv_cache [list][cache_idx+8]= 0;
385
                    h->ref_cache[list][cache_idx  ]=
386
                    h->ref_cache[list][cache_idx+8]= left_type[i] ? LIST_NOT_USED : PART_NOT_AVAILABLE;
387
                }
388
            }
389

    
390
            if((for_deblock || (IS_DIRECT(mb_type) && !h->direct_spatial_mv_pred)) && !FRAME_MBAFF)
391
                continue;
392

    
393
            if(USES_LIST(topleft_type, list)){
394
                const int b_xy = h->mb2b_xy[topleft_xy] + 3 + h->b_stride + (topleft_partition & 2*h->b_stride);
395
                const int b8_xy= h->mb2b8_xy[topleft_xy] + 1 + (topleft_partition & h->b8_stride);
396
                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
397
                h->ref_cache[list][scan8[0] - 1 - 1*8]= s->current_picture.ref_index[list][b8_xy];
398
            }else{
399
                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= 0;
400
                h->ref_cache[list][scan8[0] - 1 - 1*8]= topleft_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
401
            }
402

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

    
413
            if((IS_SKIP(mb_type) || IS_DIRECT(mb_type)) && !FRAME_MBAFF)
414
                continue;
415

    
416
            h->ref_cache[list][scan8[5 ]+1] =
417
            h->ref_cache[list][scan8[7 ]+1] =
418
            h->ref_cache[list][scan8[13]+1] =  //FIXME remove past 3 (init somewhere else)
419
            h->ref_cache[list][scan8[4 ]] =
420
            h->ref_cache[list][scan8[12]] = PART_NOT_AVAILABLE;
421
            *(uint32_t*)h->mv_cache [list][scan8[5 ]+1]=
422
            *(uint32_t*)h->mv_cache [list][scan8[7 ]+1]=
423
            *(uint32_t*)h->mv_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)
424
            *(uint32_t*)h->mv_cache [list][scan8[4 ]]=
425
            *(uint32_t*)h->mv_cache [list][scan8[12]]= 0;
426

    
427
            if( h->pps.cabac ) {
428
                /* XXX beurk, Load mvd */
429
                if(USES_LIST(top_type, list)){
430
                    const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
431
                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 0];
432
                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 1];
433
                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 2];
434
                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 3];
435
                }else{
436
                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 0 - 1*8]=
437
                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 1 - 1*8]=
438
                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 2 - 1*8]=
439
                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 3 - 1*8]= 0;
440
                }
441
                if(USES_LIST(left_type[0], list)){
442
                    const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
443
                    *(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]];
444
                    *(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]];
445
                }else{
446
                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 0*8]=
447
                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 1*8]= 0;
448
                }
449
                if(USES_LIST(left_type[1], list)){
450
                    const int b_xy= h->mb2b_xy[left_xy[1]] + 3;
451
                    *(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]];
452
                    *(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]];
453
                }else{
454
                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 2*8]=
455
                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 3*8]= 0;
456
                }
457
                *(uint32_t*)h->mvd_cache [list][scan8[5 ]+1]=
458
                *(uint32_t*)h->mvd_cache [list][scan8[7 ]+1]=
459
                *(uint32_t*)h->mvd_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)
460
                *(uint32_t*)h->mvd_cache [list][scan8[4 ]]=
461
                *(uint32_t*)h->mvd_cache [list][scan8[12]]= 0;
462

    
463
                if(h->slice_type_nos == FF_B_TYPE){
464
                    fill_rectangle(&h->direct_cache[scan8[0]], 4, 4, 8, 0, 1);
465

    
466
                    if(IS_DIRECT(top_type)){
467
                        *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0x01010101;
468
                    }else if(IS_8X8(top_type)){
469
                        int b8_xy = h->mb2b8_xy[top_xy] + h->b8_stride;
470
                        h->direct_cache[scan8[0] + 0 - 1*8]= h->direct_table[b8_xy];
471
                        h->direct_cache[scan8[0] + 2 - 1*8]= h->direct_table[b8_xy + 1];
472
                    }else{
473
                        *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0;
474
                    }
475

    
476
                    if(IS_DIRECT(left_type[0]))
477
                        h->direct_cache[scan8[0] - 1 + 0*8]= 1;
478
                    else if(IS_8X8(left_type[0]))
479
                        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)];
480
                    else
481
                        h->direct_cache[scan8[0] - 1 + 0*8]= 0;
482

    
483
                    if(IS_DIRECT(left_type[1]))
484
                        h->direct_cache[scan8[0] - 1 + 2*8]= 1;
485
                    else if(IS_8X8(left_type[1]))
486
                        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)];
487
                    else
488
                        h->direct_cache[scan8[0] - 1 + 2*8]= 0;
489
                }
490
            }
491

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

    
528
    h->neighbor_transform_size= !!IS_8x8DCT(top_type) + !!IS_8x8DCT(left_type[0]);
529
}
530

    
531
static inline void write_back_intra_pred_mode(H264Context *h){
532
    const int mb_xy= h->mb_xy;
533

    
534
    h->intra4x4_pred_mode[mb_xy][0]= h->intra4x4_pred_mode_cache[7+8*1];
535
    h->intra4x4_pred_mode[mb_xy][1]= h->intra4x4_pred_mode_cache[7+8*2];
536
    h->intra4x4_pred_mode[mb_xy][2]= h->intra4x4_pred_mode_cache[7+8*3];
537
    h->intra4x4_pred_mode[mb_xy][3]= h->intra4x4_pred_mode_cache[7+8*4];
538
    h->intra4x4_pred_mode[mb_xy][4]= h->intra4x4_pred_mode_cache[4+8*4];
539
    h->intra4x4_pred_mode[mb_xy][5]= h->intra4x4_pred_mode_cache[5+8*4];
540
    h->intra4x4_pred_mode[mb_xy][6]= h->intra4x4_pred_mode_cache[6+8*4];
541
}
542

    
543
/**
544
 * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
545
 */
546
static inline int check_intra4x4_pred_mode(H264Context *h){
547
    MpegEncContext * const s = &h->s;
548
    static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
549
    static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
550
    int i;
551

    
552
    if(!(h->top_samples_available&0x8000)){
553
        for(i=0; i<4; i++){
554
            int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
555
            if(status<0){
556
                av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
557
                return -1;
558
            } else if(status){
559
                h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
560
            }
561
        }
562
    }
563

    
564
    if(!(h->left_samples_available&0x8000)){
565
        for(i=0; i<4; i++){
566
            int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
567
            if(status<0){
568
                av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
569
                return -1;
570
            } else if(status){
571
                h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
572
            }
573
        }
574
    }
575

    
576
    return 0;
577
} //FIXME cleanup like next
578

    
579
/**
580
 * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
581
 */
582
static inline int check_intra_pred_mode(H264Context *h, int mode){
583
    MpegEncContext * const s = &h->s;
584
    static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
585
    static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
586

    
587
    if(mode > 6U) {
588
        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);
589
        return -1;
590
    }
591

    
592
    if(!(h->top_samples_available&0x8000)){
593
        mode= top[ mode ];
594
        if(mode<0){
595
            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);
596
            return -1;
597
        }
598
    }
599

    
600
    if(!(h->left_samples_available&0x8000)){
601
        mode= left[ mode ];
602
        if(mode<0){
603
            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);
604
            return -1;
605
        }
606
    }
607

    
608
    return mode;
609
}
610

    
611
/**
612
 * gets the predicted intra4x4 prediction mode.
613
 */
614
static inline int pred_intra_mode(H264Context *h, int n){
615
    const int index8= scan8[n];
616
    const int left= h->intra4x4_pred_mode_cache[index8 - 1];
617
    const int top = h->intra4x4_pred_mode_cache[index8 - 8];
618
    const int min= FFMIN(left, top);
619

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

    
622
    if(min<0) return DC_PRED;
623
    else      return min;
624
}
625

    
626
static inline void write_back_non_zero_count(H264Context *h){
627
    const int mb_xy= h->mb_xy;
628

    
629
    h->non_zero_count[mb_xy][0]= h->non_zero_count_cache[7+8*1];
630
    h->non_zero_count[mb_xy][1]= h->non_zero_count_cache[7+8*2];
631
    h->non_zero_count[mb_xy][2]= h->non_zero_count_cache[7+8*3];
632
    h->non_zero_count[mb_xy][3]= h->non_zero_count_cache[7+8*4];
633
    h->non_zero_count[mb_xy][4]= h->non_zero_count_cache[4+8*4];
634
    h->non_zero_count[mb_xy][5]= h->non_zero_count_cache[5+8*4];
635
    h->non_zero_count[mb_xy][6]= h->non_zero_count_cache[6+8*4];
636

    
637
    h->non_zero_count[mb_xy][9]= h->non_zero_count_cache[1+8*2];
638
    h->non_zero_count[mb_xy][8]= h->non_zero_count_cache[2+8*2];
639
    h->non_zero_count[mb_xy][7]= h->non_zero_count_cache[2+8*1];
640

    
641
    h->non_zero_count[mb_xy][12]=h->non_zero_count_cache[1+8*5];
642
    h->non_zero_count[mb_xy][11]=h->non_zero_count_cache[2+8*5];
643
    h->non_zero_count[mb_xy][10]=h->non_zero_count_cache[2+8*4];
644

    
645
    if(FRAME_MBAFF){
646
        // store all luma nnzs, for deblocking
647
        int v = 0, i;
648
        for(i=0; i<16; i++)
649
            v += (!!h->non_zero_count_cache[scan8[i]]) << i;
650
        *(uint16_t*)&h->non_zero_count[mb_xy][14] = v;
651
    }
652
}
653

    
654
/**
655
 * gets the predicted number of non-zero coefficients.
656
 * @param n block index
657
 */
658
static inline int pred_non_zero_count(H264Context *h, int n){
659
    const int index8= scan8[n];
660
    const int left= h->non_zero_count_cache[index8 - 1];
661
    const int top = h->non_zero_count_cache[index8 - 8];
662
    int i= left + top;
663

    
664
    if(i<64) i= (i+1)>>1;
665

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

    
668
    return i&31;
669
}
670

    
671
static inline int fetch_diagonal_mv(H264Context *h, const int16_t **C, int i, int list, int part_width){
672
    const int topright_ref= h->ref_cache[list][ i - 8 + part_width ];
673
    MpegEncContext *s = &h->s;
674

    
675
    /* there is no consistent mapping of mvs to neighboring locations that will
676
     * make mbaff happy, so we can't move all this logic to fill_caches */
677
    if(FRAME_MBAFF){
678
        const uint32_t *mb_types = s->current_picture_ptr->mb_type;
679
        const int16_t *mv;
680
        *(uint32_t*)h->mv_cache[list][scan8[0]-2] = 0;
681
        *C = h->mv_cache[list][scan8[0]-2];
682

    
683
        if(!MB_FIELD
684
           && (s->mb_y&1) && i < scan8[0]+8 && topright_ref != PART_NOT_AVAILABLE){
685
            int topright_xy = s->mb_x + (s->mb_y-1)*s->mb_stride + (i == scan8[0]+3);
686
            if(IS_INTERLACED(mb_types[topright_xy])){
687
#define SET_DIAG_MV(MV_OP, REF_OP, X4, Y4)\
688
                const int x4 = X4, y4 = Y4;\
689
                const int mb_type = mb_types[(x4>>2)+(y4>>2)*s->mb_stride];\
690
                if(!USES_LIST(mb_type,list))\
691
                    return LIST_NOT_USED;\
692
                mv = s->current_picture_ptr->motion_val[list][x4 + y4*h->b_stride];\
693
                h->mv_cache[list][scan8[0]-2][0] = mv[0];\
694
                h->mv_cache[list][scan8[0]-2][1] = mv[1] MV_OP;\
695
                return s->current_picture_ptr->ref_index[list][(x4>>1) + (y4>>1)*h->b8_stride] REF_OP;
696

    
697
                SET_DIAG_MV(*2, >>1, s->mb_x*4+(i&7)-4+part_width, s->mb_y*4-1);
698
            }
699
        }
700
        if(topright_ref == PART_NOT_AVAILABLE
701
           && ((s->mb_y&1) || i >= scan8[0]+8) && (i&7)==4
702
           && h->ref_cache[list][scan8[0]-1] != PART_NOT_AVAILABLE){
703
            if(!MB_FIELD
704
               && IS_INTERLACED(mb_types[h->left_mb_xy[0]])){
705
                SET_DIAG_MV(*2, >>1, s->mb_x*4-1, (s->mb_y|1)*4+(s->mb_y&1)*2+(i>>4)-1);
706
            }
707
            if(MB_FIELD
708
               && !IS_INTERLACED(mb_types[h->left_mb_xy[0]])
709
               && i >= scan8[0]+8){
710
                // left shift will turn LIST_NOT_USED into PART_NOT_AVAILABLE, but that's OK.
711
                SET_DIAG_MV(/2, <<1, s->mb_x*4-1, (s->mb_y&~1)*4 - 1 + ((i-scan8[0])>>3)*2);
712
            }
713
        }
714
#undef SET_DIAG_MV
715
    }
716

    
717
    if(topright_ref != PART_NOT_AVAILABLE){
718
        *C= h->mv_cache[list][ i - 8 + part_width ];
719
        return topright_ref;
720
    }else{
721
        tprintf(s->avctx, "topright MV not available\n");
722

    
723
        *C= h->mv_cache[list][ i - 8 - 1 ];
724
        return h->ref_cache[list][ i - 8 - 1 ];
725
    }
726
}
727

    
728
/**
729
 * gets the predicted MV.
730
 * @param n the block index
731
 * @param part_width the width of the partition (4, 8,16) -> (1, 2, 4)
732
 * @param mx the x component of the predicted motion vector
733
 * @param my the y component of the predicted motion vector
734
 */
735
static inline void pred_motion(H264Context * const h, int n, int part_width, int list, int ref, int * const mx, int * const my){
736
    const int index8= scan8[n];
737
    const int top_ref=      h->ref_cache[list][ index8 - 8 ];
738
    const int left_ref=     h->ref_cache[list][ index8 - 1 ];
739
    const int16_t * const A= h->mv_cache[list][ index8 - 1 ];
740
    const int16_t * const B= h->mv_cache[list][ index8 - 8 ];
741
    const int16_t * C;
742
    int diagonal_ref, match_count;
743

    
744
    assert(part_width==1 || part_width==2 || part_width==4);
745

    
746
/* mv_cache
747
  B . . A T T T T
748
  U . . L . . , .
749
  U . . L . . . .
750
  U . . L . . , .
751
  . . . L . . . .
752
*/
753

    
754
    diagonal_ref= fetch_diagonal_mv(h, &C, index8, list, part_width);
755
    match_count= (diagonal_ref==ref) + (top_ref==ref) + (left_ref==ref);
756
    tprintf(h->s.avctx, "pred_motion match_count=%d\n", match_count);
757
    if(match_count > 1){ //most common
758
        *mx= mid_pred(A[0], B[0], C[0]);
759
        *my= mid_pred(A[1], B[1], C[1]);
760
    }else if(match_count==1){
761
        if(left_ref==ref){
762
            *mx= A[0];
763
            *my= A[1];
764
        }else if(top_ref==ref){
765
            *mx= B[0];
766
            *my= B[1];
767
        }else{
768
            *mx= C[0];
769
            *my= C[1];
770
        }
771
    }else{
772
        if(top_ref == PART_NOT_AVAILABLE && diagonal_ref == PART_NOT_AVAILABLE && left_ref != PART_NOT_AVAILABLE){
773
            *mx= A[0];
774
            *my= A[1];
775
        }else{
776
            *mx= mid_pred(A[0], B[0], C[0]);
777
            *my= mid_pred(A[1], B[1], C[1]);
778
        }
779
    }
780

    
781
    tprintf(h->s.avctx, "pred_motion (%2d %2d %2d) (%2d %2d %2d) (%2d %2d %2d) -> (%2d %2d %2d) at %2d %2d %d list %d\n", top_ref, B[0], B[1],                    diagonal_ref, C[0], C[1], left_ref, A[0], A[1], ref, *mx, *my, h->s.mb_x, h->s.mb_y, n, list);
782
}
783

    
784
/**
785
 * gets the directionally predicted 16x8 MV.
786
 * @param n the block index
787
 * @param mx the x component of the predicted motion vector
788
 * @param my the y component of the predicted motion vector
789
 */
790
static inline void pred_16x8_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
791
    if(n==0){
792
        const int top_ref=      h->ref_cache[list][ scan8[0] - 8 ];
793
        const int16_t * const B= h->mv_cache[list][ scan8[0] - 8 ];
794

    
795
        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);
796

    
797
        if(top_ref == ref){
798
            *mx= B[0];
799
            *my= B[1];
800
            return;
801
        }
802
    }else{
803
        const int left_ref=     h->ref_cache[list][ scan8[8] - 1 ];
804
        const int16_t * const A= h->mv_cache[list][ scan8[8] - 1 ];
805

    
806
        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);
807

    
808
        if(left_ref == ref){
809
            *mx= A[0];
810
            *my= A[1];
811
            return;
812
        }
813
    }
814

    
815
    //RARE
816
    pred_motion(h, n, 4, list, ref, mx, my);
817
}
818

    
819
/**
820
 * gets the directionally predicted 8x16 MV.
821
 * @param n the block index
822
 * @param mx the x component of the predicted motion vector
823
 * @param my the y component of the predicted motion vector
824
 */
825
static inline void pred_8x16_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
826
    if(n==0){
827
        const int left_ref=      h->ref_cache[list][ scan8[0] - 1 ];
828
        const int16_t * const A=  h->mv_cache[list][ scan8[0] - 1 ];
829

    
830
        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);
831

    
832
        if(left_ref == ref){
833
            *mx= A[0];
834
            *my= A[1];
835
            return;
836
        }
837
    }else{
838
        const int16_t * C;
839
        int diagonal_ref;
840

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

    
843
        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);
844

    
845
        if(diagonal_ref == ref){
846
            *mx= C[0];
847
            *my= C[1];
848
            return;
849
        }
850
    }
851

    
852
    //RARE
853
    pred_motion(h, n, 2, list, ref, mx, my);
854
}
855

    
856
static inline void pred_pskip_motion(H264Context * const h, int * const mx, int * const my){
857
    const int top_ref = h->ref_cache[0][ scan8[0] - 8 ];
858
    const int left_ref= h->ref_cache[0][ scan8[0] - 1 ];
859

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

    
862
    if(top_ref == PART_NOT_AVAILABLE || left_ref == PART_NOT_AVAILABLE
863
       || (top_ref == 0  && *(uint32_t*)h->mv_cache[0][ scan8[0] - 8 ] == 0)
864
       || (left_ref == 0 && *(uint32_t*)h->mv_cache[0][ scan8[0] - 1 ] == 0)){
865

    
866
        *mx = *my = 0;
867
        return;
868
    }
869

    
870
    pred_motion(h, 0, 4, 0, 0, mx, my);
871

    
872
    return;
873
}
874

    
875
static inline void direct_dist_scale_factor(H264Context * const h){
876
    const int poc = h->s.current_picture_ptr->poc;
877
    const int poc1 = h->ref_list[1][0].poc;
878
    int i;
879
    for(i=0; i<h->ref_count[0]; i++){
880
        int poc0 = h->ref_list[0][i].poc;
881
        int td = av_clip(poc1 - poc0, -128, 127);
882
        if(td == 0 /* FIXME || pic0 is a long-term ref */){
883
            h->dist_scale_factor[i] = 256;
884
        }else{
885
            int tb = av_clip(poc - poc0, -128, 127);
886
            int tx = (16384 + (FFABS(td) >> 1)) / td;
887
            h->dist_scale_factor[i] = av_clip((tb*tx + 32) >> 6, -1024, 1023);
888
        }
889
    }
890
    if(FRAME_MBAFF){
891
        for(i=0; i<h->ref_count[0]; i++){
892
            h->dist_scale_factor_field[2*i] =
893
            h->dist_scale_factor_field[2*i+1] = h->dist_scale_factor[i];
894
        }
895
    }
896
}
897
static inline void direct_ref_list_init(H264Context * const h){
898
    MpegEncContext * const s = &h->s;
899
    Picture * const ref1 = &h->ref_list[1][0];
900
    Picture * const cur = s->current_picture_ptr;
901
    int list, i, j;
902
    if(cur->pict_type == FF_I_TYPE)
903
        cur->ref_count[0] = 0;
904
    if(cur->pict_type != FF_B_TYPE)
905
        cur->ref_count[1] = 0;
906
    for(list=0; list<2; list++){
907
        cur->ref_count[list] = h->ref_count[list];
908
        for(j=0; j<h->ref_count[list]; j++)
909
            cur->ref_poc[list][j] = h->ref_list[list][j].poc;
910
    }
911
    if(cur->pict_type != FF_B_TYPE || h->direct_spatial_mv_pred)
912
        return;
913
    for(list=0; list<2; list++){
914
        for(i=0; i<ref1->ref_count[list]; i++){
915
            const int poc = ref1->ref_poc[list][i];
916
            h->map_col_to_list0[list][i] = 0; /* bogus; fills in for missing frames */
917
            for(j=0; j<h->ref_count[list]; j++)
918
                if(h->ref_list[list][j].poc == poc){
919
                    h->map_col_to_list0[list][i] = j;
920
                    break;
921
                }
922
        }
923
    }
924
    if(FRAME_MBAFF){
925
        for(list=0; list<2; list++){
926
            for(i=0; i<ref1->ref_count[list]; i++){
927
                j = h->map_col_to_list0[list][i];
928
                h->map_col_to_list0_field[list][2*i] = 2*j;
929
                h->map_col_to_list0_field[list][2*i+1] = 2*j+1;
930
            }
931
        }
932
    }
933
}
934

    
935
static inline void pred_direct_motion(H264Context * const h, int *mb_type){
936
    MpegEncContext * const s = &h->s;
937
    const int mb_xy =   h->mb_xy;
938
    const int b8_xy = 2*s->mb_x + 2*s->mb_y*h->b8_stride;
939
    const int b4_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
940
    const int mb_type_col = h->ref_list[1][0].mb_type[mb_xy];
941
    const int16_t (*l1mv0)[2] = (const int16_t (*)[2]) &h->ref_list[1][0].motion_val[0][b4_xy];
942
    const int16_t (*l1mv1)[2] = (const int16_t (*)[2]) &h->ref_list[1][0].motion_val[1][b4_xy];
943
    const int8_t *l1ref0 = &h->ref_list[1][0].ref_index[0][b8_xy];
944
    const int8_t *l1ref1 = &h->ref_list[1][0].ref_index[1][b8_xy];
945
    const int is_b8x8 = IS_8X8(*mb_type);
946
    unsigned int sub_mb_type;
947
    int i8, i4;
948

    
949
#define MB_TYPE_16x16_OR_INTRA (MB_TYPE_16x16|MB_TYPE_INTRA4x4|MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM)
950
    if(IS_8X8(mb_type_col) && !h->sps.direct_8x8_inference_flag){
951
        /* FIXME save sub mb types from previous frames (or derive from MVs)
952
         * so we know exactly what block size to use */
953
        sub_mb_type = MB_TYPE_8x8|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_4x4 */
954
        *mb_type =    MB_TYPE_8x8|MB_TYPE_L0L1;
955
    }else if(!is_b8x8 && (mb_type_col & MB_TYPE_16x16_OR_INTRA)){
956
        sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
957
        *mb_type =    MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_16x16 */
958
    }else{
959
        sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
960
        *mb_type =    MB_TYPE_8x8|MB_TYPE_L0L1;
961
    }
962
    if(!is_b8x8)
963
        *mb_type |= MB_TYPE_DIRECT2;
964
    if(MB_FIELD)
965
        *mb_type |= MB_TYPE_INTERLACED;
966

    
967
    tprintf(s->avctx, "mb_type = %08x, sub_mb_type = %08x, is_b8x8 = %d, mb_type_col = %08x\n", *mb_type, sub_mb_type, is_b8x8, mb_type_col);
968

    
969
    if(h->direct_spatial_mv_pred){
970
        int ref[2];
971
        int mv[2][2];
972
        int list;
973

    
974
        /* FIXME interlacing + spatial direct uses wrong colocated block positions */
975

    
976
        /* ref = min(neighbors) */
977
        for(list=0; list<2; list++){
978
            int refa = h->ref_cache[list][scan8[0] - 1];
979
            int refb = h->ref_cache[list][scan8[0] - 8];
980
            int refc = h->ref_cache[list][scan8[0] - 8 + 4];
981
            if(refc == -2)
982
                refc = h->ref_cache[list][scan8[0] - 8 - 1];
983
            ref[list] = FFMIN3((unsigned)refa, (unsigned)refb, (unsigned)refc);
984
            if(ref[list] < 0)
985
                ref[list] = -1;
986
        }
987

    
988
        if(ref[0] < 0 && ref[1] < 0){
989
            ref[0] = ref[1] = 0;
990
            mv[0][0] = mv[0][1] =
991
            mv[1][0] = mv[1][1] = 0;
992
        }else{
993
            for(list=0; list<2; list++){
994
                if(ref[list] >= 0)
995
                    pred_motion(h, 0, 4, list, ref[list], &mv[list][0], &mv[list][1]);
996
                else
997
                    mv[list][0] = mv[list][1] = 0;
998
            }
999
        }
1000

    
1001
        if(ref[1] < 0){
1002
            if(!is_b8x8)
1003
                *mb_type &= ~MB_TYPE_L1;
1004
            sub_mb_type &= ~MB_TYPE_L1;
1005
        }else if(ref[0] < 0){
1006
            if(!is_b8x8)
1007
                *mb_type &= ~MB_TYPE_L0;
1008
            sub_mb_type &= ~MB_TYPE_L0;
1009
        }
1010

    
1011
        if(IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col)){
1012
            int pair_xy = s->mb_x + (s->mb_y&~1)*s->mb_stride;
1013
            int mb_types_col[2];
1014
            int b8_stride = h->b8_stride;
1015
            int b4_stride = h->b_stride;
1016

    
1017
            *mb_type = (*mb_type & ~MB_TYPE_16x16) | MB_TYPE_8x8;
1018

    
1019
            if(IS_INTERLACED(*mb_type)){
1020
                mb_types_col[0] = h->ref_list[1][0].mb_type[pair_xy];
1021
                mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy+s->mb_stride];
1022
                if(s->mb_y&1){
1023
                    l1ref0 -= 2*b8_stride;
1024
                    l1ref1 -= 2*b8_stride;
1025
                    l1mv0 -= 4*b4_stride;
1026
                    l1mv1 -= 4*b4_stride;
1027
                }
1028
                b8_stride *= 3;
1029
                b4_stride *= 6;
1030
            }else{
1031
                int cur_poc = s->current_picture_ptr->poc;
1032
                int *col_poc = h->ref_list[1]->field_poc;
1033
                int col_parity = FFABS(col_poc[0] - cur_poc) >= FFABS(col_poc[1] - cur_poc);
1034
                int dy = 2*col_parity - (s->mb_y&1);
1035
                mb_types_col[0] =
1036
                mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy + col_parity*s->mb_stride];
1037
                l1ref0 += dy*b8_stride;
1038
                l1ref1 += dy*b8_stride;
1039
                l1mv0 += 2*dy*b4_stride;
1040
                l1mv1 += 2*dy*b4_stride;
1041
                b8_stride = 0;
1042
            }
1043

    
1044
            for(i8=0; i8<4; i8++){
1045
                int x8 = i8&1;
1046
                int y8 = i8>>1;
1047
                int xy8 = x8+y8*b8_stride;
1048
                int xy4 = 3*x8+y8*b4_stride;
1049
                int a=0, b=0;
1050

    
1051
                if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1052
                    continue;
1053
                h->sub_mb_type[i8] = sub_mb_type;
1054

    
1055
                fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[0], 1);
1056
                fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[1], 1);
1057
                if(!IS_INTRA(mb_types_col[y8])
1058
                   && (   (l1ref0[xy8] == 0 && FFABS(l1mv0[xy4][0]) <= 1 && FFABS(l1mv0[xy4][1]) <= 1)
1059
                       || (l1ref0[xy8]  < 0 && l1ref1[xy8] == 0 && FFABS(l1mv1[xy4][0]) <= 1 && FFABS(l1mv1[xy4][1]) <= 1))){
1060
                    if(ref[0] > 0)
1061
                        a= pack16to32(mv[0][0],mv[0][1]);
1062
                    if(ref[1] > 0)
1063
                        b= pack16to32(mv[1][0],mv[1][1]);
1064
                }else{
1065
                    a= pack16to32(mv[0][0],mv[0][1]);
1066
                    b= pack16to32(mv[1][0],mv[1][1]);
1067
                }
1068
                fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, a, 4);
1069
                fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, b, 4);
1070
            }
1071
        }else if(IS_16X16(*mb_type)){
1072
            int a=0, b=0;
1073

    
1074
            fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);
1075
            fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);
1076
            if(!IS_INTRA(mb_type_col)
1077
               && (   (l1ref0[0] == 0 && FFABS(l1mv0[0][0]) <= 1 && FFABS(l1mv0[0][1]) <= 1)
1078
                   || (l1ref0[0]  < 0 && l1ref1[0] == 0 && FFABS(l1mv1[0][0]) <= 1 && FFABS(l1mv1[0][1]) <= 1
1079
                       && (h->x264_build>33 || !h->x264_build)))){
1080
                if(ref[0] > 0)
1081
                    a= pack16to32(mv[0][0],mv[0][1]);
1082
                if(ref[1] > 0)
1083
                    b= pack16to32(mv[1][0],mv[1][1]);
1084
            }else{
1085
                a= pack16to32(mv[0][0],mv[0][1]);
1086
                b= pack16to32(mv[1][0],mv[1][1]);
1087
            }
1088
            fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);
1089
            fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);
1090
        }else{
1091
            for(i8=0; i8<4; i8++){
1092
                const int x8 = i8&1;
1093
                const int y8 = i8>>1;
1094

    
1095
                if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1096
                    continue;
1097
                h->sub_mb_type[i8] = sub_mb_type;
1098

    
1099
                fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mv[0][0],mv[0][1]), 4);
1100
                fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mv[1][0],mv[1][1]), 4);
1101
                fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[0], 1);
1102
                fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[1], 1);
1103

    
1104
                /* col_zero_flag */
1105
                if(!IS_INTRA(mb_type_col) && (   l1ref0[x8 + y8*h->b8_stride] == 0
1106
                                              || (l1ref0[x8 + y8*h->b8_stride] < 0 && l1ref1[x8 + y8*h->b8_stride] == 0
1107
                                                  && (h->x264_build>33 || !h->x264_build)))){
1108
                    const int16_t (*l1mv)[2]= l1ref0[x8 + y8*h->b8_stride] == 0 ? l1mv0 : l1mv1;
1109
                    if(IS_SUB_8X8(sub_mb_type)){
1110
                        const int16_t *mv_col = l1mv[x8*3 + y8*3*h->b_stride];
1111
                        if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){
1112
                            if(ref[0] == 0)
1113
                                fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
1114
                            if(ref[1] == 0)
1115
                                fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
1116
                        }
1117
                    }else
1118
                    for(i4=0; i4<4; i4++){
1119
                        const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*h->b_stride];
1120
                        if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){
1121
                            if(ref[0] == 0)
1122
                                *(uint32_t*)h->mv_cache[0][scan8[i8*4+i4]] = 0;
1123
                            if(ref[1] == 0)
1124
                                *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] = 0;
1125
                        }
1126
                    }
1127
                }
1128
            }
1129
        }
1130
    }else{ /* direct temporal mv pred */
1131
        const int *map_col_to_list0[2] = {h->map_col_to_list0[0], h->map_col_to_list0[1]};
1132
        const int *dist_scale_factor = h->dist_scale_factor;
1133

    
1134
        if(FRAME_MBAFF){
1135
            if(IS_INTERLACED(*mb_type)){
1136
                map_col_to_list0[0] = h->map_col_to_list0_field[0];
1137
                map_col_to_list0[1] = h->map_col_to_list0_field[1];
1138
                dist_scale_factor = h->dist_scale_factor_field;
1139
            }
1140
            if(IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col)){
1141
                /* FIXME assumes direct_8x8_inference == 1 */
1142
                const int pair_xy = s->mb_x + (s->mb_y&~1)*s->mb_stride;
1143
                int mb_types_col[2];
1144
                int y_shift;
1145

    
1146
                *mb_type = MB_TYPE_8x8|MB_TYPE_L0L1
1147
                         | (is_b8x8 ? 0 : MB_TYPE_DIRECT2)
1148
                         | (*mb_type & MB_TYPE_INTERLACED);
1149
                sub_mb_type = MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_16x16;
1150

    
1151
                if(IS_INTERLACED(*mb_type)){
1152
                    /* frame to field scaling */
1153
                    mb_types_col[0] = h->ref_list[1][0].mb_type[pair_xy];
1154
                    mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy+s->mb_stride];
1155
                    if(s->mb_y&1){
1156
                        l1ref0 -= 2*h->b8_stride;
1157
                        l1ref1 -= 2*h->b8_stride;
1158
                        l1mv0 -= 4*h->b_stride;
1159
                        l1mv1 -= 4*h->b_stride;
1160
                    }
1161
                    y_shift = 0;
1162

    
1163
                    if(   (mb_types_col[0] & MB_TYPE_16x16_OR_INTRA)
1164
                       && (mb_types_col[1] & MB_TYPE_16x16_OR_INTRA)
1165
                       && !is_b8x8)
1166
                        *mb_type |= MB_TYPE_16x8;
1167
                    else
1168
                        *mb_type |= MB_TYPE_8x8;
1169
                }else{
1170
                    /* field to frame scaling */
1171
                    /* col_mb_y = (mb_y&~1) + (topAbsDiffPOC < bottomAbsDiffPOC ? 0 : 1)
1172
                     * but in MBAFF, top and bottom POC are equal */
1173
                    int dy = (s->mb_y&1) ? 1 : 2;
1174
                    mb_types_col[0] =
1175
                    mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy+s->mb_stride];
1176
                    l1ref0 += dy*h->b8_stride;
1177
                    l1ref1 += dy*h->b8_stride;
1178
                    l1mv0 += 2*dy*h->b_stride;
1179
                    l1mv1 += 2*dy*h->b_stride;
1180
                    y_shift = 2;
1181

    
1182
                    if((mb_types_col[0] & (MB_TYPE_16x16_OR_INTRA|MB_TYPE_16x8))
1183
                       && !is_b8x8)
1184
                        *mb_type |= MB_TYPE_16x16;
1185
                    else
1186
                        *mb_type |= MB_TYPE_8x8;
1187
                }
1188

    
1189
                for(i8=0; i8<4; i8++){
1190
                    const int x8 = i8&1;
1191
                    const int y8 = i8>>1;
1192
                    int ref0, scale;
1193
                    const int16_t (*l1mv)[2]= l1mv0;
1194

    
1195
                    if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1196
                        continue;
1197
                    h->sub_mb_type[i8] = sub_mb_type;
1198

    
1199
                    fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
1200
                    if(IS_INTRA(mb_types_col[y8])){
1201
                        fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
1202
                        fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
1203
                        fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
1204
                        continue;
1205
                    }
1206

    
1207
                    ref0 = l1ref0[x8 + (y8*2>>y_shift)*h->b8_stride];
1208
                    if(ref0 >= 0)
1209
                        ref0 = map_col_to_list0[0][ref0*2>>y_shift];
1210
                    else{
1211
                        ref0 = map_col_to_list0[1][l1ref1[x8 + (y8*2>>y_shift)*h->b8_stride]*2>>y_shift];
1212
                        l1mv= l1mv1;
1213
                    }
1214
                    scale = dist_scale_factor[ref0];
1215
                    fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
1216

    
1217
                    {
1218
                        const int16_t *mv_col = l1mv[x8*3 + (y8*6>>y_shift)*h->b_stride];
1219
                        int my_col = (mv_col[1]<<y_shift)/2;
1220
                        int mx = (scale * mv_col[0] + 128) >> 8;
1221
                        int my = (scale * my_col + 128) >> 8;
1222
                        fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mx,my), 4);
1223
                        fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mx-mv_col[0],my-my_col), 4);
1224
                    }
1225
                }
1226
                return;
1227
            }
1228
        }
1229

    
1230
        /* one-to-one mv scaling */
1231

    
1232
        if(IS_16X16(*mb_type)){
1233
            int ref, mv0, mv1;
1234

    
1235
            fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, 0, 1);
1236
            if(IS_INTRA(mb_type_col)){
1237
                ref=mv0=mv1=0;
1238
            }else{
1239
                const int ref0 = l1ref0[0] >= 0 ? map_col_to_list0[0][l1ref0[0]]
1240
                                                : map_col_to_list0[1][l1ref1[0]];
1241
                const int scale = dist_scale_factor[ref0];
1242
                const int16_t *mv_col = l1ref0[0] >= 0 ? l1mv0[0] : l1mv1[0];
1243
                int mv_l0[2];
1244
                mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
1245
                mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
1246
                ref= ref0;
1247
                mv0= pack16to32(mv_l0[0],mv_l0[1]);
1248
                mv1= pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
1249
            }
1250
            fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
1251
            fill_rectangle(&h-> mv_cache[0][scan8[0]], 4, 4, 8, mv0, 4);
1252
            fill_rectangle(&h-> mv_cache[1][scan8[0]], 4, 4, 8, mv1, 4);
1253
        }else{
1254
            for(i8=0; i8<4; i8++){
1255
                const int x8 = i8&1;
1256
                const int y8 = i8>>1;
1257
                int ref0, scale;
1258
                const int16_t (*l1mv)[2]= l1mv0;
1259

    
1260
                if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
1261
                    continue;
1262
                h->sub_mb_type[i8] = sub_mb_type;
1263
                fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
1264
                if(IS_INTRA(mb_type_col)){
1265
                    fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
1266
                    fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
1267
                    fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
1268
                    continue;
1269
                }
1270

    
1271
                ref0 = l1ref0[x8 + y8*h->b8_stride];
1272
                if(ref0 >= 0)
1273
                    ref0 = map_col_to_list0[0][ref0];
1274
                else{
1275
                    ref0 = map_col_to_list0[1][l1ref1[x8 + y8*h->b8_stride]];
1276
                    l1mv= l1mv1;
1277
                }
1278
                scale = dist_scale_factor[ref0];
1279

    
1280
                fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
1281
                if(IS_SUB_8X8(sub_mb_type)){
1282
                    const int16_t *mv_col = l1mv[x8*3 + y8*3*h->b_stride];
1283
                    int mx = (scale * mv_col[0] + 128) >> 8;
1284
                    int my = (scale * mv_col[1] + 128) >> 8;
1285
                    fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mx,my), 4);
1286
                    fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mx-mv_col[0],my-mv_col[1]), 4);
1287
                }else
1288
                for(i4=0; i4<4; i4++){
1289
                    const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*h->b_stride];
1290
                    int16_t *mv_l0 = h->mv_cache[0][scan8[i8*4+i4]];
1291
                    mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
1292
                    mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
1293
                    *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] =
1294
                        pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
1295
                }
1296
            }
1297
        }
1298
    }
1299
}
1300

    
1301
static inline void write_back_motion(H264Context *h, int mb_type){
1302
    MpegEncContext * const s = &h->s;
1303
    const int b_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
1304
    const int b8_xy= 2*s->mb_x + 2*s->mb_y*h->b8_stride;
1305
    int list;
1306

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

    
1310
    for(list=0; list<h->list_count; list++){
1311
        int y;
1312
        if(!USES_LIST(mb_type, list))
1313
            continue;
1314

    
1315
        for(y=0; y<4; y++){
1316
            *(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];
1317
            *(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];
1318
        }
1319
        if( h->pps.cabac ) {
1320
            if(IS_SKIP(mb_type))
1321
                fill_rectangle(h->mvd_table[list][b_xy], 4, 4, h->b_stride, 0, 4);
1322
            else
1323
            for(y=0; y<4; y++){
1324
                *(uint64_t*)h->mvd_table[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+0 + 8*y];
1325
                *(uint64_t*)h->mvd_table[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+2 + 8*y];
1326
            }
1327
        }
1328

    
1329
        {
1330
            int8_t *ref_index = &s->current_picture.ref_index[list][b8_xy];
1331
            ref_index[0+0*h->b8_stride]= h->ref_cache[list][scan8[0]];
1332
            ref_index[1+0*h->b8_stride]= h->ref_cache[list][scan8[4]];
1333
            ref_index[0+1*h->b8_stride]= h->ref_cache[list][scan8[8]];
1334
            ref_index[1+1*h->b8_stride]= h->ref_cache[list][scan8[12]];
1335
        }
1336
    }
1337

    
1338
    if(h->slice_type_nos == FF_B_TYPE && h->pps.cabac){
1339
        if(IS_8X8(mb_type)){
1340
            uint8_t *direct_table = &h->direct_table[b8_xy];
1341
            direct_table[1+0*h->b8_stride] = IS_DIRECT(h->sub_mb_type[1]) ? 1 : 0;
1342
            direct_table[0+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[2]) ? 1 : 0;
1343
            direct_table[1+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[3]) ? 1 : 0;
1344
        }
1345
    }
1346
}
1347

    
1348
/**
1349
 * Decodes a network abstraction layer unit.
1350
 * @param consumed is the number of bytes used as input
1351
 * @param length is the length of the array
1352
 * @param dst_length is the number of decoded bytes FIXME here or a decode rbsp tailing?
1353
 * @returns decoded bytes, might be src+1 if no escapes
1354
 */
1355
static const uint8_t *decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
1356
    int i, si, di;
1357
    uint8_t *dst;
1358
    int bufidx;
1359

    
1360
//    src[0]&0x80;                //forbidden bit
1361
    h->nal_ref_idc= src[0]>>5;
1362
    h->nal_unit_type= src[0]&0x1F;
1363

    
1364
    src++; length--;
1365
#if 0
1366
    for(i=0; i<length; i++)
1367
        printf("%2X ", src[i]);
1368
#endif
1369
    for(i=0; i+1<length; i+=2){
1370
        if(src[i]) continue;
1371
        if(i>0 && src[i-1]==0) i--;
1372
        if(i+2<length && src[i+1]==0 && src[i+2]<=3){
1373
            if(src[i+2]!=3){
1374
                /* startcode, so we must be past the end */
1375
                length=i;
1376
            }
1377
            break;
1378
        }
1379
    }
1380

    
1381
    if(i>=length-1){ //no escaped 0
1382
        *dst_length= length;
1383
        *consumed= length+1; //+1 for the header
1384
        return src;
1385
    }
1386

    
1387
    bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
1388
    h->rbsp_buffer[bufidx]= av_fast_realloc(h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length);
1389
    dst= h->rbsp_buffer[bufidx];
1390

    
1391
    if (dst == NULL){
1392
        return NULL;
1393
    }
1394

    
1395
//printf("decoding esc\n");
1396
    si=di=0;
1397
    while(si<length){
1398
        //remove escapes (very rare 1:2^22)
1399
        if(si+2<length && src[si]==0 && src[si+1]==0 && src[si+2]<=3){
1400
            if(src[si+2]==3){ //escape
1401
                dst[di++]= 0;
1402
                dst[di++]= 0;
1403
                si+=3;
1404
                continue;
1405
            }else //next start code
1406
                break;
1407
        }
1408

    
1409
        dst[di++]= src[si++];
1410
    }
1411

    
1412
    *dst_length= di;
1413
    *consumed= si + 1;//+1 for the header
1414
//FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
1415
    return dst;
1416
}
1417

    
1418
/**
1419
 * identifies the exact end of the bitstream
1420
 * @return the length of the trailing, or 0 if damaged
1421
 */
1422
static int decode_rbsp_trailing(H264Context *h, const uint8_t *src){
1423
    int v= *src;
1424
    int r;
1425

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

    
1428
    for(r=1; r<9; r++){
1429
        if(v&1) return r;
1430
        v>>=1;
1431
    }
1432
    return 0;
1433
}
1434

    
1435
/**
1436
 * IDCT transforms the 16 dc values and dequantizes them.
1437
 * @param qp quantization parameter
1438
 */
1439
static void h264_luma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
1440
#define stride 16
1441
    int i;
1442
    int temp[16]; //FIXME check if this is a good idea
1443
    static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
1444
    static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
1445

    
1446
//memset(block, 64, 2*256);
1447
//return;
1448
    for(i=0; i<4; i++){
1449
        const int offset= y_offset[i];
1450
        const int z0= block[offset+stride*0] + block[offset+stride*4];
1451
        const int z1= block[offset+stride*0] - block[offset+stride*4];
1452
        const int z2= block[offset+stride*1] - block[offset+stride*5];
1453
        const int z3= block[offset+stride*1] + block[offset+stride*5];
1454

    
1455
        temp[4*i+0]= z0+z3;
1456
        temp[4*i+1]= z1+z2;
1457
        temp[4*i+2]= z1-z2;
1458
        temp[4*i+3]= z0-z3;
1459
    }
1460

    
1461
    for(i=0; i<4; i++){
1462
        const int offset= x_offset[i];
1463
        const int z0= temp[4*0+i] + temp[4*2+i];
1464
        const int z1= temp[4*0+i] - temp[4*2+i];
1465
        const int z2= temp[4*1+i] - temp[4*3+i];
1466
        const int z3= temp[4*1+i] + temp[4*3+i];
1467

    
1468
        block[stride*0 +offset]= ((((z0 + z3)*qmul + 128 ) >> 8)); //FIXME think about merging this into decode_residual
1469
        block[stride*2 +offset]= ((((z1 + z2)*qmul + 128 ) >> 8));
1470
        block[stride*8 +offset]= ((((z1 - z2)*qmul + 128 ) >> 8));
1471
        block[stride*10+offset]= ((((z0 - z3)*qmul + 128 ) >> 8));
1472
    }
1473
}
1474

    
1475
#if 0
1476
/**
1477
 * DCT transforms the 16 dc values.
1478
 * @param qp quantization parameter ??? FIXME
1479
 */
1480
static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
1481
//    const int qmul= dequant_coeff[qp][0];
1482
    int i;
1483
    int temp[16]; //FIXME check if this is a good idea
1484
    static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
1485
    static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
1486

1487
    for(i=0; i<4; i++){
1488
        const int offset= y_offset[i];
1489
        const int z0= block[offset+stride*0] + block[offset+stride*4];
1490
        const int z1= block[offset+stride*0] - block[offset+stride*4];
1491
        const int z2= block[offset+stride*1] - block[offset+stride*5];
1492
        const int z3= block[offset+stride*1] + block[offset+stride*5];
1493

1494
        temp[4*i+0]= z0+z3;
1495
        temp[4*i+1]= z1+z2;
1496
        temp[4*i+2]= z1-z2;
1497
        temp[4*i+3]= z0-z3;
1498
    }
1499

1500
    for(i=0; i<4; i++){
1501
        const int offset= x_offset[i];
1502
        const int z0= temp[4*0+i] + temp[4*2+i];
1503
        const int z1= temp[4*0+i] - temp[4*2+i];
1504
        const int z2= temp[4*1+i] - temp[4*3+i];
1505
        const int z3= temp[4*1+i] + temp[4*3+i];
1506

1507
        block[stride*0 +offset]= (z0 + z3)>>1;
1508
        block[stride*2 +offset]= (z1 + z2)>>1;
1509
        block[stride*8 +offset]= (z1 - z2)>>1;
1510
        block[stride*10+offset]= (z0 - z3)>>1;
1511
    }
1512
}
1513
#endif
1514

    
1515
#undef xStride
1516
#undef stride
1517

    
1518
static void chroma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
1519
    const int stride= 16*2;
1520
    const int xStride= 16;
1521
    int a,b,c,d,e;
1522

    
1523
    a= block[stride*0 + xStride*0];
1524
    b= block[stride*0 + xStride*1];
1525
    c= block[stride*1 + xStride*0];
1526
    d= block[stride*1 + xStride*1];
1527

    
1528
    e= a-b;
1529
    a= a+b;
1530
    b= c-d;
1531
    c= c+d;
1532

    
1533
    block[stride*0 + xStride*0]= ((a+c)*qmul) >> 7;
1534
    block[stride*0 + xStride*1]= ((e+b)*qmul) >> 7;
1535
    block[stride*1 + xStride*0]= ((a-c)*qmul) >> 7;
1536
    block[stride*1 + xStride*1]= ((e-b)*qmul) >> 7;
1537
}
1538

    
1539
#if 0
1540
static void chroma_dc_dct_c(DCTELEM *block){
1541
    const int stride= 16*2;
1542
    const int xStride= 16;
1543
    int a,b,c,d,e;
1544

1545
    a= block[stride*0 + xStride*0];
1546
    b= block[stride*0 + xStride*1];
1547
    c= block[stride*1 + xStride*0];
1548
    d= block[stride*1 + xStride*1];
1549

1550
    e= a-b;
1551
    a= a+b;
1552
    b= c-d;
1553
    c= c+d;
1554

1555
    block[stride*0 + xStride*0]= (a+c);
1556
    block[stride*0 + xStride*1]= (e+b);
1557
    block[stride*1 + xStride*0]= (a-c);
1558
    block[stride*1 + xStride*1]= (e-b);
1559
}
1560
#endif
1561

    
1562
/**
1563
 * gets the chroma qp.
1564
 */
1565
static inline int get_chroma_qp(H264Context *h, int t, int qscale){
1566
    return h->pps.chroma_qp_table[t][qscale];
1567
}
1568

    
1569
//FIXME need to check that this does not overflow signed 32 bit for low qp, I am not sure, it's very close
1570
//FIXME check that gcc inlines this (and optimizes intra & separate_dc stuff away)
1571
static inline int quantize_c(DCTELEM *block, uint8_t *scantable, int qscale, int intra, int separate_dc){
1572
    int i;
1573
    const int * const quant_table= quant_coeff[qscale];
1574
    const int bias= intra ? (1<<QUANT_SHIFT)/3 : (1<<QUANT_SHIFT)/6;
1575
    const unsigned int threshold1= (1<<QUANT_SHIFT) - bias - 1;
1576
    const unsigned int threshold2= (threshold1<<1);
1577
    int last_non_zero;
1578

    
1579
    if(separate_dc){
1580
        if(qscale<=18){
1581
            //avoid overflows
1582
            const int dc_bias= intra ? (1<<(QUANT_SHIFT-2))/3 : (1<<(QUANT_SHIFT-2))/6;
1583
            const unsigned int dc_threshold1= (1<<(QUANT_SHIFT-2)) - dc_bias - 1;
1584
            const unsigned int dc_threshold2= (dc_threshold1<<1);
1585

    
1586
            int level= block[0]*quant_coeff[qscale+18][0];
1587
            if(((unsigned)(level+dc_threshold1))>dc_threshold2){
1588
                if(level>0){
1589
                    level= (dc_bias + level)>>(QUANT_SHIFT-2);
1590
                    block[0]= level;
1591
                }else{
1592
                    level= (dc_bias - level)>>(QUANT_SHIFT-2);
1593
                    block[0]= -level;
1594
                }
1595
//                last_non_zero = i;
1596
            }else{
1597
                block[0]=0;
1598
            }
1599
        }else{
1600
            const int dc_bias= intra ? (1<<(QUANT_SHIFT+1))/3 : (1<<(QUANT_SHIFT+1))/6;
1601
            const unsigned int dc_threshold1= (1<<(QUANT_SHIFT+1)) - dc_bias - 1;
1602
            const unsigned int dc_threshold2= (dc_threshold1<<1);
1603

    
1604
            int level= block[0]*quant_table[0];
1605
            if(((unsigned)(level+dc_threshold1))>dc_threshold2){
1606
                if(level>0){
1607
                    level= (dc_bias + level)>>(QUANT_SHIFT+1);
1608
                    block[0]= level;
1609
                }else{
1610
                    level= (dc_bias - level)>>(QUANT_SHIFT+1);
1611
                    block[0]= -level;
1612
                }
1613
//                last_non_zero = i;
1614
            }else{
1615
                block[0]=0;
1616
            }
1617
        }
1618
        last_non_zero= 0;
1619
        i=1;
1620
    }else{
1621
        last_non_zero= -1;
1622
        i=0;
1623
    }
1624

    
1625
    for(; i<16; i++){
1626
        const int j= scantable[i];
1627
        int level= block[j]*quant_table[j];
1628

    
1629
//        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
1630
//           || bias-level >= (1<<(QMAT_SHIFT - 3))){
1631
        if(((unsigned)(level+threshold1))>threshold2){
1632
            if(level>0){
1633
                level= (bias + level)>>QUANT_SHIFT;
1634
                block[j]= level;
1635
            }else{
1636
                level= (bias - level)>>QUANT_SHIFT;
1637
                block[j]= -level;
1638
            }
1639
            last_non_zero = i;
1640
        }else{
1641
            block[j]=0;
1642
        }
1643
    }
1644

    
1645
    return last_non_zero;
1646
}
1647

    
1648
static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
1649
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1650
                           int src_x_offset, int src_y_offset,
1651
                           qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
1652
    MpegEncContext * const s = &h->s;
1653
    const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
1654
    int my=       h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
1655
    const int luma_xy= (mx&3) + ((my&3)<<2);
1656
    uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*h->mb_linesize;
1657
    uint8_t * src_cb, * src_cr;
1658
    int extra_width= h->emu_edge_width;
1659
    int extra_height= h->emu_edge_height;
1660
    int emu=0;
1661
    const int full_mx= mx>>2;
1662
    const int full_my= my>>2;
1663
    const int pic_width  = 16*s->mb_width;
1664
    const int pic_height = 16*s->mb_height >> MB_FIELD;
1665

    
1666
    if(!pic->data[0]) //FIXME this is unacceptable, some sensible error concealment must be done for missing reference frames
1667
        return;
1668

    
1669
    if(mx&7) extra_width -= 3;
1670
    if(my&7) extra_height -= 3;
1671

    
1672
    if(   full_mx < 0-extra_width
1673
       || full_my < 0-extra_height
1674
       || full_mx + 16/*FIXME*/ > pic_width + extra_width
1675
       || full_my + 16/*FIXME*/ > pic_height + extra_height){
1676
        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);
1677
            src_y= s->edge_emu_buffer + 2 + 2*h->mb_linesize;
1678
        emu=1;
1679
    }
1680

    
1681
    qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
1682
    if(!square){
1683
        qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
1684
    }
1685

    
1686
    if(ENABLE_GRAY && s->flags&CODEC_FLAG_GRAY) return;
1687

    
1688
    if(MB_FIELD){
1689
        // chroma offset when predicting from a field of opposite parity
1690
        my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
1691
        emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
1692
    }
1693
    src_cb= pic->data[1] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
1694
    src_cr= pic->data[2] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
1695

    
1696
    if(emu){
1697
        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);
1698
            src_cb= s->edge_emu_buffer;
1699
    }
1700
    chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
1701

    
1702
    if(emu){
1703
        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);
1704
            src_cr= s->edge_emu_buffer;
1705
    }
1706
    chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
1707
}
1708

    
1709
static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
1710
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1711
                           int x_offset, int y_offset,
1712
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1713
                           qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
1714
                           int list0, int list1){
1715
    MpegEncContext * const s = &h->s;
1716
    qpel_mc_func *qpix_op=  qpix_put;
1717
    h264_chroma_mc_func chroma_op= chroma_put;
1718

    
1719
    dest_y  += 2*x_offset + 2*y_offset*h->  mb_linesize;
1720
    dest_cb +=   x_offset +   y_offset*h->mb_uvlinesize;
1721
    dest_cr +=   x_offset +   y_offset*h->mb_uvlinesize;
1722
    x_offset += 8*s->mb_x;
1723
    y_offset += 8*(s->mb_y >> MB_FIELD);
1724

    
1725
    if(list0){
1726
        Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
1727
        mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
1728
                           dest_y, dest_cb, dest_cr, x_offset, y_offset,
1729
                           qpix_op, chroma_op);
1730

    
1731
        qpix_op=  qpix_avg;
1732
        chroma_op= chroma_avg;
1733
    }
1734

    
1735
    if(list1){
1736
        Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
1737
        mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
1738
                           dest_y, dest_cb, dest_cr, x_offset, y_offset,
1739
                           qpix_op, chroma_op);
1740
    }
1741
}
1742

    
1743
static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
1744
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1745
                           int x_offset, int y_offset,
1746
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1747
                           h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
1748
                           h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
1749
                           int list0, int list1){
1750
    MpegEncContext * const s = &h->s;
1751

    
1752
    dest_y  += 2*x_offset + 2*y_offset*h->  mb_linesize;
1753
    dest_cb +=   x_offset +   y_offset*h->mb_uvlinesize;
1754
    dest_cr +=   x_offset +   y_offset*h->mb_uvlinesize;
1755
    x_offset += 8*s->mb_x;
1756
    y_offset += 8*(s->mb_y >> MB_FIELD);
1757

    
1758
    if(list0 && list1){
1759
        /* don't optimize for luma-only case, since B-frames usually
1760
         * use implicit weights => chroma too. */
1761
        uint8_t *tmp_cb = s->obmc_scratchpad;
1762
        uint8_t *tmp_cr = s->obmc_scratchpad + 8;
1763
        uint8_t *tmp_y  = s->obmc_scratchpad + 8*h->mb_uvlinesize;
1764
        int refn0 = h->ref_cache[0][ scan8[n] ];
1765
        int refn1 = h->ref_cache[1][ scan8[n] ];
1766

    
1767
        mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
1768
                    dest_y, dest_cb, dest_cr,
1769
                    x_offset, y_offset, qpix_put, chroma_put);
1770
        mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
1771
                    tmp_y, tmp_cb, tmp_cr,
1772
                    x_offset, y_offset, qpix_put, chroma_put);
1773

    
1774
        if(h->use_weight == 2){
1775
            int weight0 = h->implicit_weight[refn0][refn1];
1776
            int weight1 = 64 - weight0;
1777
            luma_weight_avg(  dest_y,  tmp_y,  h->  mb_linesize, 5, weight0, weight1, 0);
1778
            chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
1779
            chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
1780
        }else{
1781
            luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
1782
                            h->luma_weight[0][refn0], h->luma_weight[1][refn1],
1783
                            h->luma_offset[0][refn0] + h->luma_offset[1][refn1]);
1784
            chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1785
                            h->chroma_weight[0][refn0][0], h->chroma_weight[1][refn1][0],
1786
                            h->chroma_offset[0][refn0][0] + h->chroma_offset[1][refn1][0]);
1787
            chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1788
                            h->chroma_weight[0][refn0][1], h->chroma_weight[1][refn1][1],
1789
                            h->chroma_offset[0][refn0][1] + h->chroma_offset[1][refn1][1]);
1790
        }
1791
    }else{
1792
        int list = list1 ? 1 : 0;
1793
        int refn = h->ref_cache[list][ scan8[n] ];
1794
        Picture *ref= &h->ref_list[list][refn];
1795
        mc_dir_part(h, ref, n, square, chroma_height, delta, list,
1796
                    dest_y, dest_cb, dest_cr, x_offset, y_offset,
1797
                    qpix_put, chroma_put);
1798

    
1799
        luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
1800
                       h->luma_weight[list][refn], h->luma_offset[list][refn]);
1801
        if(h->use_weight_chroma){
1802
            chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1803
                             h->chroma_weight[list][refn][0], h->chroma_offset[list][refn][0]);
1804
            chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
1805
                             h->chroma_weight[list][refn][1], h->chroma_offset[list][refn][1]);
1806
        }
1807
    }
1808
}
1809

    
1810
static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
1811
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1812
                           int x_offset, int y_offset,
1813
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1814
                           qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
1815
                           h264_weight_func *weight_op, h264_biweight_func *weight_avg,
1816
                           int list0, int list1){
1817
    if((h->use_weight==2 && list0 && list1
1818
        && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ] != 32))
1819
       || h->use_weight==1)
1820
        mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
1821
                         x_offset, y_offset, qpix_put, chroma_put,
1822
                         weight_op[0], weight_op[3], weight_avg[0], weight_avg[3], list0, list1);
1823
    else
1824
        mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
1825
                    x_offset, y_offset, qpix_put, chroma_put, qpix_avg, chroma_avg, list0, list1);
1826
}
1827

    
1828
static inline void prefetch_motion(H264Context *h, int list){
1829
    /* fetch pixels for estimated mv 4 macroblocks ahead
1830
     * optimized for 64byte cache lines */
1831
    MpegEncContext * const s = &h->s;
1832
    const int refn = h->ref_cache[list][scan8[0]];
1833
    if(refn >= 0){
1834
        const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
1835
        const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
1836
        uint8_t **src= h->ref_list[list][refn].data;
1837
        int off= mx + (my + (s->mb_x&3)*4)*h->mb_linesize + 64;
1838
        s->dsp.prefetch(src[0]+off, s->linesize, 4);
1839
        off= (mx>>1) + ((my>>1) + (s->mb_x&7))*s->uvlinesize + 64;
1840
        s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
1841
    }
1842
}
1843

    
1844
static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1845
                      qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
1846
                      qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
1847
                      h264_weight_func *weight_op, h264_biweight_func *weight_avg){
1848
    MpegEncContext * const s = &h->s;
1849
    const int mb_xy= h->mb_xy;
1850
    const int mb_type= s->current_picture.mb_type[mb_xy];
1851

    
1852
    assert(IS_INTER(mb_type));
1853

    
1854
    prefetch_motion(h, 0);
1855

    
1856
    if(IS_16X16(mb_type)){
1857
        mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
1858
                qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
1859
                &weight_op[0], &weight_avg[0],
1860
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1861
    }else if(IS_16X8(mb_type)){
1862
        mc_part(h, 0, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 0,
1863
                qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
1864
                &weight_op[1], &weight_avg[1],
1865
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1866
        mc_part(h, 8, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 4,
1867
                qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
1868
                &weight_op[1], &weight_avg[1],
1869
                IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
1870
    }else if(IS_8X16(mb_type)){
1871
        mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
1872
                qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1873
                &weight_op[2], &weight_avg[2],
1874
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1875
        mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
1876
                qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1877
                &weight_op[2], &weight_avg[2],
1878
                IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
1879
    }else{
1880
        int i;
1881

    
1882
        assert(IS_8X8(mb_type));
1883

    
1884
        for(i=0; i<4; i++){
1885
            const int sub_mb_type= h->sub_mb_type[i];
1886
            const int n= 4*i;
1887
            int x_offset= (i&1)<<2;
1888
            int y_offset= (i&2)<<1;
1889

    
1890
            if(IS_SUB_8X8(sub_mb_type)){
1891
                mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1892
                    qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1893
                    &weight_op[3], &weight_avg[3],
1894
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1895
            }else if(IS_SUB_8X4(sub_mb_type)){
1896
                mc_part(h, n  , 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1897
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
1898
                    &weight_op[4], &weight_avg[4],
1899
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1900
                mc_part(h, n+2, 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
1901
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
1902
                    &weight_op[4], &weight_avg[4],
1903
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1904
            }else if(IS_SUB_4X8(sub_mb_type)){
1905
                mc_part(h, n  , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1906
                    qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1907
                    &weight_op[5], &weight_avg[5],
1908
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1909
                mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
1910
                    qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1911
                    &weight_op[5], &weight_avg[5],
1912
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1913
            }else{
1914
                int j;
1915
                assert(IS_SUB_4X4(sub_mb_type));
1916
                for(j=0; j<4; j++){
1917
                    int sub_x_offset= x_offset + 2*(j&1);
1918
                    int sub_y_offset= y_offset +   (j&2);
1919
                    mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
1920
                        qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
1921
                        &weight_op[6], &weight_avg[6],
1922
                        IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1923
                }
1924
            }
1925
        }
1926
    }
1927

    
1928
    prefetch_motion(h, 1);
1929
}
1930

    
1931
static av_cold void decode_init_vlc(void){
1932
    static int done = 0;
1933

    
1934
    if (!done) {
1935
        int i;
1936
        done = 1;
1937

    
1938
        init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5,
1939
                 &chroma_dc_coeff_token_len [0], 1, 1,
1940
                 &chroma_dc_coeff_token_bits[0], 1, 1, 1);
1941

    
1942
        for(i=0; i<4; i++){
1943
            init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17,
1944
                     &coeff_token_len [i][0], 1, 1,
1945
                     &coeff_token_bits[i][0], 1, 1, 1);
1946
        }
1947

    
1948
        for(i=0; i<3; i++){
1949
            init_vlc(&chroma_dc_total_zeros_vlc[i], CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,
1950
                     &chroma_dc_total_zeros_len [i][0], 1, 1,
1951
                     &chroma_dc_total_zeros_bits[i][0], 1, 1, 1);
1952
        }
1953
        for(i=0; i<15; i++){
1954
            init_vlc(&total_zeros_vlc[i], TOTAL_ZEROS_VLC_BITS, 16,
1955
                     &total_zeros_len [i][0], 1, 1,
1956
                     &total_zeros_bits[i][0], 1, 1, 1);
1957
        }
1958

    
1959
        for(i=0; i<6; i++){
1960
            init_vlc(&run_vlc[i], RUN_VLC_BITS, 7,
1961
                     &run_len [i][0], 1, 1,
1962
                     &run_bits[i][0], 1, 1, 1);
1963
        }
1964
        init_vlc(&run7_vlc, RUN7_VLC_BITS, 16,
1965
                 &run_len [6][0], 1, 1,
1966
                 &run_bits[6][0], 1, 1, 1);
1967
    }
1968
}
1969

    
1970
static void free_tables(H264Context *h){
1971
    int i;
1972
    H264Context *hx;
1973
    av_freep(&h->intra4x4_pred_mode);
1974
    av_freep(&h->chroma_pred_mode_table);
1975
    av_freep(&h->cbp_table);
1976
    av_freep(&h->mvd_table[0]);
1977
    av_freep(&h->mvd_table[1]);
1978
    av_freep(&h->direct_table);
1979
    av_freep(&h->non_zero_count);
1980
    av_freep(&h->slice_table_base);
1981
    h->slice_table= NULL;
1982

    
1983
    av_freep(&h->mb2b_xy);
1984
    av_freep(&h->mb2b8_xy);
1985

    
1986
    for(i = 0; i < MAX_SPS_COUNT; i++)
1987
        av_freep(h->sps_buffers + i);
1988

    
1989
    for(i = 0; i < MAX_PPS_COUNT; i++)
1990
        av_freep(h->pps_buffers + i);
1991

    
1992
    for(i = 0; i < h->s.avctx->thread_count; i++) {
1993
        hx = h->thread_context[i];
1994
        if(!hx) continue;
1995
        av_freep(&hx->top_borders[1]);
1996
        av_freep(&hx->top_borders[0]);
1997
        av_freep(&hx->s.obmc_scratchpad);
1998
    }
1999
}
2000

    
2001
static void init_dequant8_coeff_table(H264Context *h){
2002
    int i,q,x;
2003
    const int transpose = (h->s.dsp.h264_idct8_add != ff_h264_idct8_add_c); //FIXME ugly
2004
    h->dequant8_coeff[0] = h->dequant8_buffer[0];
2005
    h->dequant8_coeff[1] = h->dequant8_buffer[1];
2006

    
2007
    for(i=0; i<2; i++ ){
2008
        if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
2009
            h->dequant8_coeff[1] = h->dequant8_buffer[0];
2010
            break;
2011
        }
2012

    
2013
        for(q=0; q<52; q++){
2014
            int shift = ff_div6[q];
2015
            int idx = ff_rem6[q];
2016
            for(x=0; x<64; x++)
2017
                h->dequant8_coeff[i][q][transpose ? (x>>3)|((x&7)<<3) : x] =
2018
                    ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
2019
                    h->pps.scaling_matrix8[i][x]) << shift;
2020
        }
2021
    }
2022
}
2023

    
2024
static void init_dequant4_coeff_table(H264Context *h){
2025
    int i,j,q,x;
2026
    const int transpose = (h->s.dsp.h264_idct_add != ff_h264_idct_add_c); //FIXME ugly
2027
    for(i=0; i<6; i++ ){
2028
        h->dequant4_coeff[i] = h->dequant4_buffer[i];
2029
        for(j=0; j<i; j++){
2030
            if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
2031
                h->dequant4_coeff[i] = h->dequant4_buffer[j];
2032
                break;
2033
            }
2034
        }
2035
        if(j<i)
2036
            continue;
2037

    
2038
        for(q=0; q<52; q++){
2039
            int shift = ff_div6[q] + 2;
2040
            int idx = ff_rem6[q];
2041
            for(x=0; x<16; x++)
2042
                h->dequant4_coeff[i][q][transpose ? (x>>2)|((x<<2)&0xF) : x] =
2043
                    ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
2044
                    h->pps.scaling_matrix4[i][x]) << shift;
2045
        }
2046
    }
2047
}
2048

    
2049
static void init_dequant_tables(H264Context *h){
2050
    int i,x;
2051
    init_dequant4_coeff_table(h);
2052
    if(h->pps.transform_8x8_mode)
2053
        init_dequant8_coeff_table(h);
2054
    if(h->sps.transform_bypass){
2055
        for(i=0; i<6; i++)
2056
            for(x=0; x<16; x++)
2057
                h->dequant4_coeff[i][0][x] = 1<<6;
2058
        if(h->pps.transform_8x8_mode)
2059
            for(i=0; i<2; i++)
2060
                for(x=0; x<64; x++)
2061
                    h->dequant8_coeff[i][0][x] = 1<<6;
2062
    }
2063
}
2064

    
2065

    
2066
/**
2067
 * allocates tables.
2068
 * needs width/height
2069
 */
2070
static int alloc_tables(H264Context *h){
2071
    MpegEncContext * const s = &h->s;
2072
    const int big_mb_num= s->mb_stride * (s->mb_height+1);
2073
    int x,y;
2074

    
2075
    CHECKED_ALLOCZ(h->intra4x4_pred_mode, big_mb_num * 8  * sizeof(uint8_t))
2076

    
2077
    CHECKED_ALLOCZ(h->non_zero_count    , big_mb_num * 16 * sizeof(uint8_t))
2078
    CHECKED_ALLOCZ(h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(uint8_t))
2079
    CHECKED_ALLOCZ(h->cbp_table, big_mb_num * sizeof(uint16_t))
2080

    
2081
    CHECKED_ALLOCZ(h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t))
2082
    CHECKED_ALLOCZ(h->mvd_table[0], 32*big_mb_num * sizeof(uint16_t));
2083
    CHECKED_ALLOCZ(h->mvd_table[1], 32*big_mb_num * sizeof(uint16_t));
2084
    CHECKED_ALLOCZ(h->direct_table, 32*big_mb_num * sizeof(uint8_t));
2085

    
2086
    memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(uint8_t));
2087
    h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
2088

    
2089
    CHECKED_ALLOCZ(h->mb2b_xy  , big_mb_num * sizeof(uint32_t));
2090
    CHECKED_ALLOCZ(h->mb2b8_xy , big_mb_num * sizeof(uint32_t));
2091
    for(y=0; y<s->mb_height; y++){
2092
        for(x=0; x<s->mb_width; x++){
2093
            const int mb_xy= x + y*s->mb_stride;
2094
            const int b_xy = 4*x + 4*y*h->b_stride;
2095
            const int b8_xy= 2*x + 2*y*h->b8_stride;
2096

    
2097
            h->mb2b_xy [mb_xy]= b_xy;
2098
            h->mb2b8_xy[mb_xy]= b8_xy;
2099
        }
2100
    }
2101

    
2102
    s->obmc_scratchpad = NULL;
2103

    
2104
    if(!h->dequant4_coeff[0])
2105
        init_dequant_tables(h);
2106

    
2107
    return 0;
2108
fail:
2109
    free_tables(h);
2110
    return -1;
2111
}
2112

    
2113
/**
2114
 * Mimic alloc_tables(), but for every context thread.
2115
 */
2116
static void clone_tables(H264Context *dst, H264Context *src){
2117
    dst->intra4x4_pred_mode       = src->intra4x4_pred_mode;
2118
    dst->non_zero_count           = src->non_zero_count;
2119
    dst->slice_table              = src->slice_table;
2120
    dst->cbp_table                = src->cbp_table;
2121
    dst->mb2b_xy                  = src->mb2b_xy;
2122
    dst->mb2b8_xy                 = src->mb2b8_xy;
2123
    dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;
2124
    dst->mvd_table[0]             = src->mvd_table[0];
2125
    dst->mvd_table[1]             = src->mvd_table[1];
2126
    dst->direct_table             = src->direct_table;
2127

    
2128
    dst->s.obmc_scratchpad = NULL;
2129
    ff_h264_pred_init(&dst->hpc, src->s.codec_id);
2130
}
2131

    
2132
/**
2133
 * Init context
2134
 * Allocate buffers which are not shared amongst multiple threads.
2135
 */
2136
static int context_init(H264Context *h){
2137
    CHECKED_ALLOCZ(h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
2138
    CHECKED_ALLOCZ(h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
2139

    
2140
    return 0;
2141
fail:
2142
    return -1; // free_tables will clean up for us
2143
}
2144

    
2145
static av_cold void common_init(H264Context *h){
2146
    MpegEncContext * const s = &h->s;
2147

    
2148
    s->width = s->avctx->width;
2149
    s->height = s->avctx->height;
2150
    s->codec_id= s->avctx->codec->id;
2151

    
2152
    ff_h264_pred_init(&h->hpc, s->codec_id);
2153

    
2154
    h->dequant_coeff_pps= -1;
2155
    s->unrestricted_mv=1;
2156
    s->decode=1; //FIXME
2157

    
2158
    memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
2159
    memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
2160
}
2161

    
2162
static av_cold int decode_init(AVCodecContext *avctx){
2163
    H264Context *h= avctx->priv_data;
2164
    MpegEncContext * const s = &h->s;
2165

    
2166
    MPV_decode_defaults(s);
2167

    
2168
    s->avctx = avctx;
2169
    common_init(h);
2170

    
2171
    s->out_format = FMT_H264;
2172
    s->workaround_bugs= avctx->workaround_bugs;
2173

    
2174
    // set defaults
2175
//    s->decode_mb= ff_h263_decode_mb;
2176
    s->quarter_sample = 1;
2177
    s->low_delay= 1;
2178

    
2179
    if(avctx->codec_id == CODEC_ID_SVQ3)
2180
        avctx->pix_fmt= PIX_FMT_YUVJ420P;
2181
    else
2182
        avctx->pix_fmt= PIX_FMT_YUV420P;
2183

    
2184
    decode_init_vlc();
2185

    
2186
    if(avctx->extradata_size > 0 && avctx->extradata &&
2187
       *(char *)avctx->extradata == 1){
2188
        h->is_avc = 1;
2189
        h->got_avcC = 0;
2190
    } else {
2191
        h->is_avc = 0;
2192
    }
2193

    
2194
    h->thread_context[0] = h;
2195
    h->outputed_poc = INT_MIN;
2196
    return 0;
2197
}
2198

    
2199
static int frame_start(H264Context *h){
2200
    MpegEncContext * const s = &h->s;
2201
    int i;
2202

    
2203
    if(MPV_frame_start(s, s->avctx) < 0)
2204
        return -1;
2205
    ff_er_frame_start(s);
2206
    /*
2207
     * MPV_frame_start uses pict_type to derive key_frame.
2208
     * This is incorrect for H.264; IDR markings must be used.
2209
     * Zero here; IDR markings per slice in frame or fields are ORed in later.
2210
     * See decode_nal_units().
2211
     */
2212
    s->current_picture_ptr->key_frame= 0;
2213

    
2214
    assert(s->linesize && s->uvlinesize);
2215

    
2216
    for(i=0; i<16; i++){
2217
        h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
2218
        h->block_offset[24+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
2219
    }
2220
    for(i=0; i<4; i++){
2221
        h->block_offset[16+i]=
2222
        h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
2223
        h->block_offset[24+16+i]=
2224
        h->block_offset[24+20+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
2225
    }
2226

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

    
2233
    /* some macroblocks will be accessed before they're available */
2234
    if(FRAME_MBAFF || s->avctx->thread_count > 1)
2235
        memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(uint8_t));
2236

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

    
2239
    // We mark the current picture as non-reference after allocating it, so
2240
    // that if we break out due to an error it can be released automatically
2241
    // in the next MPV_frame_start().
2242
    // SVQ3 as well as most other codecs have only last/next/current and thus
2243
    // get released even with set reference, besides SVQ3 and others do not
2244
    // mark frames as reference later "naturally".
2245
    if(s->codec_id != CODEC_ID_SVQ3)
2246
        s->current_picture_ptr->reference= 0;
2247

    
2248
    s->current_picture_ptr->field_poc[0]=
2249
    s->current_picture_ptr->field_poc[1]= INT_MAX;
2250
    assert(s->current_picture_ptr->long_ref==0);
2251

    
2252
    return 0;
2253
}
2254

    
2255
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){
2256
    MpegEncContext * const s = &h->s;
2257
    int i;
2258

    
2259
    src_y  -=   linesize;
2260
    src_cb -= uvlinesize;
2261
    src_cr -= uvlinesize;
2262

    
2263
    // There are two lines saved, the line above the the top macroblock of a pair,
2264
    // and the line above the bottom macroblock
2265
    h->left_border[0]= h->top_borders[0][s->mb_x][15];
2266
    for(i=1; i<17; i++){
2267
        h->left_border[i]= src_y[15+i*  linesize];
2268
    }
2269

    
2270
    *(uint64_t*)(h->top_borders[0][s->mb_x]+0)= *(uint64_t*)(src_y +  16*linesize);
2271
    *(uint64_t*)(h->top_borders[0][s->mb_x]+8)= *(uint64_t*)(src_y +8+16*linesize);
2272

    
2273
    if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2274
        h->left_border[17  ]= h->top_borders[0][s->mb_x][16+7];
2275
        h->left_border[17+9]= h->top_borders[0][s->mb_x][24+7];
2276
        for(i=1; i<9; i++){
2277
            h->left_border[i+17  ]= src_cb[7+i*uvlinesize];
2278
            h->left_border[i+17+9]= src_cr[7+i*uvlinesize];
2279
        }
2280
        *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+8*uvlinesize);
2281
        *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+8*uvlinesize);
2282
    }
2283
}
2284

    
2285
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){
2286
    MpegEncContext * const s = &h->s;
2287
    int temp8, i;
2288
    uint64_t temp64;
2289
    int deblock_left;
2290
    int deblock_top;
2291
    int mb_xy;
2292

    
2293
    if(h->deblocking_filter == 2) {
2294
        mb_xy = h->mb_xy;
2295
        deblock_left = h->slice_table[mb_xy] == h->slice_table[mb_xy - 1];
2296
        deblock_top  = h->slice_table[mb_xy] == h->slice_table[h->top_mb_xy];
2297
    } else {
2298
        deblock_left = (s->mb_x > 0);
2299
        deblock_top =  (s->mb_y > 0);
2300
    }
2301

    
2302
    src_y  -=   linesize + 1;
2303
    src_cb -= uvlinesize + 1;
2304
    src_cr -= uvlinesize + 1;
2305

    
2306
#define XCHG(a,b,t,xchg)\
2307
t= a;\
2308
if(xchg)\
2309
    a= b;\
2310
b= t;
2311

    
2312
    if(deblock_left){
2313
        for(i = !deblock_top; i<17; i++){
2314
            XCHG(h->left_border[i     ], src_y [i*  linesize], temp8, xchg);
2315
        }
2316
    }
2317

    
2318
    if(deblock_top){
2319
        XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
2320
        XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
2321
        if(s->mb_x+1 < s->mb_width){
2322
            XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
2323
        }
2324
    }
2325

    
2326
    if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2327
        if(deblock_left){
2328
            for(i = !deblock_top; i<9; i++){
2329
                XCHG(h->left_border[i+17  ], src_cb[i*uvlinesize], temp8, xchg);
2330
                XCHG(h->left_border[i+17+9], src_cr[i*uvlinesize], temp8, xchg);
2331
            }
2332
        }
2333
        if(deblock_top){
2334
            XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
2335
            XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
2336
        }
2337
    }
2338
}
2339

    
2340
static inline void backup_pair_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize){
2341
    MpegEncContext * const s = &h->s;
2342
    int i;
2343

    
2344
    src_y  -= 2 *   linesize;
2345
    src_cb -= 2 * uvlinesize;
2346
    src_cr -= 2 * uvlinesize;
2347

    
2348
    // There are two lines saved, the line above the the top macroblock of a pair,
2349
    // and the line above the bottom macroblock
2350
    h->left_border[0]= h->top_borders[0][s->mb_x][15];
2351
    h->left_border[1]= h->top_borders[1][s->mb_x][15];
2352
    for(i=2; i<34; i++){
2353
        h->left_border[i]= src_y[15+i*  linesize];
2354
    }
2355

    
2356
    *(uint64_t*)(h->top_borders[0][s->mb_x]+0)= *(uint64_t*)(src_y +  32*linesize);
2357
    *(uint64_t*)(h->top_borders[0][s->mb_x]+8)= *(uint64_t*)(src_y +8+32*linesize);
2358
    *(uint64_t*)(h->top_borders[1][s->mb_x]+0)= *(uint64_t*)(src_y +  33*linesize);
2359
    *(uint64_t*)(h->top_borders[1][s->mb_x]+8)= *(uint64_t*)(src_y +8+33*linesize);
2360

    
2361
    if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2362
        h->left_border[34     ]= h->top_borders[0][s->mb_x][16+7];
2363
        h->left_border[34+   1]= h->top_borders[1][s->mb_x][16+7];
2364
        h->left_border[34+18  ]= h->top_borders[0][s->mb_x][24+7];
2365
        h->left_border[34+18+1]= h->top_borders[1][s->mb_x][24+7];
2366
        for(i=2; i<18; i++){
2367
            h->left_border[i+34   ]= src_cb[7+i*uvlinesize];
2368
            h->left_border[i+34+18]= src_cr[7+i*uvlinesize];
2369
        }
2370
        *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+16*uvlinesize);
2371
        *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+16*uvlinesize);
2372
        *(uint64_t*)(h->top_borders[1][s->mb_x]+16)= *(uint64_t*)(src_cb+17*uvlinesize);
2373
        *(uint64_t*)(h->top_borders[1][s->mb_x]+24)= *(uint64_t*)(src_cr+17*uvlinesize);
2374
    }
2375
}
2376

    
2377
static inline void xchg_pair_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg){
2378
    MpegEncContext * const s = &h->s;
2379
    int temp8, i;
2380
    uint64_t temp64;
2381
    int deblock_left = (s->mb_x > 0);
2382
    int deblock_top  = (s->mb_y > 1);
2383

    
2384
    tprintf(s->avctx, "xchg_pair_border: src_y:%p src_cb:%p src_cr:%p ls:%d uvls:%d\n", src_y, src_cb, src_cr, linesize, uvlinesize);
2385

    
2386
    src_y  -= 2 *   linesize + 1;
2387
    src_cb -= 2 * uvlinesize + 1;
2388
    src_cr -= 2 * uvlinesize + 1;
2389

    
2390
#define XCHG(a,b,t,xchg)\
2391
t= a;\
2392
if(xchg)\
2393
    a= b;\
2394
b= t;
2395

    
2396
    if(deblock_left){
2397
        for(i = (!deblock_top)<<1; i<34; i++){
2398
            XCHG(h->left_border[i     ], src_y [i*  linesize], temp8, xchg);
2399
        }
2400
    }
2401

    
2402
    if(deblock_top){
2403
        XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
2404
        XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
2405
        XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+0), *(uint64_t*)(src_y +1 +linesize), temp64, xchg);
2406
        XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+8), *(uint64_t*)(src_y +9 +linesize), temp64, 1);
2407
        if(s->mb_x+1 < s->mb_width){
2408
            XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
2409
            XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x+1]), *(uint64_t*)(src_y +17 +linesize), temp64, 1);
2410
        }
2411
    }
2412

    
2413
    if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2414
        if(deblock_left){
2415
            for(i = (!deblock_top) << 1; i<18; i++){
2416
                XCHG(h->left_border[i+34   ], src_cb[i*uvlinesize], temp8, xchg);
2417
                XCHG(h->left_border[i+34+18], src_cr[i*uvlinesize], temp8, xchg);
2418
            }
2419
        }
2420
        if(deblock_top){
2421
            XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
2422
            XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
2423
            XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+16), *(uint64_t*)(src_cb+1 +uvlinesize), temp64, 1);
2424
            XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+24), *(uint64_t*)(src_cr+1 +uvlinesize), temp64, 1);
2425
        }
2426
    }
2427
}
2428

    
2429
static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
2430
    MpegEncContext * const s = &h->s;
2431
    const int mb_x= s->mb_x;
2432
    const int mb_y= s->mb_y;
2433
    const int mb_xy= h->mb_xy;
2434
    const int mb_type= s->current_picture.mb_type[mb_xy];
2435
    uint8_t  *dest_y, *dest_cb, *dest_cr;
2436
    int linesize, uvlinesize /*dct_offset*/;
2437
    int i;
2438
    int *block_offset = &h->block_offset[0];
2439
    const unsigned int bottom = mb_y & 1;
2440
    const int transform_bypass = (s->qscale == 0 && h->sps.transform_bypass), is_h264 = (simple || s->codec_id == CODEC_ID_H264);
2441
    void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
2442
    void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
2443

    
2444
    dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
2445
    dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2446
    dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2447

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

    
2451
    if (!simple && MB_FIELD) {
2452
        linesize   = h->mb_linesize   = s->linesize * 2;
2453
        uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
2454
        block_offset = &h->block_offset[24];
2455
        if(mb_y&1){ //FIXME move out of this function?
2456
            dest_y -= s->linesize*15;
2457
            dest_cb-= s->uvlinesize*7;
2458
            dest_cr-= s->uvlinesize*7;
2459
        }
2460
        if(FRAME_MBAFF) {
2461
            int list;
2462
            for(list=0; list<h->list_count; list++){
2463
                if(!USES_LIST(mb_type, list))
2464
                    continue;
2465
                if(IS_16X16(mb_type)){
2466
                    int8_t *ref = &h->ref_cache[list][scan8[0]];
2467
                    fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
2468
                }else{
2469
                    for(i=0; i<16; i+=4){
2470
                        //FIXME can refs be smaller than 8x8 when !direct_8x8_inference ?
2471
                        int ref = h->ref_cache[list][scan8[i]];
2472
                        if(ref >= 0)
2473
                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
2474
                    }
2475
                }
2476
            }
2477
        }
2478
    } else {
2479
        linesize   = h->mb_linesize   = s->linesize;
2480
        uvlinesize = h->mb_uvlinesize = s->uvlinesize;
2481
//        dct_offset = s->linesize * 16;
2482
    }
2483

    
2484
    if(transform_bypass){
2485
        idct_dc_add =
2486
        idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
2487
    }else if(IS_8x8DCT(mb_type)){
2488
        idct_dc_add = s->dsp.h264_idct8_dc_add;
2489
        idct_add = s->dsp.h264_idct8_add;
2490
    }else{
2491
        idct_dc_add = s->dsp.h264_idct_dc_add;
2492
        idct_add = s->dsp.h264_idct_add;
2493
    }
2494

    
2495
    if(!simple && FRAME_MBAFF && h->deblocking_filter && IS_INTRA(mb_type)
2496
       && (!bottom || !IS_INTRA(s->current_picture.mb_type[mb_xy-s->mb_stride]))){
2497
        int mbt_y = mb_y&~1;
2498
        uint8_t *top_y  = s->current_picture.data[0] + (mbt_y * 16* s->linesize  ) + mb_x * 16;
2499
        uint8_t *top_cb = s->current_picture.data[1] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;
2500
        uint8_t *top_cr = s->current_picture.data[2] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;
2501
        xchg_pair_border(h, top_y, top_cb, top_cr, s->linesize, s->uvlinesize, 1);
2502
    }
2503

    
2504
    if (!simple && IS_INTRA_PCM(mb_type)) {
2505
        unsigned int x, y;
2506

    
2507
        // The pixels are stored in h->mb array in the same order as levels,
2508
        // copy them in output in the correct order.
2509
        for(i=0; i<16; i++) {
2510
            for (y=0; y<4; y++) {
2511
                for (x=0; x<4; x++) {
2512
                    *(dest_y + block_offset[i] + y*linesize + x) = h->mb[i*16+y*4+x];
2513
                }
2514
            }
2515
        }
2516
        for(i=16; i<16+4; i++) {
2517
            for (y=0; y<4; y++) {
2518
                for (x=0; x<4; x++) {
2519
                    *(dest_cb + block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];
2520
                }
2521
            }
2522
        }
2523
        for(i=20; i<20+4; i++) {
2524
            for (y=0; y<4; y++) {
2525
                for (x=0; x<4; x++) {
2526
                    *(dest_cr + block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];
2527
                }
2528
            }
2529
        }
2530
    } else {
2531
        if(IS_INTRA(mb_type)){
2532
            if(h->deblocking_filter && (simple || !FRAME_MBAFF))
2533
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
2534

    
2535
            if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2536
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
2537
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
2538
            }
2539

    
2540
            if(IS_INTRA4x4(mb_type)){
2541
                if(simple || !s->encoding){
2542
                    if(IS_8x8DCT(mb_type)){
2543
                        for(i=0; i<16; i+=4){
2544
                            uint8_t * const ptr= dest_y + block_offset[i];
2545
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
2546
                            const int nnz = h->non_zero_count_cache[ scan8[i] ];
2547
                            h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
2548
                                                   (h->topright_samples_available<<i)&0x4000, linesize);
2549
                            if(nnz){
2550
                                if(nnz == 1 && h->mb[i*16])
2551
                                    idct_dc_add(ptr, h->mb + i*16, linesize);
2552
                                else
2553
                                    idct_add(ptr, h->mb + i*16, linesize);
2554
                            }
2555
                        }
2556
                    }else
2557
                    for(i=0; i<16; i++){
2558
                        uint8_t * const ptr= dest_y + block_offset[i];
2559
                        uint8_t *topright;
2560
                        const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
2561
                        int nnz, tr;
2562

    
2563
                        if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
2564
                            const int topright_avail= (h->topright_samples_available<<i)&0x8000;
2565
                            assert(mb_y || linesize <= block_offset[i]);
2566
                            if(!topright_avail){
2567
                                tr= ptr[3 - linesize]*0x01010101;
2568
                                topright= (uint8_t*) &tr;
2569
                            }else
2570
                                topright= ptr + 4 - linesize;
2571
                        }else
2572
                            topright= NULL;
2573

    
2574
                        h->hpc.pred4x4[ dir ](ptr, topright, linesize);
2575
                        nnz = h->non_zero_count_cache[ scan8[i] ];
2576
                        if(nnz){
2577
                            if(is_h264){
2578
                                if(nnz == 1 && h->mb[i*16])
2579
                                    idct_dc_add(ptr, h->mb + i*16, linesize);
2580
                                else
2581
                                    idct_add(ptr, h->mb + i*16, linesize);
2582
                            }else
2583
                                svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
2584
                        }
2585
                    }
2586
                }
2587
            }else{
2588
                h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
2589
                if(is_h264){
2590
                    if(!transform_bypass)
2591
                        h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[0][s->qscale][0]);
2592
                }else
2593
                    svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
2594
            }
2595
            if(h->deblocking_filter && (simple || !FRAME_MBAFF))
2596
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
2597
        }else if(is_h264){
2598
            hl_motion(h, dest_y, dest_cb, dest_cr,
2599
                      s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2600
                      s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2601
                      s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);
2602
        }
2603

    
2604

    
2605
        if(!IS_INTRA4x4(mb_type)){
2606
            if(is_h264){
2607
                if(IS_INTRA16x16(mb_type)){
2608
                    for(i=0; i<16; i++){
2609
                        if(h->non_zero_count_cache[ scan8[i] ])
2610
                            idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2611
                        else if(h->mb[i*16])
2612
                            idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2613
                    }
2614
                }else{
2615
                    const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2616
                    for(i=0; i<16; i+=di){
2617
                        int nnz = h->non_zero_count_cache[ scan8[i] ];
2618
                        if(nnz){
2619
                            if(nnz==1 && h->mb[i*16])
2620
                                idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2621
                            else
2622
                                idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2623
                        }
2624
                    }
2625
                }
2626
            }else{
2627
                for(i=0; i<16; i++){
2628
                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
2629
                        uint8_t * const ptr= dest_y + block_offset[i];
2630
                        svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
2631
                    }
2632
                }
2633
            }
2634
        }
2635

    
2636
        if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2637
            uint8_t *dest[2] = {dest_cb, dest_cr};
2638
            if(transform_bypass){
2639
                idct_add = idct_dc_add = s->dsp.add_pixels4;
2640
            }else{
2641
                idct_add = s->dsp.h264_idct_add;
2642
                idct_dc_add = s->dsp.h264_idct_dc_add;
2643
                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]);
2644
                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]);
2645
            }
2646
            if(is_h264){
2647
                for(i=16; i<16+8; i++){
2648
                    if(h->non_zero_count_cache[ scan8[i] ])
2649
                        idct_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2650
                    else if(h->mb[i*16])
2651
                        idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2652
                }
2653
            }else{
2654
                for(i=16; i<16+8; i++){
2655
                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2656
                        uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
2657
                        svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
2658
                    }
2659
                }
2660
            }
2661
        }
2662
    }
2663
    if(h->deblocking_filter) {
2664
        if (!simple && FRAME_MBAFF) {
2665
            //FIXME try deblocking one mb at a time?
2666
            // the reduction in load/storing mvs and such might outweigh the extra backup/xchg_border
2667
            const int mb_y = s->mb_y - 1;
2668
            uint8_t  *pair_dest_y, *pair_dest_cb, *pair_dest_cr;
2669
            const int mb_xy= mb_x + mb_y*s->mb_stride;
2670
            const int mb_type_top   = s->current_picture.mb_type[mb_xy];
2671
            const int mb_type_bottom= s->current_picture.mb_type[mb_xy+s->mb_stride];
2672
            if (!bottom) return;
2673
            pair_dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
2674
            pair_dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2675
            pair_dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2676

    
2677
            if(IS_INTRA(mb_type_top | mb_type_bottom))
2678
                xchg_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize, 0);
2679

    
2680
            backup_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize);
2681
            // deblock a pair
2682
            // top
2683
            s->mb_y--; h->mb_xy -= s->mb_stride;
2684
            tprintf(h->s.avctx, "call mbaff filter_mb mb_x:%d mb_y:%d pair_dest_y = %p, dest_y = %p\n", mb_x, mb_y, pair_dest_y, dest_y);
2685
            fill_caches(h, mb_type_top, 1); //FIXME don't fill stuff which isn't used by filter_mb
2686
            h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2687
            h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2688
            filter_mb(h, mb_x, mb_y, pair_dest_y, pair_dest_cb, pair_dest_cr, linesize, uvlinesize);
2689
            // bottom
2690
            s->mb_y++; h->mb_xy += s->mb_stride;
2691
            tprintf(h->s.avctx, "call mbaff filter_mb\n");
2692
            fill_caches(h, mb_type_bottom, 1); //FIXME don't fill stuff which isn't used by filter_mb
2693
            h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
2694
            h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
2695
            filter_mb(h, mb_x, mb_y+1, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2696
        } else {
2697
            tprintf(h->s.avctx, "call filter_mb\n");
2698
            backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, simple);
2699
            fill_caches(h, mb_type, 1); //FIXME don't fill stuff which isn't used by filter_mb
2700
            h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2701
            h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2702
            filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2703
        }
2704
    }
2705
}
2706

    
2707
/**
2708
 * Process a macroblock; this case avoids checks for expensive uncommon cases.
2709
 */
2710
static void hl_decode_mb_simple(H264Context *h){
2711
    hl_decode_mb_internal(h, 1);
2712
}
2713

    
2714
/**
2715
 * Process a macroblock; this handles edge cases, such as interlacing.
2716
 */
2717
static void av_noinline hl_decode_mb_complex(H264Context *h){
2718
    hl_decode_mb_internal(h, 0);
2719
}
2720

    
2721
static void hl_decode_mb(H264Context *h){
2722
    MpegEncContext * const s = &h->s;
2723
    const int mb_xy= h->mb_xy;
2724
    const int mb_type= s->current_picture.mb_type[mb_xy];
2725
    int is_complex = FRAME_MBAFF || MB_FIELD || IS_INTRA_PCM(mb_type) || s->codec_id != CODEC_ID_H264 ||
2726
                    (ENABLE_GRAY && (s->flags&CODEC_FLAG_GRAY)) || (ENABLE_H264_ENCODER && s->encoding) || ENABLE_SMALL;
2727

    
2728
    if(ENABLE_H264_ENCODER && !s->decode)
2729
        return;
2730

    
2731
    if (is_complex)
2732
        hl_decode_mb_complex(h);
2733
    else hl_decode_mb_simple(h);
2734
}
2735

    
2736
static void pic_as_field(Picture *pic, const int parity){
2737
    int i;
2738
    for (i = 0; i < 4; ++i) {
2739
        if (parity == PICT_BOTTOM_FIELD)
2740
            pic->data[i] += pic->linesize[i];
2741
        pic->reference = parity;
2742
        pic->linesize[i] *= 2;
2743
    }
2744
}
2745

    
2746
static int split_field_copy(Picture *dest, Picture *src,
2747
                            int parity, int id_add){
2748
    int match = !!(src->reference & parity);
2749

    
2750
    if (match) {
2751
        *dest = *src;
2752
        if(parity != PICT_FRAME){
2753
            pic_as_field(dest, parity);
2754
            dest->pic_id *= 2;
2755
            dest->pic_id += id_add;
2756
        }
2757
    }
2758

    
2759
    return match;
2760
}
2761

    
2762
static int build_def_list(Picture *def, Picture **in, int len, int is_long, int sel){
2763
    int i[2]={0};
2764
    int index=0;
2765

    
2766
    while(i[0]<len || i[1]<len){
2767
        while(i[0]<len && !(in[ i[0] ] && (in[ i[0] ]->reference & sel)))
2768
            i[0]++;
2769
        while(i[1]<len && !(in[ i[1] ] && (in[ i[1] ]->reference & (sel^3))))
2770
            i[1]++;
2771
        if(i[0] < len){
2772
            in[ i[0] ]->pic_id= is_long ? i[0] : in[ i[0] ]->frame_num;
2773
            split_field_copy(&def[index++], in[ i[0]++ ], sel  , 1);
2774
        }
2775
        if(i[1] < len){
2776
            in[ i[1] ]->pic_id= is_long ? i[1] : in[ i[1] ]->frame_num;
2777
            split_field_copy(&def[index++], in[ i[1]++ ], sel^3, 0);
2778
        }
2779
    }
2780

    
2781
    return index;
2782
}
2783

    
2784
static int add_sorted(Picture **sorted, Picture **src, int len, int limit, int dir){
2785
    int i, best_poc;
2786
    int out_i= 0;
2787

    
2788
    for(;;){
2789
        best_poc= dir ? INT_MIN : INT_MAX;
2790

    
2791
        for(i=0; i<len; i++){
2792
            const int poc= src[i]->poc;
2793
            if(((poc > limit) ^ dir) && ((poc < best_poc) ^ dir)){
2794
                best_poc= poc;
2795
                sorted[out_i]= src[i];
2796
            }
2797
        }
2798
        if(best_poc == (dir ? INT_MIN : INT_MAX))
2799
            break;
2800
        limit= sorted[out_i++]->poc - dir;
2801
    }
2802
    return out_i;
2803
}
2804

    
2805
/**
2806
 * fills the default_ref_list.
2807
 */
2808
static int fill_default_ref_list(H264Context *h){
2809
    MpegEncContext * const s = &h->s;
2810
    int i, len;
2811

    
2812
    if(h->slice_type_nos==FF_B_TYPE){
2813
        Picture *sorted[32];
2814
        int cur_poc, list;
2815
        int lens[2];
2816

    
2817
        if(FIELD_PICTURE)
2818
            cur_poc= s->current_picture_ptr->field_poc[ s->picture_structure == PICT_BOTTOM_FIELD ];
2819
        else
2820
            cur_poc= s->current_picture_ptr->poc;
2821

    
2822
        for(list= 0; list<2; list++){
2823
            len= add_sorted(sorted    , h->short_ref, h->short_ref_count, cur_poc, 1^list);
2824
            len+=add_sorted(sorted+len, h->short_ref, h->short_ref_count, cur_poc, 0^list);
2825
            assert(len<=32);
2826
            len= build_def_list(h->default_ref_list[list]    , sorted     , len, 0, s->picture_structure);
2827
            len+=build_def_list(h->default_ref_list[list]+len, h->long_ref, 16 , 1, s->picture_structure);
2828
            assert(len<=32);
2829

    
2830
            if(len < h->ref_count[list])
2831
                memset(&h->default_ref_list[list][len], 0, sizeof(Picture)*(h->ref_count[list] - len));
2832
            lens[list]= len;
2833
        }
2834

    
2835
        if(lens[0] == lens[1] && lens[1] > 1){
2836
            for(i=0; h->default_ref_list[0][i].data[0] == h->default_ref_list[1][i].data[0] && i<lens[0]; i++);
2837
            if(i == lens[0])
2838
                FFSWAP(Picture, h->default_ref_list[1][0], h->default_ref_list[1][1]);
2839
        }
2840
    }else{
2841
        len = build_def_list(h->default_ref_list[0]    , h->short_ref, h->short_ref_count, 0, s->picture_structure);
2842
        len+= build_def_list(h->default_ref_list[0]+len, h-> long_ref, 16                , 1, s->picture_structure);
2843
        assert(len <= 32);
2844
        if(len < h->ref_count[0])
2845
            memset(&h->default_ref_list[0][len], 0, sizeof(Picture)*(h->ref_count[0] - len));
2846
    }
2847
#ifdef TRACE
2848
    for (i=0; i<h->ref_count[0]; i++) {
2849
        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]);
2850
    }
2851
    if(h->slice_type_nos==FF_B_TYPE){
2852
        for (i=0; i<h->ref_count[1]; i++) {
2853
            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]);
2854
        }
2855
    }
2856
#endif
2857
    return 0;
2858
}
2859

    
2860
static void print_short_term(H264Context *h);
2861
static void print_long_term(H264Context *h);
2862

    
2863
/**
2864
 * Extract structure information about the picture described by pic_num in
2865
 * the current decoding context (frame or field). Note that pic_num is
2866
 * picture number without wrapping (so, 0<=pic_num<max_pic_num).
2867
 * @param pic_num picture number for which to extract structure information
2868
 * @param structure one of PICT_XXX describing structure of picture
2869
 *                      with pic_num
2870
 * @return frame number (short term) or long term index of picture
2871
 *         described by pic_num
2872
 */
2873
static int pic_num_extract(H264Context *h, int pic_num, int *structure){
2874
    MpegEncContext * const s = &h->s;
2875

    
2876
    *structure = s->picture_structure;
2877
    if(FIELD_PICTURE){
2878
        if (!(pic_num & 1))
2879
            /* opposite field */
2880
            *structure ^= PICT_FRAME;
2881
        pic_num >>= 1;
2882
    }
2883

    
2884
    return pic_num;
2885
}
2886

    
2887
static int decode_ref_pic_list_reordering(H264Context *h){
2888
    MpegEncContext * const s = &h->s;
2889
    int list, index, pic_structure;
2890

    
2891
    print_short_term(h);
2892
    print_long_term(h);
2893

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

    
2897
        if(get_bits1(&s->gb)){
2898
            int pred= h->curr_pic_num;
2899

    
2900
            for(index=0; ; index++){
2901
                unsigned int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
2902
                unsigned int pic_id;
2903
                int i;
2904
                Picture *ref = NULL;
2905

    
2906
                if(reordering_of_pic_nums_idc==3)
2907
                    break;
2908

    
2909
                if(index >= h->ref_count[list]){
2910
                    av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
2911
                    return -1;
2912
                }
2913

    
2914
                if(reordering_of_pic_nums_idc<3){
2915
                    if(reordering_of_pic_nums_idc<2){
2916
                        const unsigned int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
2917
                        int frame_num;
2918

    
2919
                        if(abs_diff_pic_num > h->max_pic_num){
2920
                            av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
2921
                            return -1;
2922
                        }
2923

    
2924
                        if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
2925
                        else                                pred+= abs_diff_pic_num;
2926
                        pred &= h->max_pic_num - 1;
2927

    
2928
                        frame_num = pic_num_extract(h, pred, &pic_structure);
2929

    
2930
                        for(i= h->short_ref_count-1; i>=0; i--){
2931
                            ref = h->short_ref[i];
2932
                            assert(ref->reference);
2933
                            assert(!ref->long_ref);
2934
                            if(
2935
                                   ref->frame_num == frame_num &&
2936
                                   (ref->reference & pic_structure)
2937
                              )
2938
                                break;
2939
                        }
2940
                        if(i>=0)
2941
                            ref->pic_id= pred;
2942
                    }else{
2943
                        int long_idx;
2944
                        pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
2945

    
2946
                        long_idx= pic_num_extract(h, pic_id, &pic_structure);
2947

    
2948
                        if(long_idx>31){
2949
                            av_log(h->s.avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
2950
                            return -1;
2951
                        }
2952
                        ref = h->long_ref[long_idx];
2953
                        assert(!(ref && !ref->reference));
2954
                        if(ref && (ref->reference & pic_structure)){
2955
                            ref->pic_id= pic_id;
2956
                            assert(ref->long_ref);
2957
                            i=0;
2958
                        }else{
2959
                            i=-1;
2960
                        }
2961
                    }
2962

    
2963
                    if (i < 0) {
2964
                        av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
2965
                        memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
2966
                    } else {
2967
                        for(i=index; i+1<h->ref_count[list]; i++){
2968
                            if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)
2969
                                break;
2970
                        }
2971
                        for(; i > index; i--){
2972
                            h->ref_list[list][i]= h->ref_list[list][i-1];
2973
                        }
2974
                        h->ref_list[list][index]= *ref;
2975
                        if (FIELD_PICTURE){
2976
                            pic_as_field(&h->ref_list[list][index], pic_structure);
2977
                        }
2978
                    }
2979
                }else{
2980
                    av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
2981
                    return -1;
2982
                }
2983
            }
2984
        }
2985
    }
2986
    for(list=0; list<h->list_count; list++){
2987
        for(index= 0; index < h->ref_count[list]; index++){
2988
            if(!h->ref_list[list][index].data[0]){
2989
                av_log(h->s.avctx, AV_LOG_ERROR, "Missing reference picture\n");
2990
                h->ref_list[list][index]= s->current_picture; //FIXME this is not a sensible solution
2991
            }
2992
        }
2993
    }
2994

    
2995
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2996
        direct_dist_scale_factor(h);
2997
    direct_ref_list_init(h);
2998
    return 0;
2999
}
3000

    
3001
static void fill_mbaff_ref_list(H264Context *h){
3002
    int list, i, j;
3003
    for(list=0; list<2; list++){ //FIXME try list_count
3004
        for(i=0; i<h->ref_count[list]; i++){
3005
            Picture *frame = &h->ref_list[list][i];
3006
            Picture *field = &h->ref_list[list][16+2*i];
3007
            field[0] = *frame;
3008
            for(j=0; j<3; j++)
3009
                field[0].linesize[j] <<= 1;
3010
            field[0].reference = PICT_TOP_FIELD;
3011
            field[1] = field[0];
3012
            for(j=0; j<3; j++)
3013
                field[1].data[j] += frame->linesize[j];
3014
            field[1].reference = PICT_BOTTOM_FIELD;
3015

    
3016
            h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i];
3017
            h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i];
3018
            for(j=0; j<2; j++){
3019
                h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j];
3020
                h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j];
3021
            }
3022
        }
3023
    }
3024
    for(j=0; j<h->ref_count[1]; j++){
3025
        for(i=0; i<h->ref_count[0]; i++)
3026
            h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i];
3027
        memcpy(h->implicit_weight[16+2*j],   h->implicit_weight[j], sizeof(*h->implicit_weight));
3028
        memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight));
3029
    }
3030
}
3031

    
3032
static int pred_weight_table(H264Context *h){
3033
    MpegEncContext * const s = &h->s;
3034
    int list, i;
3035
    int luma_def, chroma_def;
3036

    
3037
    h->use_weight= 0;
3038
    h->use_weight_chroma= 0;
3039
    h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
3040
    h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
3041
    luma_def = 1<<h->luma_log2_weight_denom;
3042
    chroma_def = 1<<h->chroma_log2_weight_denom;
3043

    
3044
    for(list=0; list<2; list++){
3045
        for(i=0; i<h->ref_count[list]; i++){
3046
            int luma_weight_flag, chroma_weight_flag;
3047

    
3048
            luma_weight_flag= get_bits1(&s->gb);
3049
            if(luma_weight_flag){
3050
                h->luma_weight[list][i]= get_se_golomb(&s->gb);
3051
                h->luma_offset[list][i]= get_se_golomb(&s->gb);
3052
                if(   h->luma_weight[list][i] != luma_def
3053
                   || h->luma_offset[list][i] != 0)
3054
                    h->use_weight= 1;
3055
            }else{
3056
                h->luma_weight[list][i]= luma_def;
3057
                h->luma_offset[list][i]= 0;
3058
            }
3059

    
3060
            if(CHROMA){
3061
                chroma_weight_flag= get_bits1(&s->gb);
3062
                if(chroma_weight_flag){
3063
                    int j;
3064
                    for(j=0; j<2; j++){
3065
                        h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
3066
                        h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
3067
                        if(   h->chroma_weight[list][i][j] != chroma_def
3068
                        || h->chroma_offset[list][i][j] != 0)
3069
                            h->use_weight_chroma= 1;
3070
                    }
3071
                }else{
3072
                    int j;
3073
                    for(j=0; j<2; j++){
3074
                        h->chroma_weight[list][i][j]= chroma_def;
3075
                        h->chroma_offset[list][i][j]= 0;
3076
                    }
3077
                }
3078
            }
3079
        }
3080
        if(h->slice_type_nos != FF_B_TYPE) break;
3081
    }
3082
    h->use_weight= h->use_weight || h->use_weight_chroma;
3083
    return 0;
3084
}
3085

    
3086
static void implicit_weight_table(H264Context *h){
3087
    MpegEncContext * const s = &h->s;
3088
    int ref0, ref1;
3089
    int cur_poc = s->current_picture_ptr->poc;
3090

    
3091
    if(   h->ref_count[0] == 1 && h->ref_count[1] == 1
3092
       && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
3093
        h->use_weight= 0;
3094
        h->use_weight_chroma= 0;
3095
        return;
3096
    }
3097

    
3098
    h->use_weight= 2;
3099
    h->use_weight_chroma= 2;
3100
    h->luma_log2_weight_denom= 5;
3101
    h->chroma_log2_weight_denom= 5;
3102

    
3103
    for(ref0=0; ref0 < h->ref_count[0]; ref0++){
3104
        int poc0 = h->ref_list[0][ref0].poc;
3105
        for(ref1=0; ref1 < h->ref_count[1]; ref1++){
3106
            int poc1 = h->ref_list[1][ref1].poc;
3107
            int td = av_clip(poc1 - poc0, -128, 127);
3108
            if(td){
3109
                int tb = av_clip(cur_poc - poc0, -128, 127);
3110
                int tx = (16384 + (FFABS(td) >> 1)) / td;
3111
                int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
3112
                if(dist_scale_factor < -64 || dist_scale_factor > 128)
3113
                    h->implicit_weight[ref0][ref1] = 32;
3114
                else
3115
                    h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
3116
            }else
3117
                h->implicit_weight[ref0][ref1] = 32;
3118
        }
3119
    }
3120
}
3121

    
3122
/**
3123
 * Mark a picture as no longer needed for reference. The refmask
3124
 * argument allows unreferencing of individual fields or the whole frame.
3125
 * If the picture becomes entirely unreferenced, but is being held for
3126
 * display purposes, it is marked as such.
3127
 * @param refmask mask of fields to unreference; the mask is bitwise
3128
 *                anded with the reference marking of pic
3129
 * @return non-zero if pic becomes entirely unreferenced (except possibly
3130
 *         for display purposes) zero if one of the fields remains in
3131
 *         reference
3132
 */
3133
static inline int unreference_pic(H264Context *h, Picture *pic, int refmask){
3134
    int i;
3135
    if (pic->reference &= refmask) {
3136
        return 0;
3137
    } else {
3138
        for(i = 0; h->delayed_pic[i]; i++)
3139
            if(pic == h->delayed_pic[i]){
3140
                pic->reference=DELAYED_PIC_REF;
3141
                break;
3142
            }
3143
        return 1;
3144
    }
3145
}
3146

    
3147
/**
3148
 * instantaneous decoder refresh.
3149
 */
3150
static void idr(H264Context *h){
3151
    int i;
3152

    
3153
    for(i=0; i<16; i++){
3154
        remove_long(h, i, 0);
3155
    }
3156
    assert(h->long_ref_count==0);
3157

    
3158
    for(i=0; i<h->short_ref_count; i++){
3159
        unreference_pic(h, h->short_ref[i], 0);
3160
        h->short_ref[i]= NULL;
3161
    }
3162
    h->short_ref_count=0;
3163
    h->prev_frame_num= 0;
3164
    h->prev_frame_num_offset= 0;
3165
    h->prev_poc_msb=
3166
    h->prev_poc_lsb= 0;
3167
}
3168

    
3169
/* forget old pics after a seek */
3170
static void flush_dpb(AVCodecContext *avctx){
3171
    H264Context *h= avctx->priv_data;
3172
    int i;
3173
    for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
3174
        if(h->delayed_pic[i])
3175
            h->delayed_pic[i]->reference= 0;
3176
        h->delayed_pic[i]= NULL;
3177
    }
3178
    h->outputed_poc= INT_MIN;
3179
    idr(h);
3180
    if(h->s.current_picture_ptr)
3181
        h->s.current_picture_ptr->reference= 0;
3182
    h->s.first_field= 0;
3183
    ff_mpeg_flush(avctx);
3184
}
3185

    
3186
/**
3187
 * Find a Picture in the short term reference list by frame number.
3188
 * @param frame_num frame number to search for
3189
 * @param idx the index into h->short_ref where returned picture is found
3190
 *            undefined if no picture found.
3191
 * @return pointer to the found picture, or NULL if no pic with the provided
3192
 *                 frame number is found
3193
 */
3194
static Picture * find_short(H264Context *h, int frame_num, int *idx){
3195
    MpegEncContext * const s = &h->s;
3196
    int i;
3197

    
3198
    for(i=0; i<h->short_ref_count; i++){
3199
        Picture *pic= h->short_ref[i];
3200
        if(s->avctx->debug&FF_DEBUG_MMCO)
3201
            av_log(h->s.avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
3202
        if(pic->frame_num == frame_num) {
3203
            *idx = i;
3204
            return pic;
3205
        }
3206
    }
3207
    return NULL;
3208
}
3209

    
3210
/**
3211
 * Remove a picture from the short term reference list by its index in
3212
 * that list.  This does no checking on the provided index; it is assumed
3213
 * to be valid. Other list entries are shifted down.
3214
 * @param i index into h->short_ref of picture to remove.
3215
 */
3216
static void remove_short_at_index(H264Context *h, int i){
3217
    assert(i >= 0 && i < h->short_ref_count);
3218
    h->short_ref[i]= NULL;
3219
    if (--h->short_ref_count)
3220
        memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i)*sizeof(Picture*));
3221
}
3222

    
3223
/**
3224
 *
3225
 * @return the removed picture or NULL if an error occurs
3226
 */
3227
static Picture * remove_short(H264Context *h, int frame_num, int ref_mask){
3228
    MpegEncContext * const s = &h->s;
3229
    Picture *pic;
3230
    int i;
3231

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

    
3235
    pic = find_short(h, frame_num, &i);
3236
    if (pic){
3237
        if(unreference_pic(h, pic, ref_mask))
3238
        remove_short_at_index(h, i);
3239
    }
3240

    
3241
    return pic;
3242
}
3243

    
3244
/**
3245
 * Remove a picture from the long term reference list by its index in
3246
 * that list.
3247
 * @return the removed picture or NULL if an error occurs
3248
 */
3249
static Picture * remove_long(H264Context *h, int i, int ref_mask){
3250
    Picture *pic;
3251

    
3252
    pic= h->long_ref[i];
3253
    if (pic){
3254
        if(unreference_pic(h, pic, ref_mask)){
3255
            assert(h->long_ref[i]->long_ref == 1);
3256
            h->long_ref[i]->long_ref= 0;
3257
            h->long_ref[i]= NULL;
3258
            h->long_ref_count--;
3259
        }
3260
    }
3261

    
3262
    return pic;
3263
}
3264

    
3265
/**
3266
 * print short term list
3267
 */
3268
static void print_short_term(H264Context *h) {
3269
    uint32_t i;
3270
    if(h->s.avctx->debug&FF_DEBUG_MMCO) {
3271
        av_log(h->s.avctx, AV_LOG_DEBUG, "short term list:\n");
3272
        for(i=0; i<h->short_ref_count; i++){
3273
            Picture *pic= h->short_ref[i];
3274
            av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
3275
        }
3276
    }
3277
}
3278

    
3279
/**
3280
 * print long term list
3281
 */
3282
static void print_long_term(H264Context *h) {
3283
    uint32_t i;
3284
    if(h->s.avctx->debug&FF_DEBUG_MMCO) {
3285
        av_log(h->s.avctx, AV_LOG_DEBUG, "long term list:\n");
3286
        for(i = 0; i < 16; i++){
3287
            Picture *pic= h->long_ref[i];
3288
            if (pic) {
3289
                av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
3290
            }
3291
        }
3292
    }
3293
}
3294

    
3295
/**
3296
 * Executes the reference picture marking (memory management control operations).
3297
 */
3298
static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
3299
    MpegEncContext * const s = &h->s;
3300
    int i, j;
3301
    int current_ref_assigned=0;
3302
    Picture *pic;
3303

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

    
3307
    for(i=0; i<mmco_count; i++){
3308
        int structure, frame_num;
3309
        if(s->avctx->debug&FF_DEBUG_MMCO)
3310
            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);
3311

    
3312
        if(   mmco[i].opcode == MMCO_SHORT2UNUSED
3313
           || mmco[i].opcode == MMCO_SHORT2LONG){
3314
            frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
3315
            pic = find_short(h, frame_num, &j);
3316
            if(!pic){
3317
                if(mmco[i].opcode != MMCO_SHORT2LONG || !h->long_ref[mmco[i].long_arg]
3318
                   || h->long_ref[mmco[i].long_arg]->frame_num != frame_num)
3319
                av_log(h->s.avctx, AV_LOG_ERROR, "mmco: unref short failure\n");
3320
                continue;
3321
            }
3322
        }
3323

    
3324
        switch(mmco[i].opcode){
3325
        case MMCO_SHORT2UNUSED:
3326
            if(s->avctx->debug&FF_DEBUG_MMCO)
3327
                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);
3328
            remove_short(h, frame_num, structure ^ PICT_FRAME);
3329
            break;
3330
        case MMCO_SHORT2LONG:
3331
                if (h->long_ref[mmco[i].long_arg] != pic)
3332
                    remove_long(h, mmco[i].long_arg, 0);
3333

    
3334
                remove_short_at_index(h, j);
3335
                h->long_ref[ mmco[i].long_arg ]= pic;
3336
                if (h->long_ref[ mmco[i].long_arg ]){
3337
                    h->long_ref[ mmco[i].long_arg ]->long_ref=1;
3338
                    h->long_ref_count++;
3339
                }
3340
            break;
3341
        case MMCO_LONG2UNUSED:
3342
            j = pic_num_extract(h, mmco[i].long_arg, &structure);
3343
            pic = h->long_ref[j];
3344
            if (pic) {
3345
                remove_long(h, j, structure ^ PICT_FRAME);
3346
            } else if(s->avctx->debug&FF_DEBUG_MMCO)
3347
                av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
3348
            break;
3349
        case MMCO_LONG:
3350
                    // Comment below left from previous code as it is an interresting note.
3351
                    /* First field in pair is in short term list or
3352
                     * at a different long term index.
3353
                     * This is not allowed; see 7.4.3.3, notes 2 and 3.
3354
                     * Report the problem and keep the pair where it is,
3355
                     * and mark this field valid.
3356
                     */
3357

    
3358
            if (h->long_ref[mmco[i].long_arg] != s->current_picture_ptr) {
3359
                remove_long(h, mmco[i].long_arg, 0);
3360

    
3361
                h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;
3362
                h->long_ref[ mmco[i].long_arg ]->long_ref=1;
3363
                h->long_ref_count++;
3364
            }
3365

    
3366
            s->current_picture_ptr->reference |= s->picture_structure;
3367
            current_ref_assigned=1;
3368
            break;
3369
        case MMCO_SET_MAX_LONG:
3370
            assert(mmco[i].long_arg <= 16);
3371
            // just remove the long term which index is greater than new max
3372
            for(j = mmco[i].long_arg; j<16; j++){
3373
                remove_long(h, j, 0);
3374
            }
3375
            break;
3376
        case MMCO_RESET:
3377
            while(h->short_ref_count){
3378
                remove_short(h, h->short_ref[0]->frame_num, 0);
3379
            }
3380
            for(j = 0; j < 16; j++) {
3381
                remove_long(h, j, 0);
3382
            }
3383
            s->current_picture_ptr->poc=
3384
            s->current_picture_ptr->field_poc[0]=
3385
            s->current_picture_ptr->field_poc[1]=
3386
            h->poc_lsb=
3387
            h->poc_msb=
3388
            h->frame_num=
3389
            s->current_picture_ptr->frame_num= 0;
3390
            break;
3391
        default: assert(0);
3392
        }
3393
    }
3394

    
3395
    if (!current_ref_assigned) {
3396
        /* Second field of complementary field pair; the first field of
3397
         * which is already referenced. If short referenced, it
3398
         * should be first entry in short_ref. If not, it must exist
3399
         * in long_ref; trying to put it on the short list here is an
3400
         * error in the encoded bit stream (ref: 7.4.3.3, NOTE 2 and 3).
3401
         */
3402
        if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {
3403
            /* Just mark the second field valid */
3404
            s->current_picture_ptr->reference = PICT_FRAME;
3405
        } else if (s->current_picture_ptr->long_ref) {
3406
            av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "
3407
                                             "assignment for second field "
3408
                                             "in complementary field pair "
3409
                                             "(first field is long term)\n");
3410
        } else {
3411
            pic= remove_short(h, s->current_picture_ptr->frame_num, 0);
3412
            if(pic){
3413
                av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
3414
            }
3415

    
3416
            if(h->short_ref_count)
3417
                memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
3418

    
3419
            h->short_ref[0]= s->current_picture_ptr;
3420
            h->short_ref_count++;
3421
            s->current_picture_ptr->reference |= s->picture_structure;
3422
        }
3423
    }
3424

    
3425
    if (h->long_ref_count + h->short_ref_count > h->sps.ref_frame_count){
3426

    
3427
        /* We have too many reference frames, probably due to corrupted
3428
         * stream. Need to discard one frame. Prevents overrun of the
3429
         * short_ref and long_ref buffers.
3430
         */
3431
        av_log(h->s.avctx, AV_LOG_ERROR,
3432
               "number of reference frames exceeds max (probably "
3433
               "corrupt input), discarding one\n");
3434

    
3435
        if (h->long_ref_count && !h->short_ref_count) {
3436
            for (i = 0; i < 16; ++i)
3437
                if (h->long_ref[i])
3438
                    break;
3439

    
3440
            assert(i < 16);
3441
            remove_long(h, i, 0);
3442
        } else {
3443
            pic = h->short_ref[h->short_ref_count - 1];
3444
            remove_short(h, pic->frame_num, 0);
3445
        }
3446
    }
3447

    
3448
    print_short_term(h);
3449
    print_long_term(h);
3450
    return 0;
3451
}
3452

    
3453
static int decode_ref_pic_marking(H264Context *h, GetBitContext *gb){
3454
    MpegEncContext * const s = &h->s;
3455
    int i;
3456

    
3457
    h->mmco_index= 0;
3458
    if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields
3459
        s->broken_link= get_bits1(gb) -1;
3460
        if(get_bits1(gb)){
3461
            h->mmco[0].opcode= MMCO_LONG;
3462
            h->mmco[0].long_arg= 0;
3463
            h->mmco_index= 1;
3464
        }
3465
    }else{
3466
        if(get_bits1(gb)){ // adaptive_ref_pic_marking_mode_flag
3467
            for(i= 0; i<MAX_MMCO_COUNT; i++) {
3468
                MMCOOpcode opcode= get_ue_golomb(gb);
3469

    
3470
                h->mmco[i].opcode= opcode;
3471
                if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){
3472
                    h->mmco[i].short_pic_num= (h->curr_pic_num - get_ue_golomb(gb) - 1) & (h->max_pic_num - 1);
3473
/*                    if(h->mmco[i].short_pic_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_pic_num ] == NULL){
3474
                        av_log(s->avctx, AV_LOG_ERROR, "illegal short ref in memory management control operation %d\n", mmco);
3475
                        return -1;
3476
                    }*/
3477
                }
3478
                if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){
3479
                    unsigned int long_arg= get_ue_golomb(gb);
3480
                    if(long_arg >= 32 || (long_arg >= 16 && !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){
3481
                        av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);
3482
                        return -1;
3483
                    }
3484
                    h->mmco[i].long_arg= long_arg;
3485
                }
3486

    
3487
                if(opcode > (unsigned)MMCO_LONG){
3488
                    av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);
3489
                    return -1;
3490
                }
3491
                if(opcode == MMCO_END)
3492
                    break;
3493
            }
3494
            h->mmco_index= i;
3495
        }else{
3496
            assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
3497

    
3498
            if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
3499
                    !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {
3500
                h->mmco[0].opcode= MMCO_SHORT2UNUSED;
3501
                h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
3502
                h->mmco_index= 1;
3503
                if (FIELD_PICTURE) {
3504
                    h->mmco[0].short_pic_num *= 2;
3505
                    h->mmco[1].opcode= MMCO_SHORT2UNUSED;
3506
                    h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;
3507
                    h->mmco_index= 2;
3508
                }
3509
            }
3510
        }
3511
    }
3512

    
3513
    return 0;
3514
}
3515

    
3516
static int init_poc(H264Context *h){
3517
    MpegEncContext * const s = &h->s;
3518
    const int max_frame_num= 1<<h->sps.log2_max_frame_num;
3519
    int field_poc[2];
3520
    Picture *cur = s->current_picture_ptr;
3521

    
3522
    h->frame_num_offset= h->prev_frame_num_offset;
3523
    if(h->frame_num < h->prev_frame_num)
3524
        h->frame_num_offset += max_frame_num;
3525

    
3526
    if(h->sps.poc_type==0){
3527
        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
3528

    
3529
        if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
3530
            h->poc_msb = h->prev_poc_msb + max_poc_lsb;
3531
        else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
3532
            h->poc_msb = h->prev_poc_msb - max_poc_lsb;
3533
        else
3534
            h->poc_msb = h->prev_poc_msb;
3535
//printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
3536
        field_poc[0] =
3537
        field_poc[1] = h->poc_msb + h->poc_lsb;
3538
        if(s->picture_structure == PICT_FRAME)
3539
            field_poc[1] += h->delta_poc_bottom;
3540
    }else if(h->sps.poc_type==1){
3541
        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
3542
        int i;
3543

    
3544
        if(h->sps.poc_cycle_length != 0)
3545
            abs_frame_num = h->frame_num_offset + h->frame_num;
3546
        else
3547
            abs_frame_num = 0;
3548

    
3549
        if(h->nal_ref_idc==0 && abs_frame_num > 0)
3550
            abs_frame_num--;
3551

    
3552
        expected_delta_per_poc_cycle = 0;
3553
        for(i=0; i < h->sps.poc_cycle_length; i++)
3554
            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
3555

    
3556
        if(abs_frame_num > 0){
3557
            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
3558
            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
3559

    
3560
            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
3561
            for(i = 0; i <= frame_num_in_poc_cycle; i++)
3562
                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
3563
        } else
3564
            expectedpoc = 0;
3565

    
3566
        if(h->nal_ref_idc == 0)
3567
            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
3568

    
3569
        field_poc[0] = expectedpoc + h->delta_poc[0];
3570
        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
3571

    
3572
        if(s->picture_structure == PICT_FRAME)
3573
            field_poc[1] += h->delta_poc[1];
3574
    }else{
3575
        int poc= 2*(h->frame_num_offset + h->frame_num);
3576

    
3577
        if(!h->nal_ref_idc)
3578
            poc--;
3579

    
3580
        field_poc[0]= poc;
3581
        field_poc[1]= poc;
3582
    }
3583

    
3584
    if(s->picture_structure != PICT_BOTTOM_FIELD)
3585
        s->current_picture_ptr->field_poc[0]= field_poc[0];
3586
    if(s->picture_structure != PICT_TOP_FIELD)
3587
        s->current_picture_ptr->field_poc[1]= field_poc[1];
3588
    cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
3589

    
3590
    return 0;
3591
}
3592

    
3593

    
3594
/**
3595
 * initialize scan tables
3596
 */
3597
static void init_scan_tables(H264Context *h){
3598
    MpegEncContext * const s = &h->s;
3599
    int i;
3600
    if(s->dsp.h264_idct_add == ff_h264_idct_add_c){ //FIXME little ugly
3601
        memcpy(h->zigzag_scan, zigzag_scan, 16*sizeof(uint8_t));
3602
        memcpy(h-> field_scan,  field_scan, 16*sizeof(uint8_t));
3603
    }else{
3604
        for(i=0; i<16; i++){
3605
#define T(x) (x>>2) | ((x<<2) & 0xF)
3606
            h->zigzag_scan[i] = T(zigzag_scan[i]);
3607
            h-> field_scan[i] = T( field_scan[i]);
3608
#undef T
3609
        }
3610
    }
3611
    if(s->dsp.h264_idct8_add == ff_h264_idct8_add_c){
3612
        memcpy(h->zigzag_scan8x8,       zigzag_scan8x8,       64*sizeof(uint8_t));
3613
        memcpy(h->zigzag_scan8x8_cavlc, zigzag_scan8x8_cavlc, 64*sizeof(uint8_t));
3614
        memcpy(h->field_scan8x8,        field_scan8x8,        64*sizeof(uint8_t));
3615
        memcpy(h->field_scan8x8_cavlc,  field_scan8x8_cavlc,  64*sizeof(uint8_t));
3616
    }else{
3617
        for(i=0; i<64; i++){
3618
#define T(x) (x>>3) | ((x&7)<<3)
3619
            h->zigzag_scan8x8[i]       = T(zigzag_scan8x8[i]);
3620
            h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
3621
            h->field_scan8x8[i]        = T(field_scan8x8[i]);
3622
            h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
3623
#undef T
3624
        }
3625
    }
3626
    if(h->sps.transform_bypass){ //FIXME same ugly
3627
        h->zigzag_scan_q0          = zigzag_scan;
3628
        h->zigzag_scan8x8_q0       = zigzag_scan8x8;
3629
        h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
3630
        h->field_scan_q0           = field_scan;
3631
        h->field_scan8x8_q0        = field_scan8x8;
3632
        h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
3633
    }else{
3634
        h->zigzag_scan_q0          = h->zigzag_scan;
3635
        h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
3636
        h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
3637
        h->field_scan_q0           = h->field_scan;
3638
        h->field_scan8x8_q0        = h->field_scan8x8;
3639
        h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
3640
    }
3641
}
3642

    
3643
/**
3644
 * Replicates H264 "master" context to thread contexts.
3645
 */
3646
static void clone_slice(H264Context *dst, H264Context *src)
3647
{
3648
    memcpy(dst->block_offset,     src->block_offset, sizeof(dst->block_offset));
3649
    dst->s.current_picture_ptr  = src->s.current_picture_ptr;
3650
    dst->s.current_picture      = src->s.current_picture;
3651
    dst->s.linesize             = src->s.linesize;
3652
    dst->s.uvlinesize           = src->s.uvlinesize;
3653
    dst->s.first_field          = src->s.first_field;
3654

    
3655
    dst->prev_poc_msb           = src->prev_poc_msb;
3656
    dst->prev_poc_lsb           = src->prev_poc_lsb;
3657
    dst->prev_frame_num_offset  = src->prev_frame_num_offset;
3658
    dst->prev_frame_num         = src->prev_frame_num;
3659
    dst->short_ref_count        = src->short_ref_count;
3660

    
3661
    memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
3662
    memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
3663
    memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3664
    memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
3665

    
3666
    memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
3667
    memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
3668
}
3669

    
3670
/**
3671
 * decodes a slice header.
3672
 * This will also call MPV_common_init() and frame_start() as needed.
3673
 *
3674
 * @param h h264context
3675
 * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
3676
 *
3677
 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3678
 */
3679
static int decode_slice_header(H264Context *h, H264Context *h0){
3680
    MpegEncContext * const s = &h->s;
3681
    MpegEncContext * const s0 = &h0->s;
3682
    unsigned int first_mb_in_slice;
3683
    unsigned int pps_id;
3684
    int num_ref_idx_active_override_flag;
3685
    static const uint8_t slice_type_map[5]= {FF_P_TYPE, FF_B_TYPE, FF_I_TYPE, FF_SP_TYPE, FF_SI_TYPE};
3686
    unsigned int slice_type, tmp, i, j;
3687
    int default_ref_list_done = 0;
3688
    int last_pic_structure;
3689

    
3690
    s->dropable= h->nal_ref_idc == 0;
3691

    
3692
    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
3693
        s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
3694
        s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
3695
    }else{
3696
        s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
3697
        s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
3698
    }
3699

    
3700
    first_mb_in_slice= get_ue_golomb(&s->gb);
3701

    
3702
    if((s->flags2 & CODEC_FLAG2_CHUNKS) && first_mb_in_slice == 0){
3703
        h0->current_slice = 0;
3704
        if (!s0->first_field)
3705
            s->current_picture_ptr= NULL;
3706
    }
3707

    
3708
    slice_type= get_ue_golomb(&s->gb);
3709
    if(slice_type > 9){
3710
        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);
3711
        return -1;
3712
    }
3713
    if(slice_type > 4){
3714
        slice_type -= 5;
3715
        h->slice_type_fixed=1;
3716
    }else
3717
        h->slice_type_fixed=0;
3718

    
3719
    slice_type= slice_type_map[ slice_type ];
3720
    if (slice_type == FF_I_TYPE
3721
        || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
3722
        default_ref_list_done = 1;
3723
    }
3724
    h->slice_type= slice_type;
3725
    h->slice_type_nos= slice_type & 3;
3726

    
3727
    s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
3728
    if (s->pict_type == FF_B_TYPE && s0->last_picture_ptr == NULL) {
3729
        av_log(h->s.avctx, AV_LOG_ERROR,
3730
               "B picture before any references, skipping\n");
3731
        return -1;
3732
    }
3733

    
3734
    pps_id= get_ue_golomb(&s->gb);
3735
    if(pps_id>=MAX_PPS_COUNT){
3736
        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
3737
        return -1;
3738
    }
3739
    if(!h0->pps_buffers[pps_id]) {
3740
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS referenced\n");
3741
        return -1;
3742
    }
3743
    h->pps= *h0->pps_buffers[pps_id];
3744

    
3745
    if(!h0->sps_buffers[h->pps.sps_id]) {
3746
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS referenced\n");
3747
        return -1;
3748
    }
3749
    h->sps = *h0->sps_buffers[h->pps.sps_id];
3750

    
3751
    if(h == h0 && h->dequant_coeff_pps != pps_id){
3752
        h->dequant_coeff_pps = pps_id;
3753
        init_dequant_tables(h);
3754
    }
3755

    
3756
    s->mb_width= h->sps.mb_width;
3757
    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3758

    
3759
    h->b_stride=  s->mb_width*4;
3760
    h->b8_stride= s->mb_width*2;
3761

    
3762
    s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
3763
    if(h->sps.frame_mbs_only_flag)
3764
        s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
3765
    else
3766
        s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 3);
3767

    
3768
    if (s->context_initialized
3769
        && (   s->width != s->avctx->width || s->height != s->avctx->height)) {
3770
        if(h != h0)
3771
            return -1;   // width / height changed during parallelized decoding
3772
        free_tables(h);
3773
        MPV_common_end(s);
3774
    }
3775
    if (!s->context_initialized) {
3776
        if(h != h0)
3777
            return -1;  // we cant (re-)initialize context during parallel decoding
3778
        if (MPV_common_init(s) < 0)
3779
            return -1;
3780
        s->first_field = 0;
3781

    
3782
        init_scan_tables(h);
3783
        alloc_tables(h);
3784

    
3785
        for(i = 1; i < s->avctx->thread_count; i++) {
3786
            H264Context *c;
3787
            c = h->thread_context[i] = av_malloc(sizeof(H264Context));
3788
            memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
3789
            memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
3790
            c->sps = h->sps;
3791
            c->pps = h->pps;
3792
            init_scan_tables(c);
3793
            clone_tables(c, h);
3794
        }
3795

    
3796
        for(i = 0; i < s->avctx->thread_count; i++)
3797
            if(context_init(h->thread_context[i]) < 0)
3798
                return -1;
3799

    
3800
        s->avctx->width = s->width;
3801
        s->avctx->height = s->height;
3802
        s->avctx->sample_aspect_ratio= h->sps.sar;
3803
        if(!s->avctx->sample_aspect_ratio.den)
3804
            s->avctx->sample_aspect_ratio.den = 1;
3805

    
3806
        if(h->sps.timing_info_present_flag){
3807
            s->avctx->time_base= (AVRational){h->sps.num_units_in_tick * 2, h->sps.time_scale};
3808
            if(h->x264_build > 0 && h->x264_build < 44)
3809
                s->avctx->time_base.den *= 2;
3810
            av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
3811
                      s->avctx->time_base.num, s->avctx->time_base.den, 1<<30);
3812
        }
3813
    }
3814

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

    
3817
    h->mb_mbaff = 0;
3818
    h->mb_aff_frame = 0;
3819
    last_pic_structure = s0->picture_structure;
3820
    if(h->sps.frame_mbs_only_flag){
3821
        s->picture_structure= PICT_FRAME;
3822
    }else{
3823
        if(get_bits1(&s->gb)) { //field_pic_flag
3824
            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
3825
        } else {
3826
            s->picture_structure= PICT_FRAME;
3827
            h->mb_aff_frame = h->sps.mb_aff;
3828
        }
3829
    }
3830

    
3831
    if(h0->current_slice == 0){
3832
        while(h->frame_num !=  h->prev_frame_num &&
3833
              h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
3834
            av_log(NULL, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
3835
            frame_start(h);
3836
            h->prev_frame_num++;
3837
            h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
3838
            s->current_picture_ptr->frame_num= h->prev_frame_num;
3839
            execute_ref_pic_marking(h, NULL, 0);
3840
        }
3841

    
3842
        /* See if we have a decoded first field looking for a pair... */
3843
        if (s0->first_field) {
3844
            assert(s0->current_picture_ptr);
3845
            assert(s0->current_picture_ptr->data[0]);
3846
            assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
3847

    
3848
            /* figure out if we have a complementary field pair */
3849
            if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
3850
                /*
3851
                 * Previous field is unmatched. Don't display it, but let it
3852
                 * remain for reference if marked as such.
3853
                 */
3854
                s0->current_picture_ptr = NULL;
3855
                s0->first_field = FIELD_PICTURE;
3856

    
3857
            } else {
3858
                if (h->nal_ref_idc &&
3859
                        s0->current_picture_ptr->reference &&
3860
                        s0->current_picture_ptr->frame_num != h->frame_num) {
3861
                    /*
3862
                     * This and previous field were reference, but had
3863
                     * different frame_nums. Consider this field first in
3864
                     * pair. Throw away previous field except for reference
3865
                     * purposes.
3866
                     */
3867
                    s0->first_field = 1;
3868
                    s0->current_picture_ptr = NULL;
3869

    
3870
                } else {
3871
                    /* Second field in complementary pair */
3872
                    s0->first_field = 0;
3873
                }
3874
            }
3875

    
3876
        } else {
3877
            /* Frame or first field in a potentially complementary pair */
3878
            assert(!s0->current_picture_ptr);
3879
            s0->first_field = FIELD_PICTURE;
3880
        }
3881

    
3882
        if((!FIELD_PICTURE || s0->first_field) && frame_start(h) < 0) {
3883
            s0->first_field = 0;
3884
            return -1;
3885
        }
3886
    }
3887
    if(h != h0)
3888
        clone_slice(h, h0);
3889

    
3890
    s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
3891

    
3892
    assert(s->mb_num == s->mb_width * s->mb_height);
3893
    if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
3894
       first_mb_in_slice                    >= s->mb_num){
3895
        av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3896
        return -1;
3897
    }
3898
    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
3899
    s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
3900
    if (s->picture_structure == PICT_BOTTOM_FIELD)
3901
        s->resync_mb_y = s->mb_y = s->mb_y + 1;
3902
    assert(s->mb_y < s->mb_height);
3903

    
3904
    if(s->picture_structure==PICT_FRAME){
3905
        h->curr_pic_num=   h->frame_num;
3906
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
3907
    }else{
3908
        h->curr_pic_num= 2*h->frame_num + 1;
3909
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
3910
    }
3911

    
3912
    if(h->nal_unit_type == NAL_IDR_SLICE){
3913
        get_ue_golomb(&s->gb); /* idr_pic_id */
3914
    }
3915

    
3916
    if(h->sps.poc_type==0){
3917
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3918

    
3919
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
3920
            h->delta_poc_bottom= get_se_golomb(&s->gb);
3921
        }
3922
    }
3923

    
3924
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
3925
        h->delta_poc[0]= get_se_golomb(&s->gb);
3926

    
3927
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
3928
            h->delta_poc[1]= get_se_golomb(&s->gb);
3929
    }
3930

    
3931
    init_poc(h);
3932

    
3933
    if(h->pps.redundant_pic_cnt_present){
3934
        h->redundant_pic_count= get_ue_golomb(&s->gb);
3935
    }
3936

    
3937
    //set defaults, might be overridden a few lines later
3938
    h->ref_count[0]= h->pps.ref_count[0];
3939
    h->ref_count[1]= h->pps.ref_count[1];
3940

    
3941
    if(h->slice_type_nos != FF_I_TYPE){
3942
        if(h->slice_type_nos == FF_B_TYPE){
3943
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
3944
        }
3945
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
3946

    
3947
        if(num_ref_idx_active_override_flag){
3948
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
3949
            if(h->slice_type_nos==FF_B_TYPE)
3950
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
3951

    
3952
            if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
3953
                av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3954
                h->ref_count[0]= h->ref_count[1]= 1;
3955
                return -1;
3956
            }
3957
        }
3958
        if(h->slice_type_nos == FF_B_TYPE)
3959
            h->list_count= 2;
3960
        else
3961
            h->list_count= 1;
3962
    }else
3963
        h->list_count= 0;
3964

    
3965
    if(!default_ref_list_done){
3966
        fill_default_ref_list(h);
3967
    }
3968

    
3969
    if(h->slice_type_nos!=FF_I_TYPE && decode_ref_pic_list_reordering(h) < 0)
3970
        return -1;
3971

    
3972
    if(   (h->pps.weighted_pred          && h->slice_type_nos == FF_P_TYPE )
3973
       ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
3974
        pred_weight_table(h);
3975
    else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE)
3976
        implicit_weight_table(h);
3977
    else
3978
        h->use_weight = 0;
3979

    
3980
    if(h->nal_ref_idc)
3981
        decode_ref_pic_marking(h0, &s->gb);
3982

    
3983
    if(FRAME_MBAFF)
3984
        fill_mbaff_ref_list(h);
3985

    
3986
    if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
3987
        tmp = get_ue_golomb(&s->gb);
3988
        if(tmp > 2){
3989
            av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3990
            return -1;
3991
        }
3992
        h->cabac_init_idc= tmp;
3993
    }
3994

    
3995
    h->last_qscale_diff = 0;
3996
    tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3997
    if(tmp>51){
3998
        av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3999
        return -1;
4000
    }
4001
    s->qscale= tmp;
4002
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
4003
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
4004
    //FIXME qscale / qp ... stuff
4005
    if(h->slice_type == FF_SP_TYPE){
4006
        get_bits1(&s->gb); /* sp_for_switch_flag */
4007
    }
4008
    if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
4009
        get_se_golomb(&s->gb); /* slice_qs_delta */
4010
    }
4011

    
4012
    h->deblocking_filter = 1;
4013
    h->slice_alpha_c0_offset = 0;
4014
    h->slice_beta_offset = 0;
4015
    if( h->pps.deblocking_filter_parameters_present ) {
4016
        tmp= get_ue_golomb(&s->gb);
4017
        if(tmp > 2){
4018
            av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
4019
            return -1;
4020
        }
4021
        h->deblocking_filter= tmp;
4022
        if(h->deblocking_filter < 2)
4023
            h->deblocking_filter^= 1; // 1<->0
4024

    
4025
        if( h->deblocking_filter ) {
4026
            h->slice_alpha_c0_offset = get_se_golomb(&s->gb) << 1;
4027
            h->slice_beta_offset = get_se_golomb(&s->gb) << 1;
4028
        }
4029
    }
4030

    
4031
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
4032
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
4033
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
4034
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
4035
        h->deblocking_filter= 0;
4036

    
4037
    if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
4038
        if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
4039
            /* Cheat slightly for speed:
4040
               Do not bother to deblock across slices. */
4041
            h->deblocking_filter = 2;
4042
        } else {
4043
            h0->max_contexts = 1;
4044
            if(!h0->single_decode_warning) {
4045
                av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
4046
                h0->single_decode_warning = 1;
4047
            }
4048
            if(h != h0)
4049
                return 1; // deblocking switched inside frame
4050
        }
4051
    }
4052

    
4053
#if 0 //FMO
4054
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
4055
        slice_group_change_cycle= get_bits(&s->gb, ?);
4056
#endif
4057

    
4058
    h0->last_slice_type = slice_type;
4059
    h->slice_num = ++h0->current_slice;
4060

    
4061
    for(j=0; j<2; j++){
4062
        int *ref2frm= h->ref2frm[h->slice_num&15][j];
4063
        ref2frm[0]=
4064
        ref2frm[1]= -1;
4065
        for(i=0; i<48; i++)
4066
            ref2frm[i+2]= 4*h->ref_list[j][i].frame_num
4067
                          +(h->ref_list[j][i].reference&3);
4068
    }
4069

    
4070
    h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16;
4071
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
4072

    
4073
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
4074
        av_log(h->s.avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
4075
               h->slice_num,
4076
               (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
4077
               first_mb_in_slice,
4078
               av_get_pict_type_char(h->slice_type),
4079
               pps_id, h->frame_num,
4080
               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
4081
               h->ref_count[0], h->ref_count[1],
4082
               s->qscale,
4083
               h->deblocking_filter, h->slice_alpha_c0_offset/2, h->slice_beta_offset/2,
4084
               h->use_weight,
4085
               h->use_weight==1 && h->use_weight_chroma ? "c" : "",
4086
               h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
4087
               );
4088
    }
4089

    
4090
    return 0;
4091
}
4092

    
4093
/**
4094
 *
4095
 */
4096
static inline int get_level_prefix(GetBitContext *gb){
4097
    unsigned int buf;
4098
    int log;
4099

    
4100
    OPEN_READER(re, gb);
4101
    UPDATE_CACHE(re, gb);
4102
    buf=GET_CACHE(re, gb);
4103

    
4104
    log= 32 - av_log2(buf);
4105
#ifdef TRACE
4106
    print_bin(buf>>(32-log), log);
4107
    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__);
4108
#endif
4109

    
4110
    LAST_SKIP_BITS(re, gb, log);
4111
    CLOSE_READER(re, gb);
4112

    
4113
    return log-1;
4114
}
4115

    
4116
static inline int get_dct8x8_allowed(H264Context *h){
4117
    int i;
4118
    for(i=0; i<4; i++){
4119
        if(!IS_SUB_8X8(h->sub_mb_type[i])
4120
           || (!h->sps.direct_8x8_inference_flag && IS_DIRECT(h->sub_mb_type[i])))
4121
            return 0;
4122
    }
4123
    return 1;
4124
}
4125

    
4126
/**
4127
 * decodes a residual block.
4128
 * @param n block index
4129
 * @param scantable scantable
4130
 * @param max_coeff number of coefficients in the block
4131
 * @return <0 if an error occurred
4132
 */
4133
static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff){
4134
    MpegEncContext * const s = &h->s;
4135
    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};
4136
    int level[16];
4137
    int zeros_left, coeff_num, coeff_token, total_coeff, i, j, trailing_ones, run_before;
4138

    
4139
    //FIXME put trailing_onex into the context
4140

    
4141
    if(n == CHROMA_DC_BLOCK_INDEX){
4142
        coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
4143
        total_coeff= coeff_token>>2;
4144
    }else{
4145
        if(n == LUMA_DC_BLOCK_INDEX){
4146
            total_coeff= pred_non_zero_count(h, 0);
4147
            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
4148
            total_coeff= coeff_token>>2;
4149
        }else{
4150
            total_coeff= pred_non_zero_count(h, n);
4151
            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
4152
            total_coeff= coeff_token>>2;
4153
            h->non_zero_count_cache[ scan8[n] ]= total_coeff;
4154
        }
4155
    }
4156

    
4157
    //FIXME set last_non_zero?
4158

    
4159
    if(total_coeff==0)
4160
        return 0;
4161
    if(total_coeff > (unsigned)max_coeff) {
4162
        av_log(h->s.avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", s->mb_x, s->mb_y, total_coeff);
4163
        return -1;
4164
    }
4165

    
4166
    trailing_ones= coeff_token&3;
4167
    tprintf(h->s.avctx, "trailing:%d, total:%d\n", trailing_ones, total_coeff);
4168
    assert(total_coeff<=16);
4169

    
4170
    for(i=0; i<trailing_ones; i++){
4171
        level[i]= 1 - 2*get_bits1(gb);
4172
    }
4173

    
4174
    if(i<total_coeff) {
4175
        int level_code, mask;
4176
        int suffix_length = total_coeff > 10 && trailing_ones < 3;
4177
        int prefix= get_level_prefix(gb);
4178

    
4179
        //first coefficient has suffix_length equal to 0 or 1
4180
        if(prefix<14){ //FIXME try to build a large unified VLC table for all this
4181
            if(suffix_length)
4182
                level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
4183
            else
4184
                level_code= (prefix<<suffix_length); //part
4185
        }else if(prefix==14){
4186
            if(suffix_length)
4187
                level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
4188
            else
4189
                level_code= prefix + get_bits(gb, 4); //part
4190
        }else{
4191
            level_code= (15<<suffix_length) + get_bits(gb, prefix-3); //part
4192
            if(suffix_length==0) level_code+=15; //FIXME doesn't make (much)sense
4193
            if(prefix>=16)
4194
                level_code += (1<<(prefix-3))-4096;
4195
        }
4196

    
4197
        if(trailing_ones < 3) level_code += 2;
4198

    
4199
        suffix_length = 1;
4200
        if(level_code > 5)
4201
            suffix_length++;
4202
        mask= -(level_code&1);
4203
        level[i]= (((2+level_code)>>1) ^ mask) - mask;
4204
        i++;
4205

    
4206
        //remaining coefficients have suffix_length > 0
4207
        for(;i<total_coeff;i++) {
4208
            static const int suffix_limit[7] = {0,5,11,23,47,95,INT_MAX };
4209
            prefix = get_level_prefix(gb);
4210
            if(prefix<15){
4211
                level_code = (prefix<<suffix_length) + get_bits(gb, suffix_length);
4212
            }else{
4213
                level_code = (15<<suffix_length) + get_bits(gb, prefix-3);
4214
                if(prefix>=16)
4215
                    level_code += (1<<(prefix-3))-4096;
4216
            }
4217
            mask= -(level_code&1);
4218
            level[i]= (((2+level_code)>>1) ^ mask) - mask;
4219
            if(level_code > suffix_limit[suffix_length])
4220
                suffix_length++;
4221
        }
4222
    }
4223

    
4224
    if(total_coeff == max_coeff)
4225
        zeros_left=0;
4226
    else{
4227
        if(n == CHROMA_DC_BLOCK_INDEX)
4228
            zeros_left= get_vlc2(gb, chroma_dc_total_zeros_vlc[ total_coeff-1 ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
4229
        else
4230
            zeros_left= get_vlc2(gb, total_zeros_vlc[ total_coeff-1 ].table, TOTAL_ZEROS_VLC_BITS, 1);
4231
    }
4232

    
4233
    coeff_num = zeros_left + total_coeff - 1;
4234
    j = scantable[coeff_num];
4235
    if(n > 24){
4236
        block[j] = level[0];
4237
        for(i=1;i<total_coeff;i++) {
4238
            if(zeros_left <= 0)
4239
                run_before = 0;
4240
            else if(zeros_left < 7){
4241
                run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
4242
            }else{
4243
                run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
4244
            }
4245
            zeros_left -= run_before;
4246
            coeff_num -= 1 + run_before;
4247
            j= scantable[ coeff_num ];
4248

    
4249
            block[j]= level[i];
4250
        }
4251
    }else{
4252
        block[j] = (level[0] * qmul[j] + 32)>>6;
4253
        for(i=1;i<total_coeff;i++) {
4254
            if(zeros_left <= 0)
4255
                run_before = 0;
4256
            else if(zeros_left < 7){
4257
                run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
4258
            }else{
4259
                run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
4260
            }
4261
            zeros_left -= run_before;
4262
            coeff_num -= 1 + run_before;
4263
            j= scantable[ coeff_num ];
4264

    
4265
            block[j]= (level[i] * qmul[j] + 32)>>6;
4266
        }
4267
    }
4268

    
4269
    if(zeros_left<0){
4270
        av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);
4271
        return -1;
4272
    }
4273

    
4274
    return 0;
4275
}
4276

    
4277
static void predict_field_decoding_flag(H264Context *h){
4278
    MpegEncContext * const s = &h->s;
4279
    const int mb_xy= h->mb_xy;
4280
    int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
4281
                ? s->current_picture.mb_type[mb_xy-1]
4282
                : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
4283
                ? s->current_picture.mb_type[mb_xy-s->mb_stride]
4284
                : 0;
4285
    h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4286
}
4287

    
4288
/**
4289
 * decodes a P_SKIP or B_SKIP macroblock
4290
 */
4291
static void decode_mb_skip(H264Context *h){
4292
    MpegEncContext * const s = &h->s;
4293
    const int mb_xy= h->mb_xy;
4294
    int mb_type=0;
4295

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

    
4299
    if(MB_FIELD)
4300
        mb_type|= MB_TYPE_INTERLACED;
4301

    
4302
    if( h->slice_type_nos == FF_B_TYPE )
4303
    {
4304
        // just for fill_caches. pred_direct_motion will set the real mb_type
4305
        mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_SKIP;
4306

    
4307
        fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
4308
        pred_direct_motion(h, &mb_type);
4309
        mb_type|= MB_TYPE_SKIP;
4310
    }
4311
    else
4312
    {
4313
        int mx, my;
4314
        mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P1L0|MB_TYPE_SKIP;
4315

    
4316
        fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
4317
        pred_pskip_motion(h, &mx, &my);
4318
        fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
4319
        fill_rectangle(  h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx,my), 4);
4320
    }
4321

    
4322
    write_back_motion(h, mb_type);
4323
    s->current_picture.mb_type[mb_xy]= mb_type;
4324
    s->current_picture.qscale_table[mb_xy]= s->qscale;
4325
    h->slice_table[ mb_xy ]= h->slice_num;
4326
    h->prev_mb_skipped= 1;
4327
}
4328

    
4329
/**
4330
 * decodes a macroblock
4331
 * @returns 0 if OK, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
4332
 */
4333
static int decode_mb_cavlc(H264Context *h){
4334
    MpegEncContext * const s = &h->s;
4335
    int mb_xy;
4336
    int partition_count;
4337
    unsigned int mb_type, cbp;
4338
    int dct8x8_allowed= h->pps.transform_8x8_mode;
4339

    
4340
    mb_xy = h->mb_xy = s->mb_x + s->mb_y*s->mb_stride;
4341

    
4342
    s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?
4343

    
4344
    tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
4345
    cbp = 0; /* avoid warning. FIXME: find a solution without slowing
4346
                down the code */
4347
    if(h->slice_type_nos != FF_I_TYPE){
4348
        if(s->mb_skip_run==-1)
4349
            s->mb_skip_run= get_ue_golomb(&s->gb);
4350

    
4351
        if (s->mb_skip_run--) {
4352
            if(FRAME_MBAFF && (s->mb_y&1) == 0){
4353
                if(s->mb_skip_run==0)
4354
                    h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
4355
                else
4356
                    predict_field_decoding_flag(h);
4357
            }
4358
            decode_mb_skip(h);
4359
            return 0;
4360
        }
4361
    }
4362
    if(FRAME_MBAFF){
4363
        if( (s->mb_y&1) == 0 )
4364
            h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
4365
    }else
4366
        h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);
4367

    
4368
    h->prev_mb_skipped= 0;
4369

    
4370
    mb_type= get_ue_golomb(&s->gb);
4371
    if(h->slice_type_nos == FF_B_TYPE){
4372
        if(mb_type < 23){
4373
            partition_count= b_mb_type_info[mb_type].partition_count;
4374
            mb_type=         b_mb_type_info[mb_type].type;
4375
        }else{
4376
            mb_type -= 23;
4377
            goto decode_intra_mb;
4378
        }
4379
    }else if(h->slice_type_nos == FF_P_TYPE){
4380
        if(mb_type < 5){
4381
            partition_count= p_mb_type_info[mb_type].partition_count;
4382
            mb_type=         p_mb_type_info[mb_type].type;
4383
        }else{
4384
            mb_type -= 5;
4385
            goto decode_intra_mb;
4386
        }
4387
    }else{
4388
       assert(h->slice_type_nos == FF_I_TYPE);
4389
        if(h->slice_type == FF_SI_TYPE && mb_type)
4390
            mb_type--;
4391
decode_intra_mb:
4392
        if(mb_type > 25){
4393
            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);
4394
            return -1;
4395
        }
4396
        partition_count=0;
4397
        cbp= i_mb_type_info[mb_type].cbp;
4398
        h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
4399
        mb_type= i_mb_type_info[mb_type].type;
4400
    }
4401

    
4402
    if(MB_FIELD)
4403
        mb_type |= MB_TYPE_INTERLACED;
4404

    
4405
    h->slice_table[ mb_xy ]= h->slice_num;
4406

    
4407
    if(IS_INTRA_PCM(mb_type)){
4408
        unsigned int x, y;
4409

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

    
4413
        // The pixels are stored in the same order as levels in h->mb array.
4414
        for(y=0; y<16; y++){
4415
            const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);
4416
            for(x=0; x<16; x++){
4417
                tprintf(s->avctx, "LUMA ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
4418
                h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= get_bits(&s->gb, 8);
4419
            }
4420
        }
4421
        if(CHROMA){
4422
            for(y=0; y<8; y++){
4423
                const int index= 256 + 4*(y&3) + 32*(y>>2);
4424
                for(x=0; x<8; x++){
4425
                    tprintf(s->avctx, "CHROMA U ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
4426
                    h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
4427
                }
4428
            }
4429
            for(y=0; y<8; y++){
4430
                const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
4431
                for(x=0; x<8; x++){
4432
                    tprintf(s->avctx, "CHROMA V ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
4433
                    h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
4434
                }
4435
            }
4436
        }
4437

    
4438
        // In deblocking, the quantizer is 0
4439
        s->current_picture.qscale_table[mb_xy]= 0;
4440
        // All coeffs are present
4441
        memset(h->non_zero_count[mb_xy], 16, 16);
4442

    
4443
        s->current_picture.mb_type[mb_xy]= mb_type;
4444
        return 0;
4445
    }
4446

    
4447
    if(MB_MBAFF){
4448
        h->ref_count[0] <<= 1;
4449
        h->ref_count[1] <<= 1;
4450
    }
4451

    
4452
    fill_caches(h, mb_type, 0);
4453 <