Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h264.c @ c009df3f

History | View | Annotate | Download (150 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 library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 *
19
 */
20
 
21
/**
22
 * @file h264.c
23
 * H.264 / AVC / MPEG4 part10 codec.
24
 * @author Michael Niedermayer <michaelni@gmx.at>
25
 */
26

    
27
#include "common.h"
28
#include "dsputil.h"
29
#include "avcodec.h"
30
#include "mpegvideo.h"
31
#include "h264data.h"
32
#include "golomb.h"
33

    
34
#undef NDEBUG
35
#include <assert.h>
36

    
37
#define interlaced_dct interlaced_dct_is_a_bad_name
38
#define mb_intra mb_intra_isnt_initalized_see_mb_type
39

    
40
#define LUMA_DC_BLOCK_INDEX   25
41
#define CHROMA_DC_BLOCK_INDEX 26
42

    
43
#define CHROMA_DC_COEFF_TOKEN_VLC_BITS 8
44
#define COEFF_TOKEN_VLC_BITS           8
45
#define TOTAL_ZEROS_VLC_BITS           9
46
#define CHROMA_DC_TOTAL_ZEROS_VLC_BITS 3
47
#define RUN_VLC_BITS                   3
48
#define RUN7_VLC_BITS                  6
49

    
50
#define MAX_SPS_COUNT 32
51
#define MAX_PPS_COUNT 256
52

    
53
#define MAX_MMCO_COUNT 66
54

    
55
/**
56
 * Sequence parameter set
57
 */
58
typedef struct SPS{
59
    
60
    int profile_idc;
61
    int level_idc;
62
    int multiple_slice_groups;         ///< more_than_one_slice_group_allowed_flag
63
    int arbitrary_slice_order;         ///< arbitrary_slice_order_allowed_flag
64
    int redundant_slices;              ///< redundant_slices_allowed_flag
65
    int log2_max_frame_num;            ///< log2_max_frame_num_minus4 + 4
66
    int poc_type;                      ///< pic_order_cnt_type
67
    int log2_max_poc_lsb;              ///< log2_max_pic_order_cnt_lsb_minus4
68
    int delta_pic_order_always_zero_flag;
69
    int offset_for_non_ref_pic;
70
    int offset_for_top_to_bottom_field;
71
    int poc_cycle_length;              ///< num_ref_frames_in_pic_order_cnt_cycle
72
    int ref_frame_count;               ///< num_ref_frames
73
    int required_frame_num_update_behaviour_flag;
74
    int mb_width;                      ///< frame_width_in_mbs_minus1 + 1
75
    int mb_height;                     ///< frame_height_in_mbs_minus1 + 1
76
    int frame_mbs_only_flag;
77
    int mb_aff;                        ///<mb_adaptive_frame_field_flag
78
    int direct_8x8_inference_flag;
79
    int vui_parameters_present_flag;
80
    int sar_width;
81
    int sar_height;
82
    short offset_for_ref_frame[256]; //FIXME dyn aloc?
83
}SPS;
84

    
85
/**
86
 * Picture parameter set
87
 */
88
typedef struct PPS{
89
    int sps_id;
90
    int cabac;                  ///< entropy_coding_mode_flag
91
    int pic_order_present;      ///< pic_order_present_flag
92
    int slice_group_count;      ///< num_slice_groups_minus1 + 1
93
    int mb_slice_group_map_type;
94
    int ref_count[2];           ///< num_ref_idx_l0/1_active_minus1 + 1
95
    int weighted_pred;          ///< weighted_pred_flag
96
    int weighted_bipred_idc;
97
    int init_qp;                ///< pic_init_qp_minus26 + 26
98
    int init_qs;                ///< pic_init_qs_minus26 + 26
99
    int chroma_qp_index_offset;
100
    int deblocking_filter_parameters_present; ///< deblocking_filter_parameters_present_flag
101
    int constrained_intra_pred; ///< constrained_intra_pred_flag
102
    int redundant_pic_cnt_present; ///< redundant_pic_cnt_present_flag
103
    int crop;                   ///< frame_cropping_flag
104
    int crop_left;              ///< frame_cropping_rect_left_offset
105
    int crop_right;             ///< frame_cropping_rect_right_offset
106
    int crop_top;               ///< frame_cropping_rect_top_offset
107
    int crop_bottom;            ///< frame_cropping_rect_bottom_offset
108
}PPS;
109

    
110
/**
111
 * Memory management control operation opcode.
112
 */
113
typedef enum MMCOOpcode{
114
    MMCO_END=0,
115
    MMCO_SHORT2UNUSED,
116
    MMCO_LONG2UNUSED,
117
    MMCO_SHORT2LONG,
118
    MMCO_SET_MAX_LONG,
119
    MMCO_RESET, 
120
    MMCO_LONG,
121
} MMCOOpcode;
122

    
123
/**
124
 * Memory management control operation.
125
 */
126
typedef struct MMCO{
127
    MMCOOpcode opcode;
128
    int short_frame_num;
129
    int long_index;
130
} MMCO;
131

    
132
/**
133
 * H264Context
134
 */
135
typedef struct H264Context{
136
    MpegEncContext s;
137
    int nal_ref_idc;        
138
    int nal_unit_type;
139
#define NAL_SLICE                1
140
#define NAL_DPA                        2
141
#define NAL_DPB                        3
142
#define NAL_DPC                        4
143
#define NAL_IDR_SLICE                5
144
#define NAL_SEI                        6
145
#define NAL_SPS                        7
146
#define NAL_PPS                        8
147
#define NAL_PICTURE_DELIMITER        9
148
#define NAL_FILTER_DATA                10
149
    uint8_t *rbsp_buffer;
150
    int rbsp_buffer_size;
151

    
152
    int chroma_qp; //QPc
153

    
154
    int prev_mb_skiped; //FIXME remove (IMHO not used)
155

    
156
    //prediction stuff
157
    int chroma_pred_mode;
158
    int intra16x16_pred_mode;
159
    
160
    int8_t intra4x4_pred_mode_cache[5*8];
161
    int8_t (*intra4x4_pred_mode)[8];
162
    void (*pred4x4  [9+3])(uint8_t *src, uint8_t *topright, int stride);//FIXME move to dsp?
163
    void (*pred8x8  [4+3])(uint8_t *src, int stride);
164
    void (*pred16x16[4+3])(uint8_t *src, int stride);
165
    unsigned int topleft_samples_available;
166
    unsigned int top_samples_available;
167
    unsigned int topright_samples_available;
168
    unsigned int left_samples_available;
169

    
170
    /**
171
     * non zero coeff count cache.
172
     * is 64 if not available.
173
     */
174
    uint8_t non_zero_count_cache[6*8];
175
    uint8_t (*non_zero_count)[16];
176

    
177
    /**
178
     * Motion vector cache.
179
     */
180
    int16_t mv_cache[2][5*8][2];
181
    int8_t ref_cache[2][5*8];
182
#define LIST_NOT_USED -1 //FIXME rename?
183
#define PART_NOT_AVAILABLE -2
184
    
185
    /**
186
     * is 1 if the specific list MV&references are set to 0,0,-2.
187
     */
188
    int mv_cache_clean[2];
189

    
190
    int block_offset[16+8];
191
    int chroma_subblock_offset[16]; //FIXME remove
192
    
193
    uint16_t *mb2b_xy; //FIXME are these 4 a good idea?
194
    uint16_t *mb2b8_xy;
195
    int b_stride;
196
    int b8_stride;
197

    
198
    int halfpel_flag;
199
    int thirdpel_flag;
200

    
201
    SPS sps_buffer[MAX_SPS_COUNT];
202
    SPS sps; ///< current sps
203
    
204
    PPS pps_buffer[MAX_PPS_COUNT];
205
    /**
206
     * current pps
207
     */
208
    PPS pps; //FIXME move tp Picture perhaps? (->no) do we need that?
209

    
210
    int slice_num;
211
    uint8_t *slice_table_base;
212
    uint8_t *slice_table;      ///< slice_table_base + mb_stride + 1
213
    int slice_type;
214
    int slice_type_fixed;
215
    
216
    //interlacing specific flags
217
    int mb_field_decoding_flag;
218
    
219
    int sub_mb_type[4];
220
    
221
    //POC stuff
222
    int poc_lsb;
223
    int poc_msb;
224
    int delta_poc_bottom;
225
    int delta_poc[2];
226
    int frame_num;
227
    int prev_poc_msb;             ///< poc_msb of the last reference pic for POC type 0
228
    int prev_poc_lsb;             ///< poc_lsb of the last reference pic for POC type 0
229
    int frame_num_offset;         ///< for POC type 2
230
    int prev_frame_num_offset;    ///< for POC type 2
231
    int prev_frame_num;           ///< frame_num of the last pic for POC type 1/2
232

    
233
    /**
234
     * frame_num for frames or 2*frame_num for field pics.
235
     */
236
    int curr_pic_num;
237
    
238
    /**
239
     * max_frame_num or 2*max_frame_num for field pics.
240
     */
241
    int max_pic_num;
242

    
243
    //Weighted pred stuff
244
    int luma_log2_weight_denom;
245
    int chroma_log2_weight_denom;
246
    int luma_weight[2][16];
247
    int luma_offset[2][16];
248
    int chroma_weight[2][16][2];
249
    int chroma_offset[2][16][2];
250
   
251
    //deblock
252
    int disable_deblocking_filter_idc;
253
    int slice_alpha_c0_offset_div2;
254
    int slice_beta_offset_div2;
255
     
256
    int redundant_pic_count;
257
    
258
    int direct_spatial_mv_pred;
259

    
260
    /**
261
     * num_ref_idx_l0/1_active_minus1 + 1
262
     */
263
    int ref_count[2];// FIXME split for AFF
264
    Picture *short_ref[16];
265
    Picture *long_ref[16];
266
    Picture default_ref_list[2][32];
267
    Picture ref_list[2][32]; //FIXME size?
268
    Picture field_ref_list[2][32]; //FIXME size?
269
    
270
    /**
271
     * memory management control operations buffer.
272
     */
273
    MMCO mmco[MAX_MMCO_COUNT];
274
    int mmco_index;
275
    
276
    int long_ref_count;  ///< number of actual long term references
277
    int short_ref_count; ///< number of actual short term references
278
    
279
    //data partitioning
280
    GetBitContext intra_gb;
281
    GetBitContext inter_gb;
282
    GetBitContext *intra_gb_ptr;
283
    GetBitContext *inter_gb_ptr;
284
    
285
    DCTELEM mb[16*24] __align8;
286
}H264Context;
287

    
288
static VLC coeff_token_vlc[4];
289
static VLC chroma_dc_coeff_token_vlc;
290

    
291
static VLC total_zeros_vlc[15];
292
static VLC chroma_dc_total_zeros_vlc[3];
293

    
294
static VLC run_vlc[6];
295
static VLC run7_vlc;
296

    
297
static void svq3_luma_dc_dequant_idct_c(DCTELEM *block, int qp);
298
static void svq3_add_idct_c(uint8_t *dst, DCTELEM *block, int stride, int qp, int dc);
299

    
300
static inline uint32_t pack16to32(int a, int b){
301
#ifdef WORDS_BIGENDIAN
302
   return (b&0xFFFF) + (a<<16);
303
#else
304
   return (a&0xFFFF) + (b<<16);
305
#endif
306
}
307

    
308
/**
309
 * fill a rectangle.
310
 * @param h height of the recatangle, should be a constant
311
 * @param w width of the recatangle, should be a constant
312
 * @param size the size of val (1 or 4), should be a constant
313
 */
314
static inline void fill_rectangle(void *vp, int w, int h, int stride, uint32_t val, int size){ //FIXME ensure this IS inlined
315
    uint8_t *p= (uint8_t*)vp;
316
    assert(size==1 || size==4);
317
    
318
    w      *= size;
319
    stride *= size;
320
    
321
//FIXME check what gcc generates for 64 bit on x86 and possible write a 32 bit ver of it
322
    if(w==2 && h==2){
323
        *(uint16_t*)(p + 0)=
324
        *(uint16_t*)(p + stride)= size==4 ? val : val*0x0101;
325
    }else if(w==2 && h==4){
326
        *(uint16_t*)(p + 0*stride)=
327
        *(uint16_t*)(p + 1*stride)=
328
        *(uint16_t*)(p + 2*stride)=
329
        *(uint16_t*)(p + 3*stride)= size==4 ? val : val*0x0101;
330
    }else if(w==4 && h==1){
331
        *(uint32_t*)(p + 0*stride)= size==4 ? val : val*0x01010101;
332
    }else if(w==4 && h==2){
333
        *(uint32_t*)(p + 0*stride)=
334
        *(uint32_t*)(p + 1*stride)= size==4 ? val : val*0x01010101;
335
    }else if(w==4 && h==4){
336
        *(uint32_t*)(p + 0*stride)=
337
        *(uint32_t*)(p + 1*stride)=
338
        *(uint32_t*)(p + 2*stride)=
339
        *(uint32_t*)(p + 3*stride)= size==4 ? val : val*0x01010101;
340
    }else if(w==8 && h==1){
341
        *(uint32_t*)(p + 0)=
342
        *(uint32_t*)(p + 4)= size==4 ? val : val*0x01010101;
343
    }else if(w==8 && h==2){
344
        *(uint32_t*)(p + 0 + 0*stride)=
345
        *(uint32_t*)(p + 4 + 0*stride)=
346
        *(uint32_t*)(p + 0 + 1*stride)=
347
        *(uint32_t*)(p + 4 + 1*stride)=  size==4 ? val : val*0x01010101;
348
    }else if(w==8 && h==4){
349
        *(uint64_t*)(p + 0*stride)=
350
        *(uint64_t*)(p + 1*stride)=
351
        *(uint64_t*)(p + 2*stride)=
352
        *(uint64_t*)(p + 3*stride)= size==4 ? val*0x0100000001ULL : val*0x0101010101010101ULL;
353
    }else if(w==16 && h==2){
354
        *(uint64_t*)(p + 0+0*stride)=
355
        *(uint64_t*)(p + 8+0*stride)=
356
        *(uint64_t*)(p + 0+1*stride)=
357
        *(uint64_t*)(p + 8+1*stride)= size==4 ? val*0x0100000001ULL : val*0x0101010101010101ULL;
358
    }else if(w==16 && h==4){
359
        *(uint64_t*)(p + 0+0*stride)=
360
        *(uint64_t*)(p + 8+0*stride)=
361
        *(uint64_t*)(p + 0+1*stride)=
362
        *(uint64_t*)(p + 8+1*stride)=
363
        *(uint64_t*)(p + 0+2*stride)=
364
        *(uint64_t*)(p + 8+2*stride)=
365
        *(uint64_t*)(p + 0+3*stride)=
366
        *(uint64_t*)(p + 8+3*stride)= size==4 ? val*0x0100000001ULL : val*0x0101010101010101ULL;
367
    }else
368
        assert(0);
369
}
370

    
371
static inline void fill_caches(H264Context *h, int mb_type){
372
    MpegEncContext * const s = &h->s;
373
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
374
    int topleft_xy, top_xy, topright_xy, left_xy[2];
375
    int topleft_type, top_type, topright_type, left_type[2];
376
    int left_block[4];
377
    int i;
378

    
379
    //wow what a mess, why didnt they simplify the interlacing&intra stuff, i cant imagine that these complex rules are worth it 
380
    
381
    if(h->sps.mb_aff){
382
    //FIXME
383
    }else{
384
        topleft_xy = mb_xy-1 - s->mb_stride;
385
        top_xy     = mb_xy   - s->mb_stride;
386
        topright_xy= mb_xy+1 - s->mb_stride;
387
        left_xy[0]   = mb_xy-1;
388
        left_xy[1]   = mb_xy-1;
389
        left_block[0]= 0;
390
        left_block[1]= 1;
391
        left_block[2]= 2;
392
        left_block[3]= 3;
393
    }
394

    
395
    topleft_type = h->slice_table[topleft_xy ] == h->slice_num ? s->current_picture.mb_type[topleft_xy] : 0;
396
    top_type     = h->slice_table[top_xy     ] == h->slice_num ? s->current_picture.mb_type[top_xy]     : 0;
397
    topright_type= h->slice_table[topright_xy] == h->slice_num ? s->current_picture.mb_type[topright_xy]: 0;
398
    left_type[0] = h->slice_table[left_xy[0] ] == h->slice_num ? s->current_picture.mb_type[left_xy[0]] : 0;
399
    left_type[1] = h->slice_table[left_xy[1] ] == h->slice_num ? s->current_picture.mb_type[left_xy[1]] : 0;
400

    
401
    if(IS_INTRA(mb_type)){
402
        h->topleft_samples_available= 
403
        h->top_samples_available= 
404
        h->left_samples_available= 0xFFFF;
405
        h->topright_samples_available= 0xEEEA;
406

    
407
        if(!IS_INTRA(top_type) && (top_type==0 || h->pps.constrained_intra_pred)){
408
            h->topleft_samples_available= 0xB3FF;
409
            h->top_samples_available= 0x33FF;
410
            h->topright_samples_available= 0x26EA;
411
        }
412
        for(i=0; i<2; i++){
413
            if(!IS_INTRA(left_type[i]) && (left_type[i]==0 || h->pps.constrained_intra_pred)){
414
                h->topleft_samples_available&= 0xDF5F;
415
                h->left_samples_available&= 0x5F5F;
416
            }
417
        }
418
        
419
        if(!IS_INTRA(topleft_type) && (topleft_type==0 || h->pps.constrained_intra_pred))
420
            h->topleft_samples_available&= 0x7FFF;
421
        
422
        if(!IS_INTRA(topright_type) && (topright_type==0 || h->pps.constrained_intra_pred))
423
            h->topright_samples_available&= 0xFBFF;
424
    
425
        if(IS_INTRA4x4(mb_type)){
426
            if(IS_INTRA4x4(top_type)){
427
                h->intra4x4_pred_mode_cache[4+8*0]= h->intra4x4_pred_mode[top_xy][4];
428
                h->intra4x4_pred_mode_cache[5+8*0]= h->intra4x4_pred_mode[top_xy][5];
429
                h->intra4x4_pred_mode_cache[6+8*0]= h->intra4x4_pred_mode[top_xy][6];
430
                h->intra4x4_pred_mode_cache[7+8*0]= h->intra4x4_pred_mode[top_xy][3];
431
            }else{
432
                int pred;
433
                if(IS_INTRA16x16(top_type) || (IS_INTER(top_type) && !h->pps.constrained_intra_pred))
434
                    pred= 2;
435
                else{
436
                    pred= -1;
437
                }
438
                h->intra4x4_pred_mode_cache[4+8*0]=
439
                h->intra4x4_pred_mode_cache[5+8*0]=
440
                h->intra4x4_pred_mode_cache[6+8*0]=
441
                h->intra4x4_pred_mode_cache[7+8*0]= pred;
442
            }
443
            for(i=0; i<2; i++){
444
                if(IS_INTRA4x4(left_type[i])){
445
                    h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[0+2*i]];
446
                    h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[1+2*i]];
447
                }else{
448
                    int pred;
449
                    if(IS_INTRA16x16(left_type[i]) || (IS_INTER(left_type[i]) && !h->pps.constrained_intra_pred))
450
                        pred= 2;
451
                    else{
452
                        pred= -1;
453
                    }
454
                    h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]=
455
                    h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= pred;
456
                }
457
            }
458
        }
459
    }
460
    
461
    
462
/*
463
0 . T T. T T T T 
464
1 L . .L . . . . 
465
2 L . .L . . . . 
466
3 . T TL . . . . 
467
4 L . .L . . . . 
468
5 L . .. . . . . 
469
*/
470
//FIXME constraint_intra_pred & partitioning & nnz (lets hope this is just a typo in the spec)
471
    if(top_type){
472
        h->non_zero_count_cache[4+8*0]= h->non_zero_count[top_xy][0];
473
        h->non_zero_count_cache[5+8*0]= h->non_zero_count[top_xy][1];
474
        h->non_zero_count_cache[6+8*0]= h->non_zero_count[top_xy][2];
475
        h->non_zero_count_cache[7+8*0]= h->non_zero_count[top_xy][3];
476
    
477
        h->non_zero_count_cache[1+8*0]= h->non_zero_count[top_xy][7];
478
        h->non_zero_count_cache[2+8*0]= h->non_zero_count[top_xy][8];
479
    
480
        h->non_zero_count_cache[1+8*3]= h->non_zero_count[top_xy][10];
481
        h->non_zero_count_cache[2+8*3]= h->non_zero_count[top_xy][11];
482
    }else{
483
        h->non_zero_count_cache[4+8*0]=      
484
        h->non_zero_count_cache[5+8*0]=
485
        h->non_zero_count_cache[6+8*0]=
486
        h->non_zero_count_cache[7+8*0]=
487
    
488
        h->non_zero_count_cache[1+8*0]=
489
        h->non_zero_count_cache[2+8*0]=
490
    
491
        h->non_zero_count_cache[1+8*3]=
492
        h->non_zero_count_cache[2+8*3]= 64;
493
    }
494
    
495
    if(left_type[0]){
496
        h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][6];
497
        h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][5];
498
        h->non_zero_count_cache[0+8*1]= h->non_zero_count[left_xy[0]][9]; //FIXME left_block
499
        h->non_zero_count_cache[0+8*4]= h->non_zero_count[left_xy[0]][12];
500
    }else{
501
        h->non_zero_count_cache[3+8*1]= 
502
        h->non_zero_count_cache[3+8*2]= 
503
        h->non_zero_count_cache[0+8*1]= 
504
        h->non_zero_count_cache[0+8*4]= 64;
505
    }
506
    
507
    if(left_type[1]){
508
        h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[1]][4];
509
        h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[1]][3];
510
        h->non_zero_count_cache[0+8*2]= h->non_zero_count[left_xy[1]][8];
511
        h->non_zero_count_cache[0+8*5]= h->non_zero_count[left_xy[1]][11];
512
    }else{
513
        h->non_zero_count_cache[3+8*3]= 
514
        h->non_zero_count_cache[3+8*4]= 
515
        h->non_zero_count_cache[0+8*2]= 
516
        h->non_zero_count_cache[0+8*5]= 64;
517
    }
518
    
519
#if 1
520
    if(IS_INTER(mb_type)){
521
        int list;
522
        for(list=0; list<2; list++){
523
            if((!IS_8X8(mb_type)) && !USES_LIST(mb_type, list)){
524
                /*if(!h->mv_cache_clean[list]){
525
                    memset(h->mv_cache [list],  0, 8*5*2*sizeof(int16_t)); //FIXME clean only input? clean at all?
526
                    memset(h->ref_cache[list], PART_NOT_AVAILABLE, 8*5*sizeof(int8_t));
527
                    h->mv_cache_clean[list]= 1;
528
                }*/
529
                continue; //FIXME direct mode ...
530
            }
531
            h->mv_cache_clean[list]= 0;
532
            
533
            if(IS_INTER(topleft_type)){
534
                const int b_xy = h->mb2b_xy[topleft_xy] + 3 + 3*h->b_stride;
535
                const int b8_xy= h->mb2b8_xy[topleft_xy] + 1 + h->b8_stride;
536
                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
537
                h->ref_cache[list][scan8[0] - 1 - 1*8]= s->current_picture.ref_index[list][b8_xy];
538
            }else{
539
                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= 0;
540
                h->ref_cache[list][scan8[0] - 1 - 1*8]= topleft_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
541
            }
542
            
543
            if(IS_INTER(top_type)){
544
                const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
545
                const int b8_xy= h->mb2b8_xy[top_xy] + h->b8_stride;
546
                *(uint32_t*)h->mv_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 0];
547
                *(uint32_t*)h->mv_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 1];
548
                *(uint32_t*)h->mv_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 2];
