Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ c1708e8d

History | View | Annotate | Download (307 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 == PART_NOT_AVAILABLE)
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
        for (i=0; i<16; i++) {
2506
            memcpy(dest_y + i*  linesize, h->mb       + i*8, 16);
2507
        }
2508
        for (i=0; i<8; i++) {
2509
            memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4,  8);
2510
            memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4,  8);
2511
        }
2512
    } else {
2513
        if(IS_INTRA(mb_type)){
2514
            if(h->deblocking_filter && (simple || !FRAME_MBAFF))
2515
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
2516

    
2517
            if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2518
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
2519
                h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
2520
            }
2521

    
2522
            if(IS_INTRA4x4(mb_type)){
2523
                if(simple || !s->encoding){
2524
                    if(IS_8x8DCT(mb_type)){
2525
                        for(i=0; i<16; i+=4){
2526
                            uint8_t * const ptr= dest_y + block_offset[i];
2527
                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
2528
                            const int nnz = h->non_zero_count_cache[ scan8[i] ];
2529
                            h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
2530
                                                   (h->topright_samples_available<<i)&0x4000, linesize);
2531
                            if(nnz){
2532
                                if(nnz == 1 && h->mb[i*16])
2533
                                    idct_dc_add(ptr, h->mb + i*16, linesize);
2534
                                else
2535
                                    idct_add(ptr, h->mb + i*16, linesize);
2536
                            }
2537
                        }
2538
                    }else
2539
                    for(i=0; i<16; i++){
2540
                        uint8_t * const ptr= dest_y + block_offset[i];
2541
                        uint8_t *topright;
2542
                        const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
2543
                        int nnz, tr;
2544

    
2545
                        if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
2546
                            const int topright_avail= (h->topright_samples_available<<i)&0x8000;
2547
                            assert(mb_y || linesize <= block_offset[i]);
2548
                            if(!topright_avail){
2549
                                tr= ptr[3 - linesize]*0x01010101;
2550
                                topright= (uint8_t*) &tr;
2551
                            }else
2552
                                topright= ptr + 4 - linesize;
2553
                        }else
2554
                            topright= NULL;
2555

    
2556
                        h->hpc.pred4x4[ dir ](ptr, topright, linesize);
2557
                        nnz = h->non_zero_count_cache[ scan8[i] ];
2558
                        if(nnz){
2559
                            if(is_h264){
2560
                                if(nnz == 1 && h->mb[i*16])
2561
                                    idct_dc_add(ptr, h->mb + i*16, linesize);
2562
                                else
2563
                                    idct_add(ptr, h->mb + i*16, linesize);
2564
                            }else
2565
                                svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
2566
                        }
2567
                    }
2568
                }
2569
            }else{
2570
                h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
2571
                if(is_h264){
2572
                    if(!transform_bypass)
2573
                        h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[0][s->qscale][0]);
2574
                }else
2575
                    svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
2576
            }
2577
            if(h->deblocking_filter && (simple || !FRAME_MBAFF))
2578
                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
2579
        }else if(is_h264){
2580
            hl_motion(h, dest_y, dest_cb, dest_cr,
2581
                      s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
2582
                      s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
2583
                      s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);
2584
        }
2585

    
2586

    
2587
        if(!IS_INTRA4x4(mb_type)){
2588
            if(is_h264){
2589
                if(IS_INTRA16x16(mb_type)){
2590
                    for(i=0; i<16; i++){
2591
                        if(h->non_zero_count_cache[ scan8[i] ])
2592
                            idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2593
                        else if(h->mb[i*16])
2594
                            idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2595
                    }
2596
                }else{
2597
                    const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2598
                    for(i=0; i<16; i+=di){
2599
                        int nnz = h->non_zero_count_cache[ scan8[i] ];
2600
                        if(nnz){
2601
                            if(nnz==1 && h->mb[i*16])
2602
                                idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2603
                            else
2604
                                idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
2605
                        }
2606
                    }
2607
                }
2608
            }else{
2609
                for(i=0; i<16; i++){
2610
                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
2611
                        uint8_t * const ptr= dest_y + block_offset[i];
2612
                        svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
2613
                    }
2614
                }
2615
            }
2616
        }
2617

    
2618
        if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2619
            uint8_t *dest[2] = {dest_cb, dest_cr};
2620
            if(transform_bypass){
2621
                idct_add = idct_dc_add = s->dsp.add_pixels4;
2622
            }else{
2623
                idct_add = s->dsp.h264_idct_add;
2624
                idct_dc_add = s->dsp.h264_idct_dc_add;
2625
                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]);
2626
                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]);
2627
            }
2628
            if(is_h264){
2629
                for(i=16; i<16+8; i++){
2630
                    if(h->non_zero_count_cache[ scan8[i] ])
2631
                        idct_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2632
                    else if(h->mb[i*16])
2633
                        idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
2634
                }
2635
            }else{
2636
                for(i=16; i<16+8; i++){
2637
                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2638
                        uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
2639
                        svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
2640
                    }
2641
                }
2642
            }
2643
        }
2644
    }
2645
    if(h->deblocking_filter) {
2646
        if (!simple && FRAME_MBAFF) {
2647
            //FIXME try deblocking one mb at a time?
2648
            // the reduction in load/storing mvs and such might outweigh the extra backup/xchg_border
2649
            const int mb_y = s->mb_y - 1;
2650
            uint8_t  *pair_dest_y, *pair_dest_cb, *pair_dest_cr;
2651
            const int mb_xy= mb_x + mb_y*s->mb_stride;
2652
            const int mb_type_top   = s->current_picture.mb_type[mb_xy];
2653
            const int mb_type_bottom= s->current_picture.mb_type[mb_xy+s->mb_stride];
2654
            if (!bottom) return;
2655
            pair_dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
2656
            pair_dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2657
            pair_dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2658

    
2659
            if(IS_INTRA(mb_type_top | mb_type_bottom))
2660
                xchg_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize, 0);
2661

    
2662
            backup_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize);
2663
            // deblock a pair
2664
            // top
2665
            s->mb_y--; h->mb_xy -= s->mb_stride;
2666
            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);
2667
            fill_caches(h, mb_type_top, 1); //FIXME don't fill stuff which isn't used by filter_mb
2668
            h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2669
            h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2670
            filter_mb(h, mb_x, mb_y, pair_dest_y, pair_dest_cb, pair_dest_cr, linesize, uvlinesize);
2671
            // bottom
2672
            s->mb_y++; h->mb_xy += s->mb_stride;
2673
            tprintf(h->s.avctx, "call mbaff filter_mb\n");
2674
            fill_caches(h, mb_type_bottom, 1); //FIXME don't fill stuff which isn't used by filter_mb
2675
            h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
2676
            h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
2677
            filter_mb(h, mb_x, mb_y+1, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2678
        } else {
2679
            tprintf(h->s.avctx, "call filter_mb\n");
2680
            backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, simple);
2681
            fill_caches(h, mb_type, 1); //FIXME don't fill stuff which isn't used by filter_mb
2682
            h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
2683
            h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
2684
            filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
2685
        }
2686
    }
2687
}
2688

    
2689
/**
2690
 * Process a macroblock; this case avoids checks for expensive uncommon cases.
2691
 */
2692
static void hl_decode_mb_simple(H264Context *h){
2693
    hl_decode_mb_internal(h, 1);
2694
}
2695

    
2696
/**
2697
 * Process a macroblock; this handles edge cases, such as interlacing.
2698
 */