549
                *(uint32_t*)h->mv_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 3];
550
                h->ref_cache[list][scan8[0] + 0 - 1*8]=
551
                h->ref_cache[list][scan8[0] + 1 - 1*8]= s->current_picture.ref_index[list][b8_xy + 0];
552
                h->ref_cache[list][scan8[0] + 2 - 1*8]=
553
                h->ref_cache[list][scan8[0] + 3 - 1*8]= s->current_picture.ref_index[list][b8_xy + 1];
554
            }else{
555
                *(uint32_t*)h->mv_cache [list][scan8[0] + 0 - 1*8]= 
556
                *(uint32_t*)h->mv_cache [list][scan8[0] + 1 - 1*8]= 
557
                *(uint32_t*)h->mv_cache [list][scan8[0] + 2 - 1*8]= 
558
                *(uint32_t*)h->mv_cache [list][scan8[0] + 3 - 1*8]= 0;
559
                *(uint32_t*)&h->ref_cache[list][scan8[0] + 0 - 1*8]= ((top_type ? LIST_NOT_USED : PART_NOT_AVAILABLE)&0xFF)*0x01010101;
560
            }
561

    
562
            if(IS_INTER(topright_type)){
563
                const int b_xy= h->mb2b_xy[topright_xy] + 3*h->b_stride;
564
                const int b8_xy= h->mb2b8_xy[topright_xy] + h->b8_stride;
565
                *(uint32_t*)h->mv_cache[list][scan8[0] + 4 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
566
                h->ref_cache[list][scan8[0] + 4 - 1*8]= s->current_picture.ref_index[list][b8_xy];
567
            }else{
568
                *(uint32_t*)h->mv_cache [list][scan8[0] + 4 - 1*8]= 0;
569
                h->ref_cache[list][scan8[0] + 4 - 1*8]= topright_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
570
            }
571
            
572
            //FIXME unify cleanup or sth
573
            if(IS_INTER(left_type[0])){
574
                const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
575
                const int b8_xy= h->mb2b8_xy[left_xy[0]] + 1;
576
                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 + 0*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[0]];
577
                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 + 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[1]];
578
                h->ref_cache[list][scan8[0] - 1 + 0*8]= 
579
                h->ref_cache[list][scan8[0] - 1 + 1*8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[0]>>1)];
580
            }else{
581
                *(uint32_t*)h->mv_cache [list][scan8[0] - 1 + 0*8]=
582
                *(uint32_t*)h->mv_cache [list][scan8[0] - 1 + 1*8]= 0;
583
                h->ref_cache[list][scan8[0] - 1 + 0*8]=
584
                h->ref_cache[list][scan8[0] - 1 + 1*8]= left_type[0] ? LIST_NOT_USED : PART_NOT_AVAILABLE;
585
            }
586
            
587
            if(IS_INTER(left_type[1])){
588
                const int b_xy= h->mb2b_xy[left_xy[1]] + 3;
589
                const int b8_xy= h->mb2b8_xy[left_xy[1]] + 1;
590
                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 + 2*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[2]];
591
                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 + 3*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[3]];
592
                h->ref_cache[list][scan8[0] - 1 + 2*8]= 
593
                h->ref_cache[list][scan8[0] - 1 + 3*8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[2]>>1)];
594
            }else{
595
                *(uint32_t*)h->mv_cache [list][scan8[0] - 1 + 2*8]=
596
                *(uint32_t*)h->mv_cache [list][scan8[0] - 1 + 3*8]= 0;
597
                h->ref_cache[list][scan8[0] - 1 + 2*8]=
598
                h->ref_cache[list][scan8[0] - 1 + 3*8]= left_type[0] ? LIST_NOT_USED : PART_NOT_AVAILABLE;
599
            }
600

    
601
            h->ref_cache[list][scan8[5 ]+1] = 
602
            h->ref_cache[list][scan8[7 ]+1] = 
603
            h->ref_cache[list][scan8[13]+1] =  //FIXME remove past 3 (init somewher else)
604
            h->ref_cache[list][scan8[4 ]] = 
605
            h->ref_cache[list][scan8[12]] = PART_NOT_AVAILABLE;
606
            *(uint32_t*)h->mv_cache [list][scan8[5 ]+1]=
607
            *(uint32_t*)h->mv_cache [list][scan8[7 ]+1]=
608
            *(uint32_t*)h->mv_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewher else)
609
            *(uint32_t*)h->mv_cache [list][scan8[4 ]]=
610
            *(uint32_t*)h->mv_cache [list][scan8[12]]= 0;
611
        }
612
//FIXME
613

    
614
    }
615
#endif
616
}
617

    
618
static inline void write_back_intra_pred_mode(H264Context *h){
619
    MpegEncContext * const s = &h->s;
620
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
621

    
622
    h->intra4x4_pred_mode[mb_xy][0]= h->intra4x4_pred_mode_cache[7+8*1];
623
    h->intra4x4_pred_mode[mb_xy][1]= h->intra4x4_pred_mode_cache[7+8*2];
624
    h->intra4x4_pred_mode[mb_xy][2]= h->intra4x4_pred_mode_cache[7+8*3];
625
    h->intra4x4_pred_mode[mb_xy][3]= h->intra4x4_pred_mode_cache[7+8*4];
626
    h->intra4x4_pred_mode[mb_xy][4]= h->intra4x4_pred_mode_cache[4+8*4];
627
    h->intra4x4_pred_mode[mb_xy][5]= h->intra4x4_pred_mode_cache[5+8*4];
628
    h->intra4x4_pred_mode[mb_xy][6]= h->intra4x4_pred_mode_cache[6+8*4];
629
}
630

    
631
/**
632
 * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
633
 */
634
static inline int check_intra4x4_pred_mode(H264Context *h){
635
    MpegEncContext * const s = &h->s;
636
    static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
637
    static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
638
    int i;
639
    
640
    if(!(h->top_samples_available&0x8000)){
641
        for(i=0; i<4; i++){
642
            int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
643
            if(status<0){
644
                fprintf(stderr, "top block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
645
                return -1;
646
            } else if(status){
647
                h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
648
            }
649
        }
650
    }
651
    
652
    if(!(h->left_samples_available&0x8000)){
653
        for(i=0; i<4; i++){
654
            int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
655
            if(status<0){
656
                fprintf(stderr, "left block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
657
                return -1;
658
            } else if(status){
659
                h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
660
            }
661
        }
662
    }
663

    
664
    return 0;
665
} //FIXME cleanup like next
666

    
667
/**
668
 * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
669
 */
670
static inline int check_intra_pred_mode(H264Context *h, int mode){
671
    MpegEncContext * const s = &h->s;
672
    static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
673
    static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
674
    
675
    if(!(h->top_samples_available&0x8000)){
676
        mode= top[ mode ];
677
        if(mode<0){
678
            fprintf(stderr, "top block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
679
            return -1;
680
        }
681
    }
682
    
683
    if(!(h->left_samples_available&0x8000)){
684
        mode= left[ mode ];
685
        if(mode<0){
686
            fprintf(stderr, "left block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
687
            return -1;
688
        } 
689
    }
690

    
691
    return mode;
692
}
693

    
694
/**
695
 * gets the predicted intra4x4 prediction mode.
696
 */
697
static inline int pred_intra_mode(H264Context *h, int n){
698
    const int index8= scan8[n];
699
    const int left= h->intra4x4_pred_mode_cache[index8 - 1];
700
    const int top = h->intra4x4_pred_mode_cache[index8 - 8];
701
    const int min= FFMIN(left, top);
702

    
703
    tprintf("mode:%d %d min:%d\n", left ,top, min);
704

    
705
    if(min<0) return DC_PRED;
706
    else      return min;
707
}
708

    
709
static inline void write_back_non_zero_count(H264Context *h){
710
    MpegEncContext * const s = &h->s;
711
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
712

    
713
    h->non_zero_count[mb_xy][0]= h->non_zero_count_cache[4+8*4];
714
    h->non_zero_count[mb_xy][1]= h->non_zero_count_cache[5+8*4];
715
    h->non_zero_count[mb_xy][2]= h->non_zero_count_cache[6+8*4];
716
    h->non_zero_count[mb_xy][3]= h->non_zero_count_cache[7+8*4];
717
    h->non_zero_count[mb_xy][4]= h->non_zero_count_cache[7+8*3];
718
    h->non_zero_count[mb_xy][5]= h->non_zero_count_cache[7+8*2];
719
    h->non_zero_count[mb_xy][6]= h->non_zero_count_cache[7+8*1];
720
    
721
    h->non_zero_count[mb_xy][7]= h->non_zero_count_cache[1+8*2];
722
    h->non_zero_count[mb_xy][8]= h->non_zero_count_cache[2+8*2];
723
    h->non_zero_count[mb_xy][9]= h->non_zero_count_cache[2+8*1];
724

    
725
    h->non_zero_count[mb_xy][10]=h->non_zero_count_cache[1+8*5];
726
    h->non_zero_count[mb_xy][11]=h->non_zero_count_cache[2+8*5];
727
    h->non_zero_count[mb_xy][12]=h->non_zero_count_cache[2+8*4];
728
}
729

    
730
/**
731
 * gets the predicted number of non zero coefficients.
732
 * @param n block index
733
 */
734
static inline int pred_non_zero_count(H264Context *h, int n){
735
    const int index8= scan8[n];
736
    const int left= h->non_zero_count_cache[index8 - 1];
737
    const int top = h->non_zero_count_cache[index8 - 8];
738
    int i= left + top;
739
    
740
    if(i<64) i= (i+1)>>1;
741

    
742
    tprintf("pred_nnz L%X T%X n%d s%d P%X\n", left, top, n, scan8[n], i&31);
743

    
744
    return i&31;
745
}
746

    
747
static inline int fetch_diagonal_mv(H264Context *h, const int16_t **C, int i, int list, int part_width){
748
    const int topright_ref= h->ref_cache[list][ i - 8 + part_width ];
749

    
750
    if(topright_ref != PART_NOT_AVAILABLE){
751
        *C= h->mv_cache[list][ i - 8 + part_width ];
752
        return topright_ref;
753
    }else{
754
        tprintf("topright MV not available\n");
755

    
756
        *C= h->mv_cache[list][ i - 8 - 1 ];
757
        return h->ref_cache[list][ i - 8 - 1 ];
758
    }
759
}
760

    
761
/**
762
 * gets the predicted MV.
763
 * @param n the block index
764
 * @param part_width the width of the partition (4, 8,16) -> (1, 2, 4)
765
 * @param mx the x component of the predicted motion vector
766
 * @param my the y component of the predicted motion vector
767
 */
768
static inline void pred_motion(H264Context * const h, int n, int part_width, int list, int ref, int * const mx, int * const my){
769
    const int index8= scan8[n];
770
    const int top_ref=      h->ref_cache[list][ index8 - 8 ];
771
    const int left_ref=     h->ref_cache[list][ index8 - 1 ];
772
    const int16_t * const A= h->mv_cache[list][ index8 - 1 ];
773
    const int16_t * const B= h->mv_cache[list][ index8 - 8 ];
774
    const int16_t * C;
775
    int diagonal_ref, match_count;
776

    
777
    assert(part_width==1 || part_width==2 || part_width==4);
778

    
779
/* mv_cache
780
  B . . A T T T T 
781
  U . . L . . , .
782
  U . . L . . . .
783
  U . . L . . , .
784
  . . . L . . . .
785
*/
786

    
787
    diagonal_ref= fetch_diagonal_mv(h, &C, index8, list, part_width);
788
    match_count= (diagonal_ref==ref) + (top_ref==ref) + (left_ref==ref);
789
    
790
    if(match_count > 1){ //most common
791
        *mx= mid_pred(A[0], B[0], C[0]);
792
        *my= mid_pred(A[1], B[1], C[1]);
793
    }else if(match_count==1){
794
        if(left_ref==ref){
795
            *mx= A[0];
796
            *my= A[1];        
797
        }else if(top_ref==ref){
798
            *mx= B[0];
799
            *my= B[1];        
800
        }else{
801
            *mx= C[0];
802
            *my= C[1];        
803
        }
804
    }else{
805
        if(top_ref == PART_NOT_AVAILABLE && diagonal_ref == PART_NOT_AVAILABLE && left_ref != PART_NOT_AVAILABLE){
806
            *mx= A[0];
807
            *my= A[1];        
808
        }else{
809
            *mx= mid_pred(A[0], B[0], C[0]);
810
            *my= mid_pred(A[1], B[1], C[1]);
811
        }
812
    }
813
        
814
    tprintf("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);
815
}
816

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

    
828
        tprintf("pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d", top_ref, B[0], B[1], h->s.mb_x, h->s.mb_y, n, list);
829
        
830
        if(top_ref == ref){
831
            *mx= B[0];
832
            *my= B[1];
833
            return;
834
        }
835
    }else{
836
        const int left_ref=     h->ref_cache[list][ scan8[8] - 1 ];
837
        const int16_t * const A= h->mv_cache[list][ scan8[8] - 1 ];
838
        
839
        tprintf("pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d", left_ref, A[0], A[1], h->s.mb_x, h->s.mb_y, n, list);
840

    
841
        if(left_ref == ref){
842
            *mx= A[0];
843
            *my= A[1];
844
            return;
845
        }
846
    }
847

    
848
    //RARE
849
    pred_motion(h, n, 4, list, ref, mx, my);
850
}
851

    
852
/**
853
 * gets the directionally predicted 8x16 MV.
854
 * @param n the block index
855
 * @param mx the x component of the predicted motion vector
856
 * @param my the y component of the predicted motion vector
857
 */
858
static inline void pred_8x16_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
859
    if(n==0){
860
        const int left_ref=      h->ref_cache[list][ scan8[0] - 1 ];
861
        const int16_t * const A=  h->mv_cache[list][ scan8[0] - 1 ];
862
        
863
        tprintf("pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d", left_ref, A[0], A[1], h->s.mb_x, h->s.mb_y, n, list);
864

    
865
        if(left_ref == ref){
866
            *mx= A[0];
867
            *my= A[1];
868
            return;
869
        }
870
    }else{
871
        const int16_t * C;
872
        int diagonal_ref;
873

    
874
        diagonal_ref= fetch_diagonal_mv(h, &C, scan8[4], list, 2);
875
        
876
        tprintf("pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d", diagonal_ref, C[0], C[1], h->s.mb_x, h->s.mb_y, n, list);
877

    
878
        if(diagonal_ref == ref){ 
879
            *mx= C[0];
880
            *my= C[1];
881
            return;
882
        }
883
    }
884

    
885
    //RARE
886
    pred_motion(h, n, 2, list, ref, mx, my);
887
}
888

    
889
static inline void pred_pskip_motion(H264Context * const h, int * const mx, int * const my){
890
    const int top_ref = h->ref_cache[0][ scan8[0] - 8 ];
891
    const int left_ref= h->ref_cache[0][ scan8[0] - 1 ];
892

    
893
    tprintf("pred_pskip: (%d) (%d) at %2d %2d", top_ref, left_ref, h->s.mb_x, h->s.mb_y);
894

    
895
    if(top_ref == PART_NOT_AVAILABLE || left_ref == PART_NOT_AVAILABLE
896
       || (top_ref == 0  && *(uint32_t*)h->mv_cache[0][ scan8[0] - 8 ] == 0)
897
       || (left_ref == 0 && *(uint32_t*)h->mv_cache[0][ scan8[0] - 1 ] == 0)){
898
       
899
        *mx = *my = 0;
900
        return;
901
    }
902
        
903
    pred_motion(h, 0, 4, 0, 0, mx, my);
904

    
905
    return;
906
}
907

    
908
static inline void write_back_motion(H264Context *h, int mb_type){
909
    MpegEncContext * const s = &h->s;
910
    const int b_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
911
    const int b8_xy= 2*s->mb_x + 2*s->mb_y*h->b8_stride;
912
    int list;
913

    
914
    for(list=0; list<2; list++){
915
        int y;
916
        if((!IS_8X8(mb_type)) && !USES_LIST(mb_type, list)){
917
            if(1){ //FIXME skip or never read if mb_type doesnt use it
918
                for(y=0; y<4; y++){
919
                    *(uint64_t*)s->current_picture.motion_val[list][b_xy + 0 + y*h->b_stride]=
920
                    *(uint64_t*)s->current_picture.motion_val[list][b_xy + 2 + y*h->b_stride]= 0;
921
                }
922
                for(y=0; y<2; y++){
923
                    *(uint16_t*)s->current_picture.motion_val[list][b8_xy + y*h->b8_stride]= (LIST_NOT_USED&0xFF)*0x0101;
924
                }
925
            }
926
            continue; //FIXME direct mode ...
927
        }
928
        
929
        for(y=0; y<4; y++){
930
            *(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];
931
            *(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];
932
        }
933
        for(y=0; y<2; y++){
934
            s->current_picture.ref_index[list][b8_xy + 0 + y*h->b8_stride]= h->ref_cache[list][scan8[0]+0 + 16*y];
935
            s->current_picture.ref_index[list][b8_xy + 1 + y*h->b8_stride]= h->ref_cache[list][scan8[0]+2 + 16*y];
936
        }
937
    }
938
}
939

    
940
/**
941
 * Decodes a network abstraction layer unit.
942
 * @param consumed is the number of bytes used as input
943
 * @param length is the length of the array
944
 * @param dst_length is the number of decoded bytes FIXME here or a decode rbsp ttailing?
945
 * @returns decoded bytes, might be src+1 if no escapes 
946
 */
947
static uint8_t *decode_nal(H264Context *h, uint8_t *src, int *dst_length, int *consumed, int length){
948
    int i, si, di;
949
    uint8_t *dst;
950

    
951
//    src[0]&0x80;                //forbidden bit
952
    h->nal_ref_idc= src[0]>>5;
953
    h->nal_unit_type= src[0]&0x1F;
954

    
955
    src++; length--;
956
#if 0    
957
    for(i=0; i<length; i++)
958
        printf("%2X ", src[i]);
959
#endif
960
    for(i=0; i+1<length; i+=2){
961
        if(src[i]) continue;
962
        if(i>0 && src[i-1]==0) i--;
963
        if(i+2<length && src[i+1]==0 && src[i+2]<=3){
964
            if(src[i+2]!=3){
965
                /* startcode, so we must be past the end */
966
                length=i;
967
            }
968
            break;
969
        }
970
    }
971

    
972
    if(i>=length-1){ //no escaped 0
973
        *dst_length= length;
974
        *consumed= length+1; //+1 for the header
975
        return src; 
976
    }
977

    
978
    h->rbsp_buffer= av_fast_realloc(h->rbsp_buffer, &h->rbsp_buffer_size, length);
979
    dst= h->rbsp_buffer;
980

    
981
//printf("deoding esc\n");
982
    si=di=0;
983
    while(si<length){ 
984
        //remove escapes (very rare 1:2^22)
985
        if(si+2<length && src[si]==0 && src[si+1]==0 && src[si+2]<=3){
986
            if(src[si+2]==3){ //escape
987
                dst[di++]= 0;
988
                dst[di++]= 0;
989
                si+=3;
990
            }else //next start code
991
                break;
992
        }
993

    
994
        dst[di++]= src[si++];
995
    }
996

    
997
    *dst_length= di;
998
    *consumed= si + 1;//+1 for the header
999
//FIXME store exact number of bits in the getbitcontext (its needed for decoding)
1000
    return dst;
1001
}
1002

    
1003
/**
1004
 * @param src the data which should be escaped
1005
 * @param dst the target buffer, dst+1 == src is allowed as a special case
1006
 * @param length the length of the src data
1007
 * @param dst_length the length of the dst array
1008
 * @returns length of escaped data in bytes or -1 if an error occured
1009
 */
1010
static int encode_nal(H264Context *h, uint8_t *dst, uint8_t *src, int length, int dst_length){
1011
    int i, escape_count, si, di;
1012
    uint8_t *temp;
1013
    
1014
    assert(length>=0);
1015
    assert(dst_length>0);
1016
    
1017
    dst[0]= (h->nal_ref_idc<<5) + h->nal_unit_type;
1018

    
1019
    if(length==0) return 1;
1020

    
1021
    escape_count= 0;
1022
    for(i=0; i<length; i+=2){
1023
        if(src[i]) continue;
1024
        if(i>0 && src[i-1]==0) 
1025
            i--;
1026
        if(i+2<length && src[i+1]==0 && src[i+2]<=3){
1027
            escape_count++;
1028
            i+=2;
1029
        }
1030
    }
1031
    
1032
    if(escape_count==0){ 
1033
        if(dst+1 != src)
1034
            memcpy(dst+1, src, length);
1035
        return length + 1;
1036
    }
1037
    
1038
    if(length + escape_count + 1> dst_length)
1039
        return -1;
1040

    
1041
    //this should be damn rare (hopefully)
1042

    
1043
    h->rbsp_buffer= av_fast_realloc(h->rbsp_buffer, &h->rbsp_buffer_size, length + escape_count);
1044
    temp= h->rbsp_buffer;
1045
//printf("encoding esc\n");
1046
    
1047
    si= 0;
1048
    di= 0;
1049
    while(si < length){
1050
        if(si+2<length && src[si]==0 && src[si+1]==0 && src[si+2]<=3){
1051
            temp[di++]= 0; si++;
1052
            temp[di++]= 0; si++;
1053
            temp[di++]= 3; 
1054
            temp[di++]= src[si++];
1055
        }
1056
        else
1057
            temp[di++]= src[si++];
1058
    }
1059
    memcpy(dst+1, temp, length+escape_count);
1060
    
1061
    assert(di == length+escape_count);
1062
    
1063
    return di + 1;
1064
}
1065

    
1066
/**
1067
 * write 1,10,100,1000,... for alignment, yes its exactly inverse to mpeg4
1068
 */
1069
static void encode_rbsp_trailing(PutBitContext *pb){
1070
    int length;
1071
    put_bits(pb, 1, 1);
1072
    length= (-get_bit_count(pb))&7;
1073
    if(length) put_bits(pb, length, 0);
1074
}
1075

    
1076
/**
1077
 * identifies the exact end of the bitstream
1078
 * @return the length of the trailing, or 0 if damaged
1079
 */
1080
static int decode_rbsp_trailing(uint8_t *src){
1081
    int v= *src;
1082
    int r;
1083

    
1084
    tprintf("rbsp trailing %X\n", v);
1085

    
1086
    for(r=1; r<9; r++){
1087
        if(v&1) return r;
1088
        v>>=1;
1089
    }
1090
    return 0;
1091
}
1092

    
1093
/**
1094
 * idct tranforms the 16 dc values and dequantize them.
1095
 * @param qp quantization parameter
1096
 */
1097
static void h264_luma_dc_dequant_idct_c(DCTELEM *block, int qp){
1098
    const int qmul= dequant_coeff[qp][0];
1099
#define stride 16
1100
    int i;
1101
    int temp[16]; //FIXME check if this is a good idea
1102
    static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
1103
    static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
1104

    
1105
//memset(block, 64, 2*256);
1106
//return;
1107
    for(i=0; i<4; i++){
1108
        const int offset= y_offset[i];
1109
        const int z0= block[offset+stride*0] + block[offset+stride*4];
1110
        const int z1= block[offset+stride*0] - block[offset+stride*4];
1111
        const int z2= block[offset+stride*1] - block[offset+stride*5];
1112
        const int z3= block[offset+stride*1] + block[offset+stride*5];
1113

    
1114
        temp[4*i+0]= z0+z3;
1115
        temp[4*i+1]= z1+z2;
1116
        temp[4*i+2]= z1-z2;
1117
        temp[4*i+3]= z0-z3;
1118
    }
1119

    
1120
    for(i=0; i<4; i++){
1121
        const int offset= x_offset[i];
1122
        const int z0= temp[4*0+i] + temp[4*2+i];
1123
        const int z1= temp[4*0+i] - temp[4*2+i];
1124
        const int z2= temp[4*1+i] - temp[4*3+i];
1125
        const int z3= temp[4*1+i] + temp[4*3+i];
1126

    
1127
        block[stride*0 +offset]= ((z0 + z3)*qmul + 2)>>2; //FIXME think about merging this into decode_resdual
1128
        block[stride*2 +offset]= ((z1 + z2)*qmul + 2)>>2;
1129
        block[stride*8 +offset]= ((z1 - z2)*qmul + 2)>>2;
1130
        block[stride*10+offset]= ((z0 - z3)*qmul + 2)>>2;
1131
    }
1132
}
1133

    
1134
/**
1135
 * dct tranforms the 16 dc values.
1136
 * @param qp quantization parameter ??? FIXME
1137
 */
1138
static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
1139
//    const int qmul= dequant_coeff[qp][0];
1140
    int i;
1141
    int temp[16]; //FIXME check if this is a good idea
1142
    static const int x_offset[4]={0, 1*stride, 4* stride,  5*stride};
1143
    static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
1144

    
1145
    for(i=0; i<4; i++){
1146
        const int offset= y_offset[i];
1147
        const int z0= block[offset+stride*0] + block[offset+stride*4];
1148
        const int z1= block[offset+stride*0] - block[offset+stride*4];
1149
        const int z2= block[offset+stride*1] - block[offset+stride*5];
1150
        const int z3= block[offset+stride*1] + block[offset+stride*5];
1151

    
1152
        temp[4*i+0]= z0+z3;
1153
        temp[4*i+1]= z1+z2;
1154
        temp[4*i+2]= z1-z2;
1155
        temp[4*i+3]= z0-z3;
1156
    }
1157

    
1158
    for(i=0; i<4; i++){
1159
        const int offset= x_offset[i];
1160
        const int z0= temp[4*0+i] + temp[4*2+i];
1161
        const int z1= temp[4*0+i] - temp[4*2+i];
1162
        const int z2= temp[4*1+i] - temp[4*3+i];
1163
        const int z3= temp[4*1+i] + temp[4*3+i];
1164

    
1165
        block[stride*0 +offset]= (z0 + z3)>>1;
1166
        block[stride*2 +offset]= (z1 + z2)>>1;
1167
        block[stride*8 +offset]= (z1 - z2)>>1;
1168
        block[stride*10+offset]= (z0 - z3)>>1;
1169
    }
1170
}
1171
#undef xStride
1172
#undef stride
1173

    
1174
static void chroma_dc_dequant_idct_c(DCTELEM *block, int qp){
1175
    const int qmul= dequant_coeff[qp][0];
1176
    const int stride= 16*2;
1177
    const int xStride= 16;
1178
    int a,b,c,d,e;
1179

    
1180
    a= block[stride*0 + xStride*0];
1181
    b= block[stride*0 + xStride*1];
1182
    c= block[stride*1 + xStride*0];
1183
    d= block[stride*1 + xStride*1];
1184

    
1185
    e= a-b;
1186
    a= a+b;
1187
    b= c-d;
1188
    c= c+d;
1189

    
1190
    block[stride*0 + xStride*0]= ((a+c)*qmul + 0)>>1;
1191
    block[stride*0 + xStride*1]= ((e+b)*qmul + 0)>>1;
1192
    block[stride*1 + xStride*0]= ((a-c)*qmul + 0)>>1;
1193
    block[stride*1 + xStride*1]= ((e-b)*qmul + 0)>>1;
1194
}
1195

    
1196
static void chroma_dc_dct_c(DCTELEM *block){
1197
    const int stride= 16*2;
1198
    const int xStride= 16;
1199
    int a,b,c,d,e;
1200

    
1201
    a= block[stride*0 + xStride*0];
1202
    b= block[stride*0 + xStride*1];
1203
    c= block[stride*1 + xStride*0];
1204
    d= block[stride*1 + xStride*1];
1205

    
1206
    e= a-b;
1207
    a= a+b;
1208
    b= c-d;
1209
    c= c+d;
1210

    
1211
    block[stride*0 + xStride*0]= (a+c);
1212
    block[stride*0 + xStride*1]= (e+b);
1213
    block[stride*1 + xStride*0]= (a-c);
1214
    block[stride*1 + xStride*1]= (e-b);
1215
}
1216

    
1217
/**
1218
 * gets the chroma qp.
1219
 */
1220
static inline int get_chroma_qp(H264Context *h, int qscale){
1221
    
1222
    return chroma_qp[clip(qscale + h->pps.chroma_qp_index_offset, 0, 51)];
1223
}
1224

    
1225

    
1226
/**
1227
 *
1228
 */
1229
static void h264_add_idct_c(uint8_t *dst, DCTELEM *block, int stride){
1230
    int i;
1231
    uint8_t *cm = cropTbl + MAX_NEG_CROP;
1232

    
1233
    block[0] += 32;
1234
#if 1
1235
    for(i=0; i<4; i++){
1236
        const int z0=  block[i + 4*0]     +  block[i + 4*2];
1237
        const int z1=  block[i + 4*0]     -  block[i + 4*2];
1238
        const int z2= (block[i + 4*1]>>1) -  block[i + 4*3];
1239
        const int z3=  block[i + 4*1]     + (block[i + 4*3]>>1);
1240

    
1241
        block[i + 4*0]= z0 + z3;
1242
        block[i + 4*1]= z1 + z2;
1243
        block[i + 4*2]= z1 - z2;
1244
        block[i + 4*3]= z0 - z3;
1245
    }
1246

    
1247
    for(i=0; i<4; i++){
1248
        const int z0=  block[0 + 4*i]     +  block[2 + 4*i];
1249
        const int z1=  block[0 + 4*i]     -  block[2 + 4*i];
1250
        const int z2= (block[1 + 4*i]>>1) -  block[3 + 4*i];
1251
        const int z3=  block[1 + 4*i]     + (block[3 + 4*i]>>1);
1252

    
1253
        dst[0 + i*stride]= cm[ dst[0 + i*stride] + ((z0 + z3) >> 6) ];
1254
        dst[1 + i*stride]= cm[ dst[1 + i*stride] + ((z1 + z2) >> 6) ];
1255
        dst[2 + i*stride]= cm[ dst[2 + i*stride] + ((z1 - z2) >> 6) ];
1256
        dst[3 + i*stride]= cm[ dst[3 + i*stride] + ((z0 - z3) >> 6) ];
1257
    }
1258
#else
1259
    for(i=0; i<4; i++){
1260
        const int z0=  block[0 + 4*i]     +  block[2 + 4*i];
1261
        const int z1=  block[0 + 4*i]     -  block[2 + 4*i];
1262
        const int z2= (block[1 + 4*i]>>1) -  block[3 + 4*i];
1263
        const int z3=  block[1 + 4*i]     + (block[3 + 4*i]>>1);
1264

    
1265
        block[0 + 4*i]= z0 + z3;
1266
        block[1 + 4*i]= z1 + z2;
1267
        block[2 + 4*i]= z1 - z2;
1268
        block[3 + 4*i]= z0 - z3;
1269
    }
1270

    
1271
    for(i=0; i<4; i++){
1272
        const int z0=  block[i + 4*0]     +  block[i + 4*2];
1273
        const int z1=  block[i + 4*0]     -  block[i + 4*2];
1274
        const int z2= (block[i + 4*1]>>1) -  block[i + 4*3];
1275
        const int z3=  block[i + 4*1]     + (block[i + 4*3]>>1);
1276

    
1277
        dst[i + 0*stride]= cm[ dst[i + 0*stride] + ((z0 + z3) >> 6) ];
1278
        dst[i + 1*stride]= cm[ dst[i + 1*stride] + ((z1 + z2) >> 6) ];
1279
        dst[i + 2*stride]= cm[ dst[i + 2*stride] + ((z1 - z2) >> 6) ];
1280
        dst[i + 3*stride]= cm[ dst[i + 3*stride] + ((z0 - z3) >> 6) ];
1281
    }
1282
#endif
1283
}
1284

    
1285
static void h264_diff_dct_c(DCTELEM *block, uint8_t *src1, uint8_t *src2, int stride){
1286
    int i;
1287
    //FIXME try int temp instead of block
1288
    
1289
    for(i=0; i<4; i++){
1290
        const int d0= src1[0 + i*stride] - src2[0 + i*stride];
1291
        const int d1= src1[1 + i*stride] - src2[1 + i*stride];
1292
        const int d2= src1[2 + i*stride] - src2[2 + i*stride];
1293
        const int d3= src1[3 + i*stride] - src2[3 + i*stride];
1294
        const int z0= d0 + d3;
1295
        const int z3= d0 - d3;
1296
        const int z1= d1 + d2;
1297
        const int z2= d1 - d2;
1298
        
1299
        block[0 + 4*i]=   z0 +   z1;
1300
        block[1 + 4*i]= 2*z3 +   z2;
1301
        block[2 + 4*i]=   z0 -   z1;
1302
        block[3 + 4*i]=   z3 - 2*z2;
1303
    }    
1304

    
1305
    for(i=0; i<4; i++){
1306
        const int z0= block[0*4 + i] + block[3*4 + i];
1307
        const int z3= block[0*4 + i] - block[3*4 + i];
1308
        const int z1= block[1*4 + i] + block[2*4 + i];
1309
        const int z2= block[1*4 + i] - block[2*4 + i];
1310
        
1311
        block[0*4 + i]=   z0 +   z1;
1312
        block[1*4 + i]= 2*z3 +   z2;
1313
        block[2*4 + i]=   z0 -   z1;
1314
        block[3*4 + i]=   z3 - 2*z2;
1315
    }
1316
}
1317

    
1318
//FIXME need to check that this doesnt overflow signed 32 bit for low qp, iam not sure, its very close
1319
//FIXME check that gcc inlines this (and optimizes intra & seperate_dc stuff away)
1320
static inline int quantize_c(DCTELEM *block, uint8_t *scantable, int qscale, int intra, int seperate_dc){
1321
    int i;
1322
    const int * const quant_table= quant_coeff[qscale];
1323
    const int bias= intra ? (1<<QUANT_SHIFT)/3 : (1<<QUANT_SHIFT)/6;
1324
    const unsigned int threshold1= (1<<QUANT_SHIFT) - bias - 1;
1325
    const unsigned int threshold2= (threshold1<<1);
1326
    int last_non_zero;
1327

    
1328
    if(seperate_dc){
1329
        if(qscale<=18){
1330
            //avoid overflows
1331
            const int dc_bias= intra ? (1<<(QUANT_SHIFT-2))/3 : (1<<(QUANT_SHIFT-2))/6;
1332
            const unsigned int dc_threshold1= (1<<(QUANT_SHIFT-2)) - dc_bias - 1;
1333
            const unsigned int dc_threshold2= (dc_threshold1<<1);
1334

    
1335
            int level= block[0]*quant_coeff[qscale+18][0];
1336
            if(((unsigned)(level+dc_threshold1))>dc_threshold2){
1337
                if(level>0){
1338
                    level= (dc_bias + level)>>(QUANT_SHIFT-2);
1339
                    block[0]= level;
1340
                }else{
1341
                    level= (dc_bias - level)>>(QUANT_SHIFT-2);
1342
                    block[0]= -level;
1343
                }
1344
//                last_non_zero = i;
1345
            }else{
1346
                block[0]=0;
1347
            }
1348
        }else{
1349
            const int dc_bias= intra ? (1<<(QUANT_SHIFT+1))/3 : (1<<(QUANT_SHIFT+1))/6;
1350
            const unsigned int dc_threshold1= (1<<(QUANT_SHIFT+1)) - dc_bias - 1;
1351
            const unsigned int dc_threshold2= (dc_threshold1<<1);
1352

    
1353
            int level= block[0]*quant_table[0];
1354
            if(((unsigned)(level+dc_threshold1))>dc_threshold2){
1355
                if(level>0){
1356
                    level= (dc_bias + level)>>(QUANT_SHIFT+1);
1357
                    block[0]= level;
1358
                }else{
1359
                    level= (dc_bias - level)>>(QUANT_SHIFT+1);
1360
                    block[0]= -level;
1361
                }
1362
//                last_non_zero = i;
1363
            }else{
1364
                block[0]=0;
1365
            }
1366
        }
1367
        last_non_zero= 0;
1368
        i=1;
1369
    }else{
1370
        last_non_zero= -1;
1371
        i=0;
1372
    }
1373

    
1374
    for(; i<16; i++){
1375
        const int j= scantable[i];
1376
        int level= block[j]*quant_table[j];
1377

    
1378
//        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
1379
//           || bias-level >= (1<<(QMAT_SHIFT - 3))){
1380
        if(((unsigned)(level+threshold1))>threshold2){
1381
            if(level>0){
1382
                level= (bias + level)>>QUANT_SHIFT;
1383
                block[j]= level;
1384
            }else{
1385
                level= (bias - level)>>QUANT_SHIFT;
1386
                block[j]= -level;
1387
            }
1388
            last_non_zero = i;
1389
        }else{
1390
            block[j]=0;
1391
        }
1392
    }
1393

    
1394
    return last_non_zero;
1395
}
1396

    
1397
static void pred4x4_vertical_c(uint8_t *src, uint8_t *topright, int stride){
1398
    const uint32_t a= ((uint32_t*)(src-stride))[0];
1399
    ((uint32_t*)(src+0*stride))[0]= a;
1400
    ((uint32_t*)(src+1*stride))[0]= a;
1401
    ((uint32_t*)(src+2*stride))[0]= a;
1402
    ((uint32_t*)(src+3*stride))[0]= a;
1403
}
1404

    
1405
static void pred4x4_horizontal_c(uint8_t *src, uint8_t *topright, int stride){
1406
    ((uint32_t*)(src+0*stride))[0]= src[-1+0*stride]*0x01010101;
1407
    ((uint32_t*)(src+1*stride))[0]= src[-1+1*stride]*0x01010101;
1408
    ((uint32_t*)(src+2*stride))[0]= src[-1+2*stride]*0x01010101;
1409
    ((uint32_t*)(src+3*stride))[0]= src[-1+3*stride]*0x01010101;
1410
}
1411

    
1412
static void pred4x4_dc_c(uint8_t *src, uint8_t *topright, int stride){
1413
    const int dc= (  src[-stride] + src[1-stride] + src[2-stride] + src[3-stride]
1414
                   + src[-1+0*stride] + src[-1+1*stride] + src[-1+2*stride] + src[-1+3*stride] + 4) >>3;
1415
    
1416
    ((uint32_t*)(src+0*stride))[0]= 
1417
    ((uint32_t*)(src+1*stride))[0]= 
1418
    ((uint32_t*)(src+2*stride))[0]= 
1419
    ((uint32_t*)(src+3*stride))[0]= dc* 0x01010101; 
1420
}
1421

    
1422
static void pred4x4_left_dc_c(uint8_t *src, uint8_t *topright, int stride){
1423
    const int dc= (  src[-1+0*stride] + src[-1+1*stride] + src[-1+2*stride] + src[-1+3*stride] + 2) >>2;
1424
    
1425
    ((uint32_t*)(src+0*stride))[0]= 
1426
    ((uint32_t*)(src+1*stride))[0]= 
1427
    ((uint32_t*)(src+2*stride))[0]= 
1428
    ((uint32_t*)(src+3*stride))[0]= dc* 0x01010101; 
1429
}
1430

    
1431
static void pred4x4_top_dc_c(uint8_t *src, uint8_t *topright, int stride){
1432
    const int dc= (  src[-stride] + src[1-stride] + src[2-stride] + src[3-stride] + 2) >>2;
1433
    
1434
    ((uint32_t*)(src+0*stride))[0]= 
1435
    ((uint32_t*)(src+1*stride))[0]= 
1436
    ((uint32_t*)(src+2*stride))[0]= 
1437
    ((uint32_t*)(src+3*stride))[0]= dc* 0x01010101; 
1438
}
1439

    
1440
static void pred4x4_128_dc_c(uint8_t *src, uint8_t *topright, int stride){
1441
    ((uint32_t*)(src+0*stride))[0]= 
1442
    ((uint32_t*)(src+1*stride))[0]= 
1443
    ((uint32_t*)(src+2*stride))[0]= 
1444
    ((uint32_t*)(src+3*stride))[0]= 128U*0x01010101U;
1445
}
1446

    
1447

    
1448
#define LOAD_TOP_RIGHT_EDGE\
1449
    const int t4= topright[0];\
1450
    const int t5= topright[1];\
1451
    const int t6= topright[2];\
1452
    const int t7= topright[3];\
1453

    
1454
#define LOAD_LEFT_EDGE\
1455
    const int l0= src[-1+0*stride];\
1456
    const int l1= src[-1+1*stride];\
1457
    const int l2= src[-1+2*stride];\
1458
    const int l3= src[-1+3*stride];\
1459

    
1460
#define LOAD_TOP_EDGE\
1461
    const int t0= src[ 0-1*stride];\
1462
    const int t1= src[ 1-1*stride];\
1463
    const int t2= src[ 2-1*stride];\
1464
    const int t3= src[ 3-1*stride];\
1465

    
1466
static void pred4x4_down_right_c(uint8_t *src, uint8_t *topright, int stride){
1467
    const int lt= src[-1-1*stride];
1468
    LOAD_TOP_EDGE
1469
    LOAD_LEFT_EDGE
1470

    
1471
    src[0+3*stride]=(l3 + 2*l2 + l1 + 2)>>2; 
1472
    src[0+2*stride]=
1473
    src[1+3*stride]=(l2 + 2*l1 + l0 + 2)>>2; 
1474
    src[0+1*stride]=
1475
    src[1+2*stride]=
1476
    src[2+3*stride]=(l1 + 2*l0 + lt + 2)>>2; 
1477
    src[0+0*stride]=
1478
    src[1+1*stride]=
1479
    src[2+2*stride]=
1480
    src[3+3*stride]=(l0 + 2*lt + t0 + 2)>>2; 
1481
    src[1+0*stride]=
1482
    src[2+1*stride]=
1483
    src[3+2*stride]=(lt + 2*t0 + t1 + 2)>>2;
1484
    src[2+0*stride]=
1485
    src[3+1*stride]=(t0 + 2*t1 + t2 + 2)>>2;
1486
    src[3+0*stride]=(t1 + 2*t2 + t3 + 2)>>2;
1487
}
1488

    
1489
static void pred4x4_down_left_c(uint8_t *src, uint8_t *topright, int stride){
1490
    LOAD_TOP_EDGE    
1491
    LOAD_TOP_RIGHT_EDGE    
1492
//    LOAD_LEFT_EDGE    
1493

    
1494
    src[0+0*stride]=(t0 + t2 + 2*t1 + 2)>>2;
1495
    src[1+0*stride]=
1496
    src[0+1*stride]=(t1 + t3 + 2*t2 + 2)>>2;
1497
    src[2+0*stride]=
1498
    src[1+1*stride]=
1499
    src[0+2*stride]=(t2 + t4 + 2*t3 + 2)>>2;
1500
    src[3+0*stride]=
1501
    src[2+1*stride]=
1502
    src[1+2*stride]=
1503
    src[0+3*stride]=(t3 + t5 + 2*t4 + 2)>>2;
1504
    src[3+1*stride]=
1505
    src[2+2*stride]=
1506
    src[1+3*stride]=(t4 + t6 + 2*t5 + 2)>>2;
1507
    src[3+2*stride]=
1508
    src[2+3*stride]=(t5 + t7 + 2*t6 + 2)>>2;
1509
    src[3+3*stride]=(t6 + 3*t7 + 2)>>2;
1510
}
1511

    
1512
static void pred4x4_vertical_right_c(uint8_t *src, uint8_t *topright, int stride){
1513
    const int lt= src[-1-1*stride];
1514
    LOAD_TOP_EDGE    
1515
    LOAD_LEFT_EDGE    
1516
    const __attribute__((unused)) int unu= l3;
1517

    
1518
    src[0+0*stride]=
1519
    src[1+2*stride]=(lt + t0 + 1)>>1;
1520
    src[1+0*stride]=
1521
    src[2+2*stride]=(t0 + t1 + 1)>>1;
1522
    src[2+0*stride]=
1523
    src[3+2*stride]=(t1 + t2 + 1)>>1;
1524
    src[3+0*stride]=(t2 + t3 + 1)>>1;
1525
    src[0+1*stride]=
1526
    src[1+3*stride]=(l0 + 2*lt + t0 + 2)>>2;
1527
    src[1+1*stride]=
1528
    src[2+3*stride]=(lt + 2*t0 + t1 + 2)>>2;
1529
    src[2+1*stride]=
1530
    src[3+3*stride]=(t0 + 2*t1 + t2 + 2)>>2;
1531
    src[3+1*stride]=(t1 + 2*t2 + t3 + 2)>>2;
1532
    src[0+2*stride]=(lt + 2*l0 + l1 + 2)>>2;
1533
    src[0+3*stride]=(l0 + 2*l1 + l2 + 2)>>2;
1534
}
1535

    
1536
static void pred4x4_vertical_left_c(uint8_t *src, uint8_t *topright, int stride){
1537
    LOAD_TOP_EDGE    
1538
    LOAD_TOP_RIGHT_EDGE    
1539
    const __attribute__((unused)) int unu= t7;
1540

    
1541
    src[0+0*stride]=(t0 + t1 + 1)>>1;
1542
    src[1+0*stride]=
1543
    src[0+2*stride]=(t1 + t2 + 1)>>1;
1544
    src[2+0*stride]=
1545
    src[1+2*stride]=(t2 + t3 + 1)>>1;
1546
    src[3+0*stride]=
1547
    src[2+2*stride]=(t3 + t4+ 1)>>1;
1548
    src[3+2*stride]=(t4 + t5+ 1)>>1;
1549
    src[0+1*stride]=(t0 + 2*t1 + t2 + 2)>>2;
1550
    src[1+1*stride]=
1551
    src[0+3*stride]=(t1 + 2*t2 + t3 + 2)>>2;
1552
    src[2+1*stride]=
1553
    src[1+3*stride]=(t2 + 2*t3 + t4 + 2)>>2;
1554
    src[3+1*stride]=
1555
    src[2+3*stride]=(t3 + 2*t4 + t5 + 2)>>2;
1556
    src[3+3*stride]=(t4 + 2*t5 + t6 + 2)>>2;
1557
}
1558

    
1559
static void pred4x4_horizontal_up_c(uint8_t *src, uint8_t *topright, int stride){
1560
    LOAD_LEFT_EDGE    
1561

    
1562
    src[0+0*stride]=(l0 + l1 + 1)>>1;
1563
    src[1+0*stride]=(l0 + 2*l1 + l2 + 2)>>2;
1564
    src[2+0*stride]=
1565
    src[0+1*stride]=(l1 + l2 + 1)>>1;
1566
    src[3+0*stride]=
1567
    src[1+1*stride]=(l1 + 2*l2 + l3 + 2)>>2;
1568
    src[2+1*stride]=
1569
    src[0+2*stride]=(l2 + l3 + 1)>>1;
1570
    src[3+1*stride]=
1571
    src[1+2*stride]=(l2 + 2*l3 + l3 + 2)>>2;
1572
    src[3+2*stride]=
1573
    src[1+3*stride]=
1574
    src[0+3*stride]=
1575
    src[2+2*stride]=
1576
    src[2+3*stride]=
1577
    src[3+3*stride]=l3;
1578
}
1579
    
1580
static void pred4x4_horizontal_down_c(uint8_t *src, uint8_t *topright, int stride){
1581
    const int lt= src[-1-1*stride];
1582
    LOAD_TOP_EDGE    
1583
    LOAD_LEFT_EDGE    
1584
    const __attribute__((unused)) int unu= t3;
1585

    
1586
    src[0+0*stride]=
1587
    src[2+1*stride]=(lt + l0 + 1)>>1;
1588
    src[1+0*stride]=
1589
    src[3+1*stride]=(l0 + 2*lt + t0 + 2)>>2;
1590
    src[2+0*stride]=(lt + 2*t0 + t1 + 2)>>2;
1591
    src[3+0*stride]=(t0 + 2*t1 + t2 + 2)>>2;
1592
    src[0+1*stride]=
1593
    src[2+2*stride]=(l0 + l1 + 1)>>1;
1594
    src[1+1*stride]=
1595
    src[3+2*stride]=(lt + 2*l0 + l1 + 2)>>2;
1596
    src[0+2*stride]=
1597
    src[2+3*stride]=(l1 + l2+ 1)>>1;
1598
    src[1+2*stride]=
1599
    src[3+3*stride]=(l0 + 2*l1 + l2 + 2)>>2;
1600
    src[0+3*stride]=(l2 + l3 + 1)>>1;
1601
    src[1+3*stride]=(l1 + 2*l2 + l3 + 2)>>2;
1602
}
1603

    
1604
static void pred16x16_vertical_c(uint8_t *src, int stride){
1605
    int i;
1606
    const uint32_t a= ((uint32_t*)(src-stride))[0];
1607
    const uint32_t b= ((uint32_t*)(src-stride))[1];
1608
    const uint32_t c= ((uint32_t*)(src-stride))[2];
1609
    const uint32_t d= ((uint32_t*)(src-stride))[3];
1610
    
1611
    for(i=0; i<16; i++){
1612
        ((uint32_t*)(src+i*stride))[0]= a;
1613
        ((uint32_t*)(src+i*stride))[1]= b;
1614
        ((uint32_t*)(src+i*stride))[2]= c;
1615
        ((uint32_t*)(src+i*stride))[3]= d;
1616
    }
1617
}
1618

    
1619
static void pred16x16_horizontal_c(uint8_t *src, int stride){
1620
    int i;
1621

    
1622
    for(i=0; i<16; i++){
1623
        ((uint32_t*)(src+i*stride))[0]=
1624
        ((uint32_t*)(src+i*stride))[1]=
1625
        ((uint32_t*)(src+i*stride))[2]=
1626
        ((uint32_t*)(src+i*stride))[3]= src[-1+i*stride]*0x01010101;
1627
    }
1628
}
1629

    
1630
static void pred16x16_dc_c(uint8_t *src, int stride){
1631
    int i, dc=0;
1632

    
1633
    for(i=0;i<16; i++){
1634
        dc+= src[-1+i*stride];
1635
    }
1636
    
1637
    for(i=0;i<16; i++){
1638
        dc+= src[i-stride];
1639
    }
1640

    
1641
    dc= 0x01010101*((dc + 16)>>5);
1642

    
1643
    for(i=0; i<16; i++){
1644
        ((uint32_t*)(src+i*stride))[0]=
1645
        ((uint32_t*)(src+i*stride))[1]=
1646
        ((uint32_t*)(src+i*stride))[2]=
1647
        ((uint32_t*)(src+i*stride))[3]= dc;
1648
    }
1649
}
1650

    
1651
static void pred16x16_left_dc_c(uint8_t *src, int stride){
1652
    int i, dc=0;
1653

    
1654
    for(i=0;i<16; i++){
1655
        dc+= src[-1+i*stride];
1656
    }
1657
    
1658
    dc= 0x01010101*((dc + 8)>>4);
1659

    
1660
    for(i=0; i<16; i++){
1661
        ((uint32_t*)(src+i*stride))[0]=
1662
        ((uint32_t*)(src+i*stride))[1]=
1663
        ((uint32_t*)(src+i*stride))[2]=
1664
        ((uint32_t*)(src+i*stride))[3]= dc;
1665
    }
1666
}
1667

    
1668
static void pred16x16_top_dc_c(uint8_t *src, int stride){
1669
    int i, dc=0;
1670

    
1671
    for(i=0;i<16; i++){
1672
        dc+= src[i-stride];
1673
    }
1674
    dc= 0x01010101*((dc + 8)>>4);
1675

    
1676
    for(i=0; i<16; i++){
1677
        ((uint32_t*)(src+i*stride))[0]=
1678
        ((uint32_t*)(src+i*stride))[1]=
1679
        ((uint32_t*)(src+i*stride))[2]=
1680
        ((uint32_t*)(src+i*stride))[3]= dc;
1681
    }
1682
}
1683

    
1684
static void pred16x16_128_dc_c(uint8_t *src, int stride){
1685
    int i;
1686

    
1687
    for(i=0; i<16; i++){
1688
        ((uint32_t*)(src+i*stride))[0]=
1689
        ((uint32_t*)(src+i*stride))[1]=
1690
        ((uint32_t*)(src+i*stride))[2]=
1691
        ((uint32_t*)(src+i*stride))[3]= 0x01010101U*128U;
1692
    }
1693
}
1694

    
1695
static inline void pred16x16_plane_compat_c(uint8_t *src, int stride, const int svq3){
1696
  int i, j, k;
1697
  int a;
1698
  uint8_t *cm = cropTbl + MAX_NEG_CROP;
1699
  const uint8_t * const src0 = src+7-stride;
1700
  const uint8_t *src1 = src+8*stride-1;
1701
  const uint8_t *src2 = src1-2*stride;      // == src+6*stride-1;
1702
  int H = src0[1] - src0[-1];
1703
  int V = src1[0] - src2[ 0];
1704
  for(k=2; k<=8; ++k) {
1705
    src1 += stride; src2 -= stride;
1706
    H += k*(src0[k] - src0[-k]);
1707
    V += k*(src1[0] - src2[ 0]);
1708
  }
1709
  if(svq3){
1710
    H = ( 5*(H/4) ) / 16;
1711
    V = ( 5*(V/4) ) / 16;
1712
  }else{
1713
    H = ( 5*H+32 ) >> 6;
1714
    V = ( 5*V+32 ) >> 6;
1715
  }
1716

    
1717
  a = 16*(src1[0] + src2[16] + 1) - 7*(V+H);
1718
  for(j=16; j>0; --j) {
1719
    int b = a;
1720
    a += V;
1721
    for(i=-16; i<0; i+=4) {
1722
      src[16+i] = cm[ (b    ) >> 5 ];
1723
      src[17+i] = cm[ (b+  H) >> 5 ];
1724
      src[18+i] = cm[ (b+2*H) >> 5 ];
1725
      src[19+i] = cm[ (b+3*H) >> 5 ];
1726
      b += 4*H;
1727
    }
1728
    src += stride;
1729
  }
1730
}
1731

    
1732
static void pred16x16_plane_c(uint8_t *src, int stride){
1733
    pred16x16_plane_compat_c(src, stride, 0);
1734
}
1735

    
1736
static void pred8x8_vertical_c(uint8_t *src, int stride){
1737
    int i;
1738
    const uint32_t a= ((uint32_t*)(src-stride))[0];
1739
    const uint32_t b= ((uint32_t*)(src-stride))[1];
1740
    
1741
    for(i=0; i<8; i++){
1742
        ((uint32_t*)(src+i*stride))[0]= a;
1743
        ((uint32_t*)(src+i*stride))[1]= b;
1744
    }
1745
}
1746

    
1747
static void pred8x8_horizontal_c(uint8_t *src, int stride){
1748
    int i;
1749

    
1750
    for(i=0; i<8; i++){
1751
        ((uint32_t*)(src+i*stride))[0]=
1752
        ((uint32_t*)(src+i*stride))[1]= src[-1+i*stride]*0x01010101;
1753
    }
1754
}
1755

    
1756
static void pred8x8_128_dc_c(uint8_t *src, int stride){
1757
    int i;
1758

    
1759
    for(i=0; i<4; i++){
1760
        ((uint32_t*)(src+i*stride))[0]= 
1761
        ((uint32_t*)(src+i*stride))[1]= 0x01010101U*128U;
1762
    }
1763
    for(i=4; i<8; i++){
1764
        ((uint32_t*)(src+i*stride))[0]= 
1765
        ((uint32_t*)(src+i*stride))[1]= 0x01010101U*128U;
1766
    }
1767
}
1768

    
1769
static void pred8x8_left_dc_c(uint8_t *src, int stride){
1770
    int i;
1771
    int dc0, dc2;
1772

    
1773
    dc0=dc2=0;
1774
    for(i=0;i<4; i++){
1775
        dc0+= src[-1+i*stride];
1776
        dc2+= src[-1+(i+4)*stride];
1777
    }
1778
    dc0= 0x01010101*((dc0 + 2)>>2);
1779
    dc2= 0x01010101*((dc2 + 2)>>2);
1780

    
1781
    for(i=0; i<4; i++){
1782
        ((uint32_t*)(src+i*stride))[0]=
1783
        ((uint32_t*)(src+i*stride))[1]= dc0;
1784
    }
1785
    for(i=4; i<8; i++){
1786
        ((uint32_t*)(src+i*stride))[0]=
1787
        ((uint32_t*)(src+i*stride))[1]= dc2;
1788
    }
1789
}
1790

    
1791
static void pred8x8_top_dc_c(uint8_t *src, int stride){
1792
    int i;
1793
    int dc0, dc1;
1794

    
1795
    dc0=dc1=0;
1796
    for(i=0;i<4; i++){
1797
        dc0+= src[i-stride];
1798
        dc1+= src[4+i-stride];
1799
    }
1800
    dc0= 0x01010101*((dc0 + 2)>>2);
1801
    dc1= 0x01010101*((dc1 + 2)>>2);
1802

    
1803
    for(i=0; i<4; i++){
1804
        ((uint32_t*)(src+i*stride))[0]= dc0;
1805
        ((uint32_t*)(src+i*stride))[1]= dc1;
1806
    }
1807
    for(i=4; i<8; i++){
1808
        ((uint32_t*)(src+i*stride))[0]= dc0;
1809
        ((uint32_t*)(src+i*stride))[1]= dc1;
1810
    }
1811
}
1812

    
1813

    
1814
static void pred8x8_dc_c(uint8_t *src, int stride){
1815
    int i;
1816
    int dc0, dc1, dc2, dc3;
1817

    
1818
    dc0=dc1=dc2=0;
1819
    for(i=0;i<4; i++){
1820
        dc0+= src[-1+i*stride] + src[i-stride];
1821
        dc1+= src[4+i-stride];
1822
        dc2+= src[-1+(i+4)*stride];
1823
    }
1824
    dc3= 0x01010101*((dc1 + dc2 + 4)>>3);
1825
    dc0= 0x01010101*((dc0 + 4)>>3);
1826
    dc1= 0x01010101*((dc1 + 2)>>2);
1827
    dc2= 0x01010101*((dc2 + 2)>>2);
1828

    
1829
    for(i=0; i<4; i++){
1830
        ((uint32_t*)(src+i*stride))[0]= dc0;
1831
        ((uint32_t*)(src+i*stride))[1]= dc1;
1832
    }
1833
    for(i=4; i<8; i++){
1834
        ((uint32_t*)(src+i*stride))[0]= dc2;
1835
        ((uint32_t*)(src+i*stride))[1]= dc3;
1836
    }
1837
}
1838

    
1839
static void pred8x8_plane_c(uint8_t *src, int stride){
1840
  int j, k;
1841
  int a;
1842
  uint8_t *cm = cropTbl + MAX_NEG_CROP;
1843
  const uint8_t * const src0 = src+3-stride;
1844
  const uint8_t *src1 = src+4*stride-1;
1845
  const uint8_t *src2 = src1-2*stride;      // == src+2*stride-1;
1846
  int H = src0[1] - src0[-1];
1847
  int V = src1[0] - src2[ 0];
1848
  for(k=2; k<=4; ++k) {
1849
    src1 += stride; src2 -= stride;
1850
    H += k*(src0[k] - src0[-k]);
1851
    V += k*(src1[0] - src2[ 0]);
1852
  }
1853
  H = ( 17*H+16 ) >> 5;
1854
  V = ( 17*V+16 ) >> 5;
1855

    
1856
  a = 16*(src1[0] + src2[8]+1) - 3*(V+H);
1857
  for(j=8; j>0; --j) {
1858
    int b = a;
1859
    a += V;
1860
    src[0] = cm[ (b    ) >> 5 ];
1861
    src[1] = cm[ (b+  H) >> 5 ];
1862
    src[2] = cm[ (b+2*H) >> 5 ];
1863
    src[3] = cm[ (b+3*H) >> 5 ];
1864
    src[4] = cm[ (b+4*H) >> 5 ];
1865
    src[5] = cm[ (b+5*H) >> 5 ];
1866
    src[6] = cm[ (b+6*H) >> 5 ];
1867
    src[7] = cm[ (b+7*H) >> 5 ];
1868
    src += stride;
1869
  }
1870
}
1871

    
1872
static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
1873
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1874
                           int src_x_offset, int src_y_offset,
1875
                           qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
1876
    MpegEncContext * const s = &h->s;
1877
    const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
1878
    const int my= h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
1879
    const int luma_xy= (mx&3) + ((my&3)<<2);
1880
    uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*s->linesize;
1881
    uint8_t * src_cb= pic->data[1] + (mx>>3) + (my>>3)*s->uvlinesize;
1882
    uint8_t * src_cr= pic->data[2] + (mx>>3) + (my>>3)*s->uvlinesize;
1883
    int extra_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16; //FIXME increase edge?, IMHO not worth it
1884
    int extra_height= extra_width;
1885
    int emu=0;
1886
    const int full_mx= mx>>2;
1887
    const int full_my= my>>2;
1888
    
1889
    assert(pic->data[0]);
1890
    
1891
    if(mx&7) extra_width -= 3;
1892
    if(my&7) extra_height -= 3;
1893
    
1894
    if(   full_mx < 0-extra_width 
1895
       || full_my < 0-extra_height 
1896
       || full_mx + 16/*FIXME*/ > s->width + extra_width 
1897
       || full_my + 16/*FIXME*/ > s->height + extra_height){
1898
        ff_emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*s->linesize, s->linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, s->width, s->height);
1899
            src_y= s->edge_emu_buffer + 2 + 2*s->linesize;
1900
        emu=1;
1901
    }