2699
static void av_noinline hl_decode_mb_complex(H264Context *h){
2700
    hl_decode_mb_internal(h, 0);
2701
}
2702

    
2703
static void hl_decode_mb(H264Context *h){
2704
    MpegEncContext * const s = &h->s;
2705
    const int mb_xy= h->mb_xy;
2706
    const int mb_type= s->current_picture.mb_type[mb_xy];
2707
    int is_complex = FRAME_MBAFF || MB_FIELD || IS_INTRA_PCM(mb_type) || s->codec_id != CODEC_ID_H264 ||
2708
                    (ENABLE_GRAY && (s->flags&CODEC_FLAG_GRAY)) || (ENABLE_H264_ENCODER && s->encoding) || ENABLE_SMALL;
2709

    
2710
    if(ENABLE_H264_ENCODER && !s->decode)
2711
        return;
2712

    
2713
    if (is_complex)
2714
        hl_decode_mb_complex(h);
2715
    else hl_decode_mb_simple(h);
2716
}
2717

    
2718
static void pic_as_field(Picture *pic, const int parity){
2719
    int i;
2720
    for (i = 0; i < 4; ++i) {
2721
        if (parity == PICT_BOTTOM_FIELD)
2722
            pic->data[i] += pic->linesize[i];
2723
        pic->reference = parity;
2724
        pic->linesize[i] *= 2;
2725
    }
2726
}
2727

    
2728
static int split_field_copy(Picture *dest, Picture *src,
2729
                            int parity, int id_add){
2730
    int match = !!(src->reference & parity);
2731

    
2732
    if (match) {
2733
        *dest = *src;
2734
        if(parity != PICT_FRAME){
2735
            pic_as_field(dest, parity);
2736
            dest->pic_id *= 2;
2737
            dest->pic_id += id_add;
2738
        }
2739
    }
2740

    
2741
    return match;
2742
}
2743

    
2744
static int build_def_list(Picture *def, Picture **in, int len, int is_long, int sel){
2745
    int i[2]={0};
2746
    int index=0;
2747

    
2748
    while(i[0]<len || i[1]<len){
2749
        while(i[0]<len && !(in[ i[0] ] && (in[ i[0] ]->reference & sel)))
2750
            i[0]++;
2751
        while(i[1]<len && !(in[ i[1] ] && (in[ i[1] ]->reference & (sel^3))))
2752
            i[1]++;
2753
        if(i[0] < len){
2754
            in[ i[0] ]->pic_id= is_long ? i[0] : in[ i[0] ]->frame_num;
2755
            split_field_copy(&def[index++], in[ i[0]++ ], sel  , 1);
2756
        }
2757
        if(i[1] < len){
2758
            in[ i[1] ]->pic_id= is_long ? i[1] : in[ i[1] ]->frame_num;
2759
            split_field_copy(&def[index++], in[ i[1]++ ], sel^3, 0);
2760
        }
2761
    }
2762

    
2763
    return index;
2764
}
2765

    
2766
static int add_sorted(Picture **sorted, Picture **src, int len, int limit, int dir){
2767
    int i, best_poc;
2768
    int out_i= 0;
2769

    
2770
    for(;;){
2771
        best_poc= dir ? INT_MIN : INT_MAX;
2772

    
2773
        for(i=0; i<len; i++){
2774
            const int poc= src[i]->poc;
2775
            if(((poc > limit) ^ dir) && ((poc < best_poc) ^ dir)){
2776
                best_poc= poc;
2777
                sorted[out_i]= src[i];
2778
            }
2779
        }
2780
        if(best_poc == (dir ? INT_MIN : INT_MAX))
2781
            break;
2782
        limit= sorted[out_i++]->poc - dir;
2783
    }
2784
    return out_i;
2785
}
2786

    
2787
/**
2788
 * fills the default_ref_list.
2789
 */
2790
static int fill_default_ref_list(H264Context *h){
2791
    MpegEncContext * const s = &h->s;
2792
    int i, len;
2793

    
2794
    if(h->slice_type_nos==FF_B_TYPE){
2795
        Picture *sorted[32];
2796
        int cur_poc, list;
2797
        int lens[2];
2798

    
2799
        if(FIELD_PICTURE)
2800
            cur_poc= s->current_picture_ptr->field_poc[ s->picture_structure == PICT_BOTTOM_FIELD ];
2801
        else
2802
            cur_poc= s->current_picture_ptr->poc;
2803

    
2804
        for(list= 0; list<2; list++){
2805
            len= add_sorted(sorted    , h->short_ref, h->short_ref_count, cur_poc, 1^list);
2806
            len+=add_sorted(sorted+len, h->short_ref, h->short_ref_count, cur_poc, 0^list);
2807
            assert(len<=32);
2808
            len= build_def_list(h->default_ref_list[list]    , sorted     , len, 0, s->picture_structure);
2809
            len+=build_def_list(h->default_ref_list[list]+len, h->long_ref, 16 , 1, s->picture_structure);
2810
            assert(len<=32);
2811

    
2812
            if(len < h->ref_count[list])
2813
                memset(&h->default_ref_list[list][len], 0, sizeof(Picture)*(h->ref_count[list] - len));
2814
            lens[list]= len;
2815
        }
2816

    
2817
        if(lens[0] == lens[1] && lens[1] > 1){
2818
            for(i=0; h->default_ref_list[0][i].data[0] == h->default_ref_list[1][i].data[0] && i<lens[0]; i++);
2819
            if(i == lens[0])
2820
                FFSWAP(Picture, h->default_ref_list[1][0], h->default_ref_list[1][1]);
2821
        }
2822
    }else{
2823
        len = build_def_list(h->default_ref_list[0]    , h->short_ref, h->short_ref_count, 0, s->picture_structure);
2824
        len+= build_def_list(h->default_ref_list[0]+len, h-> long_ref, 16                , 1, s->picture_structure);
2825
        assert(len <= 32);
2826
        if(len < h->ref_count[0])
2827
            memset(&h->default_ref_list[0][len], 0, sizeof(Picture)*(h->ref_count[0] - len));
2828
    }
2829
#ifdef TRACE
2830
    for (i=0; i<h->ref_count[0]; i++) {
2831
        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]);
2832
    }
2833
    if(h->slice_type_nos==FF_B_TYPE){
2834
        for (i=0; i<h->ref_count[1]; i++) {
2835
            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]);
2836
        }
2837
    }
2838
#endif
2839
    return 0;
2840
}
2841

    
2842
static void print_short_term(H264Context *h);
2843
static void print_long_term(H264Context *h);
2844

    
2845
/**
2846
 * Extract structure information about the picture described by pic_num in
2847
 * the current decoding context (frame or field). Note that pic_num is
2848
 * picture number without wrapping (so, 0<=pic_num<max_pic_num).
2849
 * @param pic_num picture number for which to extract structure information
2850
 * @param structure one of PICT_XXX describing structure of picture
2851
 *                      with pic_num
2852
 * @return frame number (short term) or long term index of picture
2853
 *         described by pic_num
2854
 */
2855
static int pic_num_extract(H264Context *h, int pic_num, int *structure){
2856
    MpegEncContext * const s = &h->s;
2857

    
2858
    *structure = s->picture_structure;
2859
    if(FIELD_PICTURE){
2860
        if (!(pic_num & 1))
2861
            /* opposite field */
2862
            *structure ^= PICT_FRAME;
2863
        pic_num >>= 1;
2864
    }
2865

    
2866
    return pic_num;
2867
}
2868

    
2869
static int decode_ref_pic_list_reordering(H264Context *h){
2870
    MpegEncContext * const s = &h->s;
2871
    int list, index, pic_structure;
2872

    
2873
    print_short_term(h);
2874
    print_long_term(h);
2875

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

    
2879
        if(get_bits1(&s->gb)){
2880
            int pred= h->curr_pic_num;
2881

    
2882
            for(index=0; ; index++){
2883
                unsigned int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
2884
                unsigned int pic_id;
2885
                int i;
2886
                Picture *ref = NULL;
2887

    
2888
                if(reordering_of_pic_nums_idc==3)
2889
                    break;
2890

    
2891
                if(index >= h->ref_count[list]){
2892
                    av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
2893
                    return -1;
2894
                }
2895

    
2896
                if(reordering_of_pic_nums_idc<3){
2897
                    if(reordering_of_pic_nums_idc<2){
2898
                        const unsigned int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
2899
                        int frame_num;
2900

    
2901
                        if(abs_diff_pic_num > h->max_pic_num){
2902
                            av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
2903
                            return -1;
2904
                        }
2905

    
2906
                        if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
2907
                        else                                pred+= abs_diff_pic_num;
2908
                        pred &= h->max_pic_num - 1;
2909

    
2910
                        frame_num = pic_num_extract(h, pred, &pic_structure);
2911

    
2912
                        for(i= h->short_ref_count-1; i>=0; i--){
2913
                            ref = h->short_ref[i];
2914
                            assert(ref->reference);
2915
                            assert(!ref->long_ref);
2916
                            if(
2917
                                   ref->frame_num == frame_num &&
2918
                                   (ref->reference & pic_structure)
2919
                              )
2920
                                break;
2921
                        }
2922
                        if(i>=0)
2923
                            ref->pic_id= pred;
2924
                    }else{
2925
                        int long_idx;
2926
                        pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
2927

    
2928
                        long_idx= pic_num_extract(h, pic_id, &pic_structure);
2929

    
2930
                        if(long_idx>31){
2931
                            av_log(h->s.avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
2932
                            return -1;
2933
                        }
2934
                        ref = h->long_ref[long_idx];
2935
                        assert(!(ref && !ref->reference));
2936
                        if(ref && (ref->reference & pic_structure)){
2937
                            ref->pic_id= pic_id;
2938
                            assert(ref->long_ref);
2939
                            i=0;
2940
                        }else{
2941
                            i=-1;
2942
                        }
2943
                    }
2944

    
2945
                    if (i < 0) {
2946
                        av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
2947
                        memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
2948
                    } else {
2949
                        for(i=index; i+1<h->ref_count[list]; i++){
2950
                            if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)
2951
                                break;
2952
                        }
2953
                        for(; i > index; i--){
2954
                            h->ref_list[list][i]= h->ref_list[list][i-1];
2955
                        }
2956
                        h->ref_list[list][index]= *ref;
2957
                        if (FIELD_PICTURE){
2958
                            pic_as_field(&h->ref_list[list][index], pic_structure);
2959
                        }
2960
                    }
2961
                }else{
2962
                    av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
2963
                    return -1;
2964
                }
2965
            }
2966
        }
2967
    }
2968
    for(list=0; list<h->list_count; list++){
2969
        for(index= 0; index < h->ref_count[list]; index++){
2970
            if(!h->ref_list[list][index].data[0]){
2971
                av_log(h->s.avctx, AV_LOG_ERROR, "Missing reference picture\n");
2972
                h->ref_list[list][index]= s->current_picture; //FIXME this is not a sensible solution
2973
            }
2974
        }
2975
    }