1902
    
1903
    qpix_op[luma_xy](dest_y, src_y, s->linesize); //FIXME try variable height perhaps?
1904
    if(!square){
1905
        qpix_op[luma_xy](dest_y + delta, src_y + delta, s->linesize);
1906
    }
1907
    
1908
    if(s->flags&CODEC_FLAG_GRAY) return;
1909
    
1910
    if(emu){
1911
        ff_emulated_edge_mc(s->edge_emu_buffer, src_cb, s->uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), s->width>>1, s->height>>1);
1912
            src_cb= s->edge_emu_buffer;
1913
    }
1914
    chroma_op(dest_cb, src_cb, s->uvlinesize, chroma_height, mx&7, my&7);
1915

    
1916
    if(emu){
1917
        ff_emulated_edge_mc(s->edge_emu_buffer, src_cr, s->uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), s->width>>1, s->height>>1);
1918
            src_cr= s->edge_emu_buffer;
1919
    }
1920
    chroma_op(dest_cr, src_cr, s->uvlinesize, chroma_height, mx&7, my&7);
1921
}
1922

    
1923
static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
1924
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1925
                           int x_offset, int y_offset,
1926
                           qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
1927
                           qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
1928
                           int list0, int list1){
1929
    MpegEncContext * const s = &h->s;
1930
    qpel_mc_func *qpix_op=  qpix_put;
1931
    h264_chroma_mc_func chroma_op= chroma_put;
1932
    
1933
    dest_y  += 2*x_offset + 2*y_offset*s->  linesize;
1934
    dest_cb +=   x_offset +   y_offset*s->uvlinesize;
1935
    dest_cr +=   x_offset +   y_offset*s->uvlinesize;
1936
    x_offset += 8*s->mb_x;
1937
    y_offset += 8*s->mb_y;
1938
    
1939
    if(list0){
1940
        Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
1941
        mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
1942
                           dest_y, dest_cb, dest_cr, x_offset, y_offset,
1943
                           qpix_op, chroma_op);
1944

    
1945
        qpix_op=  qpix_avg;
1946
        chroma_op= chroma_avg;
1947
    }
1948

    
1949
    if(list1){
1950
        Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
1951
        mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
1952
                           dest_y, dest_cb, dest_cr, x_offset, y_offset,
1953
                           qpix_op, chroma_op);
1954
    }
1955
}
1956

    
1957
static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
1958
                      qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