2976

    
2977
    if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
2978
        direct_dist_scale_factor(h);
2979
    direct_ref_list_init(h);
2980
    return 0;
2981
}
2982

    
2983
static void fill_mbaff_ref_list(H264Context *h){
2984
    int list, i, j;
2985
    for(list=0; list<2; list++){ //FIXME try list_count
2986
        for(i=0; i<h->ref_count[list]; i++){
2987
            Picture *frame = &h->ref_list[list][i];
2988
            Picture *field = &h->ref_list[list][16+2*i];
2989
            field[0] = *frame;
2990
            for(j=0; j<3; j++)
2991
                field[0].linesize[j] <<= 1;
2992
            field[0].reference = PICT_TOP_FIELD;
2993
            field[1] = field[0];
2994
            for(j=0; j<3; j++)
2995
                field[1].data[j] += frame->linesize[j];
2996
            field[1].reference = PICT_BOTTOM_FIELD;
2997

    
2998
            h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i];
2999
            h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i];
3000
            for(j=0; j<2; j++){
3001
                h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j];
3002
                h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j];
3003
            }
3004
        }
3005
    }
3006
    for(j=0; j<h->ref_count[1]; j++){
3007
        for(i=0; i<h->ref_count[0]; i++)
3008
            h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i];
3009
        memcpy(h->implicit_weight[16+2*j],   h->implicit_weight[j], sizeof(*h->implicit_weight));
3010
        memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight));
3011
    }
3012
}
3013

    
3014
static int pred_weight_table(H264Context *h){
3015
    MpegEncContext * const s = &h->s;
3016
    int list, i;
3017
    int luma_def, chroma_def;
3018

    
3019
    h->use_weight= 0;
3020
    h->use_weight_chroma= 0;
3021
    h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
3022
    h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
3023
    luma_def = 1<<h->luma_log2_weight_denom;
3024
    chroma_def = 1<<h->chroma_log2_weight_denom;
3025

    
3026
    for(list=0; list<2; list++){
3027
        for(i=0; i<h->ref_count[list]; i++){
3028
            int luma_weight_flag, chroma_weight_flag;
3029

    
3030
            luma_weight_flag= get_bits1(&s->gb);
3031
            if(luma_weight_flag){
3032
                h->luma_weight[list][i]= get_se_golomb(&s->gb);
3033
                h->luma_offset[list][i]= get_se_golomb(&s->gb);
3034
                if(   h->luma_weight[list][i] != luma_def
3035
                   || h->luma_offset[list][i] != 0)
3036
                    h->use_weight= 1;
3037
            }else{
3038
                h->luma_weight[list][i]= luma_def;
3039
                h->luma_offset[list][i]= 0;
3040
            }
3041

    
3042
            if(CHROMA){
3043
                chroma_weight_flag= get_bits1(&s->gb);
3044
                if(chroma_weight_flag){
3045
                    int j;
3046
                    for(j=0; j<2; j++){
3047
                        h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
3048
                        h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
3049
                        if(   h->chroma_weight[list][i][j] != chroma_def
3050
                        || h->chroma_offset[list][i][j] != 0)
3051
                            h->use_weight_chroma= 1;
3052
                    }
3053
                }else{
3054
                    int j;
3055
                    for(j=0; j<2; j++){
3056
                        h->chroma_weight[list][i][j]= chroma_def;
3057
                        h->chroma_offset[list][i][j]= 0;
3058
                    }
3059
                }
3060
            }
3061
        }
3062
        if(h->slice_type_nos != FF_B_TYPE) break;
3063
    }
3064
    h->use_weight= h->use_weight || h->use_weight_chroma;
3065
    return 0;
3066
}
3067

    
3068
static void implicit_weight_table(H264Context *h){
3069
    MpegEncContext * const s = &h->s;
3070
    int ref0, ref1;
3071
    int cur_poc = s->current_picture_ptr->poc;
3072

    
3073
    if(   h->ref_count[0] == 1 && h->ref_count[1] == 1
3074
       && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
3075
        h->use_weight= 0;
3076
        h->use_weight_chroma= 0;
3077
        return;
3078
    }
3079

    
3080
    h->use_weight= 2;
3081
    h->use_weight_chroma= 2;
3082
    h->luma_log2_weight_denom= 5;
3083
    h->chroma_log2_weight_denom= 5;
3084

    
3085
    for(ref0=0; ref0 < h->ref_count[0]; ref0++){
3086
        int poc0 = h->ref_list[0][ref0].poc;
3087
        for(ref1=0; ref1 < h->ref_count[1]; ref1++){
3088
            int poc1 = h->ref_list[1][ref1].poc;
3089
            int td = av_clip(poc1 - poc0, -128, 127);
3090
            if(td){
3091
                int tb = av_clip(cur_poc - poc0, -128, 127);
3092
                int tx = (16384 + (FFABS(td) >> 1)) / td;
3093
                int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
3094
                if(dist_scale_factor < -64 || dist_scale_factor > 128)
3095
                    h->implicit_weight[ref0][ref1] = 32;
3096
                else
3097
                    h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
3098
            }else
3099
                h->implicit_weight[ref0][ref1] = 32;
3100
        }
3101
    }
3102
}
3103

    
3104
/**
3105
 * Mark a picture as no longer needed for reference. The refmask
3106
 * argument allows unreferencing of individual fields or the whole frame.
3107
 * If the picture becomes entirely unreferenced, but is being held for
3108
 * display purposes, it is marked as such.
3109
 * @param refmask mask of fields to unreference; the mask is bitwise
3110
 *                anded with the reference marking of pic
3111
 * @return non-zero if pic becomes entirely unreferenced (except possibly
3112
 *         for display purposes) zero if one of the fields remains in
3113
 *         reference
3114
 */
3115
static inline int unreference_pic(H264Context *h, Picture *pic, int refmask){
3116
    int i;
3117
    if (pic->reference &= refmask) {
3118
        return 0;
3119
    } else {
3120
        for(i = 0; h->delayed_pic[i]; i++)
3121
            if(pic == h->delayed_pic[i]){
3122
                pic->reference=DELAYED_PIC_REF;
3123
                break;
3124
            }
3125
        return 1;
3126
    }
3127
}
3128

    
3129
/**
3130
 * instantaneous decoder refresh.
3131
 */
3132
static void idr(H264Context *h){
3133
    int i;
3134

    
3135
    for(i=0; i<16; i++){
3136
        remove_long(h, i, 0);
3137
    }
3138
    assert(h->long_ref_count==0);
3139

    
3140
    for(i=0; i<h->short_ref_count; i++){
3141
        unreference_pic(h, h->short_ref[i], 0);
3142
        h->short_ref[i]= NULL;
3143
    }
3144
    h->short_ref_count=0;
3145
    h->prev_frame_num= 0;
3146
    h->prev_frame_num_offset= 0;
3147
    h->prev_poc_msb=
3148
    h->prev_poc_lsb= 0;
3149
}
3150

    
3151
/* forget old pics after a seek */
3152
static void flush_dpb(AVCodecContext *avctx){
3153
    H264Context *h= avctx->priv_data;
3154
    int i;
3155
    for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
3156
        if(h->delayed_pic[i])
3157
            h->delayed_pic[i]->reference= 0;
3158
        h->delayed_pic[i]= NULL;
3159
    }
3160
    h->outputed_poc= INT_MIN;
3161
    idr(h);
3162
    if(h->s.current_picture_ptr)
3163
        h->s.current_picture_ptr->reference= 0;
3164
    h->s.first_field= 0;
3165
    ff_mpeg_flush(avctx);
3166
}
3167

    
3168
/**
3169
 * Find a Picture in the short term reference list by frame number.
3170
 * @param frame_num frame number to search for
3171
 * @param idx the index into h->short_ref where returned picture is found
3172
 *            undefined if no picture found.
3173
 * @return pointer to the found picture, or NULL if no pic with the provided
3174
 *                 frame number is found
3175
 */
3176
static Picture * find_short(H264Context *h, int frame_num, int *idx){
3177
    MpegEncContext * const s = &h->s;
3178
    int i;
3179

    
3180
    for(i=0; i<h->short_ref_count; i++){
3181
        Picture *pic= h->short_ref[i];
3182
        if(s->avctx->debug&FF_DEBUG_MMCO)
3183
            av_log(h->s.avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
3184
        if(pic->frame_num == frame_num) {
3185
            *idx = i;
3186
            return pic;
3187
        }
3188
    }
3189
    return NULL;
3190
}
3191

    
3192
/**
3193
 * Remove a picture from the short term reference list by its index in
3194
 * that list.  This does no checking on the provided index; it is assumed
3195
 * to be valid. Other list entries are shifted down.
3196
 * @param i index into h->short_ref of picture to remove.
3197
 */
3198
static void remove_short_at_index(H264Context *h, int i){
3199
    assert(i >= 0 && i < h->short_ref_count);
3200
    h->short_ref[i]= NULL;
3201
    if (--h->short_ref_count)
3202
        memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i)*sizeof(Picture*));
3203
}
3204

    
3205
/**
3206
 *
3207
 * @return the removed picture or NULL if an error occurs
3208
 */