1959
                      qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg)){
1960
    MpegEncContext * const s = &h->s;
1961
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
1962
    const int mb_type= s->current_picture.mb_type[mb_xy];
1963
    
1964
    assert(IS_INTER(mb_type));
1965
    
1966
    if(IS_16X16(mb_type)){
1967
        mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
1968
                qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
1969
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1970
    }else if(IS_16X8(mb_type)){
1971
        mc_part(h, 0, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 0,
1972
                qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
1973
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1974
        mc_part(h, 8, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 4,
1975
                qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
1976
                IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
1977
    }else if(IS_8X16(mb_type)){
1978
        mc_part(h, 0, 0, 8, 8*s->linesize, dest_y, dest_cb, dest_cr, 0, 0,
1979
                qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1980
                IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
1981
        mc_part(h, 4, 0, 8, 8*s->linesize, dest_y, dest_cb, dest_cr, 4, 0,
1982
                qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1983
                IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
1984
    }else{
1985
        int i;
1986
        
1987
        assert(IS_8X8(mb_type));
1988

    
1989
        for(i=0; i<4; i++){
1990
            const int sub_mb_type= h->sub_mb_type[i];
1991
            const int n= 4*i;
1992
            int x_offset= (i&1)<<2;
1993
            int y_offset= (i&2)<<1;
1994

    
1995
            if(IS_SUB_8X8(sub_mb_type)){
1996
                mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
1997
                    qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
1998
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
1999
            }else if(IS_SUB_8X4(sub_mb_type)){
2000
                mc_part(h, n  , 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset,
2001
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
2002
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2003
                mc_part(h, n+2, 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
2004
                    qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
2005
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2006
            }else if(IS_SUB_4X8(sub_mb_type)){
2007
                mc_part(h, n  , 0, 4, 4*s->linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
2008
                    qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
2009
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2010
                mc_part(h, n+1, 0, 4, 4*s->linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
2011
                    qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
2012
                    IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2013
            }else{
2014
                int j;
2015
                assert(IS_SUB_4X4(sub_mb_type));
2016
                for(j=0; j<4; j++){
2017
                    int sub_x_offset= x_offset + 2*(j&1);
2018
                    int sub_y_offset= y_offset +   (j&2);
2019
                    mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
2020
                        qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
2021
                        IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
2022
                }
2023
            }
2024
        }
2025
    }
2026
}
2027

    
2028
static void decode_init_vlc(H264Context *h){
2029
    static int done = 0;
2030

    
2031
    if (!done) {
2032
        int i;
2033
        done = 1;
2034

    
2035
        init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5, 
2036
                 &chroma_dc_coeff_token_len [0], 1, 1,
2037
                 &chroma_dc_coeff_token_bits[0], 1, 1);
2038

    
2039
        for(i=0; i<4; i++){
2040
            init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17, 
2041
                     &coeff_token_len [i][0], 1, 1,
2042
                     &coeff_token_bits[i][0], 1, 1);
2043
        }
2044

    
2045
        for(i=0; i<3; i++){
2046
            init_vlc(&chroma_dc_total_zeros_vlc[i], CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,
2047
                     &chroma_dc_total_zeros_len [i][0], 1, 1,
2048
                     &chroma_dc_total_zeros_bits[i][0], 1, 1);
2049
        }
2050
        for(i=0; i<15; i++){
2051
            init_vlc(&total_zeros_vlc[i], TOTAL_ZEROS_VLC_BITS, 16, 
2052
                     &total_zeros_len [i][0], 1, 1,
2053
                     &total_zeros_bits[i][0], 1, 1);
2054
        }
2055

    
2056
        for(i=0; i<6; i++){
2057
            init_vlc(&run_vlc[i], RUN_VLC_BITS, 7, 
2058
                     &run_len [i][0], 1, 1,
2059
                     &run_bits[i][0], 1, 1);
2060
        }
2061
        init_vlc(&run7_vlc, RUN7_VLC_BITS, 16, 
2062
                 &run_len [6][0], 1, 1,
2063
                 &run_bits[6][0], 1, 1);
2064
    }
2065
}
2066

    
2067
/**
2068
 * Sets the intra prediction function pointers.
2069
 */
2070
static void init_pred_ptrs(H264Context *h){
2071
//    MpegEncContext * const s = &h->s;
2072

    
2073
    h->pred4x4[VERT_PRED           ]= pred4x4_vertical_c;
2074
    h->pred4x4[HOR_PRED            ]= pred4x4_horizontal_c;
2075
    h->pred4x4[DC_PRED             ]= pred4x4_dc_c;
2076
    h->pred4x4[DIAG_DOWN_LEFT_PRED ]= pred4x4_down_left_c;
2077
    h->pred4x4[DIAG_DOWN_RIGHT_PRED]= pred4x4_down_right_c;
2078
    h->pred4x4[VERT_RIGHT_PRED     ]= pred4x4_vertical_right_c;
2079
    h->pred4x4[HOR_DOWN_PRED       ]= pred4x4_horizontal_down_c;
2080
    h->pred4x4[VERT_LEFT_PRED      ]= pred4x4_vertical_left_c;
2081
    h->pred4x4[HOR_UP_PRED         ]= pred4x4_horizontal_up_c;
2082
    h->pred4x4[LEFT_DC_PRED        ]= pred4x4_left_dc_c;
2083
    h->pred4x4[TOP_DC_PRED         ]= pred4x4_top_dc_c;
2084
    h->pred4x4[DC_128_PRED         ]= pred4x4_128_dc_c;
2085

    
2086
    h->pred8x8[DC_PRED8x8     ]= pred8x8_dc_c;
2087
    h->pred8x8[VERT_PRED8x8   ]= pred8x8_vertical_c;
2088
    h->pred8x8[HOR_PRED8x8    ]= pred8x8_horizontal_c;
2089
    h->pred8x8[PLANE_PRED8x8  ]= pred8x8_plane_c;
2090
    h->pred8x8[LEFT_DC_PRED8x8]= pred8x8_left_dc_c;
2091
    h->pred8x8[TOP_DC_PRED8x8 ]= pred8x8_top_dc_c;
2092
    h->pred8x8[DC_128_PRED8x8 ]= pred8x8_128_dc_c;
2093

    
2094
    h->pred16x16[DC_PRED8x8     ]= pred16x16_dc_c;
2095
    h->pred16x16[VERT_PRED8x8   ]= pred16x16_vertical_c;
2096
    h->pred16x16[HOR_PRED8x8    ]= pred16x16_horizontal_c;
2097
    h->pred16x16[PLANE_PRED8x8  ]= pred16x16_plane_c;
2098
    h->pred16x16[LEFT_DC_PRED8x8]= pred16x16_left_dc_c;
2099
    h->pred16x16[TOP_DC_PRED8x8 ]= pred16x16_top_dc_c;
2100
    h->pred16x16[DC_128_PRED8x8 ]= pred16x16_128_dc_c;
2101
}
2102

    
2103
//FIXME factorize
2104
#define CHECKED_ALLOCZ(p, size)\
2105
{\
2106
    p= av_mallocz(size);\
2107
    if(p==NULL){\
2108
        perror("malloc");\
2109
        goto fail;\
2110
    }\
2111
}
2112

    
2113
static void free_tables(H264Context *h){
2114
    av_freep(&h->intra4x4_pred_mode);
2115
    av_freep(&h->non_zero_count);
2116
    av_freep(&h->slice_table_base);
2117
    h->slice_table= NULL;
2118
    
2119
    av_freep(&h->mb2b_xy);
2120
    av_freep(&h->mb2b8_xy);
2121
}
2122

    
2123
/**
2124
 * allocates tables.
2125
 * needs widzh/height
2126
 */
2127
static int alloc_tables(H264Context *h){
2128
    MpegEncContext * const s = &h->s;
2129
    const int big_mb_num= s->mb_stride * (s->mb_height+1);
2130
    int x,y;
2131

    
2132
    CHECKED_ALLOCZ(h->intra4x4_pred_mode, big_mb_num * 8  * sizeof(uint8_t))
2133
    CHECKED_ALLOCZ(h->non_zero_count    , big_mb_num * 16 * sizeof(uint8_t))
2134
    CHECKED_ALLOCZ(h->slice_table_base  , big_mb_num * sizeof(uint8_t))
2135

    
2136
    memset(h->slice_table_base, -1, big_mb_num  * sizeof(uint8_t));
2137
    h->slice_table= h->slice_table_base + s->mb_stride + 1;
2138

    
2139
    CHECKED_ALLOCZ(h->mb2b_xy  , big_mb_num * sizeof(uint16_t));
2140
    CHECKED_ALLOCZ(h->mb2b8_xy , big_mb_num * sizeof(uint16_t));
2141
    for(y=0; y<s->mb_height; y++){
2142
        for(x=0; x<s->mb_width; x++){
2143
            const int mb_xy= x + y*s->mb_stride;
2144
            const int b_xy = 4*x + 4*y*h->b_stride;
2145
            const int b8_xy= 2*x + 2*y*h->b8_stride;
2146
        
2147
            h->mb2b_xy [mb_xy]= b_xy;
2148
            h->mb2b8_xy[mb_xy]= b8_xy;
2149
        }
2150
    }
2151
    
2152
    return 0;
2153
fail:
2154
    free_tables(h);
2155
    return -1;
2156
}
2157

    
2158
static void common_init(H264Context *h){
2159
    MpegEncContext * const s = &h->s;
2160

    
2161
    s->width = s->avctx->width;
2162
    s->height = s->avctx->height;
2163
    s->codec_id= s->avctx->codec->id;
2164
    
2165
    init_pred_ptrs(h);
2166

    
2167
    s->decode=1; //FIXME
2168
}
2169

    
2170
static int decode_init(AVCodecContext *avctx){
2171
    H264Context *h= avctx->priv_data;
2172
    MpegEncContext * const s = &h->s;
2173

    
2174
    s->avctx = avctx;
2175
    common_init(h);
2176

    
2177
    s->out_format = FMT_H264;
2178
    s->workaround_bugs= avctx->workaround_bugs;
2179

    
2180
    // set defaults
2181
    s->progressive_sequence=1;
2182
//    s->decode_mb= ff_h263_decode_mb;
2183
    s->low_delay= 1;
2184
    avctx->pix_fmt= PIX_FMT_YUV420P;
2185

    
2186
    decode_init_vlc(h);
2187
    
2188
    return 0;
2189
}
2190

    
2191
static void frame_start(H264Context *h){
2192
    MpegEncContext * const s = &h->s;
2193
    int i;
2194

    
2195
    MPV_frame_start(s, s->avctx);
2196
    ff_er_frame_start(s);
2197
    h->mmco_index=0;
2198

    
2199
    assert(s->linesize && s->uvlinesize);
2200

    
2201
    for(i=0; i<16; i++){
2202
        h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
2203
        h->chroma_subblock_offset[i]= 2*((scan8[i] - scan8[0])&7) + 2*s->uvlinesize*((scan8[i] - scan8[0])>>3);
2204
    }
2205
    for(i=0; i<4; i++){
2206
        h->block_offset[16+i]=
2207
        h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
2208
    }
2209

    
2210
//    s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
2211
}
2212

    
2213
static void hl_decode_mb(H264Context *h){
2214
    MpegEncContext * const s = &h->s;
2215
    const int mb_x= s->mb_x;
2216
    const int mb_y= s->mb_y;
2217
    const int mb_xy= mb_x + mb_y*s->mb_stride;
2218
    const int mb_type= s->current_picture.mb_type[mb_xy];
2219
    uint8_t  *dest_y, *dest_cb, *dest_cr;
2220
    int linesize, uvlinesize /*dct_offset*/;
2221
    int i;
2222

    
2223
    if(!s->decode)
2224
        return;
2225

    
2226
    if(s->mb_skiped){
2227
    }
2228

    
2229
    dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
2230
    dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2231
    dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
2232

    
2233
    if (h->mb_field_decoding_flag) {
2234
        linesize = s->linesize * 2;
2235
        uvlinesize = s->uvlinesize * 2;
2236
        if(mb_y&1){ //FIXME move out of this func?
2237
            dest_y -= s->linesize*15;
2238
            dest_cb-= s->linesize*7;
2239
            dest_cr-= s->linesize*7;
2240
        }
2241
    } else {
2242
        linesize = s->linesize;
2243
        uvlinesize = s->uvlinesize;
2244
//        dct_offset = s->linesize * 16;
2245
    }
2246

    
2247
    if(IS_INTRA(mb_type)){
2248
        if(!(s->flags&CODEC_FLAG_GRAY)){
2249
            h->pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
2250
            h->pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
2251
        }
2252

    
2253
        if(IS_INTRA4x4(mb_type)){
2254
            if(!s->encoding){
2255
                for(i=0; i<16; i++){
2256
                    uint8_t * const ptr= dest_y + h->block_offset[i];
2257
                    uint8_t *topright= ptr + 4 - linesize;
2258
                    const int topright_avail= (h->topright_samples_available<<i)&0x8000;
2259
                    const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
2260
                    int tr;
2261

    
2262
                    if(!topright_avail){
2263
                        tr= ptr[3 - linesize]*0x01010101;
2264
                        topright= (uint8_t*) &tr;
2265
                    }
2266

    
2267
                    h->pred4x4[ dir ](ptr, topright, linesize);
2268
                    if(h->non_zero_count_cache[ scan8[i] ]){
2269
                        if(s->codec_id == CODEC_ID_H264)
2270
                            h264_add_idct_c(ptr, h->mb + i*16, linesize);
2271
                        else
2272
                            svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
2273
                    }
2274
                }
2275
            }
2276
        }else{
2277
            h->pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
2278
            if(s->codec_id == CODEC_ID_H264)
2279
                h264_luma_dc_dequant_idct_c(h->mb, s->qscale);
2280
            else
2281
                svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
2282
        }
2283
    }else if(s->codec_id == CODEC_ID_H264){
2284
        hl_motion(h, dest_y, dest_cb, dest_cr,
2285
                  s->dsp.put_h264_qpel_pixels_tab, s->dsp.put_h264_chroma_pixels_tab, 
2286
                  s->dsp.avg_h264_qpel_pixels_tab, s->dsp.avg_h264_chroma_pixels_tab);
2287
    }
2288

    
2289

    
2290
    if(!IS_INTRA4x4(mb_type)){
2291
        if(s->codec_id == CODEC_ID_H264){
2292
            for(i=0; i<16; i++){
2293
                if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
2294
                    uint8_t * const ptr= dest_y + h->block_offset[i];
2295
                    h264_add_idct_c(ptr, h->mb + i*16, linesize);
2296
                }
2297
            }
2298
        }else{
2299
            for(i=0; i<16; i++){
2300
                if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
2301
                    uint8_t * const ptr= dest_y + h->block_offset[i];
2302
                    svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
2303
                }
2304
            }
2305
        }
2306
    }
2307

    
2308
    if(!(s->flags&CODEC_FLAG_GRAY)){
2309
        chroma_dc_dequant_idct_c(h->mb + 16*16, h->chroma_qp);
2310
        chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->chroma_qp);
2311
        if(s->codec_id == CODEC_ID_H264){
2312
            for(i=16; i<16+4; i++){
2313
                if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2314
                    uint8_t * const ptr= dest_cb + h->block_offset[i];
2315
                    h264_add_idct_c(ptr, h->mb + i*16, uvlinesize);
2316
                }
2317
            }
2318
            for(i=20; i<20+4; i++){
2319
                if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2320
                    uint8_t * const ptr= dest_cr + h->block_offset[i];
2321
                    h264_add_idct_c(ptr, h->mb + i*16, uvlinesize);
2322
                }
2323
            }
2324
        }else{
2325
            for(i=16; i<16+4; i++){
2326
                if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2327
                    uint8_t * const ptr= dest_cb + h->block_offset[i];
2328
                    svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
2329
                }
2330
            }
2331
            for(i=20; i<20+4; i++){
2332
                if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
2333
                    uint8_t * const ptr= dest_cr + h->block_offset[i];
2334
                    svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
2335
                }
2336
            }
2337
        }
2338
    }
2339
}
2340

    
2341
static void decode_mb_cabac(H264Context *h){
2342
//    MpegEncContext * const s = &h->s;
2343
}
2344

    
2345
/**
2346
 * fills the default_ref_list.
2347
 */
2348
static int fill_default_ref_list(H264Context *h){
2349
    MpegEncContext * const s = &h->s;
2350
    int i;
2351
    Picture sorted_short_ref[16];
2352
    
2353
    if(h->slice_type==B_TYPE){
2354
        int out_i;
2355
        int limit= -1;
2356

    
2357
        for(out_i=0; out_i<h->short_ref_count; out_i++){
2358
            int best_i=-1;
2359
            int best_poc=-1;
2360

    
2361
            for(i=0; i<h->short_ref_count; i++){
2362
                const int poc= h->short_ref[i]->poc;
2363
                if(poc > limit && poc < best_poc){
2364
                    best_poc= poc;
2365
                    best_i= i;
2366
                }
2367
            }
2368
            
2369
            assert(best_i != -1);
2370
            
2371
            limit= best_poc;
2372
            sorted_short_ref[out_i]= *h->short_ref[best_i];
2373
        }
2374
    }
2375

    
2376
    if(s->picture_structure == PICT_FRAME){
2377
        if(h->slice_type==B_TYPE){
2378
            const int current_poc= s->current_picture_ptr->poc;
2379
            int list;
2380

    
2381
            for(list=0; list<2; list++){
2382
                int index=0;
2383

    
2384
                for(i=0; i<h->short_ref_count && index < h->ref_count[list]; i++){
2385
                    const int i2= list ? h->short_ref_count - i - 1 : i;
2386
                    const int poc= sorted_short_ref[i2].poc;
2387
                    
2388
                    if(sorted_short_ref[i2].reference != 3) continue; //FIXME refernce field shit
2389

    
2390
                    if((list==1 && poc > current_poc) || (list==0 && poc < current_poc)){
2391
                        h->default_ref_list[list][index  ]= sorted_short_ref[i2];
2392
                        h->default_ref_list[list][index++].pic_id= sorted_short_ref[i2].frame_num;
2393
                    }
2394
                }
2395

    
2396
                for(i=0; i<h->long_ref_count && index < h->ref_count[ list ]; i++){
2397
                    if(h->long_ref[i]->reference != 3) continue;
2398

    
2399
                    h->default_ref_list[ list ][index  ]= *h->long_ref[i];
2400
                    h->default_ref_list[ list ][index++].pic_id= i;;
2401
                }
2402
                
2403
                if(h->long_ref_count > 1 && h->short_ref_count==0){
2404
                    Picture temp= h->default_ref_list[1][0];
2405
                    h->default_ref_list[1][0] = h->default_ref_list[1][1];
2406
                    h->default_ref_list[1][0] = temp;
2407
                }
2408

    
2409
                if(index < h->ref_count[ list ])
2410
                    memset(&h->default_ref_list[list][index], 0, sizeof(Picture)*(h->ref_count[ list ] - index));
2411
            }
2412
        }else{
2413
            int index=0;
2414
            for(i=0; i<h->short_ref_count && index < h->ref_count[0]; i++){
2415
                if(h->short_ref[i]->reference != 3) continue; //FIXME refernce field shit
2416
                h->default_ref_list[0][index  ]= *h->short_ref[i];
2417
                h->default_ref_list[0][index++].pic_id= h->short_ref[i]->frame_num;
2418
            }
2419
            for(i=0; i<h->long_ref_count && index < h->ref_count[0]; i++){
2420
                if(h->long_ref[i]->reference != 3) continue;
2421
                h->default_ref_list[0][index  ]= *h->long_ref[i];
2422
                h->default_ref_list[0][index++].pic_id= i;;
2423
            }
2424
            if(index < h->ref_count[0])
2425
                memset(&h->default_ref_list[0][index], 0, sizeof(Picture)*(h->ref_count[0] - index));
2426
        }
2427
    }else{ //FIELD
2428
        if(h->slice_type==B_TYPE){
2429
        }else{
2430
            //FIXME second field balh
2431
        }
2432
    }
2433
    return 0;
2434
}
2435

    
2436
static int decode_ref_pic_list_reordering(H264Context *h){
2437
    MpegEncContext * const s = &h->s;
2438
    int list;
2439
    
2440
    if(h->slice_type==I_TYPE || h->slice_type==SI_TYPE) return 0; //FIXME move beofre func
2441
    
2442
    for(list=0; list<2; list++){
2443
        memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);
2444

    
2445
        if(get_bits1(&s->gb)){
2446
            int pred= h->curr_pic_num;
2447
            int index;
2448

    
2449
            for(index=0; ; index++){
2450
                int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
2451
                int pic_id;
2452
                int i;
2453
                
2454
                
2455
                if(index >= h->ref_count[list]){
2456
                    fprintf(stderr, "reference count overflow\n");
2457
                    return -1;
2458
                }
2459
                
2460
                if(reordering_of_pic_nums_idc<3){
2461
                    if(reordering_of_pic_nums_idc<2){
2462
                        const int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
2463

    
2464
                        if(abs_diff_pic_num >= h->max_pic_num){
2465
                            fprintf(stderr, "abs_diff_pic_num overflow\n");
2466
                            return -1;
2467
                        }
2468

    
2469
                        if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
2470
                        else                                pred+= abs_diff_pic_num;
2471
                        pred &= h->max_pic_num - 1;
2472
                    
2473
                        for(i= h->ref_count[list]-1; i>=index; i--){
2474
                            if(h->ref_list[list][i].pic_id == pred && h->ref_list[list][i].long_ref==0)
2475
                                break;
2476
                        }
2477
                    }else{
2478
                        pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
2479

    
2480
                        for(i= h->ref_count[list]-1; i>=index; i--){
2481
                            if(h->ref_list[list][i].pic_id == pic_id && h->ref_list[list][i].long_ref==1)
2482
                                break;
2483
                        }
2484
                    }
2485

    
2486
                    if(i < index){
2487
                        fprintf(stderr, "reference picture missing during reorder\n");
2488
                        memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
2489
                    }else if(i > index){
2490
                        Picture tmp= h->ref_list[list][i];
2491
                        for(; i>index; i--){
2492
                            h->ref_list[list][i]= h->ref_list[list][i-1];
2493
                        }
2494
                        h->ref_list[list][index]= tmp;
2495
                    }
2496
                }else if(reordering_of_pic_nums_idc==3) 
2497
                    break;
2498
                else{
2499
                    fprintf(stderr, "illegal reordering_of_pic_nums_idc\n");
2500
                    return -1;
2501
                }
2502
            }
2503
        }
2504

    
2505
        if(h->slice_type!=B_TYPE) break;
2506
    }
2507
    return 0;    
2508
}
2509

    
2510
static int pred_weight_table(H264Context *h){
2511
    MpegEncContext * const s = &h->s;
2512
    int list, i;
2513
    
2514
    h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
2515
    h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
2516

    
2517
    for(list=0; list<2; list++){
2518
        for(i=0; i<h->ref_count[list]; i++){
2519
            int luma_weight_flag, chroma_weight_flag;
2520
            
2521
            luma_weight_flag= get_bits1(&s->gb);
2522
            if(luma_weight_flag){
2523
                h->luma_weight[list][i]= get_se_golomb(&s->gb);
2524
                h->luma_offset[list][i]= get_se_golomb(&s->gb);
2525
            }
2526

    
2527
            chroma_weight_flag= get_bits1(&s->gb);
2528
            if(chroma_weight_flag){
2529
                int j;
2530
                for(j=0; j<2; j++){
2531
                    h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
2532
                    h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
2533
                }
2534
            }
2535
        }
2536
        if(h->slice_type != B_TYPE) break;
2537
    }
2538
    return 0;
2539
}
2540

    
2541
/**
2542
 * instantaneos decoder refresh.
2543
 */
2544
static void idr(H264Context *h){
2545
    int i;
2546

    
2547
    for(i=0; i<h->long_ref_count; i++){
2548
        h->long_ref[i]->reference=0;
2549
        h->long_ref[i]= NULL;
2550
    }
2551
    h->long_ref_count=0;
2552

    
2553
    for(i=0; i<h->short_ref_count; i++){
2554
        h->short_ref[i]->reference=0;
2555
        h->short_ref[i]= NULL;
2556
    }
2557
    h->short_ref_count=0;
2558
}
2559

    
2560
/**
2561
 *
2562
 * @return the removed picture or NULL if an error occures
2563
 */
2564
static Picture * remove_short(H264Context *h, int frame_num){
2565
    MpegEncContext * const s = &h->s;
2566
    int i;
2567
    
2568
    if(s->avctx->debug&FF_DEBUG_MMCO)
2569
        printf("remove short %d count %d\n", frame_num, h->short_ref_count);
2570
    
2571
    for(i=0; i<h->short_ref_count; i++){
2572
        Picture *pic= h->short_ref[i];
2573
        if(s->avctx->debug&FF_DEBUG_MMCO)
2574
            printf("%d %d %p\n", i, pic->frame_num, pic);
2575
        if(pic->frame_num == frame_num){
2576
            h->short_ref[i]= NULL;
2577
            memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i - 1)*sizeof(Picture*));
2578
            h->short_ref_count--;
2579
            return pic;
2580
        }
2581
    }
2582
    return NULL;
2583
}
2584

    
2585
/**
2586
 *
2587
 * @return the removed picture or NULL if an error occures
2588
 */
2589
static Picture * remove_long(H264Context *h, int i){
2590
    Picture *pic;
2591

    
2592
    if(i >= h->long_ref_count) return NULL;
2593
    pic= h->long_ref[i];
2594
    if(pic==NULL) return NULL;
2595
    
2596
    h->long_ref[i]= NULL;
2597
    memmove(&h->long_ref[i], &h->long_ref[i+1], (h->long_ref_count - i - 1)*sizeof(Picture*));
2598
    h->long_ref_count--;
2599

    
2600
    return pic;
2601
}
2602

    
2603
/**
2604
 * Executes the reference picture marking (memory management control operations).
2605
 */
2606
static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
2607
    MpegEncContext * const s = &h->s;
2608
    int i;
2609
    int current_is_long=0;
2610
    Picture *pic;
2611
    
2612
    if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)
2613
        printf("no mmco here\n");
2614
        
2615
    for(i=0; i<mmco_count; i++){
2616
        if(s->avctx->debug&FF_DEBUG_MMCO)
2617
            printf("mmco:%d %d %d\n", h->mmco[i].opcode, h->mmco[i].short_frame_num, h->mmco[i].long_index);
2618

    
2619
        switch(mmco[i].opcode){
2620
        case MMCO_SHORT2UNUSED:
2621
            pic= remove_short(h, mmco[i].short_frame_num);
2622
            if(pic==NULL) return -1;
2623
            pic->reference= 0;
2624
            break;
2625
        case MMCO_SHORT2LONG:
2626
            pic= remove_long(h, mmco[i].long_index);
2627
            if(pic) pic->reference=0;
2628
            
2629
            h->long_ref[ mmco[i].long_index ]= remove_short(h, mmco[i].short_frame_num);
2630
            h->long_ref[ mmco[i].long_index ]->long_ref=1;
2631
            break;
2632
        case MMCO_LONG2UNUSED:
2633
            pic= remove_long(h, mmco[i].long_index);
2634
            if(pic==NULL) return -1;
2635
            pic->reference= 0;
2636
            break;
2637
        case MMCO_LONG:
2638
            pic= remove_long(h, mmco[i].long_index);
2639
            if(pic) pic->reference=0;
2640
            
2641
            h->long_ref[ mmco[i].long_index ]= s->current_picture_ptr;
2642
            h->long_ref[ mmco[i].long_index ]->long_ref=1;
2643
            h->long_ref_count++;
2644
            
2645
            current_is_long=1;
2646
            break;
2647
        case MMCO_SET_MAX_LONG:
2648
            assert(mmco[i].long_index <= 16);
2649
            while(mmco[i].long_index < h->long_ref_count){
2650
                pic= remove_long(h, mmco[i].long_index);
2651
                pic->reference=0;
2652
            }
2653
            while(mmco[i].long_index > h->long_ref_count){
2654
                h->long_ref[ h->long_ref_count++ ]= NULL;
2655
            }
2656
            break;
2657
        case MMCO_RESET:
2658
            while(h->short_ref_count){
2659
                pic= remove_short(h, h->short_ref[0]->frame_num);
2660
                pic->reference=0;
2661
            }
2662
            while(h->long_ref_count){
2663
                pic= remove_long(h, h->long_ref_count-1);
2664
                pic->reference=0;
2665
            }
2666
            break;
2667
        default: assert(0);
2668
        }
2669
    }
2670
    
2671
    if(!current_is_long){
2672
        pic= remove_short(h, s->current_picture_ptr->frame_num);
2673
        if(pic){
2674
            pic->reference=0;
2675
            fprintf(stderr, "illegal short term buffer state detected\n");
2676
        }
2677
        
2678
        if(h->short_ref_count)
2679
            memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
2680

    
2681
        h->short_ref[0]= s->current_picture_ptr;
2682
        h->short_ref[0]->long_ref=0;
2683
        h->short_ref_count++;
2684
    }