3209
static Picture * remove_short(H264Context *h, int frame_num, int ref_mask){
3210
    MpegEncContext * const s = &h->s;
3211
    Picture *pic;
3212
    int i;
3213

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

    
3217
    pic = find_short(h, frame_num, &i);
3218
    if (pic){
3219
        if(unreference_pic(h, pic, ref_mask))
3220
        remove_short_at_index(h, i);
3221
    }
3222

    
3223
    return pic;
3224
}
3225

    
3226
/**
3227
 * Remove a picture from the long term reference list by its index in
3228
 * that list.
3229
 * @return the removed picture or NULL if an error occurs
3230
 */
3231
static Picture * remove_long(H264Context *h, int i, int ref_mask){
3232
    Picture *pic;
3233

    
3234
    pic= h->long_ref[i];
3235
    if (pic){
3236
        if(unreference_pic(h, pic, ref_mask)){
3237
            assert(h->long_ref[i]->long_ref == 1);
3238
            h->long_ref[i]->long_ref= 0;
3239
            h->long_ref[i]= NULL;
3240
            h->long_ref_count--;
3241
        }
3242
    }
3243

    
3244
    return pic;
3245
}
3246

    
3247
/**
3248
 * print short term list
3249
 */
3250
static void print_short_term(H264Context *h) {
3251
    uint32_t i;
3252
    if(h->s.avctx->debug&FF_DEBUG_MMCO) {
3253
        av_log(h->s.avctx, AV_LOG_DEBUG, "short term list:\n");
3254
        for(i=0; i<h->short_ref_count; i++){
3255
            Picture *pic= h->short_ref[i];
3256
            av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
3257
        }
3258
    }
3259
}
3260

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

    
3277
/**
3278
 * Executes the reference picture marking (memory management control operations).
3279
 */
3280
static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
3281
    MpegEncContext * const s = &h->s;
3282
    int i, j;
3283
    int current_ref_assigned=0;
3284
    Picture *pic;
3285

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

    
3289
    for(i=0; i<mmco_count; i++){
3290
        int structure, frame_num;
3291
        if(s->avctx->debug&FF_DEBUG_MMCO)
3292
            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);
3293

    
3294
        if(   mmco[i].opcode == MMCO_SHORT2UNUSED
3295
           || mmco[i].opcode == MMCO_SHORT2LONG){
3296
            frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
3297
            pic = find_short(h, frame_num, &j);
3298
            if(!pic){
3299
                if(mmco[i].opcode != MMCO_SHORT2LONG || !h->long_ref[mmco[i].long_arg]
3300
                   || h->long_ref[mmco[i].long_arg]->frame_num != frame_num)
3301
                av_log(h->s.avctx, AV_LOG_ERROR, "mmco: unref short failure\n");
3302
                continue;
3303
            }
3304
        }
3305

    
3306
        switch(mmco[i].opcode){
3307
        case MMCO_SHORT2UNUSED:
3308
            if(s->avctx->debug&FF_DEBUG_MMCO)
3309
                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);
3310
            remove_short(h, frame_num, structure ^ PICT_FRAME);
3311
            break;
3312
        case MMCO_SHORT2LONG:
3313
                if (h->long_ref[mmco[i].long_arg] != pic)
3314
                    remove_long(h, mmco[i].long_arg, 0);
3315

    
3316
                remove_short_at_index(h, j);
3317
                h->long_ref[ mmco[i].long_arg ]= pic;
3318
                if (h->long_ref[ mmco[i].long_arg ]){
3319
                    h->long_ref[ mmco[i].long_arg ]->long_ref=1;
3320
                    h->long_ref_count++;
3321
                }
3322
            break;
3323
        case MMCO_LONG2UNUSED:
3324
            j = pic_num_extract(h, mmco[i].long_arg, &structure);
3325
            pic = h->long_ref[j];
3326
            if (pic) {
3327
                remove_long(h, j, structure ^ PICT_FRAME);
3328
            } else if(s->avctx->debug&FF_DEBUG_MMCO)
3329
                av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
3330
            break;
3331
        case MMCO_LONG:
3332
                    // Comment below left from previous code as it is an interresting note.
3333
                    /* First field in pair is in short term list or
3334
                     * at a different long term index.
3335
                     * This is not allowed; see 7.4.3.3, notes 2 and 3.
3336
                     * Report the problem and keep the pair where it is,
3337
                     * and mark this field valid.
3338
                     */
3339

    
3340
            if (h->long_ref[mmco[i].long_arg] != s->current_picture_ptr) {
3341
                remove_long(h, mmco[i].long_arg, 0);
3342

    
3343
                h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;
3344
                h->long_ref[ mmco[i].long_arg ]->long_ref=1;
3345
                h->long_ref_count++;
3346
            }
3347

    
3348
            s->current_picture_ptr->reference |= s->picture_structure;
3349
            current_ref_assigned=1;
3350
            break;
3351
        case MMCO_SET_MAX_LONG:
3352
            assert(mmco[i].long_arg <= 16);
3353
            // just remove the long term which index is greater than new max
3354
            for(j = mmco[i].long_arg; j<16; j++){
3355
                remove_long(h, j, 0);
3356
            }
3357
            break;
3358
        case MMCO_RESET:
3359
            while(h->short_ref_count){
3360
                remove_short(h, h->short_ref[0]->frame_num, 0);
3361
            }
3362
            for(j = 0; j < 16; j++) {
3363
                remove_long(h, j, 0);
3364
            }
3365
            s->current_picture_ptr->poc=
3366
            s->current_picture_ptr->field_poc[0]=
3367
            s->current_picture_ptr->field_poc[1]=
3368
            h->poc_lsb=
3369
            h->poc_msb=
3370
            h->frame_num=
3371
            s->current_picture_ptr->frame_num= 0;
3372
            break;
3373
        default: assert(0);
3374
        }
3375
    }
3376

    
3377
    if (!current_ref_assigned) {
3378
        /* Second field of complementary field pair; the first field of
3379
         * which is already referenced. If short referenced, it
3380
         * should be first entry in short_ref. If not, it must exist
3381
         * in long_ref; trying to put it on the short list here is an
3382
         * error in the encoded bit stream (ref: 7.4.3.3, NOTE 2 and 3).
3383
         */
3384
        if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {
3385
            /* Just mark the second field valid */
3386
            s->current_picture_ptr->reference = PICT_FRAME;
3387
        } else if (s->current_picture_ptr->long_ref) {
3388
            av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "
3389
                                             "assignment for second field "
3390
                                             "in complementary field pair "
3391
                                             "(first field is long term)\n");
3392
        } else {
3393
            pic= remove_short(h, s->current_picture_ptr->frame_num, 0);
3394
            if(pic){
3395
                av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
3396
            }
3397

    
3398
            if(h->short_ref_count)
3399
                memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
3400

    
3401
            h->short_ref[0]= s->current_picture_ptr;
3402
            h->short_ref_count++;
3403
            s->current_picture_ptr->reference |= s->picture_structure;
3404
        }
3405
    }
3406

    
3407
    if (h->long_ref_count + h->short_ref_count > h->sps.ref_frame_count){
3408

    
3409
        /* We have too many reference frames, probably due to corrupted
3410
         * stream. Need to discard one frame. Prevents overrun of the
3411
         * short_ref and long_ref buffers.
3412
         */
3413
        av_log(h->s.avctx, AV_LOG_ERROR,
3414
               "number of reference frames exceeds max (probably "
3415
               "corrupt input), discarding one\n");
3416

    
3417
        if (h->long_ref_count && !h->short_ref_count) {
3418
            for (i = 0; i < 16; ++i)
3419
                if (h->long_ref[i])
3420
                    break;
3421

    
3422
            assert(i < 16);
3423
            remove_long(h, i, 0);
3424
        } else {
3425
            pic = h->short_ref[h->short_ref_count - 1];
3426
            remove_short(h, pic->frame_num, 0);
3427
        }
3428
    }
3429

    
3430
    print_short_term(h);
3431
    print_long_term(h);
3432
    return 0;
3433
}
3434

    
3435
static int decode_ref_pic_marking(H264Context *h, GetBitContext *gb){
3436
    MpegEncContext * const s = &h->s;
3437
    int i;
3438

    
3439
    h->mmco_index= 0;
3440
    if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields
3441
        s->broken_link= get_bits1(gb) -1;
3442
        if(get_bits1(gb)){
3443
            h->mmco[0].opcode= MMCO_LONG;
3444
            h->mmco[0].long_arg= 0;
3445
            h->mmco_index= 1;
3446
        }
3447
    }else{
3448
        if(get_bits1(gb)){ // adaptive_ref_pic_marking_mode_flag
3449
            for(i= 0; i<MAX_MMCO_COUNT; i++) {
3450
                MMCOOpcode opcode= get_ue_golomb(gb);
3451

    
3452
                h->mmco[i].opcode= opcode;
3453
                if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){
3454
                    h->mmco[i].short_pic_num= (h->curr_pic_num - get_ue_golomb(gb) - 1) & (h->max_pic_num - 1);
3455
/*                    if(h->mmco[i].short_pic_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_pic_num ] == NULL){
3456
                        av_log(s->avctx, AV_LOG_ERROR, "illegal short ref in memory management control operation %d\n", mmco);
3457
                        return -1;
3458
                    }*/
3459
                }
3460
                if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){
3461
                    unsigned int long_arg= get_ue_golomb(gb);
3462
                    if(long_arg >= 32 || (long_arg >= 16 && !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){
3463
                        av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);
3464
                        return -1;
3465
                    }
3466
                    h->mmco[i].long_arg= long_arg;
3467
                }
3468

    
3469
                if(opcode > (unsigned)MMCO_LONG){
3470
                    av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);
3471
                    return -1;
3472
                }
3473
                if(opcode == MMCO_END)
3474
                    break;
3475
            }
3476
            h->mmco_index= i;
3477
        }else{
3478
            assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
3479

    
3480
            if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
3481
                    !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {
3482
                h->mmco[0].opcode= MMCO_SHORT2UNUSED;
3483
                h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
3484
                h->mmco_index= 1;
3485
                if (FIELD_PICTURE) {
3486
                    h->mmco[0].short_pic_num *= 2;
3487
                    h->mmco[1].opcode= MMCO_SHORT2UNUSED;
3488
                    h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;
3489
                    h->mmco_index= 2;
3490
                }
3491
            }
3492
        }
3493
    }
3494

    
3495
    return 0;
3496
}
3497

    
3498
static int init_poc(H264Context *h){
3499
    MpegEncContext * const s = &h->s;
3500
    const int max_frame_num= 1<<h->sps.log2_max_frame_num;
3501
    int field_poc[2];
3502
    Picture *cur = s->current_picture_ptr;
3503

    
3504
    h->frame_num_offset= h->prev_frame_num_offset;
3505
    if(h->frame_num < h->prev_frame_num)
3506
        h->frame_num_offset += max_frame_num;
3507

    
3508
    if(h->sps.poc_type==0){
3509
        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
3510

    
3511
        if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
3512
            h->poc_msb = h->prev_poc_msb + max_poc_lsb;
3513
        else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
3514
            h->poc_msb = h->prev_poc_msb - max_poc_lsb;
3515
        else
3516
            h->poc_msb = h->prev_poc_msb;
3517
//printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
3518
        field_poc[0] =
3519
        field_poc[1] = h->poc_msb + h->poc_lsb;
3520
        if(s->picture_structure == PICT_FRAME)
3521
            field_poc[1] += h->delta_poc_bottom;
3522
    }else if(h->sps.poc_type==1){
3523
        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
3524
        int i;
3525

    
3526
        if(h->sps.poc_cycle_length != 0)
3527
            abs_frame_num = h->frame_num_offset + h->frame_num;
3528
        else
3529
            abs_frame_num = 0;
3530

    
3531
        if(h->nal_ref_idc==0 && abs_frame_num > 0)
3532
            abs_frame_num--;
3533

    
3534
        expected_delta_per_poc_cycle = 0;
3535
        for(i=0; i < h->sps.poc_cycle_length; i++)
3536
            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
3537

    
3538
        if(abs_frame_num > 0){
3539
            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
3540
            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
3541

    
3542
            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
3543
            for(i = 0; i <= frame_num_in_poc_cycle; i++)
3544
                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
3545
        } else
3546
            expectedpoc = 0;
3547

    
3548
        if(h->nal_ref_idc == 0)
3549
            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
3550

    
3551
        field_poc[0] = expectedpoc + h->delta_poc[0];
3552
        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
3553

    
3554
        if(s->picture_structure == PICT_FRAME)
3555
            field_poc[1] += h->delta_poc[1];
3556
    }else{
3557
        int poc= 2*(h->frame_num_offset + h->frame_num);
3558

    
3559
        if(!h->nal_ref_idc)
3560
            poc--;
3561

    
3562
        field_poc[0]= poc;
3563
        field_poc[1]= poc;
3564
    }
3565

    
3566
    if(s->picture_structure != PICT_BOTTOM_FIELD)
3567
        s->current_picture_ptr->field_poc[0]= field_poc[0];
3568
    if(s->picture_structure != PICT_TOP_FIELD)
3569
        s->current_picture_ptr->field_poc[1]= field_poc[1];
3570
    cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
3571

    
3572
    return 0;
3573
}
3574

    
3575

    
3576
/**
3577
 * initialize scan tables
3578
 */
3579
static void init_scan_tables(H264Context *h){
3580
    MpegEncContext * const s = &h->s;
3581
    int i;
3582
    if(s->dsp.h264_idct_add == ff_h264_idct_add_c){ //FIXME little ugly
3583
        memcpy(h->zigzag_scan, zigzag_scan, 16*sizeof(uint8_t));
3584
        memcpy(h-> field_scan,  field_scan, 16*sizeof(uint8_t));
3585
    }else{
3586
        for(i=0; i<16; i++){
3587
#define T(x) (x>>2) | ((x<<2) & 0xF)
3588
            h->zigzag_scan[i] = T(zigzag_scan[i]);
3589
            h-> field_scan[i] = T( field_scan[i]);
3590
#undef T
3591
        }
3592
    }
3593
    if(s->dsp.h264_idct8_add == ff_h264_idct8_add_c){
3594
        memcpy(h->zigzag_scan8x8,       zigzag_scan8x8,       64*sizeof(uint8_t));
3595
        memcpy(h->zigzag_scan8x8_cavlc, zigzag_scan8x8_cavlc, 64*sizeof(uint8_t));
3596
        memcpy(h->field_scan8x8,        field_scan8x8,        64*sizeof(uint8_t));
3597
        memcpy(h->field_scan8x8_cavlc,  field_scan8x8_cavlc,  64*sizeof(uint8_t));
3598
    }else{
3599
        for(i=0; i<64; i++){
3600
#define T(x) (x>>3) | ((x&7)<<3)
3601
            h->zigzag_scan8x8[i]       = T(zigzag_scan8x8[i]);
3602
            h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
3603
            h->field_scan8x8[i]        = T(field_scan8x8[i]);
3604
            h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);
3605
#undef T
3606
        }
3607
    }
3608
    if(h->sps.transform_bypass){ //FIXME same ugly
3609
        h->zigzag_scan_q0          = zigzag_scan;
3610
        h->zigzag_scan8x8_q0       = zigzag_scan8x8;
3611
        h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
3612
        h->field_scan_q0           = field_scan;
3613
        h->field_scan8x8_q0        = field_scan8x8;
3614
        h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
3615
    }else{
3616
        h->zigzag_scan_q0          = h->zigzag_scan;
3617
        h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
3618
        h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
3619
        h->field_scan_q0           = h->field_scan;
3620
        h->field_scan8x8_q0        = h->field_scan8x8;
3621
        h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
3622
    }
3623
}
3624

    
3625
/**
3626
 * Replicates H264 "master" context to thread contexts.
3627
 */
3628
static void clone_slice(H264Context *dst, H264Context *src)
3629
{
3630
    memcpy(dst->block_offset,     src->block_offset, sizeof(dst->block_offset));
3631
    dst->s.current_picture_ptr  = src->s.current_picture_ptr;
3632
    dst->s.current_picture      = src->s.current_picture;
3633
    dst->s.linesize             = src->s.linesize;
3634
    dst->s.uvlinesize           = src->s.uvlinesize;
3635
    dst->s.first_field          = src->s.first_field;
3636

    
3637
    dst->prev_poc_msb           = src->prev_poc_msb;
3638
    dst->prev_poc_lsb           = src->prev_poc_lsb;
3639
    dst->prev_frame_num_offset  = src->prev_frame_num_offset;
3640
    dst->prev_frame_num         = src->prev_frame_num;
3641
    dst->short_ref_count        = src->short_ref_count;
3642

    
3643
    memcpy(dst->short_ref,        src->short_ref,        sizeof(dst->short_ref));
3644
    memcpy(dst->long_ref,         src->long_ref,         sizeof(dst->long_ref));
3645
    memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3646
    memcpy(dst->ref_list,         src->ref_list,         sizeof(dst->ref_list));
3647

    
3648
    memcpy(dst->dequant4_coeff,   src->dequant4_coeff,   sizeof(src->dequant4_coeff));
3649
    memcpy(dst->dequant8_coeff,   src->dequant8_coeff,   sizeof(src->dequant8_coeff));
3650
}
3651

    
3652
/**
3653
 * decodes a slice header.
3654
 * This will also call MPV_common_init() and frame_start() as needed.
3655
 *
3656
 * @param h h264context
3657
 * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
3658
 *
3659
 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3660
 */
3661
static int decode_slice_header(H264Context *h, H264Context *h0){
3662
    MpegEncContext * const s = &h->s;
3663
    MpegEncContext * const s0 = &h0->s;
3664
    unsigned int first_mb_in_slice;
3665
    unsigned int pps_id;
3666
    int num_ref_idx_active_override_flag;
3667
    static const uint8_t slice_type_map[5]= {FF_P_TYPE, FF_B_TYPE, FF_I_TYPE, FF_SP_TYPE, FF_SI_TYPE};
3668
    unsigned int slice_type, tmp, i, j;
3669
    int default_ref_list_done = 0;
3670
    int last_pic_structure;
3671

    
3672
    s->dropable= h->nal_ref_idc == 0;
3673

    
3674
    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
3675
        s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
3676
        s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
3677
    }else{
3678
        s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
3679
        s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
3680
    }