2685
    
2686
    return 0; 
2687
}
2688

    
2689
static int decode_ref_pic_marking(H264Context *h){
2690
    MpegEncContext * const s = &h->s;
2691
    int i;
2692
    
2693
    if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields
2694
        s->broken_link= get_bits1(&s->gb) -1;
2695
        h->mmco[0].long_index= get_bits1(&s->gb) - 1; // current_long_term_idx
2696
        if(h->mmco[0].long_index == -1)
2697
            h->mmco_index= 0;
2698
        else{
2699
            h->mmco[0].opcode= MMCO_LONG;
2700
            h->mmco_index= 1;
2701
        } 
2702
    }else{
2703
        if(get_bits1(&s->gb)){ // adaptive_ref_pic_marking_mode_flag
2704
            for(i= h->mmco_index; i<MAX_MMCO_COUNT; i++) { 
2705
                MMCOOpcode opcode= get_ue_golomb(&s->gb);;
2706

    
2707
                h->mmco[i].opcode= opcode;
2708
                if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){
2709
                    h->mmco[i].short_frame_num= (h->frame_num - get_ue_golomb(&s->gb) - 1) & ((1<<h->sps.log2_max_frame_num)-1); //FIXME fields
2710
/*                    if(h->mmco[i].short_frame_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_frame_num ] == NULL){
2711
                        fprintf(stderr, "illegal short ref in memory management control operation %d\n", mmco);
2712
                        return -1;
2713
                    }*/
2714
                }
2715
                if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){
2716
                    h->mmco[i].long_index= get_ue_golomb(&s->gb);
2717
                    if(/*h->mmco[i].long_index >= h->long_ref_count || h->long_ref[ h->mmco[i].long_index ] == NULL*/ h->mmco[i].long_index >= 16){
2718
                        fprintf(stderr, "illegal long ref in memory management control operation %d\n", opcode);
2719
                        return -1;
2720
                    }
2721
                }
2722
                    
2723
                if(opcode > MMCO_LONG){
2724
                    fprintf(stderr, "illegal memory management control operation %d\n", opcode);
2725
                    return -1;
2726
                }
2727
            }
2728
            h->mmco_index= i;
2729
        }else{
2730
            assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
2731

    
2732
            if(h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count){ //FIXME fields
2733
                h->mmco[0].opcode= MMCO_SHORT2UNUSED;
2734
                h->mmco[0].short_frame_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
2735
                h->mmco_index= 1;
2736
            }else
2737
                h->mmco_index= 0;
2738
        }
2739
    }
2740
    
2741
    return 0; 
2742
}
2743

    
2744
static int init_poc(H264Context *h){
2745
    MpegEncContext * const s = &h->s;
2746
    const int max_frame_num= 1<<h->sps.log2_max_frame_num;
2747
    int field_poc[2];
2748

    
2749
    if(h->nal_unit_type == NAL_IDR_SLICE){
2750
        h->frame_num_offset= 0;
2751
    }else{
2752
        if(h->frame_num < h->prev_frame_num)
2753
            h->frame_num_offset= h->prev_frame_num_offset + max_frame_num;
2754
        else
2755
            h->frame_num_offset= h->prev_frame_num_offset;
2756
    }
2757

    
2758
    if(h->sps.poc_type==0){
2759
        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
2760

    
2761
        if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
2762
            h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2763
        else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
2764
            h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2765
        else
2766
            h->poc_msb = h->prev_poc_msb;
2767
//printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
2768
        field_poc[0] = 
2769
        field_poc[1] = h->poc_msb + h->poc_lsb;
2770
        if(s->picture_structure == PICT_FRAME) 
2771
            field_poc[1] += h->delta_poc_bottom;
2772
    }else if(h->sps.poc_type==1){
2773
        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2774
        int i;
2775

    
2776
        if(h->sps.poc_cycle_length != 0)
2777
            abs_frame_num = h->frame_num_offset + h->frame_num;
2778
        else
2779
            abs_frame_num = 0;
2780

    
2781
        if(h->nal_ref_idc==0 && abs_frame_num > 0)
2782
            abs_frame_num--;
2783
            
2784
        expected_delta_per_poc_cycle = 0;
2785
        for(i=0; i < h->sps.poc_cycle_length; i++)
2786
            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
2787

    
2788
        if(abs_frame_num > 0){
2789
            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2790
            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2791

    
2792
            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2793
            for(i = 0; i <= frame_num_in_poc_cycle; i++)
2794
                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
2795
        } else
2796
            expectedpoc = 0;
2797

    
2798
        if(h->nal_ref_idc == 0) 
2799
            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2800
        
2801
        field_poc[0] = expectedpoc + h->delta_poc[0];
2802
        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2803

    
2804
        if(s->picture_structure == PICT_FRAME)
2805
            field_poc[1] += h->delta_poc[1];
2806
    }else{
2807
        int poc;
2808
        if(h->nal_unit_type == NAL_IDR_SLICE){
2809
            poc= 0;
2810
        }else{
2811
            if(h->nal_ref_idc) poc= 2*(h->frame_num_offset + h->frame_num);
2812
            else               poc= 2*(h->frame_num_offset + h->frame_num) - 1;
2813
        }
2814
        field_poc[0]= poc;
2815
        field_poc[1]= poc;
2816
    }
2817
    
2818
    if(s->picture_structure != PICT_BOTTOM_FIELD)
2819
        s->current_picture_ptr->field_poc[0]= field_poc[0];
2820
    if(s->picture_structure != PICT_TOP_FIELD)
2821
        s->current_picture_ptr->field_poc[1]= field_poc[1];
2822
    if(s->picture_structure == PICT_FRAME) // FIXME field pix?
2823
        s->current_picture_ptr->poc= FFMIN(field_poc[0], field_poc[1]);
2824

    
2825
    return 0;
2826
}
2827

    
2828
/**
2829
 * decodes a slice header.
2830
 * this will allso call MPV_common_init() and frame_start() as needed
2831
 */
2832
static int decode_slice_header(H264Context *h){
2833
    MpegEncContext * const s = &h->s;
2834
    int first_mb_in_slice, pps_id;
2835
    int num_ref_idx_active_override_flag;
2836
    static const uint8_t slice_type_map[5]= {P_TYPE, B_TYPE, I_TYPE, SP_TYPE, SI_TYPE};
2837
    float new_aspect;
2838

    
2839
    s->current_picture.reference= h->nal_ref_idc != 0;
2840

    
2841
    first_mb_in_slice= get_ue_golomb(&s->gb);
2842

    
2843
    h->slice_type= get_ue_golomb(&s->gb);
2844
    if(h->slice_type > 9){
2845
        fprintf(stderr, "slice type too large (%d) at %d %d\n", h->slice_type, s->mb_x, s->mb_y);
2846
    }
2847
    if(h->slice_type > 4){
2848
        h->slice_type -= 5;
2849
        h->slice_type_fixed=1;
2850
    }else
2851
        h->slice_type_fixed=0;
2852
    
2853
    h->slice_type= slice_type_map[ h->slice_type ];
2854
    
2855
    s->pict_type= h->slice_type; // to make a few old func happy, its wrong though
2856
        
2857
    pps_id= get_ue_golomb(&s->gb);
2858
    if(pps_id>255){
2859
        fprintf(stderr, "pps_id out of range\n");
2860
        return -1;
2861
    }
2862
    h->pps= h->pps_buffer[pps_id];
2863
    if(h->pps.slice_group_count == 0){
2864
        fprintf(stderr, "non existing PPS referenced\n");
2865
        return -1;
2866
    }
2867

    
2868
    h->sps= h->sps_buffer[ h->pps.sps_id ];
2869
    if(h->sps.log2_max_frame_num == 0){
2870
        fprintf(stderr, "non existing SPS referenced\n");
2871
        return -1;
2872
    }
2873
    
2874
    s->mb_width= h->sps.mb_width;
2875
    s->mb_height= h->sps.mb_height;
2876
    
2877
    h->b_stride=  s->mb_width*4;
2878
    h->b8_stride= s->mb_width*2;
2879

    
2880
    s->mb_x = first_mb_in_slice % s->mb_width;
2881
    s->mb_y = first_mb_in_slice / s->mb_width; //FIXME AFFW
2882
    
2883
    s->width = 16*s->mb_width - 2*(h->pps.crop_left + h->pps.crop_right );
2884
    if(h->sps.frame_mbs_only_flag)
2885
        s->height= 16*s->mb_height - 2*(h->pps.crop_top  + h->pps.crop_bottom);
2886
    else
2887
        s->height= 16*s->mb_height - 4*(h->pps.crop_top  + h->pps.crop_bottom); //FIXME recheck
2888
    
2889
    if(h->pps.crop_left || h->pps.crop_top){
2890
        fprintf(stderr, "insane croping not completly supported, this could look slightly wrong ...\n");
2891
    }
2892

    
2893
    if(s->aspected_height) //FIXME emms at end of slice ?
2894
        new_aspect= h->sps.sar_width*s->width / (float)(s->height*h->sps.sar_height);
2895
    else
2896
        new_aspect=0;
2897

    
2898
    if (s->context_initialized 
2899
        && (   s->width != s->avctx->width || s->height != s->avctx->height 
2900
            || ABS(new_aspect - s->avctx->aspect_ratio) > 0.001)) {
2901
        free_tables(h);
2902
        MPV_common_end(s);
2903
    }
2904
    if (!s->context_initialized) {
2905
        if (MPV_common_init(s) < 0)
2906
            return -1;
2907

    
2908
        alloc_tables(h);
2909

    
2910
        s->avctx->width = s->width;
2911
        s->avctx->height = s->height;
2912
        s->avctx->aspect_ratio= new_aspect;
2913
    }
2914

    
2915
    if(first_mb_in_slice == 0){
2916
        frame_start(h);
2917
    }
2918

    
2919
    s->current_picture_ptr->frame_num= //FIXME frame_num cleanup
2920
    h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
2921

    
2922
    if(h->sps.frame_mbs_only_flag){
2923
        s->picture_structure= PICT_FRAME;
2924
    }else{
2925
        if(get_bits1(&s->gb)) //field_pic_flag
2926
            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
2927
        else
2928
            s->picture_structure= PICT_FRAME;
2929
    }
2930

    
2931
    if(s->picture_structure==PICT_FRAME){
2932
        h->curr_pic_num=   h->frame_num;
2933
        h->max_pic_num= 1<< h->sps.log2_max_frame_num;
2934
    }else{
2935
        h->curr_pic_num= 2*h->frame_num;
2936
        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
2937
    }
2938
        
2939
    if(h->nal_unit_type == NAL_IDR_SLICE){
2940
        int idr_pic_id= get_ue_golomb(&s->gb);
2941
    }
2942
   
2943
    if(h->sps.poc_type==0){
2944
        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
2945
        
2946
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
2947
            h->delta_poc_bottom= get_se_golomb(&s->gb);
2948
        }
2949
    }
2950
    
2951
    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
2952
        h->delta_poc[0]= get_se_golomb(&s->gb);
2953
        
2954
        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
2955
            h->delta_poc[1]= get_se_golomb(&s->gb);
2956
    }
2957
    
2958
    init_poc(h);
2959
    
2960
    if(h->pps.redundant_pic_cnt_present){
2961
        h->redundant_pic_count= get_ue_golomb(&s->gb);
2962
    }
2963

    
2964
    //set defaults, might be overriden a few line later
2965
    h->ref_count[0]= h->pps.ref_count[0];
2966
    h->ref_count[1]= h->pps.ref_count[1];
2967

    
2968
    if(h->slice_type == P_TYPE || h->slice_type == SP_TYPE || h->slice_type == B_TYPE){
2969
        if(h->slice_type == B_TYPE){
2970
            h->direct_spatial_mv_pred= get_bits1(&s->gb);
2971
        }
2972
        num_ref_idx_active_override_flag= get_bits1(&s->gb);
2973
    
2974
        if(num_ref_idx_active_override_flag){
2975
            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
2976
            if(h->slice_type==B_TYPE)
2977
                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
2978

    
2979
            if(h->ref_count[0] > 32 || h->ref_count[1] > 32){
2980
                fprintf(stderr, "reference overflow\n");
2981
                return -1;
2982
            }
2983
        }
2984
    }
2985

    
2986
    if(first_mb_in_slice == 0){
2987
        fill_default_ref_list(h);
2988
    }
2989

    
2990
    decode_ref_pic_list_reordering(h);
2991

    
2992
    if(   (h->pps.weighted_pred          && (h->slice_type == P_TYPE || h->slice_type == SP_TYPE )) 
2993
       || (h->pps.weighted_bipred_idc==1 && h->slice_type==B_TYPE ) )
2994
        pred_weight_table(h);
2995
    
2996
    if(s->current_picture.reference)
2997
        decode_ref_pic_marking(h);
2998
    //FIXME CABAC stuff
2999

    
3000
    s->qscale = h->pps.init_qp + get_se_golomb(&s->gb); //slice_qp_delta
3001
    //FIXME qscale / qp ... stuff
3002
    if(h->slice_type == SP_TYPE){
3003
        int sp_for_switch_flag= get_bits1(&s->gb);
3004
    }
3005
    if(h->slice_type==SP_TYPE || h->slice_type == SI_TYPE){
3006
        int slice_qs_delta= get_se_golomb(&s->gb);
3007
    }
3008

    
3009
    if( h->pps.deblocking_filter_parameters_present ) {
3010
        h->disable_deblocking_filter_idc= get_ue_golomb(&s->gb);
3011
        if( h->disable_deblocking_filter_idc  !=  1 ) {
3012
            h->slice_alpha_c0_offset_div2= get_se_golomb(&s->gb);
3013
            h->slice_beta_offset_div2= get_se_golomb(&s->gb);
3014
        }
3015
    }else
3016
        h->disable_deblocking_filter_idc= 0;
3017

    
3018
#if 0 //FMO
3019
    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
3020
        slice_group_change_cycle= get_bits(&s->gb, ?);
3021
#endif
3022

    
3023
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
3024
        printf("mb:%d %c pps:%d frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d\n", 
3025
               first_mb_in_slice, 
3026
               av_get_pict_type_char(h->slice_type),
3027
               pps_id, h->frame_num,
3028
               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
3029
               h->ref_count[0], h->ref_count[1],
3030
               s->qscale,
3031
               h->disable_deblocking_filter_idc
3032
               );
3033
    }
3034

    
3035
    return 0;
3036
}
3037

    
3038
/**
3039
 *
3040
 */
3041
static inline int get_level_prefix(GetBitContext *gb){
3042
    unsigned int buf;
3043
    int log;
3044
    
3045
    OPEN_READER(re, gb);
3046
    UPDATE_CACHE(re, gb);
3047
    buf=GET_CACHE(re, gb);
3048
    
3049
    log= 32 - av_log2(buf);
3050
#ifdef TRACE
3051
    print_bin(buf>>(32-log), log);
3052
    printf("%5d %2d %3d lpr @%5d in %s get_level_prefix\n", buf>>(32-log), log, log-1, get_bits_count(gb), __FILE__);
3053
#endif
3054

    
3055
    LAST_SKIP_BITS(re, gb, log);
3056
    CLOSE_READER(re, gb);
3057

    
3058
    return log-1;
3059
}
3060

    
3061
/**
3062
 * decodes a residual block.
3063
 * @param n block index
3064
 * @param scantable scantable
3065
 * @param max_coeff number of coefficients in the block
3066
 * @return <0 if an error occured
3067
 */
3068
static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, int qp, int max_coeff){
3069
    MpegEncContext * const s = &h->s;
3070
    const uint16_t *qmul= dequant_coeff[qp];
3071
    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};
3072
    int level[16], run[16];
3073
    int suffix_length, zeros_left, coeff_num, coeff_token, total_coeff, i, trailing_ones;
3074

    
3075
    //FIXME put trailing_onex into the context
3076

    
3077
    if(n == CHROMA_DC_BLOCK_INDEX){
3078
        coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
3079
        total_coeff= coeff_token>>2;
3080
    }else{    
3081
        if(n == LUMA_DC_BLOCK_INDEX){
3082
            total_coeff= pred_non_zero_count(h, 0);
3083
            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
3084
            total_coeff= coeff_token>>2;
3085
        }else{
3086
            total_coeff= pred_non_zero_count(h, n);
3087
            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
3088
            total_coeff= coeff_token>>2;
3089
            h->non_zero_count_cache[ scan8[n] ]= total_coeff;
3090
        }
3091
    }
3092

    
3093
    //FIXME set last_non_zero?
3094

    
3095
    if(total_coeff==0)
3096
        return 0;
3097
        
3098
    trailing_ones= coeff_token&3;
3099
    tprintf("trailing:%d, total:%d\n", trailing_ones, total_coeff);
3100
    assert(total_coeff<=16);
3101
    
3102
    for(i=0; i<trailing_ones; i++){
3103
        level[i]= 1 - 2*get_bits1(gb);
3104
    }
3105

    
3106
    suffix_length= total_coeff > 10 && trailing_ones < 3;
3107

    
3108
    for(; i<total_coeff; i++){
3109
        const int prefix= get_level_prefix(gb);
3110
        int level_code, mask;
3111

    
3112
        if(prefix<14){ //FIXME try to build a large unified VLC table for all this
3113
            if(suffix_length)
3114
                level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
3115
            else
3116
                level_code= (prefix<<suffix_length); //part
3117
        }else if(prefix==14){
3118
            if(suffix_length)
3119
                level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
3120
            else
3121
                level_code= prefix + get_bits(gb, 4); //part
3122
        }else if(prefix==15){
3123
            level_code= (prefix<<suffix_length) + get_bits(gb, 12); //part
3124
            if(suffix_length==0) level_code+=15; //FIXME doesnt make (much)sense
3125
        }else{
3126
            fprintf(stderr, "prefix too large at %d %d\n", s->mb_x, s->mb_y);
3127
            return -1;
3128
        }
3129

    
3130
        if(i==trailing_ones && i<3) level_code+= 2; //FIXME split first iteration
3131

    
3132
        mask= -(level_code&1);
3133
        level[i]= (((2+level_code)>>1) ^ mask) - mask;
3134

    
3135
        if(suffix_length==0) suffix_length=1; //FIXME split first iteration
3136

    
3137
#if 1
3138
        if(ABS(level[i]) > (3<<(suffix_length-1)) && suffix_length<6) suffix_length++;
3139
#else        
3140
        if((2+level_code)>>1) > (3<<(suffix_length-1)) && suffix_length<6) suffix_length++;
3141
        ? == prefix > 2 or sth
3142
#endif
3143
        tprintf("level: %d suffix_length:%d\n", level[i], suffix_length);
3144
    }
3145

    
3146
    if(total_coeff == max_coeff)
3147
        zeros_left=0;