3681

    
3682
    first_mb_in_slice= get_ue_golomb(&s->gb);
3683

    
3684
    if((s->flags2 & CODEC_FLAG2_CHUNKS) && first_mb_in_slice == 0){
3685
        h0->current_slice = 0;
3686
        if (!s0->first_field)
3687
            s->current_picture_ptr= NULL;
3688
    }
3689

    
3690
    slice_type= get_ue_golomb(&s->gb);
3691
    if(slice_type > 9){
3692
        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);
3693
        return -1;
3694
    }
3695
    if(slice_type > 4){
3696
        slice_type -= 5;
3697
        h->slice_type_fixed=1;
3698
    }else
3699
        h->slice_type_fixed=0;
3700

    
3701
    slice_type= slice_type_map[ slice_type ];
3702
    if (slice_type == FF_I_TYPE
3703
        || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
3704
        default_ref_list_done = 1;
3705
    }
3706
    h->slice_type= slice_type;
3707
    h->slice_type_nos= slice_type & 3;
3708

    
3709
    s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
3710
    if (s->pict_type == FF_B_TYPE && s0->last_picture_ptr == NULL) {
3711
        av_log(h->s.avctx, AV_LOG_ERROR,
3712
               "B picture before any references, skipping\n");
3713
        return -1;
3714
    }
3715

    
3716
    pps_id= get_ue_golomb(&s->gb);
3717
    if(pps_id>=MAX_PPS_COUNT){
3718
        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
3719
        return -1;
3720
    }
3721
    if(!h0->pps_buffers[pps_id]) {
3722
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS referenced\n");
3723
        return -1;
3724
    }
3725
    h->pps= *h0->pps_buffers[pps_id];
3726

    
3727
    if(!h0->sps_buffers[h->pps.sps_id]) {
3728
        av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS referenced\n");
3729
        return -1;
3730
    }
3731
    h->sps = *h0->sps_buffers[h->pps.sps_id];
3732

    
3733
    if(h == h0 && h->dequant_coeff_pps != pps_id){
3734
        h->dequant_coeff_pps = pps_id;
3735
        init_dequant_tables(h);
3736
    }
3737

    
3738
    s->mb_width= h->sps.mb_width;
3739
    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3740

    
3741
    h->b_stride=  s->mb_width*4;
3742
    h->b8_stride= s->mb_width*2;
3743

    
3744
    s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
3745
    if(h->sps.frame_mbs_only_flag)
3746
        s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
3747
    else
3748
        s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 3);
3749

    
3750
    if (s->context_initialized
3751
        && (   s->width != s->avctx->width || s->height != s->avctx->height)) {
3752
        if(h != h0)
3753
            return -1;   // width / height changed during parallelized decoding
3754
        free_tables(h);
3755
        MPV_common_end(s);
3756
    }
3757
    if (!s->context_initialized) {
3758
        if(h != h0)
3759
            return -1;  // we cant (re-)initialize context during parallel decoding
3760
        if (MPV_common_init(s) < 0)
3761
            return -1;
3762
        s->first_field = 0;
3763

    
3764
        init_scan_tables(h);
3765
        alloc_tables(h);
3766

    
3767
        for(i = 1; i < s->avctx->thread_count; i++) {
3768
            H264Context *c;
3769
            c = h->thread_context[i] = av_malloc(sizeof(H264Context));
3770
            memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
3771
            memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
3772
            c->sps = h->sps;
3773
            c->pps = h->pps;
3774
            init_scan_tables(c);
3775
            clone_tables(c, h);
3776
        }
3777

    
3778
        for(i = 0; i < s->avctx->thread_count; i++)
3779
            if(context_init(h->thread_context[i]) < 0)
3780
                return -1;
3781

    
3782
        s->avctx->width = s->width;
3783
        s->avctx->height = s->height;
3784
        s->avctx->sample_aspect_ratio= h->sps.sar;
3785
        if(!s->avctx->sample_aspect_ratio.den)
3786
            s->avctx->sample_aspect_ratio.den = 1;
3787

    
3788
        if(h->sps.timing_info_present_flag){
3789
            s->avctx->time_base= (AVRational){h->sps.num_units_in_tick * 2, h->sps.time_scale};
3790
            if(h->x264_build > 0 && h->x264_build < 44)
3791
                s->avctx->time_base.den *= 2;
3792
            av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
3793
                      s->avctx->time_base.num, s->avctx->time_base.den, 1<<30);
3794
        }
3795
    }
3796

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

    
3799
    h->mb_mbaff = 0;
3800
    h->mb_aff_frame = 0;
3801
    last_pic_structure = s0->picture_structure;
3802
    if(h->sps.frame_mbs_only_flag){
3803
        s->picture_structure= PICT_FRAME;
3804
    }else{
3805
        if(get_bits1(&s->gb)) { //field_pic_flag
3806
            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
3807
        } else {
3808
            s->picture_structure= PICT_FRAME;
3809
            h->mb_aff_frame = h->sps.mb_aff;
3810
        }
3811
    }
3812

    
3813
    if(h0->current_slice == 0){
3814
        while(h->frame_num !=  h->prev_frame_num &&
3815
              h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
3816
            av_log(NULL, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
3817
            frame_start(h);
3818
            h->prev_frame_num++;
3819
            h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
3820
            s->current_picture_ptr->frame_num= h->prev_frame_num;
3821
            execute_ref_pic_marking(h, NULL, 0);
3822
        }
3823

    
3824
        /* See if we have a decoded first field looking for a pair... */
3825
        if (s0->first_field) {
3826
            assert(s0->current_picture_ptr);
3827
            assert(s0->current_picture_ptr->data[0]);
3828
            assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
3829

    
3830
            /* figure out if we have a complementary field pair */
3831
            if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
3832
                /*
3833
                 * Previous field is unmatched. Don't display it, but let it
3834
                 * remain for reference if marked as such.
3835
                 */
3836
                s0->current_picture_ptr = NULL;
3837
                s0->first_field = FIELD_PICTURE;
3838

    
3839
            } else {
3840
                if (h->nal_ref_idc &&
3841
                        s0->current_picture_ptr->reference &&
3842
                        s0->current_picture_ptr->frame_num != h->frame_num) {
3843
                    /*
3844
                     * This and previous field were reference, but had
3845
                     * different frame_nums. Consider this field first in
3846
                     * pair. Throw away previous field except for reference
3847
                     * purposes.
3848
                     */
3849
                    s0->first_field = 1;
3850
                    s0->current_picture_ptr = NULL;
3851

    
3852
                } else {
3853
                    /* Second field in complementary pair */
3854
                    s0->first_field = 0;
3855
                }
3856
            }
3857

    
3858
        } else {
3859
            /* Frame or first field in a potentially complementary pair */
3860
            assert(!s0->current_picture_ptr);
3861
            s0->first_field = FIELD_PICTURE;
3862
        }
3863

    
3864
        if((!FIELD_PICTURE || s0->first_field) && frame_start(h) < 0) {
3865
            s0->first_field = 0;
3866
            return -1;
3867
        }
3868
    }
3869
    if(h != h0)
3870
        clone_slice(h, h0);
3871

    
3872
    s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
3873

    
3874
    assert(s->mb_num == s->mb_width * s->mb_height);
3875
    if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
3876
       first_mb_in_slice                    >= s->mb_num){
3877
        av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3878
        return -1;
3879
    }
3880
    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
3881
    s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
3882
    if (s->picture_structure == PICT_BOTTOM_FIELD)
3883
        s->resync_mb_y = s->mb_y = s->mb_y + 1;
3884
    assert(s->mb_y < s->mb_height);
3885

    
3886
    if(s->picture_structure==PICT_FRAME){
3887
        h->curr_pic_num=   h->frame_num;
3888
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
3889
    }else{
3890
        h->curr_pic_num= 2*h->frame_num + 1;
3891
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
3892
    }
3893

    
3894
    if(h->nal_unit_type == NAL_IDR_SLICE){
3895
        get_ue_golomb(&s->gb); /* idr_pic_id */
3896
    }
3897

    
3898
    if(h->sps.poc_type==0){
3899
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
3900

    
3901
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
3902
            h->delta_poc_bottom= get_se_golomb(&s->gb);
3903
        }
3904
    }
3905

    
3906
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
3907
        h->delta_poc[0]= get_se_golomb(&s->gb);
3908

    
3909
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
3910
            h->delta_poc[1]= get_se_golomb(&s->gb);
3911
    }
3912

    
3913
    init_poc(h);
3914

    
3915
    if(h->pps.redundant_pic_cnt_present){
3916
        h->redundant_pic_count= get_ue_golomb(&s->gb);
3917
    }
3918

    
3919
    //set defaults, might be overridden a few lines later
3920
    h->ref_count[0]= h->pps.ref_count[0];
3921
    h->ref_count[1]= h->pps.ref_count[1];
3922

    
3923
    if(h->slice_type_nos != FF_I_TYPE){
3924
        if(h->slice_type_nos == FF_B_TYPE){
3925
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
3926
        }
3927
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
3928

    
3929
        if(num_ref_idx_active_override_flag){
3930
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
3931
            if(h->slice_type_nos==FF_B_TYPE)
3932
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
3933

    
3934
            if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
3935
                av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
3936
                h->ref_count[0]= h->ref_count[1]= 1;
3937
                return -1;
3938
            }
3939
        }
3940
        if(h->slice_type_nos == FF_B_TYPE)
3941
            h->list_count= 2;
3942
        else
3943
            h->list_count= 1;
3944
    }else
3945
        h->list_count= 0;
3946

    
3947
    if(!default_ref_list_done){
3948
        fill_default_ref_list(h);
3949
    }
3950

    
3951
    if(h->slice_type_nos!=FF_I_TYPE && decode_ref_pic_list_reordering(h) < 0)
3952
        return -1;
3953

    
3954
    if(   (h->pps.weighted_pred          && h->slice_type_nos == FF_P_TYPE )
3955
       ||  (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
3956
        pred_weight_table(h);
3957
    else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE)
3958
        implicit_weight_table(h);
3959
    else
3960
        h->use_weight = 0;
3961

    
3962
    if(h->nal_ref_idc)
3963
        decode_ref_pic_marking(h0, &s->gb);
3964

    
3965
    if(FRAME_MBAFF)
3966
        fill_mbaff_ref_list(h);
3967

    
3968
    if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
3969
        tmp = get_ue_golomb(&s->gb);
3970
        if(tmp > 2){
3971
            av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3972
            return -1;
3973
        }
3974
        h->cabac_init_idc= tmp;
3975
    }
3976

    
3977
    h->last_qscale_diff = 0;
3978
    tmp = h->pps.init_qp + get_se_golomb(&s->gb);
3979
    if(tmp>51){
3980
        av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3981
        return -1;
3982
    }
3983
    s->qscale= tmp;
3984
    h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
3985
    h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
3986
    //FIXME qscale / qp ... stuff
3987
    if(h->slice_type == FF_SP_TYPE){
3988
        get_bits1(&s->gb); /* sp_for_switch_flag */
3989
    }
3990
    if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
3991
        get_se_golomb(&s->gb); /* slice_qs_delta */
3992
    }
3993

    
3994
    h->deblocking_filter = 1;
3995
    h->slice_alpha_c0_offset = 0;
3996
    h->slice_beta_offset = 0;
3997
    if( h->pps.deblocking_filter_parameters_present ) {
3998
        tmp= get_ue_golomb(&s->gb);
3999
        if(tmp > 2){
4000
            av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
4001
            return -1;
4002
        }
4003
        h->deblocking_filter= tmp;
4004
        if(h->deblocking_filter < 2)
4005
            h->deblocking_filter^= 1; // 1<->0
4006

    
4007
        if( h->deblocking_filter ) {
4008
            h->slice_alpha_c0_offset = get_se_golomb(&s->gb) << 1;
4009
            h->slice_beta_offset = get_se_golomb(&s->gb) << 1;
4010
        }
4011
    }
4012

    
4013
    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL
4014
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
4015
       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type_nos == FF_B_TYPE)
4016
       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
4017
        h->deblocking_filter= 0;
4018

    
4019
    if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
4020
        if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
4021
            /* Cheat slightly for speed:
4022
               Do not bother to deblock across slices. */
4023
            h->deblocking_filter = 2;
4024
        } else {
4025
            h0->max_contexts = 1;
4026
            if(!h0->single_decode_warning) {
4027
                av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
4028
                h0->single_decode_warning = 1;
4029
            }
4030
            if(h != h0)
4031
                return 1; // deblocking switched inside frame
4032
        }
4033
    }
4034

    
4035
#if 0 //FMO
4036
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
4037
        slice_group_change_cycle= get_bits(&s->gb, ?);
4038
#endif
4039

    
4040
    h0->last_slice_type = slice_type;
4041
    h->slice_num = ++h0->current_slice;
4042

    
4043
    for(j=0; j<2; j++){
4044
        int *ref2frm= h->ref2frm[h->slice_num&15][j];
4045
        ref2frm[0]=
4046
        ref2frm[1]= -1;
4047
        for(i=0; i<48; i++)
4048
            ref2frm[i+2]= 4*h->ref_list[j][i].frame_num
4049
                          +(h->ref_list[j][i].reference&3);
4050
    }
4051

    
4052
    h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16;
4053
    h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
4054

    
4055
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
4056
        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",
4057
               h->slice_num,
4058
               (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
4059
               first_mb_in_slice,
4060
               av_get_pict_type_char(h->slice_type),
4061
               pps_id, h->frame_num,
4062
               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
4063
               h->ref_count[0], h->ref_count[1],
4064
               s->qscale,
4065
               h->deblocking_filter, h->slice_alpha_c0_offset/2, h->slice_beta_offset/2,
4066
               h->use_weight,
4067
               h->use_weight==1 && h->use_weight_chroma ? "c" : "",
4068
               h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
4069
               );
4070
    }
4071

    
4072
    return 0;
4073
}
4074

    
4075
/**
4076
 *
4077
 */
4078
static inline int get_level_prefix(GetBitContext *gb){
4079
    unsigned int buf;
4080
    int log;
4081

    
4082
    OPEN_READER(re, gb);
4083
    UPDATE_CACHE(re, gb);
4084
    buf=GET_CACHE(re, gb);
4085

    
4086
    log= 32 - av_log2(buf);
4087
#ifdef TRACE
4088
    print_bin(buf>>(32-log), log);
4089
    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__);
4090
#endif
4091

    
4092
    LAST_SKIP_BITS(re, gb, log);
4093
    CLOSE_READER(re, gb);
4094

    
4095
    return log-1;
4096
}
4097

    
4098
static inline int get_dct8x8_allowed(H264Context *h){
4099
    int i;
4100
    for(i=0; i<4; i++){
4101
        if(!IS_SUB_8X8(h->sub_mb_type[i])
4102
           || (!h->sps.direct_8x8_inference_flag && IS_DIRECT(h->sub_mb_type[i])))
4103
            return 0;
4104
    }
4105
    return 1;
4106
}
4107

    
4108
/**
4109
 * decodes a residual block.
4110
 * @param n block index
4111
 * @param scantable scantable
4112
 * @param max_coeff number of coefficients in the block
4113
 * @return <0 if an error occurred
4114
 */
4115
static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff){
4116
    MpegEncContext * const s = &h->s;
4117
    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};
4118
    int level[16];
4119
    int zeros_left, coeff_num, coeff_token, total_coeff, i, j, trailing_ones, run_before;
4120

    
4121
    //FIXME put trailing_onex into the context
4122

    
4123
    if(n == CHROMA_DC_BLOCK_INDEX){
4124
        coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
4125
        total_coeff= coeff_token>>2;
4126
    }else{
4127
        if(n == LUMA_DC_BLOCK_INDEX){
4128
            total_coeff= pred_non_zero_count(h, 0);
4129
            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
4130
            total_coeff= coeff_token>>2;
4131
        }else{
4132
            total_coeff= pred_non_zero_count(h, n);
4133
            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
4134
            total_coeff= coeff_token>>2;
4135
            h->non_zero_count_cache[ scan8[n] ]= total_coeff;
4136
        }
4137
    }
4138

    
4139
    //FIXME set last_non_zero?
4140

    
4141
    if(total_coeff==0)
4142
        return 0;