3148
    else{
3149
        if(n == CHROMA_DC_BLOCK_INDEX)
3150
            zeros_left= get_vlc2(gb, chroma_dc_total_zeros_vlc[ total_coeff-1 ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
3151
        else
3152
            zeros_left= get_vlc2(gb, total_zeros_vlc[ total_coeff-1 ].table, TOTAL_ZEROS_VLC_BITS, 1);
3153
    }
3154
    
3155
    for(i=0; i<total_coeff-1; i++){
3156
        if(zeros_left <=0)
3157
            break;
3158
        else if(zeros_left < 7){
3159
            run[i]= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
3160
        }else{
3161
            run[i]= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
3162
        }
3163
        zeros_left -= run[i];
3164
    }
3165

    
3166
    if(zeros_left<0){
3167
        fprintf(stderr, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);
3168
        return -1;
3169
    }
3170
    
3171
    for(; i<total_coeff-1; i++){
3172
        run[i]= 0;
3173
    }
3174

    
3175
    run[i]= zeros_left;
3176

    
3177
    coeff_num=-1;
3178
    if(n > 24){
3179
        for(i=total_coeff-1; i>=0; i--){ //FIXME merge into rundecode?
3180
            int j;
3181

    
3182
            coeff_num += run[i] + 1; //FIXME add 1 earlier ?
3183
            j= scantable[ coeff_num ];
3184

    
3185
            block[j]= level[i];
3186
        }
3187
    }else{
3188
        for(i=total_coeff-1; i>=0; i--){ //FIXME merge into  rundecode?
3189
            int j;
3190

    
3191
            coeff_num += run[i] + 1; //FIXME add 1 earlier ?
3192
            j= scantable[ coeff_num ];
3193

    
3194
            block[j]= level[i] * qmul[j];
3195
//            printf("%d %d  ", block[j], qmul[j]);
3196
        }
3197
    }
3198
    return 0;
3199
}
3200

    
3201
/**
3202
 * decodes a macroblock
3203
 * @returns 0 if ok, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
3204
 */
3205
static int decode_mb(H264Context *h){
3206
    MpegEncContext * const s = &h->s;
3207
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
3208
    int mb_type, partition_count, cbp;
3209

    
3210
    s->dsp.clear_blocks(h->mb); //FIXME avoid if allready clear (move after skip handlong?    
3211

    
3212
    tprintf("pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
3213

    
3214
    if(h->slice_type != I_TYPE && h->slice_type != SI_TYPE){
3215
        if(s->mb_skip_run==-1)
3216
            s->mb_skip_run= get_ue_golomb(&s->gb);
3217
        
3218
        if (s->mb_skip_run--) {
3219
            int mx, my;
3220
            /* skip mb */
3221
//FIXME b frame
3222
            mb_type= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P1L0;
3223

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

    
3227
            if(h->sps.mb_aff && s->mb_skip_run==0 && (s->mb_y&1)==0){
3228
                h->mb_field_decoding_flag= get_bits1(&s->gb);
3229
            }
3230

    
3231
            if(h->mb_field_decoding_flag)
3232
                mb_type|= MB_TYPE_INTERLACED;
3233
            
3234
            fill_caches(h, mb_type); //FIXME check what is needed and what not ...
3235
            pred_pskip_motion(h, &mx, &my);
3236
            fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
3237
            fill_rectangle(  h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx,my), 4);
3238
            write_back_motion(h, mb_type);
3239

    
3240
            s->current_picture.mb_type[mb_xy]= mb_type; //FIXME SKIP type
3241
            h->slice_table[ mb_xy ]= h->slice_num;
3242

    
3243
            h->prev_mb_skiped= 1;
3244
            return 0;
3245
        }
3246
    }
3247
    if(h->sps.mb_aff /* && !field pic FIXME needed? */){
3248
        if((s->mb_y&1)==0)
3249
            h->mb_field_decoding_flag = get_bits1(&s->gb);
3250
    }else
3251
        h->mb_field_decoding_flag=0; //FIXME som ed note ?!
3252
    
3253
    h->prev_mb_skiped= 0;
3254
    
3255
    mb_type= get_ue_golomb(&s->gb);
3256
    if(h->slice_type == B_TYPE){
3257
        if(mb_type < 23){
3258
            partition_count= b_mb_type_info[mb_type].partition_count;
3259
            mb_type=         b_mb_type_info[mb_type].type;
3260
        }else{
3261
            mb_type -= 23;
3262
            goto decode_intra_mb;
3263
        }
3264
    }else if(h->slice_type == P_TYPE /*|| h->slice_type == SP_TYPE */){
3265
        if(mb_type < 5){
3266
            partition_count= p_mb_type_info[mb_type].partition_count;
3267
            mb_type=         p_mb_type_info[mb_type].type;
3268
        }else{
3269
            mb_type -= 5;
3270
            goto decode_intra_mb;
3271
        }
3272
    }else{
3273
       assert(h->slice_type == I_TYPE);
3274
decode_intra_mb:
3275
        if(mb_type > 25){
3276
            fprintf(stderr, "mb_type %d in %c slice to large at %d %d\n", mb_type, av_get_pict_type_char(h->slice_type), s->mb_x, s->mb_y);
3277
            return -1;
3278
        }
3279
        partition_count=0;
3280
        cbp= i_mb_type_info[mb_type].cbp;
3281
        h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
3282
        mb_type= i_mb_type_info[mb_type].type;
3283
    }
3284

    
3285
    if(h->mb_field_decoding_flag)
3286
        mb_type |= MB_TYPE_INTERLACED;
3287

    
3288
    s->current_picture.mb_type[mb_xy]= mb_type;
3289
    h->slice_table[ mb_xy ]= h->slice_num;
3290
    
3291
    if(IS_INTRA_PCM(mb_type)){
3292
        const uint8_t *ptr;
3293
        int x, y;
3294
        
3295
        // we assume these blocks are very rare so we dont optimize it
3296
        align_get_bits(&s->gb);
3297
        
3298
        ptr= s->gb.buffer + get_bits_count(&s->gb);
3299
    
3300
        for(y=0; y<16; y++){
3301
            const int index= 4*(y&3) + 64*(y>>2);
3302
            for(x=0; x<16; x++){
3303
                h->mb[index + (x&3) + 16*(x>>2)]= *(ptr++);
3304
            }
3305
        }
3306
        for(y=0; y<8; y++){
3307
            const int index= 256 + 4*(y&3) + 32*(y>>2);
3308
            for(x=0; x<8; x++){
3309
                h->mb[index + (x&3) + 16*(x>>2)]= *(ptr++);
3310
            }
3311
        }
3312
        for(y=0; y<8; y++){
3313
            const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
3314
            for(x=0; x<8; x++){
3315
                h->mb[index + (x&3) + 16*(x>>2)]= *(ptr++);
3316
            }
3317
        }
3318
    
3319
        skip_bits(&s->gb, 384); //FIXME check /fix the bitstream readers
3320
        
3321
        memset(h->non_zero_count[mb_xy], 16, 16);
3322
        
3323
        return 0;
3324
    }
3325
        
3326
    fill_caches(h, mb_type);
3327

    
3328
    //mb_pred
3329
    if(IS_INTRA(mb_type)){
3330
//            init_top_left_availability(h);
3331
            if(IS_INTRA4x4(mb_type)){
3332
                int i;
3333

    
3334
//                fill_intra4x4_pred_table(h);
3335
                for(i=0; i<16; i++){
3336
                    const int mode_coded= !get_bits1(&s->gb);
3337
                    const int predicted_mode=  pred_intra_mode(h, i);
3338
                    int mode;
3339

    
3340
                    if(mode_coded){
3341
                        const int rem_mode= get_bits(&s->gb, 3);
3342
                        if(rem_mode<predicted_mode)
3343
                            mode= rem_mode;
3344
                        else
3345
                            mode= rem_mode + 1;
3346
                    }else{
3347
                        mode= predicted_mode;
3348
                    }
3349
                    
3350
                    h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;
3351
                }
3352
                write_back_intra_pred_mode(h);
3353
                if( check_intra4x4_pred_mode(h) < 0)
3354
                    return -1;
3355
            }else{
3356
                h->intra16x16_pred_mode= check_intra_pred_mode(h, h->intra16x16_pred_mode);
3357
                if(h->intra16x16_pred_mode < 0)
3358
                    return -1;
3359
            }
3360
            h->chroma_pred_mode= get_ue_golomb(&s->gb);
3361

    
3362
            h->chroma_pred_mode= check_intra_pred_mode(h, h->chroma_pred_mode);
3363
            if(h->chroma_pred_mode < 0)
3364
                return -1;
3365
    }else if(partition_count==4){
3366
        int i, j, sub_partition_count[4], list, ref[2][4];
3367
        
3368
        if(h->slice_type == B_TYPE){
3369
            for(i=0; i<4; i++){
3370
                h->sub_mb_type[i]= get_ue_golomb(&s->gb);
3371
                if(h->sub_mb_type[i] >=13){
3372
                    fprintf(stderr, "B sub_mb_type %d out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);
3373
                    return -1;
3374
                }
3375
                sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
3376
                h->sub_mb_type[i]=      b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
3377
            }
3378
        }else{
3379
            assert(h->slice_type == P_TYPE || h->slice_type == SP_TYPE); //FIXME SP correct ?
3380
            for(i=0; i<4; i++){
3381
                h->sub_mb_type[i]= get_ue_golomb(&s->gb);
3382
                if(h->sub_mb_type[i] >=4){
3383
                    fprintf(stderr, "P sub_mb_type %d out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);
3384
                    return -1;
3385
                }
3386
                sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
3387
                h->sub_mb_type[i]=      p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
3388
            }
3389
        }
3390
        
3391
        for(list=0; list<2; list++){
3392
            const int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
3393
            if(ref_count == 0) continue;
3394
            for(i=0; i<4; i++){
3395
                if(IS_DIR(h->sub_mb_type[i], 0, list) && !IS_DIRECT(h->sub_mb_type[i])){
3396
                    ref[list][i] = get_te0_golomb(&s->gb, ref_count); //FIXME init to 0 before and skip?
3397
                }else{
3398
                 //FIXME
3399
                    ref[list][i] = -1;
3400
                }
3401
            }
3402
        }
3403
        
3404
        for(list=0; list<2; list++){
3405
            const int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
3406
            if(ref_count == 0) continue;
3407

    
3408
            for(i=0; i<4; i++){
3409
                h->ref_cache[list][ scan8[4*i]   ]=h->ref_cache[list][ scan8[4*i]+1 ]=
3410
                h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
3411

    
3412
                if(IS_DIR(h->sub_mb_type[i], 0, list) && !IS_DIRECT(h->sub_mb_type[i])){
3413
                    const int sub_mb_type= h->sub_mb_type[i];
3414
                    const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
3415
                    for(j=0; j<sub_partition_count[i]; j++){
3416
                        int mx, my;
3417
                        const int index= 4*i + block_width*j;
3418
                        int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
3419
                        pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);
3420
                        mx += get_se_golomb(&s->gb);
3421
                        my += get_se_golomb(&s->gb);
3422
                        tprintf("final mv:%d %d\n", mx, my);
3423

    
3424
                        if(IS_SUB_8X8(sub_mb_type)){
3425
                            mv_cache[ 0 ][0]= mv_cache[ 1 ][0]= 
3426
                            mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
3427
                            mv_cache[ 0 ][1]= mv_cache[ 1 ][1]= 
3428
                            mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
3429
                        }else if(IS_SUB_8X4(sub_mb_type)){
3430
                            mv_cache[ 0 ][0]= mv_cache[ 1 ][0]= mx;
3431
                            mv_cache[ 0 ][1]= mv_cache[ 1 ][1]= my;
3432
                        }else if(IS_SUB_4X8(sub_mb_type)){
3433
                            mv_cache[ 0 ][0]= mv_cache[ 8 ][0]= mx;
3434
                            mv_cache[ 0 ][1]= mv_cache[ 8 ][1]= my;
3435
                        }else{
3436
                            assert(IS_SUB_4X4(sub_mb_type));
3437
                            mv_cache[ 0 ][0]= mx;
3438
                            mv_cache[ 0 ][1]= my;
3439
                        }
3440
                    }
3441
                }else{
3442
                    uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
3443
                    p[0] = p[1]=
3444
                    p[8] = p[9]= 0;
3445
                }
3446
            }
3447
        }
3448
    }else if(!IS_DIRECT(mb_type)){
3449
        int list, mx, my, i;
3450
         //FIXME we should set ref_idx_l? to 0 if we use that later ...
3451
        if(IS_16X16(mb_type)){
3452
            for(list=0; list<2; list++){
3453
                if(h->ref_count[0]>0){
3454
                    if(IS_DIR(mb_type, 0, list)){
3455
                        const int val= get_te0_golomb(&s->gb, h->ref_count[list]);
3456
                        fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);
3457
                    }
3458
                }
3459
            }
3460
            for(list=0; list<2; list++){
3461
                if(IS_DIR(mb_type, 0, list)){
3462
                    pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);
3463
                    mx += get_se_golomb(&s->gb);
3464
                    my += get_se_golomb(&s->gb);
3465
                    tprintf("final mv:%d %d\n", mx, my);
3466

    
3467
                    fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);
3468
                }
3469
            }
3470
        }
3471
        else if(IS_16X8(mb_type)){
3472
            for(list=0; list<2; list++){
3473
                if(h->ref_count[list]>0){
3474
                    for(i=0; i<2; i++){
3475
                        if(IS_DIR(mb_type, i, list)){
3476
                            const int val= get_te0_golomb(&s->gb, h->ref_count[list]);
3477
                            fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);
3478
                        }
3479
                    }
3480
                }
3481
            }
3482
            for(list=0; list<2; list++){
3483
                for(i=0; i<2; i++){
3484
                    if(IS_DIR(mb_type, i, list)){
3485
                        pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);
3486
                        mx += get_se_golomb(&s->gb);
3487
                        my += get_se_golomb(&s->gb);
3488
                        tprintf("final mv:%d %d\n", mx, my);
3489

    
3490
                        fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx,my), 4);
3491
                    }
3492
                }
3493
            }
3494
        }else{
3495
            assert(IS_8X16(mb_type));
3496
            for(list=0; list<2; list++){
3497
                if(h->ref_count[list]>0){
3498
                    for(i=0; i<2; i++){
3499
                        if(IS_DIR(mb_type, i, list)){ //FIXME optimize
3500
                            const int val= get_te0_golomb(&s->gb, h->ref_count[list]);
3501
                            fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);
3502
                        }
3503
                    }
3504
                }
3505
            }
3506
            for(list=0; list<2; list++){
3507
                for(i=0; i<2; i++){
3508
                    if(IS_DIR(mb_type, i, list)){
3509
                        pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
3510
                        mx += get_se_golomb(&s->gb);
3511
                        my += get_se_golomb(&s->gb);
3512
                        tprintf("final mv:%d %d\n", mx, my);
3513

    
3514
                        fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx,my), 4);
3515
                    }
3516
                }
3517
            }
3518
        }
3519
    }
3520
    
3521
    if(IS_INTER(mb_type))
3522
        write_back_motion(h, mb_type);
3523
    
3524
    if(!IS_INTRA16x16(mb_type)){
3525
        cbp= get_ue_golomb(&s->gb);
3526
        if(cbp > 47){
3527
            fprintf(stderr, "cbp too large (%d) at %d %d\n", cbp, s->mb_x, s->mb_y);
3528
            return -1;
3529
        }
3530
        
3531
        if(IS_INTRA4x4(mb_type))
3532
            cbp= golomb_to_intra4x4_cbp[cbp];
3533
        else
3534
            cbp= golomb_to_inter_cbp[cbp];
3535
    }
3536

    
3537
    if(cbp || IS_INTRA16x16(mb_type)){
3538
        int i8x8, i4x4, chroma_idx;
3539
        int chroma_qp, dquant;
3540
        GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;
3541
        const uint8_t *scan, *dc_scan;
3542
        
3543
//        fill_non_zero_count_cache(h);
3544

    
3545
        if(IS_INTERLACED(mb_type)){
3546
            scan= field_scan;
3547
            dc_scan= luma_dc_field_scan;
3548
        }else{
3549
            scan= zigzag_scan;
3550
            dc_scan= luma_dc_zigzag_scan;
3551
        }
3552

    
3553
        dquant= get_se_golomb(&s->gb);
3554

    
3555
        if( dquant > 25 || dquant < -26 ){
3556
            fprintf(stderr, "dquant out of range (%d) at %d %d\n", dquant, s->mb_x, s->mb_y);
3557
            return -1;
3558
        }
3559
        
3560
        s->qscale += dquant;
3561
        if(((unsigned)s->qscale) > 51){
3562
            if(s->qscale<0) s->qscale+= 52;
3563
            else            s->qscale-= 52;
3564
        }
3565
        
3566
        h->chroma_qp= chroma_qp= get_chroma_qp(h, s->qscale);
3567
        if(IS_INTRA16x16(mb_type)){
3568
            if( decode_residual(h, h->intra_gb_ptr, h->mb, LUMA_DC_BLOCK_INDEX, dc_scan, s->qscale, 16) < 0){
3569
                return -1; //FIXME continue if partotioned and other retirn -1 too
3570
            }
3571

    
3572
            assert((cbp&15) == 0 || (cbp&15) == 15);
3573

    
3574
            if(cbp&15){
3575
                for(i8x8=0; i8x8<4; i8x8++){
3576
                    for(i4x4=0; i4x4<4; i4x4++){
3577
                        const int index= i4x4 + 4*i8x8;
3578
                        if( decode_residual(h, h->intra_gb_ptr, h->mb + 16*index, index, scan + 1, s->qscale, 15) < 0 ){
3579
                            return -1;
3580
                        }
3581
                    }
3582
                }
3583
            }else{
3584
                memset(&h->non_zero_count_cache[8], 0, 8*4); //FIXME stupid & slow
3585
            }
3586
        }else{
3587
            for(i8x8=0; i8x8<4; i8x8++){
3588
                if(cbp & (1<<i8x8)){
3589
                    for(i4x4=0; i4x4<4; i4x4++){
3590
                        const int index= i4x4 + 4*i8x8;
3591
                        
3592
                        if( decode_residual(h, gb, h->mb + 16*index, index, scan, s->qscale, 16) <0 ){
3593
                            return -1;
3594
                        }
3595
                    }
3596
                }else{
3597
                    uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
3598
                    nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
3599
                }
3600
            }
3601
        }
3602
        
3603
        if(cbp&0x30){
3604
            for(chroma_idx=0; chroma_idx<2; chroma_idx++)
3605
                if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX, chroma_dc_scan, chroma_qp, 4) < 0){
3606
                    return -1;
3607
                }
3608
        }
3609

    
3610
        if(cbp&0x20){
3611
            for(chroma_idx=0; chroma_idx<2; chroma_idx++){
3612
                for(i4x4=0; i4x4<4; i4x4++){
3613
                    const int index= 16 + 4*chroma_idx + i4x4;
3614
                    if( decode_residual(h, gb, h->mb + 16*index, index, scan + 1, chroma_qp, 15) < 0){
3615
                        return -1;
3616
                    }
3617
                }
3618
            }
3619
        }else{
3620
            uint8_t * const nnz= &h->non_zero_count_cache[0];
3621
            nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
3622
            nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
3623
        }
3624
    }else{
3625
        memset(&h->non_zero_count_cache[8], 0, 8*5);
3626
    }
3627
    write_back_non_zero_count(h);
3628

    
3629
    return 0;
3630
}
3631

    
3632
static int decode_slice(H264Context *h){
3633
    MpegEncContext * const s = &h->s;
3634
    const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
3635

    
3636
    s->mb_skip_run= -1;
3637
    
3638
#if 1
3639
    for(;;){
3640
        int ret= decode_mb(h);
3641
            
3642
        hl_decode_mb(h);
3643
        
3644
        if(ret>=0 && h->sps.mb_aff){ //FIXME optimal? or let mb_decode decode 16x32 ?
3645
            s->mb_y++;
3646
            ret= decode_mb(h);
3647
            
3648
            hl_decode_mb(h);
3649
            s->mb_y--;
3650
        }
3651

    
3652
        if(ret<0){
3653
            fprintf(stderr, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3654
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
3655

    
3656
            return -1;
3657
        }
3658
        
3659
        if(++s->mb_x >= s->mb_width){
3660
            s->mb_x=0;
3661
            ff_draw_horiz_band(s, 16*s->mb_y, 16);
3662
            if(++s->mb_y >= s->mb_height){
3663
                tprintf("slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
3664

    
3665
                if(get_bits_count(&s->gb) == s->gb.size_in_bits){
3666
                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3667

    
3668
                    return 0;
3669
                }else{
3670
                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3671

    
3672
                    return -1;
3673
                }
3674
            }
3675
        }
3676
        
3677
        if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
3678
            if(get_bits_count(&s->gb) == s->gb.size_in_bits){
3679
                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3680

    
3681
                return 0;
3682
            }else{
3683
                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
3684

    
3685
                return -1;
3686
            }
3687
        }
3688
    }
3689
#endif
3690
#if 0
3691
    for(;s->mb_y < s->mb_height; s->mb_y++){
3692
        for(;s->mb_x < s->mb_width; s->mb_x++){
3693
            int ret= decode_mb(h);
3694
            
3695
            hl_decode_mb(h);
3696

3697
            if(ret<0){
3698
                fprintf(stderr, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
3699
                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
3700

3701
                return -1;
3702
            }
3703
        
3704
            if(++s->mb_x >= s->mb_width){
3705
                s->mb_x=0;
3706
                if(++s->mb_y >= s->mb_height){
3707
                    if(get_bits_count(s->gb) == s->gb.size_in_bits){
3708
                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3709

3710
                        return 0;
3711
                    }else{
3712
                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3713

3714
                        return -1;
3715
                    }
3716
                }
3717
            }
3718
        
3719
            if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
3720
                if(get_bits_count(s->gb) == s->gb.size_in_bits){
3721
                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
3722

3723
                    return 0;
3724
                }else{
3725
                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
3726

3727
                    return -1;
3728
                }
3729
            }
3730
        }
3731
        s->mb_x=0;
3732
        ff_draw_horiz_band(s, 16*s->mb_y, 16);
3733
    }
3734
#endif
3735
    return -1; //not reached
3736
}
3737

    
3738
static inline int decode_vui_parameters(H264Context *h, SPS *sps){
3739
    MpegEncContext * const s = &h->s;
3740
    int aspect_ratio_info_present_flag, aspect_ratio_idc;
3741

    
3742
    aspect_ratio_info_present_flag= get_bits1(&s->gb);
3743
    
3744
    if( aspect_ratio_info_present_flag ) {
3745
        aspect_ratio_idc= get_bits(&s->gb, 8);
3746
        if( aspect_ratio_idc == EXTENDED_SAR ) {
3747
            sps->sar_width= get_bits(&s->gb, 16);
3748
            sps->sar_height= get_bits(&s->gb, 16);
3749
        }else if(aspect_ratio_idc < 16){
3750
            sps->sar_width=  pixel_aspect[aspect_ratio_idc][0];
3751
            sps->sar_height= pixel_aspect[aspect_ratio_idc][1];
3752
        }else{
3753
            fprintf(stderr, "illegal aspect ratio\n");
3754
            return -1;
3755
        }
3756
    }else{
3757
        sps->sar_width= 
3758
        sps->sar_height= 0;
3759
    }
3760
//            s->avctx->aspect_ratio= sar_width*s->width / (float)(s->height*sar_height);
3761
#if 0
3762
| overscan_info_present_flag                        |0  |u(1)    |
3763
| if( overscan_info_present_flag )                  |   |        |
3764
|  overscan_appropriate_flag                        |0  |u(1)    |
3765
| video_signal_type_present_flag                    |0  |u(1)    |
3766
| if( video_signal_type_present_flag ) {            |   |        |
3767
|  video_format                                     |0  |u(3)    |
3768
|  video_full_range_flag                            |0  |u(1)    |
3769
|  colour_description_present_flag                  |0  |u(1)    |
3770
|  if( colour_description_present_flag ) {          |   |        |
3771
|   colour_primaries                                |0  |u(8)    |
3772
|   transfer_characteristics                        |0  |u(8)    |
3773
|   matrix_coefficients                             |0  |u(8)    |
3774
|  }                                                |   |        |
3775
| }                                                 |   |        |
3776
| chroma_location_info_present_flag                 |0  |u(1)    |
3777
| if ( chroma_location_info_present_flag ) {        |   |        |
3778
|  chroma_sample_location_type_top_field            |0  |ue(v)   |
3779
|  chroma_sample_location_type_bottom_field         |0  |ue(v)   |
3780
| }                                                 |   |        |
3781
| timing_info_present_flag                          |0  |u(1)    |
3782
| if( timing_info_present_flag ) {                  |   |        |
3783
|  num_units_in_tick                                |0  |u(32)   |
3784
|  time_scale                                       |0  |u(32)   |
3785
|  fixed_frame_rate_flag                            |0  |u(1)    |
3786
| }                                                 |   |        |
3787
| nal_hrd_parameters_present_flag                   |0  |u(1)    |
3788
| if( nal_hrd_parameters_present_flag  = =  1)      |   |        |
3789
|  hrd_parameters( )                                |   |        |
3790
| vcl_hrd_parameters_present_flag                   |0  |u(1)    |
3791
| if( vcl_hrd_parameters_present_flag  = =  1)      |   |        |
3792
|  hrd_parameters( )                                |   |        |
3793
| if( ( nal_hrd_parameters_present_flag  = =  1  | ||   |        |
3794
|                                                   |   |        |
3795
|( vcl_hrd_parameters_present_flag  = =  1 ) )      |   |        |
3796
|  low_delay_hrd_flag                               |0  |u(1)    |
3797
| bitstream_restriction_flag                        |0  |u(1)    |
3798
| if( bitstream_restriction_flag ) {                |0  |u(1)    |
3799
|  motion_vectors_over_pic_boundaries_flag          |0  |u(1)    |
3800
|  max_bytes_per_pic_denom                          |0  |ue(v)   |
3801
|  max_bits_per_mb_denom                            |0  |ue(v)   |
3802
|  log2_max_mv_length_horizontal                    |0  |ue(v)   |
3803
|  log2_max_mv_length_vertical                      |0  |ue(v)   |
3804
|  num_reorder_frames                               |0  |ue(v)   |
3805
|  max_dec_frame_buffering                          |0  |ue(v)   |
3806
| }                                                 |   |        |
3807
|}                                                  |   |        |
3808
#endif
3809
    return 0;
3810
}
3811

    
3812
static inline int decode_seq_parameter_set(H264Context *h){
3813
    MpegEncContext * const s = &h->s;
3814
    int profile_idc, level_idc, multiple_slice_groups, arbitrary_slice_order, redundant_slices;
3815
    int sps_id, i;
3816
    SPS *sps;
3817
    
3818
    profile_idc= get_bits(&s->gb, 8);
3819
    level_idc= get_bits(&s->gb, 8);
3820
    multiple_slice_groups= get_bits1(&s->gb);
3821
    arbitrary_slice_order= get_bits1(&s->gb);
3822
    redundant_slices= get_bits1(&s->gb);
3823
    
3824
    sps_id= get_ue_golomb(&s->gb);
3825
    
3826
    sps= &h->sps_buffer[ sps_id ];
3827
    
3828
    sps->profile_idc= profile_idc;
3829
    sps->level_idc= level_idc;
3830
    sps->multiple_slice_groups= multiple_slice_groups;
3831
    sps->arbitrary_slice_order= arbitrary_slice_order;
3832
    sps->redundant_slices= redundant_slices;
3833
    
3834
    sps->log2_max_frame_num= get_ue_golomb(&s->gb) + 4;
3835

    
3836
    sps->poc_type= get_ue_golomb(&s->gb);
3837
    
3838
    if(sps->poc_type == 0){ //FIXME #define
3839
        sps->log2_max_poc_lsb= get_ue_golomb(&s->gb) + 4;
3840
    } else if(sps->poc_type == 1){//FIXME #define
3841
        sps->delta_pic_order_always_zero_flag= get_bits1(&s->gb);
3842
        sps->offset_for_non_ref_pic= get_se_golomb(&s->gb);
3843
        sps->offset_for_top_to_bottom_field= get_se_golomb(&s->gb);
3844
        sps->poc_cycle_length= get_ue_golomb(&s->gb);
3845
        
3846
        for(i=0; i<sps->poc_cycle_length; i++)
3847
            sps->offset_for_ref_frame[i]= get_se_golomb(&s->gb);
3848
    }
3849
    if(sps->poc_type > 2){
3850
        fprintf(stderr, "illegal POC type %d\n", sps->poc_type);
3851
        return -1;
3852
    }
3853

    
3854
    sps->ref_frame_count= get_ue_golomb(&s->gb);
3855
    sps->required_frame_num_update_behaviour_flag= get_bits1(&s->gb);
3856
    sps->mb_width= get_ue_golomb(&s->gb) + 1;
3857
    sps->mb_height= get_ue_golomb(&s->gb) + 1;
3858
    sps->frame_mbs_only_flag= get_bits1(&s->gb);
3859
    if(!sps->frame_mbs_only_flag)
3860
        sps->mb_aff= get_bits1(&s->gb);
3861
    else
3862
        sps->mb_aff= 0;
3863

    
3864
    sps->direct_8x8_inference_flag= get_bits1(&s->gb);
3865

    
3866
    sps->vui_parameters_present_flag= get_bits1(&s->gb);
3867
    if( sps->vui_parameters_present_flag )
3868
        decode_vui_parameters(h, sps);
3869
    
3870
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
3871
        printf("sps:%d profile:%d/%d poc:%d ref:%d %dx%d %s %s %s\n", 
3872
               sps_id, sps->profile_idc, sps->level_idc,
3873
               sps->poc_type,
3874
               sps->ref_frame_count,
3875
               sps->mb_width, sps->mb_height,
3876
               sps->frame_mbs_only_flag ? "FRM" : (sps->mb_aff ? "MB-AFF" : "PIC-AFF"),
3877
               sps->direct_8x8_inference_flag ? "8B8" : "",
3878
               sps->vui_parameters_present_flag ? "VUI" : ""
3879
               );
3880
    }
3881
    return 0;
3882
}
3883

    
3884
static inline int decode_picture_parameter_set(H264Context *h){
3885
    MpegEncContext * const s = &h->s;
3886
    int pps_id= get_ue_golomb(&s->gb);
3887
    PPS *pps= &h->pps_buffer[pps_id];
3888
    
3889
    pps->sps_id= get_ue_golomb(&s->gb);
3890
    pps->cabac= get_bits1(&s->gb);
3891
    pps->pic_order_present= get_bits1(&s->gb);
3892
    pps->slice_group_count= get_ue_golomb(&s->gb) + 1;
3893
    if(pps->slice_group_count > 1 ){
3894
        pps->mb_slice_group_map_type= get_ue_golomb(&s->gb);
3895
fprintf(stderr, "FMO not supported\n");
3896
        switch(pps->mb_slice_group_map_type){
3897
        case 0:
3898
#if 0
3899
|   for( i = 0; i <= num_slice_groups_minus1; i++ ) |   |        |
3900
|    run_length[ i ]                                |1  |ue(v)   |
3901
#endif
3902
            break;
3903
        case 2:
3904
#if 0
3905
|   for( i = 0; i < num_slice_groups_minus1; i++ )  |   |        |
3906
|{                                                  |   |        |
3907
|    top_left_mb[ i ]                               |1  |ue(v)   |
3908
|    bottom_right_mb[ i ]                           |1  |ue(v)   |
3909
|   }                                               |   |        |
3910
#endif
3911
            break;
3912
        case 3:
3913
        case 4:
3914
        case 5:
3915
#if 0
3916
|   slice_group_change_direction_flag               |1  |u(1)    |
3917
|   slice_group_change_rate_minus1                  |1  |ue(v)   |
3918
#endif
3919
            break;
3920
        case 6:
3921
#if 0
3922
|   slice_group_id_cnt_minus1                       |1  |ue(v)   |
3923
|   for( i = 0; i <= slice_group_id_cnt_minus1; i++ |   |        |
3924
|)                                                  |   |        |
3925
|    slice_group_id[ i ]                            |1  |u(v)    |
3926
#endif
3927
            break;
3928
        }
3929
    }
3930
    pps->ref_count[0]= get_ue_golomb(&s->gb) + 1;
3931
    pps->ref_count[1]= get_ue_golomb(&s->gb) + 1;
3932
    if(pps->ref_count[0] > 32 || pps->ref_count[1] > 32){
3933
        fprintf(stderr, "reference overflow (pps)\n");
3934
        return -1;
3935
    }
3936
    
3937
    pps->weighted_pred= get_bits1(&s->gb);
3938
    pps->weighted_bipred_idc= get_bits(&s->gb, 2);
3939
    pps->init_qp= get_se_golomb(&s->gb) + 26;
3940
    pps->init_qs= get_se_golomb(&s->gb) + 26;
3941
    pps->chroma_qp_index_offset= get_se_golomb(&s->gb);
3942
    pps->deblocking_filter_parameters_present= get_bits1(&s->gb);
3943
    pps->constrained_intra_pred= get_bits1(&s->gb);
3944
    pps->redundant_pic_cnt_present = get_bits1(&s->gb);
3945
    pps->crop= get_bits1(&s->gb);
3946
    if(pps->crop){
3947
        pps->crop_left  = get_ue_golomb(&s->gb);
3948
        pps->crop_right = get_ue_golomb(&s->gb);
3949
        pps->crop_top   = get_ue_golomb(&s->gb);
3950
        pps->crop_bottom= get_ue_golomb(&s->gb);
3951
    }else{
3952
        pps->crop_left  = 
3953
        pps->crop_right = 
3954
        pps->crop_top   = 
3955
        pps->crop_bottom= 0;
3956
    }
3957
    
3958
    if(s->avctx->debug&FF_DEBUG_PICT_INFO){
3959
        printf("pps:%d sps:%d %s slice_groups:%d ref:%d/%d %s qp:%d/%d/%d %s %s %s crop:%d/%d/%d/%d\n", 
3960
               pps_id, pps->sps_id,
3961
               pps->cabac ? "CABAC" : "CAVLC",
3962
               pps->slice_group_count,
3963
               pps->ref_count[0], pps->ref_count[1],
3964
               pps->weighted_pred ? "weighted" : "",
3965
               pps->init_qp, pps->init_qs, pps->chroma_qp_index_offset,
3966
               pps->deblocking_filter_parameters_present ? "LPAR" : "",
3967
               pps->constrained_intra_pred ? "CONSTR" : "",
3968
               pps->redundant_pic_cnt_present ? "REDU" : "",
3969
               pps->crop_left, pps->crop_right, 
3970
               pps->crop_top, pps->crop_bottom
3971
               );
3972
    }
3973
    
3974
    return 0;
3975
}
3976

    
3977
/**
3978
 * finds the end of the current frame in the bitstream.
3979
 * @return the position of the first byte of the next frame, or -1
3980
 */
3981
static int find_frame_end(MpegEncContext *s, uint8_t *buf, int buf_size){
3982
    ParseContext *pc= &s->parse_context;
3983
    int i;
3984
    uint32_t state;
3985
//printf("first %02X%02X%02X%02X\n", buf[0], buf[1],buf[2],buf[3]);
3986
//    mb_addr= pc->mb_addr - 1;
3987
    state= pc->state;
3988
    //FIXME this will fail with slices
3989
    for(i=0; i<buf_size; i++){
3990
        state= (state<<8) | buf[i];
3991
        if((state&0xFFFFFF1F) == 0x101 || (state&0xFFFFFF1F) == 0x102 || (state&0xFFFFFF1F) == 0x105){
3992
            if(pc->frame_start_found){
3993
                pc->state=-1; 
3994
                pc->frame_start_found= 0;
3995
                return i-3;
3996
            }
3997
            pc->frame_start_found= 1;
3998
        }
3999
    }
4000
    
4001
    pc->state= state;
4002
    return END_NOT_FOUND;
4003
}
4004

    
4005
static int decode_nal_units(H264Context *h, uint8_t *buf, int buf_size){
4006
    MpegEncContext * const s = &h->s;
4007
    AVCodecContext * const avctx= s->avctx;
4008
    int buf_index=0;
4009
    int i;
4010
#if 0
4011
    for(i=0; i<32; i++){
4012
        printf("%X ", buf[i]);
4013
    }
4014
#endif
4015
    for(;;){
4016
        int consumed;
4017
        int dst_length;
4018
        int bit_length;
4019
        uint8_t *ptr;
4020
        
4021
        // start code prefix search
4022
        for(; buf_index + 3 < buf_size; buf_index++){
4023
            // this should allways succeed in the first iteration
4024
            if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
4025
                break;
4026
        }
4027
        
4028
        if(buf_index+3 >= buf_size) break;
4029
        
4030
        buf_index+=3;
4031
        
4032
        ptr= decode_nal(h, buf + buf_index, &dst_length, &consumed, buf_size - buf_index);
4033
        if(ptr[dst_length - 1] == 0) dst_length--;
4034
        bit_length= 8*dst_length - decode_rbsp_trailing(ptr + dst_length - 1);
4035

    
4036
        if(s->avctx->debug&FF_DEBUG_STARTCODE){
4037
            printf("NAL %d at %d length %d\n", h->nal_unit_type, buf_index, dst_length);
4038
        }
4039
        
4040
        buf_index += consumed;
4041

    
4042
        if(h->nal_ref_idc < s->hurry_up)
4043
            continue;
4044
        
4045
        switch(h->nal_unit_type){
4046
        case NAL_IDR_SLICE:
4047
            idr(h); //FIXME ensure we dont loose some frames if there is reordering
4048
        case NAL_SLICE:
4049
            init_get_bits(&s->gb, ptr, bit_length);
4050
            h->intra_gb_ptr=
4051
            h->inter_gb_ptr= &s->gb;
4052
            s->data_partitioning = 0;
4053
            
4054
            if(decode_slice_header(h) < 0) return -1;
4055
            if(h->redundant_pic_count==0)
4056
                decode_slice(h);
4057
            break;
4058
        case NAL_DPA:
4059
            init_get_bits(&s->gb, ptr, bit_length);
4060
            h->intra_gb_ptr=
4061
            h->inter_gb_ptr= NULL;
4062
            s->data_partitioning = 1;
4063
            
4064
            if(decode_slice_header(h) < 0) return -1;
4065
            break;
4066
        case NAL_DPB:
4067
            init_get_bits(&h->intra_gb, ptr, bit_length);
4068
            h->intra_gb_ptr= &h->intra_gb;
4069
            break;
4070
        case NAL_DPC:
4071
            init_get_bits(&h->inter_gb, ptr, bit_length);
4072
            h->inter_gb_ptr= &h->inter_gb;
4073

    
4074
            if(h->redundant_pic_count==0 && h->intra_gb_ptr && s->data_partitioning)
4075
                decode_slice(h);
4076
            break;
4077
        case NAL_SEI:
4078
            break;
4079
        case NAL_SPS:
4080
            init_get_bits(&s->gb, ptr, bit_length);
4081
            decode_seq_parameter_set(h);
4082
            
4083
            if(s->flags& CODEC_FLAG_LOW_DELAY)
4084
                s->low_delay=1;
4085
      
4086
            avctx->has_b_frames= !s->low_delay;
4087
            break;
4088
        case NAL_PPS:
4089
            init_get_bits(&s->gb, ptr, bit_length);
4090
            
4091
            decode_picture_parameter_set(h);
4092

    
4093
            break;
4094
        case NAL_PICTURE_DELIMITER:
4095
            break;
4096
        case NAL_FILTER_DATA:
4097
            break;
4098
        }        
4099

    
4100
        //FIXME move after where irt is set
4101
        s->current_picture.pict_type= s->pict_type;
4102
        s->current_picture.key_frame= s->pict_type == I_TYPE;
4103
    }
4104
    
4105
    if(!s->current_picture_ptr) return buf_index; //no frame
4106
    
4107
    h->prev_frame_num_offset= h->frame_num_offset;
4108
    h->prev_frame_num= h->frame_num;
4109
    if(s->current_picture_ptr->reference){
4110
        h->prev_poc_msb= h->poc_msb;
4111
        h->prev_poc_lsb= h->poc_lsb;
4112
    }
4113
    if(s->current_picture_ptr->reference)
4114
        execute_ref_pic_marking(h, h->mmco, h->mmco_index);
4115
    else
4116
        assert(h->mmco_index==0);
4117

    
4118
    ff_er_frame_end(s);
4119
    MPV_frame_end(s);
4120

    
4121
    return buf_index;
4122
}
4123

    
4124
/**
4125
 * retunrs the number of bytes consumed for building the current frame
4126
 */
4127
static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
4128
    if(s->flags&CODEC_FLAG_TRUNCATED){
4129
        pos -= s->parse_context.last_index;
4130
        if(pos<0) pos=0; // FIXME remove (uneeded?)
4131
        
4132
        return pos;
4133
    }else{
4134
        if(pos==0) pos=1; //avoid infinite loops (i doubt thats needed but ...)
4135
        if(pos+10>buf_size) pos=buf_size; // oops ;)
4136

    
4137
        return pos;
4138
    }
4139
}
4140

    
4141
static int decode_frame(AVCodecContext *avctx, 
4142
                             void *data, int *data_size,
4143
                             uint8_t *buf, int buf_size)
4144
{
4145
    H264Context *h = avctx->priv_data;
4146
    MpegEncContext *s = &h->s;
4147
    AVFrame *pict = data; 
4148
    int buf_index;
4149
    
4150
    s->flags= avctx->flags;
4151

    
4152
    *data_size = 0;
4153
   
4154
   /* no supplementary picture */
4155
    if (buf_size == 0) {
4156
        return 0;
4157
    }
4158
    
4159
    if(s->flags&CODEC_FLAG_TRUNCATED){
4160
        int next= find_frame_end(s, buf, buf_size);
4161
        
4162
        if( ff_combine_frame(s, next, &buf, &buf_size) < 0 )
4163
            return buf_size;
4164
//printf("next:%d buf_size:%d last_index:%d\n", next, buf_size, s->parse_context.last_index);
4165
    }
4166

    
4167
    if(s->avctx->extradata_size && s->picture_number==0){
4168
        if(0 < decode_nal_units(h, s->avctx->extradata, s->avctx->extradata_size) ) 
4169
            return -1;
4170
    }
4171

    
4172
    buf_index=decode_nal_units(h, buf, buf_size);
4173
    if(buf_index < 0) 
4174
        return -1;
4175

    
4176
    //FIXME do something with unavailable reference frames    
4177
 
4178
//    if(ret==FRAME_SKIPED) return get_consumed_bytes(s, buf_index, buf_size);
4179
#if 0
4180
    if(s->pict_type==B_TYPE || s->low_delay){
4181
        *pict= *(AVFrame*)&s->current_picture;
4182
    } else {
4183
        *pict= *(AVFrame*)&s->last_picture;
4184
    }
4185
#endif
4186
    if(!s->current_picture_ptr){
4187
        fprintf(stderr, "error, NO frame\n");
4188
        return -1;
4189
    }
4190

    
4191
    *pict= *(AVFrame*)&s->current_picture; //FIXME 
4192
    ff_print_debug_info(s, s->current_picture_ptr);
4193
    assert(pict->data[0]);
4194
//printf("out %d\n", (int)pict->data[0]);
4195
#if 0 //?
4196

4197
    /* Return the Picture timestamp as the frame number */
4198
    /* we substract 1 because it is added on utils.c    */
4199
    avctx->frame_number = s->picture_number - 1;
4200
#endif
4201
#if 0
4202
    /* dont output the last pic after seeking */
4203
    if(s->last_picture_ptr || s->low_delay)
4204
    //Note this isnt a issue as a IDR pic should flush teh buffers
4205
#endif
4206
        *data_size = sizeof(AVFrame);
4207
    return get_consumed_bytes(s, buf_index, buf_size);
4208
}
4209
#if 0
4210
static inline void fill_mb_avail(H264Context *h){
4211
    MpegEncContext * const s = &h->s;
4212
    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
4213

4214
    if(s->mb_y){
4215
        h->mb_avail[0]= s->mb_x                 && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
4216
        h->mb_avail[1]=                            h->slice_table[mb_xy - s->mb_stride    ] == h->slice_num;
4217
        h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
4218
    }else{
4219
        h->mb_avail[0]=
4220
        h->mb_avail[1]=
4221
        h->mb_avail[2]= 0;
4222
    }
4223
    h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
4224
    h->mb_avail[4]= 1; //FIXME move out
4225
    h->mb_avail[5]= 0; //FIXME move out
4226
}
4227
#endif
4228

    
4229
#if 0 //selftest
4230
#define COUNT 8000
4231
#define SIZE (COUNT*40)
4232
int main(){
4233
    int i;
4234
    uint8_t temp[SIZE];
4235
    PutBitContext pb;
4236
    GetBitContext gb;
4237
//    int int_temp[10000];
4238
    DSPContext dsp;
4239
    AVCodecContext avctx;
4240
    
4241
    dsputil_init(&dsp, &avctx);
4242

4243
    init_put_bits(&pb, temp, SIZE, NULL, NULL);
4244
    printf("testing unsigned exp golomb\n");
4245
    for(i=0; i<COUNT; i++){
4246
        START_TIMER
4247
        set_ue_golomb(&pb, i);
4248
        STOP_TIMER("set_ue_golomb");
4249
    }
4250
    flush_put_bits(&pb);
4251
    
4252
    init_get_bits(&gb, temp, 8*SIZE);
4253
    for(i=0; i<COUNT; i++){
4254
        int j, s;
4255
        
4256
        s= show_bits(&gb, 24);
4257
        
4258
        START_TIMER
4259
        j= get_ue_golomb(&gb);
4260
        if(j != i){
4261
            printf("missmatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
4262
//            return -1;
4263
        }
4264
        STOP_TIMER("get_ue_golomb");
4265
    }
4266
    
4267
    
4268
    init_put_bits(&pb, temp, SIZE, NULL, NULL);
4269
    printf("testing signed exp golomb\n");
4270
    for(i=0; i<COUNT; i++){
4271
        START_TIMER
4272
        set_se_golomb(&pb, i - COUNT/2);
4273
        STOP_TIMER("set_se_golomb");
4274
    }
4275
    flush_put_bits(&pb);
4276
    
4277
    init_get_bits(&gb, temp, 8*SIZE);
4278
    for(i=0; i<COUNT; i++){
4279
        int j, s;
4280
        
4281
        s= show_bits(&gb, 24);
4282
        
4283
        START_TIMER
4284
        j= get_se_golomb(&gb);
4285
        if(j != i - COUNT/2){
4286
            printf("missmatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
4287
//            return -1;
4288
        }
4289
        STOP_TIMER("get_se_golomb");
4290
    }
4291

4292
    printf("testing 4x4 (I)DCT\n");
4293
    
4294
    DCTELEM block[16];
4295
    uint8_t src[16], ref[16];
4296
    uint64_t error= 0, max_error=0;
4297

4298
    for(i=0; i<COUNT; i++){
4299
        int j;
4300
//        printf("%d %d %d\n", r1, r2, (r2-r1)*16);
4301
        for(j=0; j<16; j++){
4302
            ref[j]= random()%255;
4303
            src[j]= random()%255;
4304
        }
4305

4306
        h264_diff_dct_c(block, src, ref, 4);
4307
        
4308
        //normalize
4309
        for(j=0; j<16; j++){
4310
//            printf("%d ", block[j]);
4311
            block[j]= block[j]*4;
4312
            if(j&1) block[j]= (block[j]*4 + 2)/5;
4313
            if(j&4) block[j]= (block[j]*4 + 2)/5;
4314
        }
4315
//        printf("\n");
4316
        
4317
        h264_add_idct_c(ref, block, 4);
4318
/*        for(j=0; j<16; j++){
4319
            printf("%d ", ref[j]);
4320
        }
4321
        printf("\n");*/
4322
            
4323
        for(j=0; j<16; j++){
4324
            int diff= ABS(src[j] - ref[j]);
4325
            
4326
            error+= diff*diff;
4327
            max_error= FFMAX(max_error, diff);
4328
        }
4329
    }
4330
    printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
4331
#if 0
4332
    printf("testing quantizer\n");
4333
    for(qp=0; qp<52; qp++){
4334
        for(i=0; i<16; i++)
4335
            src1_block[i]= src2_block[i]= random()%255;
4336
        
4337
    }
4338
#endif
4339
    printf("Testing NAL layer\n");
4340
    
4341
    uint8_t bitstream[COUNT];
4342
    uint8_t nal[COUNT*2];
4343
    H264Context h;
4344
    memset(&h, 0, sizeof(H264Context));
4345
    
4346
    for(i=0; i<COUNT; i++){
4347
        int zeros= i;
4348
        int nal_length;
4349
        int consumed;
4350
        int out_length;
4351
        uint8_t *out;
4352
        int j;
4353
        
4354
        for(j=0; j<COUNT; j++){
4355
            bitstream[j]= (random() % 255) + 1;
4356
        }
4357
        
4358
        for(j=0; j<zeros; j++){
4359
            int pos= random() % COUNT;
4360
            while(bitstream[pos] == 0){
4361
                pos++;
4362
                pos %= COUNT;
4363
            }
4364
            bitstream[pos]=0;
4365
        }
4366
        
4367
        START_TIMER
4368
        
4369
        nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
4370
        if(nal_length<0){
4371
            printf("encoding failed\n");
4372
            return -1;
4373
        }
4374
        
4375
        out= decode_nal(&h, nal, &out_length, &consumed, nal_length);
4376

    
4377
        STOP_TIMER("NAL")
4378
        
4379
        if(out_length != COUNT){
4380
            printf("incorrect length %d %d\n", out_length, COUNT);
4381
            return -1;
4382
        }
4383
        
4384
        if(consumed != nal_length){
4385
            printf("incorrect consumed length %d %d\n", nal_length, consumed);
4386
            return -1;
4387
        }
4388
        
4389
        if(memcmp(bitstream, out, COUNT)){
4390
            printf("missmatch\n");
4391
            return -1;
4392
        }
4393
    }
4394
    
4395
    printf("Testing RBSP\n");
4396
    
4397
    
4398
    return 0;
4399
}
4400
#endif
4401

    
4402

    
4403
static int decode_end(AVCodecContext *avctx)
4404
{
4405
    H264Context *h = avctx->priv_data;
4406
    MpegEncContext *s = &h->s;
4407
    
4408
    free_tables(h); //FIXME cleanup init stuff perhaps
4409
    MPV_common_end(s);
4410

    
4411
//    memset(h, 0, sizeof(H264Context));
4412
        
4413
    return 0;
4414
}
4415

    
4416

    
4417
AVCodec h264_decoder = {
4418
    "h264",
4419
    CODEC_TYPE_VIDEO,
4420
    CODEC_ID_H264,
4421
    sizeof(H264Context),
4422
    decode_init,
4423
    NULL,
4424
    decode_end,
4425
    decode_frame,
4426
    /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED,
4427
};
4428

    
4429
#include "svq3.c"