4143
    if(total_coeff > (unsigned)max_coeff) {
4144
        av_log(h->s.avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", s->mb_x, s->mb_y, total_coeff);
4145
        return -1;
4146
    }
4147

    
4148
    trailing_ones= coeff_token&3;
4149
    tprintf(h->s.avctx, "trailing:%d, total:%d\n", trailing_ones, total_coeff);
4150
    assert(total_coeff<=16);
4151

    
4152
    for(i=0; i<trailing_ones; i++){
4153
        level[i]= 1 - 2*get_bits1(gb);
4154
    }
4155

    
4156
    if(i<total_coeff) {
4157
        int level_code, mask;
4158
        int suffix_length = total_coeff > 10 && trailing_ones < 3;
4159
        int prefix= get_level_prefix(gb);
4160

    
4161
        //first coefficient has suffix_length equal to 0 or 1
4162
        if(prefix<14){ //FIXME try to build a large unified VLC table for all this
4163
            if(suffix_length)
4164
                level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
4165
            else
4166
                level_code= (prefix<<suffix_length); //part
4167
        }else if(prefix==14){
4168
            if(suffix_length)
4169
                level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
4170
            else
4171
                level_code= prefix + get_bits(gb, 4); //part
4172
        }else{
4173
            level_code= (15<<suffix_length) + get_bits(gb, prefix-3); //part
4174
            if(suffix_length==0) level_code+=15; //FIXME doesn't make (much)sense
4175
            if(prefix>=16)
4176
                level_code += (1<<(prefix-3))-4096;
4177
        }
4178

    
4179
        if(trailing_ones < 3) level_code += 2;
4180

    
4181
        suffix_length = 1;
4182
        if(level_code > 5)
4183
            suffix_length++;
4184
        mask= -(level_code&1);
4185
        level[i]= (((2+level_code)>>1) ^ mask) - mask;
4186
        i++;
4187

    
4188
        //remaining coefficients have suffix_length > 0
4189
        for(;i<total_coeff;i++) {
4190
            static const int suffix_limit[7] = {0,5,11,23,47,95,INT_MAX };
4191
            prefix = get_level_prefix(gb);
4192
            if(prefix<15){
4193
                level_code = (prefix<<suffix_length) + get_bits(gb, suffix_length);
4194
            }else{
4195
                level_code = (15<<suffix_length) + get_bits(gb, prefix-3);
4196
                if(prefix>=16)
4197
                    level_code += (1<<(prefix-3))-4096;
4198
            }
4199
            mask= -(level_code&1);
4200
            level[i]= (((2+level_code)>>1) ^ mask) - mask;
4201
            if(level_code > suffix_limit[suffix_length])
4202
                suffix_length++;
4203
        }
4204
    }
4205

    
4206
    if(total_coeff == max_coeff)
4207
        zeros_left=0;
4208
    else{
4209
        if(n == CHROMA_DC_BLOCK_INDEX)
4210
            zeros_left= get_vlc2(gb, chroma_dc_total_zeros_vlc[ total_coeff-1 ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
4211
        else
4212
            zeros_left= get_vlc2(gb, total_zeros_vlc[ total_coeff-1 ].table, TOTAL_ZEROS_VLC_BITS, 1);
4213
    }
4214

    
4215
    coeff_num = zeros_left + total_coeff - 1;
4216
    j = scantable[coeff_num];
4217
    if(n > 24){
4218
        block[j] = level[0];
4219
        for(i=1;i<total_coeff;i++) {
4220
            if(zeros_left <= 0)
4221
                run_before = 0;
4222
            else if(zeros_left < 7){
4223
                run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
4224
            }else{
4225
                run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
4226
            }
4227
            zeros_left -= run_before;
4228
            coeff_num -= 1 + run_before;
4229
            j= scantable[ coeff_num ];
4230

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

    
4247
            block[j]= (level[i] * qmul[j] + 32)>>6;
4248
        }
4249
    }
4250

    
4251
    if(zeros_left<0){
4252
        av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);
4253
        return -1;
4254
    }
4255

    
4256
    return 0;
4257
}
4258

    
4259
static void predict_field_decoding_flag(H264Context *h){
4260
    MpegEncContext * const s = &h->s;
4261
    const int mb_xy= h->mb_xy;
4262
    int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
4263
                ? s->current_picture.mb_type[mb_xy-1]
4264
                : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
4265
                ? s->current_picture.mb_type[mb_xy-s->mb_stride]
4266
                : 0;
4267
    h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4268
}
4269

    
4270
/**
4271
 * decodes a P_SKIP or B_SKIP macroblock
4272
 */
4273
static void decode_mb_skip(H264Context *h){
4274
    MpegEncContext * const s = &h->s;
4275
    const int mb_xy= h->mb_xy;
4276
    int mb_type=0;
4277

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

    
4281
    if(MB_FIELD)
4282
        mb_type|= MB_TYPE_INTERLACED;
4283

    
4284
    if( h->slice_type_nos == FF_B_TYPE )
4285
    {
4286
        // just for fill_caches. pred_direct_motion will set the real mb_type
4287
        mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_SKIP;
4288

    
4289
        fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
4290
        pred_direct_motion(h, &mb_type);
4291
        mb_type|= MB_TYPE_SKIP;
4292
    }
4293
    else
4294
    {
4295
        int mx, my;
4296
        mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P1L0|MB_TYPE_SKIP;
4297

    
4298
        fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
4299
        pred_pskip_motion(h, &mx, &my);
4300
        fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
4301
        fill_rectangle(  h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx,my), 4);
4302
    }
4303

    
4304
    write_back_motion(h, mb_type);
4305
    s->current_picture.mb_type[mb_xy]= mb_type;
4306
    s->current_picture.qscale_table[mb_xy]= s->qscale;
4307
    h->slice_table[ mb_xy ]= h->slice_num;
4308
    h->prev_mb_skipped= 1;
4309
}
4310

    
4311
/**
4312
 * decodes a macroblock
4313
 * @returns 0 if OK, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
4314
 */
4315
static int decode_mb_cavlc(H264Context *h){
4316
    MpegEncContext * const s = &h->s;
4317
    int mb_xy;
4318
    int partition_count;
4319
    unsigned int mb_type, cbp;
4320
    int dct8x8_allowed= h->pps.transform_8x8_mode;
4321

    
4322
    mb_xy = h->mb_xy = s->mb_x + s->mb_y*s->mb_stride;
4323

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

    
4326
    tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
4327
    cbp = 0; /* avoid warning. FIXME: find a solution without slowing
4328
                down the code */
4329
    if(h->slice_type_nos != FF_I_TYPE){
4330
        if(s->mb_skip_run==-1)
4331
            s->mb_skip_run= get_ue_golomb(&s->gb);
4332

    
4333
        if (s->mb_skip_run--) {
4334
            if(FRAME_MBAFF && (s->mb_y&1) == 0){
4335
                if(s->mb_skip_run==0)
4336
                    h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
4337
                else
4338
                    predict_field_decoding_flag(h);
4339
            }
4340
            decode_mb_skip(h);
4341
            return 0;
4342
        }
4343
    }
4344
    if(FRAME_MBAFF){
4345
        if( (s->mb_y&1) == 0 )
4346
            h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
4347
    }else
4348
        h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);
4349

    
4350
    h->prev_mb_skipped= 0;
4351

    
4352
    mb_type= get_ue_golomb(&s->gb);
4353
    if(h->slice_type_nos == FF_B_TYPE){
4354
        if(mb_type < 23){
4355
            partition_count= b_mb_type_info[mb_type].partition_count;
4356
            mb_type=         b_mb_type_info[mb_type].type;
4357
        }else{
4358
            mb_type -= 23;
4359
            goto decode_intra_mb;
4360
        }
4361
    }else if(h->slice_type_nos == FF_P_TYPE){
4362
        if(mb_type < 5){
4363
            partition_count= p_mb_type_info[mb_type].partition_count;
4364
            mb_type=         p_mb_type_info[mb_type].type;
4365
        }else{
4366
            mb_type -= 5;
4367
            goto decode_intra_mb;
4368
        }
4369
    }else{
4370
       assert(h->slice_type_nos == FF_I_TYPE);
4371
        if(h->slice_type == FF_SI_TYPE && mb_type)
4372
            mb_type--;
4373
decode_intra_mb:
4374
        if(mb_type > 25){
4375
            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);
4376
            return -1;
4377
        }
4378
        partition_count=0;
4379
        cbp= i_mb_type_info[mb_type].cbp;
4380
        h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
4381
        mb_type= i_mb_type_info[mb_type].type;
4382
    }
4383

    
4384
    if(MB_FIELD)
4385
        mb_type |= MB_TYPE_INTERLACED;
4386

    
4387
    h->slice_table[ mb_xy ]= h->slice_num;
4388

    
4389
    if(IS_INTRA_PCM(mb_type)){
4390
        unsigned int x;
4391

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

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

    
4400
        // In deblocking, the quantizer is 0
4401
        s->current_picture.qscale_table[mb_xy]= 0;
4402
        // All coeffs are present
4403
        memset(h->non_zero_count[mb_xy], 16, 16);
4404

    
4405
        s->current_picture.mb_type[mb_xy]= mb_type;
4406
        return 0;
4407
    }
4408

    
4409
    if(MB_MBAFF){
4410
        h->ref_count[0] <<= 1;
4411
        h->ref_count[1] <<= 1;
4412
    }
4413

    
4414
    fill_caches(h, mb_type, 0);
4415

    
4416
    //mb_pred
4417
    if(IS_INTRA(mb_type)){
4418
        int pred_mode;
4419
//            init_top_left_availability(h);
4420
        if(IS_INTRA4x4(mb_type)){
4421
            int i;
4422
            int di = 1;
4423
            if(dct8x8_allowed && get_bits1(&s->gb)){
4424
                mb_type |= MB_TYPE_8x8DCT;
4425
                di = 4;
4426
            }
4427

    
4428
//                fill_intra4x4_pred_table(h);
4429
            for(i=0; i<16; i+=di){
4430
                int mode= pred_intra_mode(h, i);
4431

    
4432
                if(!get_bits1(&s->gb)){
4433
                    const int rem_mode= get_bits(&s->gb, 3);
4434
                    mode = rem_mode + (rem_mode >= mode);
4435
                }
4436

    
4437
                if(di==4)
4438
                    fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
4439
                else
4440
                    h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;
4441
            }
4442
            write_back_intra_pred_mode(h);
4443
            if( check_intra4x4_pred_mode(h) < 0)
4444
                return -1;
4445
        }else{
4446
            h->intra16x16_pred_mode= check_intra_pred_mode(h, h->intra16x16_pred_mode);
4447
            if(h->intra16x16_pred_mode < 0)
4448
                return -1;
4449
        }
4450
        if(CHROMA){
4451
            pred_mode= check_intra_pred_mode(h, get_ue_golomb(&s->gb));
4452
            if(pred_mode < 0)
4453
                return -1;
4454
            h->chroma_pred_mode= pred_mode;
4455
        }
4456
    }else if(partition_count==4){
4457
        int i, j, sub_partition_count[4], list, ref[2][4];
4458

    
4459
        if(h->slice_type_nos == FF_B_TYPE){
4460
            for(i=0; i<4; i++){
4461
                h->sub_mb_type[i]= get_ue_golomb(&s->gb);
4462