Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h263.c @ e0560448

History | View | Annotate | Download (167 KB)

</
1
/*
2
 * H263/MPEG4 backend for ffmpeg encoder and decoder
3
 * Copyright (c) 2000,2001 Fabrice Bellard.
4
 * H263+ support.
5
 * Copyright (c) 2001 Juan J. Sierralta P.
6
 *
7
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2 of the License, or (at your option) any later version.
11
 *
12
 * This library is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library; if not, write to the Free Software
19
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
 *
21
 * ac prediction encoding, b-frame support, error resilience, optimizations,
22
 * qpel decoding, gmc decoding, interlaced decoding, 
23
 * by Michael Niedermayer <michaelni@gmx.at>
24
 */
25

    
26
/**
27
 * @file h263.c
28
 * h263/mpeg4 codec.
29
 */
30
 
31
//#define DEBUG
32
#include "common.h"
33
#include "dsputil.h"
34
#include "avcodec.h"
35
#include "mpegvideo.h"
36
#include "h263data.h"
37
#include "mpeg4data.h"
38

    
39
//#undef NDEBUG
40
//#include <assert.h>
41

    
42
#define INTRA_MCBPC_VLC_BITS 6
43
#define INTER_MCBPC_VLC_BITS 6
44
#define CBPY_VLC_BITS 6
45
#define MV_VLC_BITS 9
46
#define DC_VLC_BITS 9
47
#define SPRITE_TRAJ_VLC_BITS 6
48
#define MB_TYPE_B_VLC_BITS 4
49
#define TEX_VLC_BITS 9
50

    
51
#ifdef CONFIG_ENCODERS
52
static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
53
                              int n);
54
static void h263_encode_motion(MpegEncContext * s, int val, int fcode);
55
static void h263p_encode_umotion(MpegEncContext * s, int val);
56
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
57
                               int n, int dc, uint8_t *scan_table, 
58
                               PutBitContext *dc_pb, PutBitContext *ac_pb);
59
#endif
60

    
61
static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
62
static int h263p_decode_umotion(MpegEncContext * s, int pred);
63
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
64
                             int n, int coded);
65
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr);
66
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
67
                              int n, int coded, int intra, int rvlc);
68
static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr);
69
#ifdef CONFIG_ENCODERS
70
static void mpeg4_inv_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
71
                              int dir);
72
#endif //CONFIG_ENCODERS
73
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s);
74
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr);
75

    
76
#ifdef CONFIG_ENCODERS
77
static uint8_t uni_DCtab_lum_len[512];
78
static uint8_t uni_DCtab_chrom_len[512];
79
static uint16_t uni_DCtab_lum_bits[512];
80
static uint16_t uni_DCtab_chrom_bits[512];
81

    
82
static uint8_t (*mv_penalty)[MAX_MV*2+1]= NULL;
83
static uint8_t fcode_tab[MAX_MV*2+1];
84
static uint8_t umv_fcode_tab[MAX_MV*2+1];
85

    
86
static uint32_t uni_mpeg4_intra_rl_bits[64*64*2*2];
87
static uint8_t  uni_mpeg4_intra_rl_len [64*64*2*2];
88
static uint32_t uni_mpeg4_inter_rl_bits[64*64*2*2];
89
static uint8_t  uni_mpeg4_inter_rl_len [64*64*2*2];
90
//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
91
//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
92
#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
93

    
94
/* mpeg4
95
inter
96
max level: 24/6
97
max run: 53/63
98

99
intra
100
max level: 53/16
101
max run: 29/41
102
*/
103
#endif
104

    
105
#if 0 //3IV1 is quite rare and tis slows things down a tiny bit
106
#define IS_3IV1 s->avctx->codec_tag == ff_get_fourcc("3IV1")
107
#else 
108
#define IS_3IV1 0
109
#endif
110

    
111
int h263_get_picture_format(int width, int height)
112
{
113
    int format;
114

    
115
    if (width == 128 && height == 96)
116
        format = 1;
117
    else if (width == 176 && height == 144)
118
        format = 2;
119
    else if (width == 352 && height == 288)
120
        format = 3;
121
    else if (width == 704 && height == 576)
122
        format = 4;
123
    else if (width == 1408 && height == 1152)
124
        format = 5;
125
    else
126
        format = 7;
127
    return format;
128
}
129

    
130
#ifdef CONFIG_ENCODERS
131

    
132
static void float_aspect_to_info(MpegEncContext * s, float aspect){
133
    int i;
134

    
135
    aspect*= s->height/(double)s->width;
136
//printf("%f\n", aspect);
137
    
138
    if(aspect==0) aspect= 1.0;
139

    
140
    ff_float2fraction(&s->aspected_width, &s->aspected_height, aspect, 255);
141

    
142
//printf("%d %d\n", s->aspected_width, s->aspected_height);
143
    for(i=1; i<6; i++){
144
        if(s->aspected_width == pixel_aspect[i][0] && s->aspected_height== pixel_aspect[i][1]){
145
            s->aspect_ratio_info=i;
146
            return;
147
        }
148
    }
149
    
150
    s->aspect_ratio_info= FF_ASPECT_EXTENDED;
151
}
152

    
153
void h263_encode_picture_header(MpegEncContext * s, int picture_number)
154
{
155
    int format;
156

    
157
    align_put_bits(&s->pb);
158

    
159
    /* Update the pointer to last GOB */
160
    s->ptr_lastgob = pbBufPtr(&s->pb);
161
    s->gob_number = 0;
162

    
163
    put_bits(&s->pb, 22, 0x20); /* PSC */
164
    put_bits(&s->pb, 8, (((int64_t)s->picture_number * 30 * s->avctx->frame_rate_base) / 
165
                         s->avctx->frame_rate) & 0xff);
166

    
167
    put_bits(&s->pb, 1, 1);        /* marker */
168
    put_bits(&s->pb, 1, 0);        /* h263 id */
169
    put_bits(&s->pb, 1, 0);        /* split screen off */
170
    put_bits(&s->pb, 1, 0);        /* camera  off */
171
    put_bits(&s->pb, 1, 0);        /* freeze picture release off */
172
    
173
    format = h263_get_picture_format(s->width, s->height);
174
    if (!s->h263_plus) {
175
        /* H.263v1 */
176
        put_bits(&s->pb, 3, format);
177
        put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
178
        /* By now UMV IS DISABLED ON H.263v1, since the restrictions
179
        of H.263v1 UMV implies to check the predicted MV after
180
        calculation of the current MB to see if we're on the limits */
181
        put_bits(&s->pb, 1, 0);        /* unrestricted motion vector: off */
182
        put_bits(&s->pb, 1, 0);        /* SAC: off */
183
        put_bits(&s->pb, 1, 0);        /* advanced prediction mode: off */
184
        put_bits(&s->pb, 1, 0);        /* not PB frame */
185
        put_bits(&s->pb, 5, s->qscale);
186
        put_bits(&s->pb, 1, 0);        /* Continuous Presence Multipoint mode: off */
187
    } else {
188
        /* H.263v2 */
189
        /* H.263 Plus PTYPE */
190
        put_bits(&s->pb, 3, 7);
191
        put_bits(&s->pb,3,1); /* Update Full Extended PTYPE */
192
        if (format == 7)
193
            put_bits(&s->pb,3,6); /* Custom Source Format */
194
        else
195
            put_bits(&s->pb, 3, format);
196
            
197
        put_bits(&s->pb,1,0); /* Custom PCF: off */
198
        s->umvplus = s->unrestricted_mv;
199
        put_bits(&s->pb, 1, s->umvplus); /* Unrestricted Motion Vector */
200
        put_bits(&s->pb,1,0); /* SAC: off */
201
        put_bits(&s->pb,1,0); /* Advanced Prediction Mode: off */
202
        put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
203
        put_bits(&s->pb,1,0); /* Deblocking Filter: off */
204
        put_bits(&s->pb,1,0); /* Slice Structured: off */
205
        put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
206
        put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
207
        put_bits(&s->pb,1,0); /* Alternative Inter VLC: off */
208
        put_bits(&s->pb,1,0); /* Modified Quantization: off */
209
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
210
        put_bits(&s->pb,3,0); /* Reserved */
211
                
212
        put_bits(&s->pb, 3, s->pict_type == P_TYPE);
213
                
214
        put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
215
        put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
216
        put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
217
        put_bits(&s->pb,2,0); /* Reserved */
218
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
219
                
220
        /* This should be here if PLUSPTYPE */
221
        put_bits(&s->pb, 1, 0);        /* Continuous Presence Multipoint mode: off */
222
                
223
                if (format == 7) {
224
            /* Custom Picture Format (CPFMT) */
225
            float_aspect_to_info(s, s->avctx->aspect_ratio);
226

    
227
            put_bits(&s->pb,4,s->aspect_ratio_info);
228
            put_bits(&s->pb,9,(s->width >> 2) - 1);
229
            put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
230
            put_bits(&s->pb,9,(s->height >> 2));
231
            if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
232
            {
233
                put_bits(&s->pb, 8, s->aspected_width);
234
                put_bits(&s->pb, 8, s->aspected_height);
235
            }
236
        }
237
        
238
        /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
239
        if (s->umvplus)
240
//            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
241
            put_bits(&s->pb,2,1); /* unlimited */
242

    
243
        put_bits(&s->pb, 5, s->qscale);
244
    }
245

    
246
    put_bits(&s->pb, 1, 0);        /* no PEI */
247

    
248
    if(s->h263_aic){
249
         s->y_dc_scale_table= 
250
         s->c_dc_scale_table= h263_aic_dc_scale_table;
251
    }else{
252
        s->y_dc_scale_table=
253
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
254
    }
255
}
256

    
257
/**
258
 * Encodes a group of blocks header.
259
 */
260
int h263_encode_gob_header(MpegEncContext * s, int mb_line)
261
{
262
           align_put_bits(&s->pb);
263
           flush_put_bits(&s->pb);
264
           /* Call the RTP callback to send the last GOB */
265
           if (s->rtp_callback) {
266
               int pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
267
               s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
268
           }
269
           put_bits(&s->pb, 17, 1); /* GBSC */
270
           s->gob_number = mb_line / s->gob_index;
271
           put_bits(&s->pb, 5, s->gob_number); /* GN */
272
           put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
273
           put_bits(&s->pb, 5, s->qscale); /* GQUANT */
274
           //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
275
    return 0;
276
}
277

    
278
static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6])
279
{
280
    int score0=0, score1=0;
281
    int i, n;
282
    int8_t * const qscale_table= s->current_picture.qscale_table;
283

    
284
    for(n=0; n<6; n++){
285
        int16_t *ac_val, *ac_val1;
286

    
287
        ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
288
        ac_val1= ac_val;
289
        if(dir[n]){
290
            const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
291
            /* top prediction */
292
            ac_val-= s->block_wrap[n]*16;
293
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
294
                /* same qscale */
295
                for(i=1; i<8; i++){
296
                    const int level= block[n][s->dsp.idct_permutation[i   ]];
297
                    score0+= ABS(level);
298
                    score1+= ABS(level - ac_val[i+8]);
299
                    ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
300
                    ac_val1[i+8]= level;
301
                }
302
            }else{
303
                /* different qscale, we must rescale */
304
                for(i=1; i<8; i++){
305
                    const int level= block[n][s->dsp.idct_permutation[i   ]];
306
                    score0+= ABS(level);
307
                    score1+= ABS(level - ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale));
308
                    ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
309
                    ac_val1[i+8]= level;
310
                }
311
            }
312
        }else{
313
            const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
314
            /* left prediction */
315
            ac_val-= 16;
316
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
317
                /* same qscale */
318
                for(i=1; i<8; i++){
319
                    const int level= block[n][s->dsp.idct_permutation[i<<3]];
320
                    score0+= ABS(level);
321
                    score1+= ABS(level - ac_val[i]);
322
                    ac_val1[i  ]= level;
323
                    ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
324
                }
325
            }else{
326
                /* different qscale, we must rescale */
327
                for(i=1; i<8; i++){
328
                    const int level= block[n][s->dsp.idct_permutation[i<<3]];
329
                    score0+= ABS(level);
330
                    score1+= ABS(level - ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale));
331
                    ac_val1[i  ]= level;
332
                    ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
333
                }
334
            }
335
        }
336
    }
337

    
338
    return score0 > score1 ? 1 : 0;    
339
}
340

    
341
/**
342
 * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
343
 */
344
void ff_clean_h263_qscales(MpegEncContext *s){
345
    int i;
346
    int8_t * const qscale_table= s->current_picture.qscale_table;
347
    
348
    for(i=1; i<s->mb_num; i++){
349
        if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i-1] ] >2)
350
            qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i-1] ]+2;
351
    }
352
    for(i=s->mb_num-2; i>=0; i--){
353
        if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i+1] ] >2)
354
            qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i+1] ]+2;
355
    }
356
}
357

    
358
/**
359
 * modify mb_type & qscale so that encoding is acually possible in mpeg4
360
 */
361
void ff_clean_mpeg4_qscales(MpegEncContext *s){
362
    int i;
363
    int8_t * const qscale_table= s->current_picture.qscale_table;
364

    
365
    ff_clean_h263_qscales(s);
366
    
367
    for(i=1; i<s->mb_num; i++){
368
        int mb_xy= s->mb_index2xy[i];
369
    
370
        if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&MB_TYPE_INTER4V)){
371
            s->mb_type[mb_xy]&= ~MB_TYPE_INTER4V;
372
            s->mb_type[mb_xy]|= MB_TYPE_INTER;
373
        }
374
    }
375

    
376
    if(s->pict_type== B_TYPE){
377
        int odd=0;
378
        /* ok, come on, this isnt funny anymore, theres more code for handling this mpeg4 mess than
379
           for the actual adaptive quantization */
380
        
381
        for(i=0; i<s->mb_num; i++){
382
            int mb_xy= s->mb_index2xy[i];
383
            odd += qscale_table[mb_xy]&1;
384
        }
385
        
386
        if(2*odd > s->mb_num) odd=1;
387
        else                  odd=0;
388
        
389
        for(i=0; i<s->mb_num; i++){
390
            int mb_xy= s->mb_index2xy[i];
391
            if((qscale_table[mb_xy]&1) != odd)
392
                qscale_table[mb_xy]++;
393
            if(qscale_table[mb_xy] > 31)
394
                qscale_table[mb_xy]= 31;
395
        }            
396
    
397
        for(i=1; i<s->mb_num; i++){
398
            int mb_xy= s->mb_index2xy[i];
399
            if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&MB_TYPE_DIRECT)){
400
                s->mb_type[mb_xy]&= ~MB_TYPE_DIRECT;
401
                s->mb_type[mb_xy]|= MB_TYPE_BIDIR;
402
            }
403
        }
404
    }
405
}
406

    
407
#endif //CONFIG_ENCODERS
408
/**
409
 *
410
 * @return the mb_type
411
 */
412
int ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
413
    const int mb_index= s->mb_x + s->mb_y*s->mb_stride;
414
    const int colocated_mb_type= s->next_picture.mb_type[mb_index]; //FIXME or next?
415
    int xy= s->block_index[0];
416
    uint16_t time_pp= s->pp_time;
417
    uint16_t time_pb= s->pb_time;
418
    int i;
419
    
420
    //FIXME avoid divides
421
    
422
    if(IS_8X8(colocated_mb_type)){
423
        s->mv_type = MV_TYPE_8X8;
424
        for(i=0; i<4; i++){
425
            xy= s->block_index[i];
426
            s->mv[0][i][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
427
            s->mv[0][i][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
428
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->motion_val[xy][0]
429
                                : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
430
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->motion_val[xy][1] 
431
                                : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
432
        }
433
        return MB_TYPE_DIRECT2 | MB_TYPE_8x8 | MB_TYPE_L0L1;
434
    } else if(IS_INTERLACED(colocated_mb_type)){
435
        s->mv_type = MV_TYPE_FIELD;
436
        for(i=0; i<2; i++){
437
            if(s->top_field_first){
438
                time_pp= s->pp_field_time - s->field_select_table[mb_index][i] + i;
439
                time_pb= s->pb_field_time - s->field_select_table[mb_index][i] + i;
440
            }else{
441
                time_pp= s->pp_field_time + s->field_select_table[mb_index][i] - i;
442
                time_pb= s->pb_field_time + s->field_select_table[mb_index][i] - i;
443
            }
444
            s->mv[0][i][0] = s->field_mv_table[mb_index][i][0]*time_pb/time_pp + mx;
445
            s->mv[0][i][1] = s->field_mv_table[mb_index][i][1]*time_pb/time_pp + my;
446
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->field_mv_table[mb_index][i][0]
447
                                : s->field_mv_table[mb_index][i][0]*(time_pb - time_pp)/time_pp;
448
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->field_mv_table[mb_index][i][1] 
449
                                : s->field_mv_table[mb_index][i][1]*(time_pb - time_pp)/time_pp;
450
        }
451
        return MB_TYPE_DIRECT2 | MB_TYPE_16x8 | MB_TYPE_L0L1 | MB_TYPE_INTERLACED;
452
    }else{
453
        s->mv[0][0][0] = s->mv[0][1][0] = s->mv[0][2][0] = s->mv[0][3][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
454
        s->mv[0][0][1] = s->mv[0][1][1] = s->mv[0][2][1] = s->mv[0][3][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
455
        s->mv[1][0][0] = s->mv[1][1][0] = s->mv[1][2][0] = s->mv[1][3][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
456
                            : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
457
        s->mv[1][0][1] = s->mv[1][1][1] = s->mv[1][2][1] = s->mv[1][3][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1] 
458
                            : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
459
        if((s->avctx->workaround_bugs & FF_BUG_DIRECT_BLOCKSIZE) || !s->quarter_sample)
460
            s->mv_type= MV_TYPE_16X16;
461
        else
462
            s->mv_type= MV_TYPE_8X8;
463
        return MB_TYPE_DIRECT2 | MB_TYPE_16x16 | MB_TYPE_L0L1; //Note see prev line
464
    }
465
}
466

    
467
#ifdef CONFIG_ENCODERS
468
void mpeg4_encode_mb(MpegEncContext * s,
469
                    DCTELEM block[6][64],
470
                    int motion_x, int motion_y)
471
{
472
    int cbpc, cbpy, pred_x, pred_y;
473
    int bits;
474
    PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
475
    PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=B_TYPE ? &s->tex_pb : &s->pb;
476
    PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=I_TYPE ? &s->pb2    : &s->pb;
477
    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
478
    const int dquant_code[5]= {1,0,9,2,3};
479
    
480
    //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
481
    if (!s->mb_intra) {
482
        /* compute cbp */
483
        int i, cbp = 0;
484
        for (i = 0; i < 6; i++) {
485
            if (s->block_last_index[i] >= 0)
486
                cbp |= 1 << (5 - i);
487
        }
488

    
489
        if(s->pict_type==B_TYPE){
490
            static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
491
            int mb_type=  mb_type_table[s->mv_dir];
492
            
493
            if(s->mb_x==0){
494
                s->last_mv[0][0][0]= 
495
                s->last_mv[0][0][1]= 
496
                s->last_mv[1][0][0]= 
497
                s->last_mv[1][0][1]= 0;
498
            }
499
            
500
            assert(s->dquant>=-2 && s->dquant<=2);
501
            assert((s->dquant&1)==0);
502
            assert(mb_type>=0);
503

    
504
            /* nothing to do if this MB was skiped in the next P Frame */
505
            if(s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]){ //FIXME avoid DCT & ...
506
                s->skip_count++;
507
                s->mv[0][0][0]= 
508
                s->mv[0][0][1]= 
509
                s->mv[1][0][0]= 
510
                s->mv[1][0][1]= 0;
511
                s->mv_dir= MV_DIR_FORWARD; //doesnt matter
512
                s->qscale -= s->dquant;
513
//                s->mb_skiped=1;
514

    
515
                return;
516
            }
517
            
518
            if ((cbp | motion_x | motion_y | mb_type) ==0) {
519
                /* direct MB with MV={0,0} */
520
                assert(s->dquant==0);
521
                
522
                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
523

    
524
                if(interleaved_stats){
525
                    s->misc_bits++;
526
                    s->last_bits++;
527
                }
528
                s->skip_count++;
529
                return;
530
            }
531
            
532
            put_bits(&s->pb, 1, 0);        /* mb coded modb1=0 */
533
            put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
534
            put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we dont need it :)
535
            if(cbp) put_bits(&s->pb, 6, cbp);
536
            
537
            if(cbp && mb_type){
538
                if(s->dquant)
539
                    put_bits(&s->pb, 2, (s->dquant>>2)+3);
540
                else
541
                    put_bits(&s->pb, 1, 0);
542
            }else
543
                s->qscale -= s->dquant;
544
            
545
            if(!s->progressive_sequence){
546
                if(cbp)
547
                    put_bits(&s->pb, 1, s->interlaced_dct);
548
                if(mb_type) // not diect mode
549
                    put_bits(&s->pb, 1, 0); // no interlaced ME yet
550
            }
551

    
552
            if(interleaved_stats){
553
                s->misc_bits+= get_bits_diff(s);
554
            }
555

    
556
            switch(mb_type)
557
            {
558
            case 0: /* direct */
559
                h263_encode_motion(s, motion_x, 1);
560
                h263_encode_motion(s, motion_y, 1);                
561
                s->b_count++;
562
                s->f_count++;
563
                break;
564
            case 1: /* bidir */
565
                h263_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
566
                h263_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
567
                h263_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
568
                h263_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
569
                s->last_mv[0][0][0]= s->mv[0][0][0];
570
                s->last_mv[0][0][1]= s->mv[0][0][1];
571
                s->last_mv[1][0][0]= s->mv[1][0][0];
572
                s->last_mv[1][0][1]= s->mv[1][0][1];
573
                s->b_count++;
574
                s->f_count++;
575
                break;
576
            case 2: /* backward */
577
                h263_encode_motion(s, motion_x - s->last_mv[1][0][0], s->b_code);
578
                h263_encode_motion(s, motion_y - s->last_mv[1][0][1], s->b_code);
579
                s->last_mv[1][0][0]= motion_x;
580
                s->last_mv[1][0][1]= motion_y;
581
                s->b_count++;
582
                break;
583
            case 3: /* forward */
584
                h263_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);
585
                h263_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);
586
                s->last_mv[0][0][0]= motion_x;
587
                s->last_mv[0][0][1]= motion_y;
588
                s->f_count++;
589
                break;
590
            default:
591
                printf("unknown mb type\n");
592
                return;
593
            }
594

    
595
            if(interleaved_stats){
596
                s->mv_bits+= get_bits_diff(s);
597
            }
598

    
599
            /* encode each block */
600
            for (i = 0; i < 6; i++) {
601
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, &s->pb);
602
            }
603

    
604
            if(interleaved_stats){
605
                s->p_tex_bits+= get_bits_diff(s);
606
            }
607
        }else{ /* s->pict_type==B_TYPE */
608
            if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
609
                /* check if the B frames can skip it too, as we must skip it if we skip here 
610
                   why didnt they just compress the skip-mb bits instead of reusing them ?! */
611
                if(s->max_b_frames>0){
612
                    int i;
613
                    int x,y, offset;
614
                    uint8_t *p_pic;
615

    
616
                    x= s->mb_x*16;
617
                    y= s->mb_y*16;
618
                    if(x+16 > s->width)  x= s->width-16;
619
                    if(y+16 > s->height) y= s->height-16;
620

    
621
                    offset= x + y*s->linesize;
622
                    p_pic= s->new_picture.data[0] + offset;
623
                    
624
                    s->mb_skiped=1;
625
                    for(i=0; i<s->max_b_frames; i++){
626
                        uint8_t *b_pic;
627
                        int diff;
628
                        Picture *pic= s->reordered_input_picture[i+1];
629

    
630
                        if(pic==NULL || pic->pict_type!=B_TYPE) break;
631

    
632
                        b_pic= pic->data[0] + offset + 16; //FIXME +16
633
                        diff= s->dsp.pix_abs16x16(p_pic, b_pic, s->linesize);
634
                        if(diff>s->qscale*70){ //FIXME check that 70 is optimal
635
                            s->mb_skiped=0;
636
                            break;
637
                        }
638
                    }
639
                }else
640
                    s->mb_skiped=1; 
641

    
642
                if(s->mb_skiped==1){
643
                    /* skip macroblock */
644
                    put_bits(&s->pb, 1, 1);
645

    
646
                    if(interleaved_stats){
647
                        s->misc_bits++;
648
                        s->last_bits++;
649
                    }
650
                    s->skip_count++;
651
                    
652
                    return;
653
                }
654
            }
655

    
656
            put_bits(&s->pb, 1, 0);        /* mb coded */
657
            if(s->mv_type==MV_TYPE_16X16){
658
                cbpc = cbp & 3;
659
                if(s->dquant) cbpc+= 8;
660
                put_bits(&s->pb,
661
                        inter_MCBPC_bits[cbpc],
662
                        inter_MCBPC_code[cbpc]);
663

    
664
                cbpy = cbp >> 2;
665
                cbpy ^= 0xf;
666
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
667
                if(s->dquant)
668
                    put_bits(pb2, 2, dquant_code[s->dquant+2]);
669

    
670
                if(!s->progressive_sequence){
671
                    if(cbp)
672
                        put_bits(pb2, 1, s->interlaced_dct);
673
                    put_bits(pb2, 1, 0); // no interlaced ME yet
674
                }
675
                    
676
                if(interleaved_stats){
677
                    s->misc_bits+= get_bits_diff(s);
678
                }
679

    
680
                /* motion vectors: 16x16 mode */
681
                h263_pred_motion(s, 0, &pred_x, &pred_y);
682
            
683
                h263_encode_motion(s, motion_x - pred_x, s->f_code);
684
                h263_encode_motion(s, motion_y - pred_y, s->f_code);
685
            }else{
686
                cbpc = (cbp & 3)+16;
687
                put_bits(&s->pb,
688
                        inter_MCBPC_bits[cbpc],
689
                        inter_MCBPC_code[cbpc]);
690
                cbpy = cbp >> 2;
691
                cbpy ^= 0xf;
692
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
693

    
694
                if(!s->progressive_sequence){
695
                    if(cbp)
696
                        put_bits(pb2, 1, s->interlaced_dct);
697
                }
698
    
699
                if(interleaved_stats){
700
                    s->misc_bits+= get_bits_diff(s);
701
                }
702

    
703
                for(i=0; i<4; i++){
704
                    /* motion vectors: 8x8 mode*/
705
                    h263_pred_motion(s, i, &pred_x, &pred_y);
706

    
707
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x, s->f_code);
708
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y, s->f_code);
709
                }
710
            }
711

    
712
            if(interleaved_stats){ 
713
                s->mv_bits+= get_bits_diff(s);
714
            }
715

    
716
            /* encode each block */
717
            for (i = 0; i < 6; i++) {
718
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, tex_pb);
719
            }
720

    
721
            if(interleaved_stats){
722
                s->p_tex_bits+= get_bits_diff(s);
723
            }
724
            s->f_count++;
725
        }
726
    } else {
727
        int cbp;
728
        int dc_diff[6];   //dc values with the dc prediction subtracted 
729
        int dir[6];  //prediction direction
730
        int zigzag_last_index[6];
731
        uint8_t *scan_table[6];
732
        int i;
733

    
734
        for(i=0; i<6; i++){
735
            const int level= block[i][0];
736
            uint16_t *dc_ptr;
737

    
738
            dc_diff[i]= level - ff_mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
739
            if (i < 4) {
740
                *dc_ptr = level * s->y_dc_scale;
741
            } else {
742
                *dc_ptr = level * s->c_dc_scale;
743
            }
744
        }
745

    
746
        s->ac_pred= decide_ac_pred(s, block, dir);
747

    
748
        if(s->ac_pred){
749
            for(i=0; i<6; i++){
750
                uint8_t *st;
751
                int last_index;
752

    
753
                mpeg4_inv_pred_ac(s, block[i], i, dir[i]);
754
                if (dir[i]==0) st = s->intra_v_scantable.permutated; /* left */
755
                else           st = s->intra_h_scantable.permutated; /* top */
756

    
757
                for(last_index=63; last_index>=0; last_index--) //FIXME optimize
758
                    if(block[i][st[last_index]]) break;
759
                zigzag_last_index[i]= s->block_last_index[i];
760
                s->block_last_index[i]= last_index;
761
                scan_table[i]= st;
762
            }
763
        }else{
764
            for(i=0; i<6; i++)
765
                scan_table[i]= s->intra_scantable.permutated;
766
        }
767

    
768
        /* compute cbp */
769
        cbp = 0;
770
        for (i = 0; i < 6; i++) {
771
            if (s->block_last_index[i] >= 1)
772
                cbp |= 1 << (5 - i);
773
        }
774

    
775
        cbpc = cbp & 3;
776
        if (s->pict_type == I_TYPE) {
777
            if(s->dquant) cbpc+=4;
778
            put_bits(&s->pb,
779
                intra_MCBPC_bits[cbpc],
780
                intra_MCBPC_code[cbpc]);
781
        } else {
782
            if(s->dquant) cbpc+=8;
783
            put_bits(&s->pb, 1, 0);        /* mb coded */
784
            put_bits(&s->pb,
785
                inter_MCBPC_bits[cbpc + 4],
786
                inter_MCBPC_code[cbpc + 4]);
787
        }
788
        put_bits(pb2, 1, s->ac_pred);
789
        cbpy = cbp >> 2;
790
        put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
791
        if(s->dquant)
792
            put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
793

    
794
        if(!s->progressive_sequence){
795
            put_bits(dc_pb, 1, s->interlaced_dct);
796
        }
797

    
798
        if(interleaved_stats){
799
            s->misc_bits+= get_bits_diff(s);
800
        }
801

    
802
        /* encode each block */
803
        for (i = 0; i < 6; i++) {
804
            mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
805
        }
806

    
807
        if(interleaved_stats){
808
            s->i_tex_bits+= get_bits_diff(s);
809
        }
810
        s->i_count++;
811

    
812
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
813
        if(s->ac_pred){
814
            for(i=0; i<6; i++){
815
                int j;    
816
                int16_t *ac_val;
817

    
818
                ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
819

    
820
                if(dir[i]){
821
                    for(j=1; j<8; j++) 
822
                        block[i][s->dsp.idct_permutation[j   ]]= ac_val[j+8];
823
                }else{
824
                    for(j=1; j<8; j++) 
825
                        block[i][s->dsp.idct_permutation[j<<3]]= ac_val[j  ];
826
                }
827
                s->block_last_index[i]= zigzag_last_index[i];
828
            }
829
        }
830
    }
831
}
832

    
833
void h263_encode_mb(MpegEncContext * s,
834
                    DCTELEM block[6][64],
835
                    int motion_x, int motion_y)
836
{
837
    int cbpc, cbpy, i, cbp, pred_x, pred_y;
838
    int16_t pred_dc;
839
    int16_t rec_intradc[6];
840
    uint16_t *dc_ptr[6];
841
    const int dquant_code[5]= {1,0,9,2,3};
842
           
843
    //printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
844
    if (!s->mb_intra) {
845
        /* compute cbp */
846
        cbp = 0;
847
        for (i = 0; i < 6; i++) {
848
            if (s->block_last_index[i] >= 0)
849
                cbp |= 1 << (5 - i);
850
        }
851
        if ((cbp | motion_x | motion_y | s->dquant) == 0) {
852
            /* skip macroblock */
853
            put_bits(&s->pb, 1, 1);
854
            return;
855
        }
856
        put_bits(&s->pb, 1, 0);        /* mb coded */
857
        cbpc = cbp & 3;
858
        if(s->dquant) cbpc+= 8;
859
        put_bits(&s->pb,
860
                    inter_MCBPC_bits[cbpc],
861
                    inter_MCBPC_code[cbpc]);
862
        cbpy = cbp >> 2;
863
        cbpy ^= 0xf;
864
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
865
        if(s->dquant)
866
            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
867

    
868
        /* motion vectors: 16x16 mode only now */
869
        h263_pred_motion(s, 0, &pred_x, &pred_y);
870
      
871
        if (!s->umvplus) {  
872
            h263_encode_motion(s, motion_x - pred_x, s->f_code);
873
            h263_encode_motion(s, motion_y - pred_y, s->f_code);
874
        }
875
        else {
876
            h263p_encode_umotion(s, motion_x - pred_x);
877
            h263p_encode_umotion(s, motion_y - pred_y);
878
            if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
879
                /* To prevent Start Code emulation */
880
                put_bits(&s->pb,1,1);
881
        }
882
    } else {
883
        int li = s->h263_aic ? 0 : 1;
884
        
885
        cbp = 0;
886
        for(i=0; i<6; i++) {
887
            /* Predict DC */
888
            if (s->h263_aic && s->mb_intra) {
889
                int16_t level = block[i][0];
890
            
891
                pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
892
                level -= pred_dc;
893
                /* Quant */
894
                if (level < 0)
895
                    level = (level + (s->qscale >> 1))/(s->y_dc_scale);
896
                else
897
                    level = (level - (s->qscale >> 1))/(s->y_dc_scale);
898
                    
899
                /* AIC can change CBP */
900
                if (level == 0 && s->block_last_index[i] == 0)
901
                    s->block_last_index[i] = -1;
902
                else if (level < -127)
903
                    level = -127;
904
                else if (level > 127)
905
                    level = 127;
906
                
907
                block[i][0] = level;
908
                /* Reconstruction */ 
909
                rec_intradc[i] = (s->y_dc_scale*level) + pred_dc;
910
                /* Oddify */
911
                rec_intradc[i] |= 1;
912
                //if ((rec_intradc[i] % 2) == 0)
913
                //    rec_intradc[i]++;
914
                /* Clipping */
915
                if (rec_intradc[i] < 0)
916
                    rec_intradc[i] = 0;
917
                else if (rec_intradc[i] > 2047)
918
                    rec_intradc[i] = 2047;
919
                                
920
                /* Update AC/DC tables */
921
                *dc_ptr[i] = rec_intradc[i];
922
            }
923
            /* compute cbp */
924
            if (s->block_last_index[i] >= li)
925
                cbp |= 1 << (5 - i);
926
        }
927

    
928
        cbpc = cbp & 3;
929
        if (s->pict_type == I_TYPE) {
930
            if(s->dquant) cbpc+=4;
931
            put_bits(&s->pb,
932
                intra_MCBPC_bits[cbpc],
933
                intra_MCBPC_code[cbpc]);
934
        } else {
935
            if(s->dquant) cbpc+=8;
936
            put_bits(&s->pb, 1, 0);        /* mb coded */
937
            put_bits(&s->pb,
938
                inter_MCBPC_bits[cbpc + 4],
939
                inter_MCBPC_code[cbpc + 4]);
940
        }
941
        if (s->h263_aic) {
942
            /* XXX: currently, we do not try to use ac prediction */
943
            put_bits(&s->pb, 1, 0);        /* no AC prediction */
944
        }
945
        cbpy = cbp >> 2;
946
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
947
        if(s->dquant)
948
            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
949
    }
950

    
951
    for(i=0; i<6; i++) {
952
        /* encode each block */
953
        h263_encode_block(s, block[i], i);
954
    
955
        /* Update INTRADC for decoding */
956
        if (s->h263_aic && s->mb_intra) {
957
            block[i][0] = rec_intradc[i];
958
            
959
        }
960
    }
961
}
962
#endif
963

    
964
static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr)
965
{
966
    int x, y, wrap, a, c, pred_dc, scale;
967
    int16_t *dc_val, *ac_val;
968

    
969
    /* find prediction */
970
    if (n < 4) {
971
        x = 2 * s->mb_x + 1 + (n & 1);
972
        y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
973
        wrap = s->mb_width * 2 + 2;
974
        dc_val = s->dc_val[0];
975
        ac_val = s->ac_val[0][0];
976
        scale = s->y_dc_scale;
977
    } else {
978
        x = s->mb_x + 1;
979
        y = s->mb_y + 1;
980
        wrap = s->mb_width + 2;
981
        dc_val = s->dc_val[n - 4 + 1];
982
        ac_val = s->ac_val[n - 4 + 1][0];
983
        scale = s->c_dc_scale;
984
    }
985
    /* B C
986
     * A X 
987
     */
988
    a = dc_val[(x - 1) + (y) * wrap];
989
    c = dc_val[(x) + (y - 1) * wrap];
990
    
991
    /* No prediction outside GOB boundary */
992
    if (s->first_slice_line && ((n < 2) || (n > 3)))
993
        c = 1024;
994
    pred_dc = 1024;
995
    /* just DC prediction */
996
    if (a != 1024 && c != 1024)
997
        pred_dc = (a + c) >> 1;
998
    else if (a != 1024)
999
        pred_dc = a;
1000
    else
1001
        pred_dc = c;
1002
    
1003
    /* we assume pred is positive */
1004
    //pred_dc = (pred_dc + (scale >> 1)) / scale;
1005
    *dc_val_ptr = &dc_val[x + y * wrap];
1006
    return pred_dc;
1007
}
1008

    
1009
static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1010
{
1011
    int x, y, wrap, a, c, pred_dc, scale, i;
1012
    int16_t *dc_val, *ac_val, *ac_val1;
1013

    
1014
    /* find prediction */
1015
    if (n < 4) {
1016
        x = 2 * s->mb_x + 1 + (n & 1);
1017
        y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
1018
        wrap = s->mb_width * 2 + 2;
1019
        dc_val = s->dc_val[0];
1020
        ac_val = s->ac_val[0][0];
1021
        scale = s->y_dc_scale;
1022
    } else {
1023
        x = s->mb_x + 1;
1024
        y = s->mb_y + 1;
1025
        wrap = s->mb_width + 2;
1026
        dc_val = s->dc_val[n - 4 + 1];
1027
        ac_val = s->ac_val[n - 4 + 1][0];
1028
        scale = s->c_dc_scale;
1029
    }
1030
    
1031
    ac_val += ((y) * wrap + (x)) * 16;
1032
    ac_val1 = ac_val;
1033
    
1034
    /* B C
1035
     * A X 
1036
     */
1037
    a = dc_val[(x - 1) + (y) * wrap];
1038
    c = dc_val[(x) + (y - 1) * wrap];
1039
    
1040
    /* No prediction outside GOB boundary */
1041
    if (s->first_slice_line && ((n < 2) || (n > 3)))
1042
        c = 1024;
1043
    pred_dc = 1024;
1044
    if (s->ac_pred) {
1045
        if (s->h263_aic_dir) {
1046
            /* left prediction */
1047
            if (a != 1024) {
1048
                ac_val -= 16;
1049
                for(i=1;i<8;i++) {
1050
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1051
                }
1052
                pred_dc = a;
1053
            }
1054
        } else {
1055
            /* top prediction */
1056
            if (c != 1024) {
1057
                ac_val -= 16 * wrap;
1058
                for(i=1;i<8;i++) {
1059
                    block[s->dsp.idct_permutation[i   ]] += ac_val[i + 8];
1060
                }
1061
                pred_dc = c;
1062
            }
1063
        }
1064
    } else {
1065
        /* just DC prediction */
1066
        if (a != 1024 && c != 1024)
1067
            pred_dc = (a + c) >> 1;
1068
        else if (a != 1024)
1069
            pred_dc = a;
1070
        else
1071
            pred_dc = c;
1072
    }
1073
    
1074
    /* we assume pred is positive */
1075
    block[0]=block[0]*scale + pred_dc;
1076
    
1077
    if (block[0] < 0)
1078
        block[0] = 0;
1079
    else if (!(block[0] & 1))
1080
        block[0]++;
1081
    
1082
    /* Update AC/DC tables */
1083
    dc_val[(x) + (y) * wrap] = block[0];
1084
    
1085
    /* left copy */
1086
    for(i=1;i<8;i++)
1087
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1088
    /* top copy */
1089
    for(i=1;i<8;i++)
1090
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1091
}
1092

    
1093
int16_t *h263_pred_motion(MpegEncContext * s, int block, 
1094
                        int *px, int *py)
1095
{
1096
    int xy, wrap;
1097
    int16_t *A, *B, *C, *mot_val;
1098
    static const int off[4]= {2, 1, 1, -1};
1099

    
1100
    wrap = s->block_wrap[0];
1101
    xy = s->block_index[block];
1102

    
1103
    mot_val = s->motion_val[xy];
1104

    
1105
    A = s->motion_val[xy - 1];
1106
    /* special case for first (slice) line */
1107
    if (s->first_slice_line && block<3) {
1108
        // we cant just change some MVs to simulate that as we need them for the B frames (and ME)
1109
        // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1110
        if(block==0){ //most common case
1111
            if(s->mb_x  == s->resync_mb_x){ //rare
1112
                *px= *py = 0;
1113
            }else if(s->mb_x + 1 == s->resync_mb_x){ //rare
1114
                C = s->motion_val[xy + off[block] - wrap];
1115
                if(s->mb_x==0){
1116
                    *px = C[0];
1117
                    *py = C[1];
1118
                }else{
1119
                    *px = mid_pred(A[0], 0, C[0]);
1120
                    *py = mid_pred(A[1], 0, C[1]);
1121
                }
1122
            }else{
1123
                *px = A[0];
1124
                *py = A[1];
1125
            }
1126
        }else if(block==1){
1127
            if(s->mb_x + 1 == s->resync_mb_x){ //rare
1128
                C = s->motion_val[xy + off[block] - wrap];
1129
                *px = mid_pred(A[0], 0, C[0]);
1130
                *py = mid_pred(A[1], 0, C[1]);
1131
            }else{
1132
                *px = A[0];
1133
                *py = A[1];
1134
            }
1135
        }else{ /* block==2*/
1136
            B = s->motion_val[xy - wrap];
1137
            C = s->motion_val[xy + off[block] - wrap];
1138
            if(s->mb_x == s->resync_mb_x) //rare
1139
                A[0]=A[1]=0;
1140
    
1141
            *px = mid_pred(A[0], B[0], C[0]);
1142
            *py = mid_pred(A[1], B[1], C[1]);
1143
        }
1144
    } else {
1145
        B = s->motion_val[xy - wrap];
1146
        C = s->motion_val[xy + off[block] - wrap];
1147
        *px = mid_pred(A[0], B[0], C[0]);
1148
        *py = mid_pred(A[1], B[1], C[1]);
1149
    }
1150
    return mot_val;
1151
}
1152

    
1153
#ifdef CONFIG_ENCODERS
1154
static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
1155
{
1156
    int range, l, bit_size, sign, code, bits;
1157

    
1158
    if (val == 0) {
1159
        /* zero vector */
1160
        code = 0;
1161
        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1162
    } else {
1163
        bit_size = f_code - 1;
1164
        range = 1 << bit_size;
1165
        /* modulo encoding */
1166
        l = range * 32;
1167
#if 1
1168
        val+= l;
1169
        val&= 2*l-1;
1170
        val-= l;
1171
        sign = val>>31;
1172
        val= (val^sign)-sign;
1173
        sign&=1;
1174
#else
1175
        if (val < -l) {
1176
            val += 2*l;
1177
        } else if (val >= l) {
1178
            val -= 2*l;
1179
        }
1180

    
1181
        assert(val>=-l && val<l);
1182

    
1183
        if (val >= 0) {
1184
            sign = 0;
1185
        } else {
1186
            val = -val;
1187
            sign = 1;
1188
        }
1189
#endif
1190
        val--;
1191
        code = (val >> bit_size) + 1;
1192
        bits = val & (range - 1);
1193

    
1194
        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
1195
        if (bit_size > 0) {
1196
            put_bits(&s->pb, bit_size, bits);
1197
        }
1198
    }
1199

    
1200
}
1201

    
1202
/* Encode MV differences on H.263+ with Unrestricted MV mode */
1203
static void h263p_encode_umotion(MpegEncContext * s, int val)
1204
{
1205
    short sval = 0; 
1206
    short i = 0;
1207
    short n_bits = 0;
1208
    short temp_val;
1209
    int code = 0;
1210
    int tcode;
1211
    
1212
    if ( val == 0)
1213
        put_bits(&s->pb, 1, 1);
1214
    else if (val == 1)
1215
        put_bits(&s->pb, 3, 0);
1216
    else if (val == -1)
1217
        put_bits(&s->pb, 3, 2);
1218
    else {
1219
        
1220
        sval = ((val < 0) ? (short)(-val):(short)val);
1221
        temp_val = sval;
1222
        
1223
        while (temp_val != 0) {
1224
            temp_val = temp_val >> 1;
1225
            n_bits++;
1226
        }
1227
        
1228
        i = n_bits - 1;
1229
        while (i > 0) {
1230
            tcode = (sval & (1 << (i-1))) >> (i-1);
1231
            tcode = (tcode << 1) | 1;
1232
            code = (code << 2) | tcode;
1233
            i--;
1234
        }
1235
        code = ((code << 1) | (val < 0)) << 1;
1236
        put_bits(&s->pb, (2*n_bits)+1, code);
1237
        //printf("\nVal = %d\tCode = %d", sval, code);
1238
    }
1239
}
1240

    
1241
static void init_mv_penalty_and_fcode(MpegEncContext *s)
1242
{
1243
    int f_code;
1244
    int mv;
1245
    
1246
    if(mv_penalty==NULL)
1247
        mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1248
    
1249
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
1250
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1251
            int len;
1252

    
1253
            if(mv==0) len= mvtab[0][1];
1254
            else{
1255
                int val, bit_size, range, code;
1256

    
1257
                bit_size = s->f_code - 1;
1258
                range = 1 << bit_size;
1259

    
1260
                val=mv;
1261
                if (val < 0) 
1262
                    val = -val;
1263
                val--;
1264
                code = (val >> bit_size) + 1;
1265
                if(code<33){
1266
                    len= mvtab[code][1] + 1 + bit_size;
1267
                }else{
1268
                    len= mvtab[32][1] + 2 + bit_size;
1269
                }
1270
            }
1271

    
1272
            mv_penalty[f_code][mv+MAX_MV]= len;
1273
        }
1274
    }
1275

    
1276
    for(f_code=MAX_FCODE; f_code>0; f_code--){
1277
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1278
            fcode_tab[mv+MAX_MV]= f_code;
1279
        }
1280
    }
1281

    
1282
    for(mv=0; mv<MAX_MV*2+1; mv++){
1283
        umv_fcode_tab[mv]= 1;
1284
    }
1285
}
1286
#endif
1287

    
1288
#ifdef CONFIG_ENCODERS
1289

    
1290
static void init_uni_dc_tab(void)
1291
{
1292
    int level, uni_code, uni_len;
1293

    
1294
    for(level=-256; level<256; level++){
1295
        int size, v, l;
1296
        /* find number of bits */
1297
        size = 0;
1298
        v = abs(level);
1299
        while (v) {
1300
            v >>= 1;
1301
            size++;
1302
        }
1303

    
1304
        if (level < 0)
1305
            l= (-level) ^ ((1 << size) - 1);
1306
        else
1307
            l= level;
1308

    
1309
        /* luminance */
1310
        uni_code= DCtab_lum[size][0];
1311
        uni_len = DCtab_lum[size][1];
1312

    
1313
        if (size > 0) {
1314
            uni_code<<=size; uni_code|=l;
1315
            uni_len+=size;
1316
            if (size > 8){
1317
                uni_code<<=1; uni_code|=1;
1318
                uni_len++;
1319
            }
1320
        }
1321
        uni_DCtab_lum_bits[level+256]= uni_code;
1322
        uni_DCtab_lum_len [level+256]= uni_len;
1323

    
1324
        /* chrominance */
1325
        uni_code= DCtab_chrom[size][0];
1326
        uni_len = DCtab_chrom[size][1];
1327
        
1328
        if (size > 0) {
1329
            uni_code<<=size; uni_code|=l;
1330
            uni_len+=size;
1331
            if (size > 8){
1332
                uni_code<<=1; uni_code|=1;
1333
                uni_len++;
1334
            }
1335
        }
1336
        uni_DCtab_chrom_bits[level+256]= uni_code;
1337
        uni_DCtab_chrom_len [level+256]= uni_len;
1338

    
1339
    }
1340
}
1341

    
1342
#endif //CONFIG_ENCODERS
1343

    
1344
#ifdef CONFIG_ENCODERS
1345
static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1346
    int slevel, run, last;
1347
    
1348
    assert(MAX_LEVEL >= 64);
1349
    assert(MAX_RUN   >= 63);
1350

    
1351
    for(slevel=-64; slevel<64; slevel++){
1352
        if(slevel==0) continue;
1353
        for(run=0; run<64; run++){
1354
            for(last=0; last<=1; last++){
1355
                const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1356
                int level= slevel < 0 ? -slevel : slevel;
1357
                int sign= slevel < 0 ? 1 : 0;
1358
                int bits, len, code;
1359
                int level1, run1;
1360
                
1361
                len_tab[index]= 100;
1362
                     
1363
                /* ESC0 */
1364
                code= get_rl_index(rl, last, run, level);
1365
                bits= rl->table_vlc[code][0];
1366
                len=  rl->table_vlc[code][1];
1367
                bits=bits*2+sign; len++;
1368
                
1369
                if(code!=rl->n && len < len_tab[index]){
1370
                    bits_tab[index]= bits;
1371
                    len_tab [index]= len;
1372
                }
1373
#if 1
1374
                /* ESC1 */
1375
                bits= rl->table_vlc[rl->n][0];
1376
                len=  rl->table_vlc[rl->n][1];
1377
                bits=bits*2;    len++; //esc1
1378
                level1= level - rl->max_level[last][run];
1379
                if(level1>0){
1380
                    code= get_rl_index(rl, last, run, level1);
1381
                    bits<<= rl->table_vlc[code][1];
1382
                    len  += rl->table_vlc[code][1];
1383
                    bits += rl->table_vlc[code][0];
1384
                    bits=bits*2+sign; len++;
1385
                
1386
                    if(code!=rl->n && len < len_tab[index]){
1387
                        bits_tab[index]= bits;
1388
                        len_tab [index]= len;
1389
                    }
1390
                }
1391
#endif 
1392
#if 1
1393
                /* ESC2 */
1394
                bits= rl->table_vlc[rl->n][0];
1395
                len=  rl->table_vlc[rl->n][1];
1396
                bits=bits*4+2;    len+=2; //esc2
1397
                run1 = run - rl->max_run[last][level] - 1;
1398
                if(run1>=0){
1399
                    code= get_rl_index(rl, last, run1, level);
1400
                    bits<<= rl->table_vlc[code][1];
1401
                    len  += rl->table_vlc[code][1];
1402
                    bits += rl->table_vlc[code][0];
1403
                    bits=bits*2+sign; len++;
1404
                
1405
                    if(code!=rl->n && len < len_tab[index]){
1406
                        bits_tab[index]= bits;
1407
                        len_tab [index]= len;
1408
                    }
1409
                }
1410
#endif           
1411
                /* ESC3 */        
1412
                bits= rl->table_vlc[rl->n][0];
1413
                len = rl->table_vlc[rl->n][1];
1414
                bits=bits*4+3;    len+=2; //esc3
1415
                bits=bits*2+last; len++;
1416
                bits=bits*64+run; len+=6;
1417
                bits=bits*2+1;    len++;  //marker
1418
                bits=bits*4096+(slevel&0xfff); len+=12;
1419
                bits=bits*2+1;    len++;  //marker
1420
                
1421
                if(len < len_tab[index]){
1422
                    bits_tab[index]= bits;
1423
                    len_tab [index]= len;
1424
                }
1425
            }
1426
        }
1427
    }
1428
}
1429

    
1430
void h263_encode_init(MpegEncContext *s)
1431
{
1432
    static int done = 0;
1433

    
1434
    if (!done) {
1435
        done = 1;
1436

    
1437
        init_uni_dc_tab();
1438

    
1439
        init_rl(&rl_inter);
1440
        init_rl(&rl_intra);
1441
        init_rl(&rl_intra_aic);
1442
        
1443
        init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1444
        init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1445

    
1446
        init_mv_penalty_and_fcode(s);
1447
    }
1448
    s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
1449
    
1450
    // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
1451
    switch(s->codec_id){
1452
    case CODEC_ID_MPEG4:
1453
        s->fcode_tab= fcode_tab;
1454
        s->min_qcoeff= -2048;
1455
        s->max_qcoeff=  2047;
1456
        s->intra_ac_vlc_length     = uni_mpeg4_intra_rl_len;
1457
        s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;
1458
        s->inter_ac_vlc_length     = uni_mpeg4_inter_rl_len;
1459
        s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;
1460
        s->luma_dc_vlc_length= uni_DCtab_lum_len;
1461
        s->chroma_dc_vlc_length= uni_DCtab_chrom_len;
1462
        s->ac_esc_length= 7+2+1+6+1+12+1;
1463
        break;
1464
    case CODEC_ID_H263P:
1465
        s->fcode_tab= umv_fcode_tab;
1466
        s->min_qcoeff= -127;
1467
        s->max_qcoeff=  127;
1468
        break;
1469
        //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later 
1470
    default: //nothing needed default table allready set in mpegvideo.c
1471
        s->min_qcoeff= -127;
1472
        s->max_qcoeff=  127;
1473
        s->y_dc_scale_table=
1474
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1475
    }
1476
}
1477

    
1478
/**
1479
 * encodes a 8x8 block.
1480
 * @param block the 8x8 block
1481
 * @param n block index (0-3 are luma, 4-5 are chroma)
1482
 */
1483
static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
1484
{
1485
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
1486
    RLTable *rl;
1487

    
1488
    rl = &rl_inter;
1489
    if (s->mb_intra && !s->h263_aic) {
1490
        /* DC coef */
1491
        level = block[0];
1492
        /* 255 cannot be represented, so we clamp */
1493
        if (level > 254) {
1494
            level = 254;
1495
            block[0] = 254;
1496
        }
1497
        /* 0 cannot be represented also */
1498
        else if (level < 1) {
1499
            level = 1;
1500
            block[0] = 1;
1501
        }
1502
        if (level == 128) //FIXME check rv10
1503
            put_bits(&s->pb, 8, 0xff);
1504
        else
1505
            put_bits(&s->pb, 8, level & 0xff);
1506
        i = 1;
1507
    } else {
1508
        i = 0;
1509
        if (s->h263_aic && s->mb_intra)
1510
            rl = &rl_intra_aic;
1511
    }
1512
   
1513
    /* AC coefs */
1514
    last_index = s->block_last_index[n];
1515
    last_non_zero = i - 1;
1516
    for (; i <= last_index; i++) {
1517
        j = s->intra_scantable.permutated[i];
1518
        level = block[j];
1519
        if (level) {
1520
            run = i - last_non_zero - 1;
1521
            last = (i == last_index);
1522
            sign = 0;
1523
            slevel = level;
1524
            if (level < 0) {
1525
                sign = 1;
1526
                level = -level;
1527
            }
1528
            code = get_rl_index(rl, last, run, level);
1529
            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1530
            if (code == rl->n) {
1531
                put_bits(&s->pb, 1, last);
1532
                put_bits(&s->pb, 6, run);
1533
                
1534
                assert(slevel != 0);
1535

    
1536
                if(slevel < 128 && slevel > -128) 
1537
                    put_bits(&s->pb, 8, slevel & 0xff);
1538
                else{
1539
                    put_bits(&s->pb, 8, 128);
1540
                    put_bits(&s->pb, 5, slevel & 0x1f);
1541
                    put_bits(&s->pb, 6, (slevel>>5)&0x3f);
1542
                }
1543
            } else {
1544
                put_bits(&s->pb, 1, sign);
1545
            }
1546
                last_non_zero = i;
1547
            }
1548
    }
1549
}
1550
#endif
1551

    
1552
#ifdef CONFIG_ENCODERS
1553

    
1554
/***************************************************/
1555
/**
1556
 * add mpeg4 stuffing bits (01...1)
1557
 */
1558
void ff_mpeg4_stuffing(PutBitContext * pbc)
1559
{
1560
    int length;
1561
    put_bits(pbc, 1, 0);
1562
    length= (-get_bit_count(pbc))&7;
1563
    if(length) put_bits(pbc, length, (1<<length)-1);
1564
}
1565

    
1566
/* must be called before writing the header */
1567
void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
1568
    int time_div, time_mod;
1569

    
1570
    if(s->pict_type==I_TYPE){ //we will encode a vol header
1571
        int dummy;
1572
        av_reduce(&s->time_increment_resolution, &dummy, s->avctx->frame_rate, s->avctx->frame_rate_base, (1<<16)-1);
1573
        
1574
        s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
1575
    }
1576
    
1577
    if(s->current_picture.pts)
1578
        s->time= (s->current_picture.pts*s->time_increment_resolution + 500*1000)/(1000*1000);
1579
    else
1580
        s->time= av_rescale(picture_number*(int64_t)s->avctx->frame_rate_base, s->time_increment_resolution, s->avctx->frame_rate);
1581
    time_div= s->time/s->time_increment_resolution;
1582
    time_mod= s->time%s->time_increment_resolution;
1583

    
1584
    if(s->pict_type==B_TYPE){
1585
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
1586
    }else{
1587
        s->last_time_base= s->time_base;
1588
        s->time_base= time_div;
1589
        s->pp_time= s->time - s->last_non_b_time;
1590
        s->last_non_b_time= s->time;
1591
    }
1592
}
1593

    
1594
static void mpeg4_encode_gop_header(MpegEncContext * s){
1595
    int hours, minutes, seconds;
1596
    
1597
    put_bits(&s->pb, 16, 0);
1598
    put_bits(&s->pb, 16, GOP_STARTCODE);
1599
    
1600
    seconds= s->time/s->time_increment_resolution;
1601
    minutes= seconds/60; seconds %= 60;
1602
    hours= minutes/60; minutes %= 60;
1603
    hours%=24;
1604

    
1605
    put_bits(&s->pb, 5, hours);
1606
    put_bits(&s->pb, 6, minutes);
1607
    put_bits(&s->pb, 1, 1);
1608
    put_bits(&s->pb, 6, seconds);
1609
    
1610
    put_bits(&s->pb, 1, 0); //closed gov == NO
1611
    put_bits(&s->pb, 1, 0); //broken link == NO
1612

    
1613
    ff_mpeg4_stuffing(&s->pb);
1614
}
1615

    
1616
static void mpeg4_encode_visual_object_header(MpegEncContext * s){
1617
    int profile_and_level_indication;
1618
    int vo_ver_id;
1619
    
1620
    if(s->max_b_frames || s->quarter_sample){
1621
        profile_and_level_indication= 0xF1; // adv simple level 1
1622
        vo_ver_id= 5;
1623
    }else{
1624
        profile_and_level_indication= 0x01; // simple level 1
1625
        vo_ver_id= 1;
1626
    }
1627
    //FIXME levels
1628

    
1629
    put_bits(&s->pb, 16, 0);
1630
    put_bits(&s->pb, 16, VOS_STARTCODE);
1631
    
1632
    put_bits(&s->pb, 8, profile_and_level_indication);
1633
    
1634
    put_bits(&s->pb, 16, 0);
1635
    put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
1636
    
1637
    put_bits(&s->pb, 1, 1);
1638
        put_bits(&s->pb, 4, vo_ver_id);
1639
        put_bits(&s->pb, 3, 1); //priority
1640
 
1641
    put_bits(&s->pb, 4, 1); //visual obj type== video obj
1642
    
1643
    put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
1644

    
1645
    ff_mpeg4_stuffing(&s->pb);
1646
}
1647

    
1648
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
1649
{
1650
    int vo_ver_id;
1651

    
1652
    if(s->max_b_frames || s->quarter_sample){
1653
        vo_ver_id= 5;
1654
        s->vo_type= ADV_SIMPLE_VO_TYPE;
1655
    }else{
1656
        vo_ver_id= 1;
1657
        s->vo_type= SIMPLE_VO_TYPE;
1658
    }
1659

    
1660
    put_bits(&s->pb, 16, 0);
1661
    put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
1662
    put_bits(&s->pb, 16, 0);
1663
    put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
1664

    
1665
    put_bits(&s->pb, 1, 0);                /* random access vol */
1666
    put_bits(&s->pb, 8, s->vo_type);        /* video obj type indication */
1667
    put_bits(&s->pb, 1, 1);                /* is obj layer id= yes */
1668
      put_bits(&s->pb, 4, vo_ver_id);        /* is obj layer ver id */
1669
      put_bits(&s->pb, 3, 1);                /* is obj layer priority */
1670
    
1671
    float_aspect_to_info(s, s->avctx->aspect_ratio);
1672

    
1673
    put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
1674
    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
1675
    {
1676
        put_bits(&s->pb, 8, s->aspected_width);
1677
        put_bits(&s->pb, 8, s->aspected_height);
1678
    }
1679

    
1680
    if(s->low_delay){
1681
        put_bits(&s->pb, 1, 1);                /* vol control parameters= yes */
1682
        put_bits(&s->pb, 2, 1);                /* chroma format YUV 420/YV12 */
1683
        put_bits(&s->pb, 1, s->low_delay);
1684
        put_bits(&s->pb, 1, 0);                /* vbv parameters= no */
1685
    }else{
1686
        put_bits(&s->pb, 1, 0);                /* vol control parameters= no */
1687
    }
1688

    
1689
    put_bits(&s->pb, 2, RECT_SHAPE);        /* vol shape= rectangle */
1690
    put_bits(&s->pb, 1, 1);                /* marker bit */
1691
    
1692
    put_bits(&s->pb, 16, s->time_increment_resolution);
1693
    if (s->time_increment_bits < 1)
1694
        s->time_increment_bits = 1;
1695
    put_bits(&s->pb, 1, 1);                /* marker bit */
1696
    put_bits(&s->pb, 1, 0);                /* fixed vop rate=no */
1697
    put_bits(&s->pb, 1, 1);                /* marker bit */
1698
    put_bits(&s->pb, 13, s->width);        /* vol width */
1699
    put_bits(&s->pb, 1, 1);                /* marker bit */
1700
    put_bits(&s->pb, 13, s->height);        /* vol height */
1701
    put_bits(&s->pb, 1, 1);                /* marker bit */
1702
    put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1703
    put_bits(&s->pb, 1, 1);                /* obmc disable */
1704
    if (vo_ver_id == 1) {
1705
        put_bits(&s->pb, 1, s->vol_sprite_usage=0);                /* sprite enable */
1706
    }else{
1707
        put_bits(&s->pb, 2, s->vol_sprite_usage=0);                /* sprite enable */
1708
    }
1709
    
1710
    s->quant_precision=5;
1711
    put_bits(&s->pb, 1, 0);                /* not 8 bit == false */
1712
    put_bits(&s->pb, 1, s->mpeg_quant);        /* quant type= (0=h263 style)*/
1713
    if(s->mpeg_quant) put_bits(&s->pb, 2, 0); /* no custom matrixes */
1714

    
1715
    if (vo_ver_id != 1)
1716
        put_bits(&s->pb, 1, s->quarter_sample);
1717
    put_bits(&s->pb, 1, 1);                /* complexity estimation disable */
1718
    s->resync_marker= s->rtp_mode;
1719
    put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
1720
    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1721
    if(s->data_partitioning){
1722
        put_bits(&s->pb, 1, 0);                /* no rvlc */
1723
    }
1724

    
1725
    if (vo_ver_id != 1){
1726
        put_bits(&s->pb, 1, 0);                /* newpred */
1727
        put_bits(&s->pb, 1, 0);                /* reduced res vop */
1728
    }
1729
    put_bits(&s->pb, 1, 0);                /* scalability */
1730
    
1731
    ff_mpeg4_stuffing(&s->pb);
1732

    
1733
    /* user data */
1734
    if(!(s->flags & CODEC_FLAG_BITEXACT)){
1735
        put_bits(&s->pb, 16, 0);
1736
        put_bits(&s->pb, 16, 0x1B2);        /* user_data */
1737
        put_string(&s->pb, LIBAVCODEC_IDENT);
1738
        ff_mpeg4_stuffing(&s->pb);
1739
    }
1740
}
1741

    
1742
/* write mpeg4 VOP header */
1743
void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
1744
{
1745
    int time_incr;
1746
    int time_div, time_mod;
1747
    
1748
    if(s->pict_type==I_TYPE){
1749
        if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
1750
            mpeg4_encode_visual_object_header(s);
1751
            mpeg4_encode_vol_header(s, 0, 0);
1752
        }
1753
        mpeg4_encode_gop_header(s);
1754
    }
1755
    
1756
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
1757

    
1758
//printf("num:%d rate:%d base:%d\n", s->picture_number, s->frame_rate, FRAME_RATE_BASE);
1759
    
1760
    put_bits(&s->pb, 16, 0);                /* vop header */
1761
    put_bits(&s->pb, 16, VOP_STARTCODE);        /* vop header */
1762
    put_bits(&s->pb, 2, s->pict_type - 1);        /* pict type: I = 0 , P = 1 */
1763

    
1764
    time_div= s->time/s->time_increment_resolution;
1765
    time_mod= s->time%s->time_increment_resolution;
1766
    time_incr= time_div - s->last_time_base;
1767
    while(time_incr--)
1768
        put_bits(&s->pb, 1, 1);
1769
        
1770
    put_bits(&s->pb, 1, 0);
1771

    
1772
    put_bits(&s->pb, 1, 1);        /* marker */
1773
    put_bits(&s->pb, s->time_increment_bits, time_mod);        /* time increment */
1774
    put_bits(&s->pb, 1, 1);        /* marker */
1775
    put_bits(&s->pb, 1, 1);        /* vop coded */
1776
    if (    s->pict_type == P_TYPE 
1777
        || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
1778
        put_bits(&s->pb, 1, s->no_rounding);        /* rounding type */
1779
    }
1780
    put_bits(&s->pb, 3, 0);        /* intra dc VLC threshold */
1781
    if(!s->progressive_sequence){
1782
         put_bits(&s->pb, 1, s->top_field_first);
1783
         put_bits(&s->pb, 1, s->alternate_scan);
1784
    }
1785
    //FIXME sprite stuff
1786

    
1787
    put_bits(&s->pb, 5, s->qscale);
1788

    
1789
    if (s->pict_type != I_TYPE)
1790
        put_bits(&s->pb, 3, s->f_code);        /* fcode_for */
1791
    if (s->pict_type == B_TYPE)
1792
        put_bits(&s->pb, 3, s->b_code);        /* fcode_back */
1793
    //    printf("****frame %d\n", picture_number);
1794

    
1795
     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support 
1796
     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
1797
     s->h_edge_pos= s->width;
1798
     s->v_edge_pos= s->height;
1799
}
1800

    
1801
#endif //CONFIG_ENCODERS
1802

    
1803
/**
1804
 * change qscale by given dquant and update qscale dependant variables.
1805
 */
1806
static void change_qscale(MpegEncContext * s, int dquant)
1807
{
1808
    s->qscale += dquant;
1809

    
1810
    if (s->qscale < 1)
1811
        s->qscale = 1;
1812
    else if (s->qscale > 31)
1813
        s->qscale = 31;
1814

    
1815
    s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
1816
    s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
1817
}
1818

    
1819
/**
1820
 * predicts the dc.
1821
 * @param n block index (0-3 are luma, 4-5 are chroma)
1822
 * @param dc_val_ptr a pointer to the dc_val entry for the current MB will be stored here
1823
 * @param dir_ptr pointer to an integer where the prediction direction will be stored
1824
 * @return the quantized predicted dc
1825
 */
1826
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr)
1827
{
1828
    int a, b, c, wrap, pred, scale;
1829
    uint16_t *dc_val;
1830

    
1831
    /* find prediction */
1832
    if (n < 4) {
1833
        scale = s->y_dc_scale;
1834
    } else {
1835
        scale = s->c_dc_scale;
1836
    }
1837
    if(IS_3IV1)
1838
        scale= 8;
1839

    
1840
    wrap= s->block_wrap[n];
1841
    dc_val = s->dc_val[0] + s->block_index[n];
1842

    
1843
    /* B C
1844
     * A X 
1845
     */
1846
    a = dc_val[ - 1];
1847
    b = dc_val[ - 1 - wrap];
1848
    c = dc_val[ - wrap];
1849

    
1850
    /* outside slice handling (we cant do that by memset as we need the dc for error resilience) */
1851
    if(s->first_slice_line && n!=3){
1852
        if(n!=2) b=c= 1024;
1853
        if(n!=1 && s->mb_x == s->resync_mb_x) b=a= 1024;
1854
    }
1855
    if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1){
1856
        if(n==0 || n==4 || n==5)
1857
            b=1024;
1858
    }
1859

    
1860
    if (abs(a - b) < abs(b - c)) {
1861
        pred = c;
1862
        *dir_ptr = 1; /* top */
1863
    } else {
1864
        pred = a;
1865
        *dir_ptr = 0; /* left */
1866
    }
1867
    /* we assume pred is positive */
1868
    pred = FASTDIV((pred + (scale >> 1)), scale);
1869

    
1870
    /* prepare address for prediction update */
1871
    *dc_val_ptr = &dc_val[0];
1872

    
1873
    return pred;
1874
}
1875

    
1876
/**
1877
 * predicts the ac.
1878
 * @param n block index (0-3 are luma, 4-5 are chroma)
1879
 * @param dir the ac prediction direction
1880
 */
1881
void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
1882
                   int dir)
1883
{
1884
    int i;
1885
    int16_t *ac_val, *ac_val1;
1886
    int8_t * const qscale_table= s->current_picture.qscale_table;
1887

    
1888
    /* find prediction */
1889
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1890
    ac_val1 = ac_val;
1891
    if (s->ac_pred) {
1892
        if (dir == 0) {
1893
            const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
1894
            /* left prediction */
1895
            ac_val -= 16;
1896
            
1897
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
1898
                /* same qscale */
1899
                for(i=1;i<8;i++) {
1900
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1901
                }
1902
            }else{
1903
                /* different qscale, we must rescale */
1904
                for(i=1;i<8;i++) {
1905
                    block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
1906
                }
1907
            }
1908
        } else {
1909
            const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
1910
            /* top prediction */
1911
            ac_val -= 16 * s->block_wrap[n];
1912

    
1913
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
1914
                /* same qscale */
1915
                for(i=1;i<8;i++) {
1916
                    block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
1917
                }
1918
            }else{
1919
                /* different qscale, we must rescale */
1920
                for(i=1;i<8;i++) {
1921
                    block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
1922
                }
1923
            }
1924
        }
1925
    }
1926
    /* left copy */
1927
    for(i=1;i<8;i++)
1928
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1929

    
1930
    /* top copy */
1931
    for(i=1;i<8;i++)
1932
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1933

    
1934
}
1935

    
1936
#ifdef CONFIG_ENCODERS
1937

    
1938
static void mpeg4_inv_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
1939
                              int dir)
1940
{
1941
    int i;
1942
    int16_t *ac_val;
1943
    int8_t * const qscale_table= s->current_picture.qscale_table;
1944

    
1945
    /* find prediction */
1946
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1947
 
1948
    if (dir == 0) {
1949
        const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
1950
        /* left prediction */
1951
        ac_val -= 16;
1952
        if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
1953
            /* same qscale */
1954
            for(i=1;i<8;i++) {
1955
                block[s->dsp.idct_permutation[i<<3]] -= ac_val[i];
1956
            }
1957
        }else{
1958
            /* different qscale, we must rescale */
1959
            for(i=1;i<8;i++) {
1960
                block[s->dsp.idct_permutation[i<<3]] -= ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
1961
            }
1962
        }
1963
    } else {
1964
        const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
1965
        /* top prediction */
1966
        ac_val -= 16 * s->block_wrap[n];
1967
        if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
1968
            /* same qscale */
1969
            for(i=1;i<8;i++) {
1970
                block[s->dsp.idct_permutation[i]] -= ac_val[i + 8];
1971
            }
1972
        }else{
1973
            /* different qscale, we must rescale */
1974
            for(i=1;i<8;i++) {
1975
                block[s->dsp.idct_permutation[i]] -= ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
1976
            }
1977
        }
1978
    }
1979
}
1980

    
1981
/**
1982
 * encodes the dc value.
1983
 * @param n block index (0-3 are luma, 4-5 are chroma)
1984
 */
1985
static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
1986
{
1987
#if 1
1988
//    if(level<-255 || level>255) printf("dc overflow\n");
1989
    level+=256;
1990
    if (n < 4) {
1991
        /* luminance */
1992
        put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
1993
    } else {
1994
        /* chrominance */
1995
        put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
1996
    }
1997
#else
1998
    int size, v;
1999
    /* find number of bits */
2000
    size = 0;
2001
    v = abs(level);
2002
    while (v) {
2003
        v >>= 1;
2004
        size++;
2005
    }
2006

    
2007
    if (n < 4) {
2008
        /* luminance */
2009
        put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
2010
    } else {
2011
        /* chrominance */
2012
        put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
2013
    }
2014

    
2015
    /* encode remaining bits */
2016
    if (size > 0) {
2017
        if (level < 0)
2018
            level = (-level) ^ ((1 << size) - 1);
2019
        put_bits(&s->pb, size, level);
2020
        if (size > 8)
2021
            put_bits(&s->pb, 1, 1);
2022
    }
2023
#endif
2024
}
2025

    
2026
/**
2027
 * encodes a 8x8 block
2028
 * @param n block index (0-3 are luma, 4-5 are chroma)
2029
 */
2030
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2031
                               uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
2032
{
2033
    int i, last_non_zero;
2034
#if 0 //variables for the outcommented version
2035
    int code, sign, last;
2036
#endif
2037
    const RLTable *rl;
2038
    uint32_t *bits_tab;
2039
    uint8_t *len_tab;
2040
    const int last_index = s->block_last_index[n];
2041

    
2042
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2043
        /* mpeg4 based DC predictor */
2044
        mpeg4_encode_dc(dc_pb, intra_dc, n);
2045
        if(last_index<1) return;
2046
        i = 1;
2047
        rl = &rl_intra;
2048
        bits_tab= uni_mpeg4_intra_rl_bits;
2049
        len_tab = uni_mpeg4_intra_rl_len;
2050
    } else {
2051
        if(last_index<0) return;
2052
        i = 0;
2053
        rl = &rl_inter;
2054
        bits_tab= uni_mpeg4_inter_rl_bits;
2055
        len_tab = uni_mpeg4_inter_rl_len;
2056
    }
2057

    
2058
    /* AC coefs */
2059
    last_non_zero = i - 1;
2060
#if 1
2061
    for (; i < last_index; i++) {
2062
        int level = block[ scan_table[i] ];
2063
        if (level) {
2064
            int run = i - last_non_zero - 1;
2065
            level+=64;
2066
            if((level&(~127)) == 0){
2067
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2068
                put_bits(ac_pb, len_tab[index], bits_tab[index]);
2069
            }else{ //ESC3
2070
                put_bits(ac_pb, 7+2+1+6+1+12+1, (3<<23)+(3<<21)+(0<<20)+(run<<14)+(1<<13)+(((level-64)&0xfff)<<1)+1);
2071
            }
2072
            last_non_zero = i;
2073
        }
2074
    }
2075
    /*if(i<=last_index)*/{
2076
        int level = block[ scan_table[i] ];
2077
        int run = i - last_non_zero - 1;
2078
        level+=64;
2079
        if((level&(~127)) == 0){
2080
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2081
            put_bits(ac_pb, len_tab[index], bits_tab[index]);
2082
        }else{ //ESC3
2083
            put_bits(ac_pb, 7+2+1+6+1+12+1, (3<<23)+(3<<21)+(1<<20)+(run<<14)+(1<<13)+(((level-64)&0xfff)<<1)+1);
2084
        }
2085
    }
2086
#else
2087
    for (; i <= last_index; i++) {
2088
        const int slevel = block[ scan_table[i] ];
2089
        if (slevel) {
2090
            int level;
2091
            int run = i - last_non_zero - 1;
2092
            last = (i == last_index);
2093
            sign = 0;
2094
            level = slevel;
2095
            if (level < 0) {
2096
                sign = 1;
2097
                level = -level;
2098
            }
2099
            code = get_rl_index(rl, last, run, level);
2100
            put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2101
            if (code == rl->n) {
2102
                int level1, run1;
2103
                level1 = level - rl->max_level[last][run];
2104
                if (level1 < 1) 
2105
                    goto esc2;
2106
                code = get_rl_index(rl, last, run, level1);
2107
                if (code == rl->n) {
2108
                esc2:
2109
                    put_bits(ac_pb, 1, 1);
2110
                    if (level > MAX_LEVEL)
2111
                        goto esc3;
2112
                    run1 = run - rl->max_run[last][level] - 1;
2113
                    if (run1 < 0)
2114
                        goto esc3;
2115
                    code = get_rl_index(rl, last, run1, level);
2116
                    if (code == rl->n) {
2117
                    esc3:
2118
                        /* third escape */
2119
                        put_bits(ac_pb, 1, 1);
2120
                        put_bits(ac_pb, 1, last);
2121
                        put_bits(ac_pb, 6, run);
2122
                        put_bits(ac_pb, 1, 1);
2123
                        put_bits(ac_pb, 12, slevel & 0xfff);
2124
                        put_bits(ac_pb, 1, 1);
2125
                    } else {
2126
                        /* second escape */
2127
                        put_bits(ac_pb, 1, 0);
2128
                        put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2129
                        put_bits(ac_pb, 1, sign);
2130
                    }
2131
                } else {
2132
                    /* first escape */
2133
                    put_bits(ac_pb, 1, 0);
2134
                    put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2135
                    put_bits(ac_pb, 1, sign);
2136
                }
2137
            } else {
2138
                put_bits(ac_pb, 1, sign);
2139
            }
2140
            last_non_zero = i;
2141
        }
2142
    }
2143
#endif
2144
}
2145

    
2146
static inline int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2147
                               uint8_t *scan_table)
2148
{
2149
    int i, last_non_zero;
2150
    const RLTable *rl;
2151
    uint8_t *len_tab;
2152
    const int last_index = s->block_last_index[n];
2153
    int len=0;
2154

    
2155
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2156
        /* mpeg4 based DC predictor */
2157
        //mpeg4_encode_dc(dc_pb, intra_dc, n); //FIXME
2158
        if(last_index<1) return len;
2159
        i = 1;
2160
        rl = &rl_intra;
2161
        len_tab = uni_mpeg4_intra_rl_len;
2162
    } else {
2163
        if(last_index<0) return 0;
2164
        i = 0;
2165
        rl = &rl_inter;
2166
        len_tab = uni_mpeg4_inter_rl_len;
2167
    }
2168

    
2169
    /* AC coefs */
2170
    last_non_zero = i - 1;
2171
    for (; i < last_index; i++) {
2172
        int level = block[ scan_table[i] ];
2173
        if (level) {
2174
            int run = i - last_non_zero - 1;
2175
            level+=64;
2176
            if((level&(~127)) == 0){
2177
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2178
                len += len_tab[index];
2179
            }else{ //ESC3
2180
                len += 7+2+1+6+1+12+1;
2181
            }
2182
            last_non_zero = i;
2183
        }
2184
    }
2185
    /*if(i<=last_index)*/{
2186
        int level = block[ scan_table[i] ];
2187
        int run = i - last_non_zero - 1;
2188
        level+=64;
2189
        if((level&(~127)) == 0){
2190
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2191
            len += len_tab[index];
2192
        }else{ //ESC3
2193
            len += 7+2+1+6+1+12+1;
2194
        }
2195
    }
2196
    
2197
    return len;
2198
}
2199

    
2200
#endif
2201

    
2202

    
2203
/***********************************************/
2204
/* decoding */
2205

    
2206
static VLC intra_MCBPC_vlc;
2207
static VLC inter_MCBPC_vlc;
2208
static VLC cbpy_vlc;
2209
static VLC mv_vlc;
2210
static VLC dc_lum, dc_chrom;
2211
static VLC sprite_trajectory;
2212
static VLC mb_type_b_vlc;
2213

    
2214
void init_vlc_rl(RLTable *rl)
2215
{
2216
    int i, q;
2217
    
2218
    init_vlc(&rl->vlc, 9, rl->n + 1, 
2219
             &rl->table_vlc[0][1], 4, 2,
2220
             &rl->table_vlc[0][0], 4, 2);
2221

    
2222
    
2223
    for(q=0; q<32; q++){
2224
        int qmul= q*2;
2225
        int qadd= (q-1)|1;
2226
        
2227
        if(q==0){
2228
            qmul=1;
2229
            qadd=0;
2230
        }
2231
        
2232
        rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2233
        for(i=0; i<rl->vlc.table_size; i++){
2234
            int code= rl->vlc.table[i][0];
2235
            int len = rl->vlc.table[i][1];
2236
            int level, run;
2237
        
2238
            if(len==0){ // illegal code
2239
                run= 66;
2240
                level= MAX_LEVEL;
2241
            }else if(len<0){ //more bits needed
2242
                run= 0;
2243
                level= code;
2244
            }else{
2245
                if(code==rl->n){ //esc
2246
                    run= 66;
2247
                    level= 0;
2248
                }else{
2249
                    run=   rl->table_run  [code] + 1;
2250
                    level= rl->table_level[code] * qmul + qadd;
2251
                    if(code >= rl->last) run+=192;
2252
                }
2253
            }
2254
            rl->rl_vlc[q][i].len= len;
2255
            rl->rl_vlc[q][i].level= level;
2256
            rl->rl_vlc[q][i].run= run;
2257
        }
2258
    }
2259
}
2260

    
2261
/* init vlcs */
2262

    
2263
/* XXX: find a better solution to handle static init */
2264
void h263_decode_init_vlc(MpegEncContext *s)
2265
{
2266
    static int done = 0;
2267

    
2268
    if (!done) {
2269
        done = 1;
2270

    
2271
        init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 8, 
2272
                 intra_MCBPC_bits, 1, 1,
2273
                 intra_MCBPC_code, 1, 1);
2274
        init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 25, 
2275
                 inter_MCBPC_bits, 1, 1,
2276
                 inter_MCBPC_code, 1, 1);
2277
        init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,
2278
                 &cbpy_tab[0][1], 2, 1,
2279
                 &cbpy_tab[0][0], 2, 1);
2280
        init_vlc(&mv_vlc, MV_VLC_BITS, 33,
2281
                 &mvtab[0][1], 2, 1,
2282
                 &mvtab[0][0], 2, 1);
2283
        init_rl(&rl_inter);
2284
        init_rl(&rl_intra);
2285
        init_rl(&rvlc_rl_inter);
2286
        init_rl(&rvlc_rl_intra);
2287
        init_rl(&rl_intra_aic);
2288
        init_vlc_rl(&rl_inter);
2289
        init_vlc_rl(&rl_intra);
2290
        init_vlc_rl(&rvlc_rl_inter);
2291
        init_vlc_rl(&rvlc_rl_intra);
2292
        init_vlc_rl(&rl_intra_aic);
2293
        init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2294
                 &DCtab_lum[0][1], 2, 1,
2295
                 &DCtab_lum[0][0], 2, 1);
2296
        init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2297
                 &DCtab_chrom[0][1], 2, 1,
2298
                 &DCtab_chrom[0][0], 2, 1);
2299
        init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2300
                 &sprite_trajectory_tab[0][1], 4, 2,
2301
                 &sprite_trajectory_tab[0][0], 4, 2);
2302
        init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2303
                 &mb_type_b_tab[0][1], 2, 1,
2304
                 &mb_type_b_tab[0][0], 2, 1);
2305
    }
2306
}
2307

    
2308
/**
2309
 * Get the GOB height based on picture height.
2310
 */
2311
int ff_h263_get_gob_height(MpegEncContext *s){
2312
    if (s->height <= 400)
2313
        return 1;
2314
    else if (s->height <= 800)
2315
        return  2;
2316
    else
2317
        return 4;
2318
}
2319

    
2320
/**
2321
 * decodes the group of blocks header.
2322
 * @return <0 if an error occured
2323
 */
2324
static int h263_decode_gob_header(MpegEncContext *s)
2325
{
2326
    unsigned int val, gfid;
2327
    int left;
2328
    
2329
    /* Check for GOB Start Code */
2330
    val = show_bits(&s->gb, 16);
2331
    if(val)
2332
        return -1;
2333

    
2334
        /* We have a GBSC probably with GSTUFF */
2335
    skip_bits(&s->gb, 16); /* Drop the zeros */
2336
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
2337
    //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2338
    for(;left>13; left--){
2339
        if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2340
    }
2341
    if(left<=13) 
2342
        return -1;
2343

    
2344
#ifdef DEBUG
2345
    fprintf(stderr,"\nGOB Start Code at MB %d\n", (s->mb_y * s->mb_width) + s->mb_x);
2346
#endif
2347
    s->gob_number = get_bits(&s->gb, 5); /* GN */
2348
    gfid = get_bits(&s->gb, 2); /* GFID */
2349
    s->qscale = get_bits(&s->gb, 5); /* GQUANT */
2350
    if(s->qscale==0) 
2351
        return -1;
2352
    s->mb_x= 0;
2353
    s->mb_y= s->gob_index* s->gob_number;
2354
#ifdef DEBUG
2355
    fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", s->gob_number, gfid, s->qscale);
2356
#endif
2357
    return 0;
2358
}
2359

    
2360
static inline void memsetw(short *tab, int val, int n)
2361
{
2362
    int i;
2363
    for(i=0;i<n;i++)
2364
        tab[i] = val;
2365
}
2366

    
2367
#ifdef CONFIG_ENCODERS
2368

    
2369
void ff_mpeg4_init_partitions(MpegEncContext *s)
2370
{
2371
    init_put_bits(&s->tex_pb, s->tex_pb_buffer, PB_BUFFER_SIZE, NULL, NULL);
2372
    init_put_bits(&s->pb2   , s->pb2_buffer   , PB_BUFFER_SIZE, NULL, NULL);
2373
}
2374

    
2375
void ff_mpeg4_merge_partitions(MpegEncContext *s)
2376
{
2377
    const int pb2_len   = get_bit_count(&s->pb2   );
2378
    const int tex_pb_len= get_bit_count(&s->tex_pb);
2379
    const int bits= get_bit_count(&s->pb);
2380

    
2381
    if(s->pict_type==I_TYPE){
2382
        put_bits(&s->pb, 19, DC_MARKER);
2383
        s->misc_bits+=19 + pb2_len + bits - s->last_bits;
2384
        s->i_tex_bits+= tex_pb_len;
2385
    }else{
2386
        put_bits(&s->pb, 17, MOTION_MARKER);
2387
        s->misc_bits+=17 + pb2_len;
2388
        s->mv_bits+= bits - s->last_bits;
2389
        s->p_tex_bits+= tex_pb_len;
2390
    }
2391

    
2392
    flush_put_bits(&s->pb2);
2393
    flush_put_bits(&s->tex_pb);
2394

    
2395
    ff_copy_bits(&s->pb, s->pb2_buffer   , pb2_len);
2396
    ff_copy_bits(&s->pb, s->tex_pb_buffer, tex_pb_len);
2397
    s->last_bits= get_bit_count(&s->pb);
2398
}
2399

    
2400
#endif //CONFIG_ENCODERS
2401

    
2402
int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
2403
    switch(s->pict_type){
2404
        case I_TYPE:
2405
            return 16;
2406
        case P_TYPE:
2407
        case S_TYPE:
2408
            return s->f_code+15;
2409
        case B_TYPE:
2410
            return FFMAX(FFMAX(s->f_code, s->b_code)+15, 17);
2411
        default:
2412
            return -1;
2413
    }
2414
}
2415

    
2416
#ifdef CONFIG_ENCODERS
2417

    
2418
void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
2419
{
2420
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2421

    
2422
    ff_mpeg4_stuffing(&s->pb);
2423
    put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
2424
    put_bits(&s->pb, 1, 1);
2425
    
2426
    put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
2427
    put_bits(&s->pb, s->quant_precision, s->qscale);
2428
    put_bits(&s->pb, 1, 0); /* no HEC */
2429
}
2430

    
2431
#endif //CONFIG_ENCODERS
2432

    
2433
/**
2434
 * check if the next stuff is a resync marker or the end.
2435
 * @return 0 if not
2436
 */
2437
static inline int mpeg4_is_resync(MpegEncContext *s){
2438
    const int bits_count= get_bits_count(&s->gb);
2439
    
2440
    if(s->workaround_bugs&FF_BUG_NO_PADDING){
2441
        return 0;
2442
    }
2443

    
2444
    if(bits_count + 8 >= s->gb.size_in_bits){
2445
        int v= show_bits(&s->gb, 8);
2446
        v|= 0x7F >> (7-(bits_count&7));
2447
                
2448
        if(v==0x7F)
2449
            return 1;
2450
    }else{
2451
        if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){
2452
            int len;
2453
            GetBitContext gb= s->gb;
2454
        
2455
            skip_bits(&s->gb, 1);
2456
            align_get_bits(&s->gb);
2457
        
2458
            for(len=0; len<32; len++){
2459
                if(get_bits1(&s->gb)) break;
2460
            }
2461

    
2462
            s->gb= gb;
2463

    
2464
            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
2465
                return 1;
2466
        }
2467
    }
2468
    return 0;
2469
}
2470

    
2471
/**
2472
 * decodes the next video packet.
2473
 * @return <0 if something went wrong
2474
 */
2475
static int mpeg4_decode_video_packet_header(MpegEncContext *s)
2476
{
2477
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2478
    int header_extension=0, mb_num, len;
2479
    
2480
    /* is there enough space left for a video packet + header */
2481
    if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
2482

    
2483
    for(len=0; len<32; len++){
2484
        if(get_bits1(&s->gb)) break;
2485
    }
2486

    
2487
    if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
2488
        printf("marker does not match f_code\n");
2489
        return -1;
2490
    }
2491
    
2492
    if(s->shape != RECT_SHAPE){
2493
        header_extension= get_bits1(&s->gb);
2494
        //FIXME more stuff here
2495
    }
2496

    
2497
    mb_num= get_bits(&s->gb, mb_num_bits);
2498
    if(mb_num>=s->mb_num){
2499
        fprintf(stderr, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
2500
        return -1;
2501
    }
2502
    if(s->pict_type == B_TYPE){
2503
        while(s->next_picture.mbskip_table[ s->mb_index2xy[ mb_num ] ]) mb_num++;
2504
        if(mb_num >= s->mb_num) return -1; // slice contains just skiped MBs which where allready decoded
2505
    }
2506
    
2507
    s->mb_x= mb_num % s->mb_width;
2508
    s->mb_y= mb_num / s->mb_width;
2509

    
2510
    if(s->shape != BIN_ONLY_SHAPE){
2511
        int qscale= get_bits(&s->gb, s->quant_precision); 
2512
        if(qscale)
2513
            s->qscale= qscale;
2514
    }
2515

    
2516
    if(s->shape == RECT_SHAPE){
2517
        header_extension= get_bits1(&s->gb);
2518
    }
2519
    if(header_extension){
2520
        int time_increment;
2521
        int time_incr=0;
2522

    
2523
        while (get_bits1(&s->gb) != 0) 
2524
            time_incr++;
2525

    
2526
        check_marker(&s->gb, "before time_increment in video packed header");
2527
        time_increment= get_bits(&s->gb, s->time_increment_bits);
2528
        check_marker(&s->gb, "before vop_coding_type in video packed header");
2529
        
2530
        skip_bits(&s->gb, 2); /* vop coding type */
2531
        //FIXME not rect stuff here
2532

    
2533
        if(s->shape != BIN_ONLY_SHAPE){
2534
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
2535
//FIXME dont just ignore everything
2536
            if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2537
                mpeg4_decode_sprite_trajectory(s);
2538
                fprintf(stderr, "untested\n");
2539
            }
2540

    
2541
            //FIXME reduced res stuff here
2542
            
2543
            if (s->pict_type != I_TYPE) {
2544
                int f_code = get_bits(&s->gb, 3);        /* fcode_for */
2545
                if(f_code==0){
2546
                    printf("Error, video packet header damaged (f_code=0)\n");
2547
                }
2548
            }
2549
            if (s->pict_type == B_TYPE) {
2550
                int b_code = get_bits(&s->gb, 3);
2551
                if(b_code==0){
2552
                    printf("Error, video packet header damaged (b_code=0)\n");
2553
                }
2554
            }       
2555
        }
2556
    }
2557
    //FIXME new-pred stuff
2558
    
2559
//printf("parse ok %d %d %d %d\n", mb_num, s->mb_x + s->mb_y*s->mb_width, get_bits_count(gb), get_bits_count(&s->gb));
2560

    
2561
    return 0;
2562
}
2563

    
2564
void ff_mpeg4_clean_buffers(MpegEncContext *s)
2565
{
2566
    int c_wrap, c_xy, l_wrap, l_xy;
2567

    
2568
    l_wrap= s->block_wrap[0];
2569
    l_xy= s->mb_y*l_wrap*2 + s->mb_x*2;
2570
    c_wrap= s->block_wrap[4];
2571
    c_xy= s->mb_y*c_wrap + s->mb_x;
2572

    
2573
#if 0
2574
    /* clean DC */
2575
    memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
2576
    memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
2577
    memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
2578
#endif
2579

    
2580
    /* clean AC */
2581
    memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(int16_t));
2582
    memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
2583
    memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
2584

    
2585
    /* clean MV */
2586
    // we cant clear the MVs as they might be needed by a b frame
2587
//    memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(int16_t));
2588
//    memset(s->motion_val, 0, 2*sizeof(int16_t)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
2589
    s->last_mv[0][0][0]=
2590
    s->last_mv[0][0][1]=
2591
    s->last_mv[1][0][0]=
2592
    s->last_mv[1][0][1]= 0;
2593
}
2594

    
2595
/**
2596
 * decodes the group of blocks / video packet header.
2597
 * @return <0 if no resync found
2598
 */
2599
int ff_h263_resync(MpegEncContext *s){
2600
    int left, ret;
2601
    
2602
    if(s->codec_id==CODEC_ID_MPEG4)
2603
        skip_bits1(&s->gb);
2604
    
2605
    align_get_bits(&s->gb);
2606

    
2607
    if(show_bits(&s->gb, 16)==0){
2608
        if(s->codec_id==CODEC_ID_MPEG4)
2609
            ret= mpeg4_decode_video_packet_header(s);
2610
        else
2611
            ret= h263_decode_gob_header(s);
2612
        if(ret>=0)
2613
            return 0;
2614
    }
2615
    //ok, its not where its supposed to be ...
2616
    s->gb= s->last_resync_gb;
2617
    align_get_bits(&s->gb);
2618
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
2619
    
2620
    for(;left>16+1+5+5; left-=8){ 
2621
        if(show_bits(&s->gb, 16)==0){
2622
            GetBitContext bak= s->gb;
2623

    
2624
            if(s->codec_id==CODEC_ID_MPEG4)
2625
                ret= mpeg4_decode_video_packet_header(s);
2626
            else
2627
                ret= h263_decode_gob_header(s);
2628
            if(ret>=0)
2629
                return 0;
2630

    
2631
            s->gb= bak;
2632
        }
2633
        skip_bits(&s->gb, 8);
2634
    }
2635
    
2636
    return -1;
2637
}
2638

    
2639
/**
2640
 * gets the average motion vector for a GMC MB.
2641
 * @param n either 0 for the x component or 1 for y
2642
 * @returns the average MV for a GMC MB
2643
 */
2644
static inline int get_amv(MpegEncContext *s, int n){
2645
    int x, y, mb_v, sum, dx, dy, shift;
2646
    int len = 1 << (s->f_code + 4);
2647
    const int a= s->sprite_warping_accuracy;
2648

    
2649
    if(s->real_sprite_warping_points==1){
2650
        if(s->divx_version==500 && s->divx_build==413)
2651
            sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
2652
        else
2653
            sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
2654
    }else{
2655
        dx= s->sprite_delta[n][0];
2656
        dy= s->sprite_delta[n][1];
2657
        shift= s->sprite_shift[0];
2658
        if(n) dy -= 1<<(shift + a + 1);
2659
        else  dx -= 1<<(shift + a + 1);
2660
        mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
2661

    
2662
        sum=0;
2663
        for(y=0; y<16; y++){
2664
            int v;
2665
        
2666
            v= mb_v + dy*y;
2667
            //XXX FIXME optimize
2668
            for(x=0; x<16; x++){
2669
                sum+= v>>shift;
2670
                v+= dx;
2671
            }
2672
        }
2673
        sum= RSHIFT(sum, a+8-s->quarter_sample);
2674
    }
2675

    
2676
    if      (sum < -len) sum= -len;
2677
    else if (sum >= len) sum= len-1;
2678

    
2679
    return sum;
2680
}
2681

    
2682
/**
2683
 * decodes first partition.
2684
 * @return number of MBs decoded or <0 if an error occured
2685
 */
2686
static int mpeg4_decode_partition_a(MpegEncContext *s){
2687
    int mb_num;
2688
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
2689
    
2690
    /* decode first partition */
2691
    mb_num=0;
2692
    s->first_slice_line=1;
2693
    for(; s->mb_y<s->mb_height; s->mb_y++){
2694
        ff_init_block_index(s);
2695
        for(; s->mb_x<s->mb_width; s->mb_x++){
2696
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
2697
            int cbpc;
2698
            int dir=0;
2699
            
2700
            mb_num++;
2701
            ff_update_block_index(s);
2702
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2703
                s->first_slice_line=0;
2704
            
2705
            if(s->pict_type==I_TYPE){
2706
                int i;
2707

    
2708
                if(show_bits_long(&s->gb, 19)==DC_MARKER){
2709
                    return mb_num-1;
2710
                }
2711

    
2712
                cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
2713
                if (cbpc < 0){
2714

    
2715
                    fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2716
                    return -1;
2717
                }
2718
                s->cbp_table[xy]= cbpc & 3;
2719
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
2720
                s->mb_intra = 1;
2721

    
2722
                if(cbpc & 4) {
2723
                    change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2724
                }
2725
                s->current_picture.qscale_table[xy]= s->qscale;
2726

    
2727
                s->mbintra_table[xy]= 1;
2728
                for(i=0; i<6; i++){
2729
                    int dc_pred_dir;
2730
                    int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2731
                    if(dc < 0){
2732
                        fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2733
                        return -1;
2734
                    }
2735
                    dir<<=1;
2736
                    if(dc_pred_dir) dir|=1;
2737
                }
2738
                s->pred_dir_table[xy]= dir;
2739
            }else{ /* P/S_TYPE */
2740
                int mx, my, pred_x, pred_y, bits;
2741
                int16_t * const mot_val= s->motion_val[s->block_index[0]];
2742
                const int stride= s->block_wrap[0]*2;
2743

    
2744
                bits= show_bits(&s->gb, 17);
2745
                if(bits==MOTION_MARKER){
2746
                    return mb_num-1;
2747
                }
2748
                skip_bits1(&s->gb);
2749
                if(bits&0x10000){
2750
                    /* skip mb */
2751
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2752
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
2753
                        mx= get_amv(s, 0);
2754
                        my= get_amv(s, 1);
2755
                    }else{
2756
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
2757
                        mx=my=0;
2758
                    }
2759
                    mot_val[0       ]= mot_val[2       ]=
2760
                    mot_val[0+stride]= mot_val[2+stride]= mx;
2761
                    mot_val[1       ]= mot_val[3       ]=
2762
                    mot_val[1+stride]= mot_val[3+stride]= my;
2763

    
2764
                    if(s->mbintra_table[xy])
2765
                        ff_clean_intra_table_entries(s);
2766
                    continue;
2767
                }
2768
                cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
2769
                if (cbpc < 0){
2770
                    fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2771
                    return -1;
2772
                }
2773
                if (cbpc > 20)
2774
                    cbpc+=3;
2775
                else if (cbpc == 20)
2776
                    fprintf(stderr, "Stuffing !");
2777
                s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
2778
    
2779
                s->mb_intra = ((cbpc & 4) != 0);
2780
        
2781
                if(s->mb_intra){
2782
                    s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
2783
                    s->mbintra_table[xy]= 1;
2784
                    mot_val[0       ]= mot_val[2       ]= 
2785
                    mot_val[0+stride]= mot_val[2+stride]= 0;
2786
                    mot_val[1       ]= mot_val[3       ]=
2787
                    mot_val[1+stride]= mot_val[3+stride]= 0;
2788
                }else{
2789
                    if(s->mbintra_table[xy])
2790
                        ff_clean_intra_table_entries(s);
2791

    
2792
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
2793
                        s->mcsel= get_bits1(&s->gb);
2794
                    else s->mcsel= 0;
2795
        
2796
                    if ((cbpc & 16) == 0) {
2797
                        /* 16x16 motion prediction */
2798

    
2799
                        h263_pred_motion(s, 0, &pred_x, &pred_y);
2800
                        if(!s->mcsel){
2801
                            mx = h263_decode_motion(s, pred_x, s->f_code);
2802
                            if (mx >= 0xffff)
2803
                                return -1;
2804

    
2805
                            my = h263_decode_motion(s, pred_y, s->f_code);
2806
                            if (my >= 0xffff)
2807
                                return -1;
2808
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
2809
                        } else {
2810
                            mx = get_amv(s, 0);
2811
                            my = get_amv(s, 1);
2812
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
2813
                        }
2814

    
2815
                        mot_val[0       ]= mot_val[2       ] =
2816
                        mot_val[0+stride]= mot_val[2+stride]= mx;
2817
                        mot_val[1       ]= mot_val[3       ]=
2818
                        mot_val[1+stride]= mot_val[3+stride]= my;
2819
                    } else {
2820
                        int i;
2821
                        s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
2822
                        for(i=0;i<4;i++) {
2823
                            int16_t *mot_val= h263_pred_motion(s, i, &pred_x, &pred_y);
2824
                            mx = h263_decode_motion(s, pred_x, s->f_code);
2825
                            if (mx >= 0xffff)
2826
                                return -1;
2827
                
2828
                            my = h263_decode_motion(s, pred_y, s->f_code);
2829
                            if (my >= 0xffff)
2830
                                return -1;
2831
                            mot_val[0] = mx;
2832
                            mot_val[1] = my;
2833
                        }
2834
                    }
2835
                }
2836
            }
2837
        }
2838
        s->mb_x= 0;
2839
    }
2840

    
2841
    return mb_num;
2842
}
2843

    
2844
/**
2845
 * decode second partition.
2846
 * @return <0 if an error occured
2847
 */
2848
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
2849
    int mb_num=0;
2850
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
2851

    
2852
    s->mb_x= s->resync_mb_x;
2853
    s->first_slice_line=1;
2854
    for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
2855
        ff_init_block_index(s);
2856
        for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
2857
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
2858

    
2859
            mb_num++;
2860
            ff_update_block_index(s);
2861
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2862
                s->first_slice_line=0;
2863
            
2864
            if(s->pict_type==I_TYPE){
2865
                int ac_pred= get_bits1(&s->gb);
2866
                int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2867
                if(cbpy<0){
2868
                    fprintf(stderr, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2869
                    return -1;
2870
                }
2871
                
2872
                s->cbp_table[xy]|= cbpy<<2;
2873
                s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
2874
            }else{ /* P || S_TYPE */
2875
                if(IS_INTRA(s->current_picture.mb_type[xy])){          
2876
                    int dir=0,i;
2877
                    int ac_pred = get_bits1(&s->gb);
2878
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2879

    
2880
                    if(cbpy<0){
2881
                        fprintf(stderr, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2882
                        return -1;
2883
                    }
2884
                    
2885
                    if(s->cbp_table[xy] & 8) {
2886
                        change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2887
                    }
2888
                    s->current_picture.qscale_table[xy]= s->qscale;
2889

    
2890
                    for(i=0; i<6; i++){
2891
                        int dc_pred_dir;
2892
                        int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2893
                        if(dc < 0){
2894
                            fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2895
                            return -1;
2896
                        }
2897
                        dir<<=1;
2898
                        if(dc_pred_dir) dir|=1;
2899
                    }
2900
                    s->cbp_table[xy]&= 3; //remove dquant
2901
                    s->cbp_table[xy]|= cbpy<<2;
2902
                    s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
2903
                    s->pred_dir_table[xy]= dir;
2904
                }else if(IS_SKIP(s->current_picture.mb_type[xy])){
2905
                    s->current_picture.qscale_table[xy]= s->qscale;
2906
                    s->cbp_table[xy]= 0;
2907
                }else{
2908
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2909

    
2910
                    if(cbpy<0){
2911
                        fprintf(stderr, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2912
                        return -1;
2913
                    }
2914
                    
2915
                    if(s->cbp_table[xy] & 8) {
2916
                        change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2917
                    }
2918
                    s->current_picture.qscale_table[xy]= s->qscale;
2919

    
2920
                    s->cbp_table[xy]&= 3; //remove dquant
2921
                    s->cbp_table[xy]|= (cbpy^0xf)<<2;
2922
                }
2923
            }
2924
        }
2925
        if(mb_num >= mb_count) return 0;
2926
        s->mb_x= 0;
2927
    }
2928
    return 0;
2929
}
2930

    
2931
/**
2932
 * decodes the first & second partition
2933
 * @return <0 if error (and sets error type in the error_status_table)
2934
 */
2935
int ff_mpeg4_decode_partitions(MpegEncContext *s)
2936
{
2937
    int mb_num;
2938
    const int part_a_error= s->pict_type==I_TYPE ? (DC_ERROR|MV_ERROR) : MV_ERROR;
2939
    const int part_a_end  = s->pict_type==I_TYPE ? (DC_END  |MV_END)   : MV_END;
2940
    
2941
    mb_num= mpeg4_decode_partition_a(s);    
2942
    if(mb_num<0){
2943
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
2944
        return -1;
2945
    }
2946
    
2947
    if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
2948
        fprintf(stderr, "slice below monitor ...\n");
2949
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
2950
        return -1;
2951
    }
2952

    
2953
    s->mb_num_left= mb_num;
2954
        
2955
    if(s->pict_type==I_TYPE){
2956
        if(get_bits_long(&s->gb, 19)!=DC_MARKER){
2957
            fprintf(stderr, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
2958
            return -1;
2959
        }
2960
    }else{
2961
        if(get_bits(&s->gb, 17)!=MOTION_MARKER){
2962
            fprintf(stderr, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
2963
            return -1;
2964
        }
2965
    }
2966
    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, part_a_end);
2967
    
2968
    if( mpeg4_decode_partition_b(s, mb_num) < 0){
2969
        if(s->pict_type==P_TYPE)
2970
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, DC_ERROR);
2971
        return -1;
2972
    }else{
2973
        if(s->pict_type==P_TYPE)
2974
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, DC_END);
2975
    }
2976

    
2977
    return 0;        
2978
}
2979

    
2980
/**
2981
 * decode partition C of one MB.
2982
 * @return <0 if an error occured
2983
 */
2984
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
2985
{
2986
    int cbp, mb_type;
2987
    const int xy= s->mb_x + s->mb_y*s->mb_stride;
2988

    
2989
    mb_type= s->current_picture.mb_type[xy];
2990
    cbp = s->cbp_table[xy];
2991

    
2992
    if(s->current_picture.qscale_table[xy] != s->qscale){
2993
        s->qscale= s->current_picture.qscale_table[xy];
2994
        s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
2995
        s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
2996
    }
2997
    
2998
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
2999
        int i;
3000
        for(i=0; i<4; i++){
3001
            s->mv[0][i][0] = s->motion_val[ s->block_index[i] ][0];
3002
            s->mv[0][i][1] = s->motion_val[ s->block_index[i] ][1];
3003
        }
3004
        s->mb_intra = IS_INTRA(mb_type);
3005

    
3006
        if (IS_SKIP(mb_type)) {
3007
            /* skip mb */
3008
            for(i=0;i<6;i++)
3009
                s->block_last_index[i] = -1;
3010
            s->mv_dir = MV_DIR_FORWARD;
3011
            s->mv_type = MV_TYPE_16X16;
3012
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3013
                s->mcsel=1;
3014
                s->mb_skiped = 0;
3015
            }else{
3016
                s->mcsel=0;
3017
                s->mb_skiped = 1;
3018
            }
3019
        }else if(s->mb_intra){
3020
            s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3021
        }else if(!s->mb_intra){
3022
//            s->mcsel= 0; //FIXME do we need to init that
3023
            
3024
            s->mv_dir = MV_DIR_FORWARD;
3025
            if (IS_8X8(mb_type)) {
3026
                s->mv_type = MV_TYPE_8X8;
3027
            } else {
3028
                s->mv_type = MV_TYPE_16X16;
3029
            }
3030
        }
3031
    } else { /* I-Frame */
3032
        s->mb_intra = 1;
3033
        s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3034
    }
3035

    
3036
    if (!IS_SKIP(mb_type)) {
3037
        int i;
3038
        /* decode each block */
3039
        for (i = 0; i < 6; i++) {
3040
            if(mpeg4_decode_block(s, block[i], i, cbp&32, s->mb_intra, s->rvlc) < 0){
3041
                fprintf(stderr, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra);
3042
                return -1;
3043
            }
3044
            cbp+=cbp;
3045
        }
3046
    }
3047

    
3048
    /* per-MB end of slice check */
3049

    
3050
    if(--s->mb_num_left <= 0){
3051
//printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size_in_bits - get_bits_count(&s->gb));
3052
        if(mpeg4_is_resync(s))
3053
            return SLICE_END;
3054
        else
3055
            return SLICE_NOEND;     
3056
    }else{
3057
        if(mpeg4_is_resync(s)){
3058
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
3059
            if(s->cbp_table[xy+delta])
3060
                return SLICE_END;
3061
        }
3062
        return SLICE_OK;
3063
    }
3064
}
3065

    
3066
int ff_h263_decode_mb(MpegEncContext *s,
3067
                      DCTELEM block[6][64])
3068
{
3069
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
3070
    int16_t *mot_val;
3071
    static int8_t quant_tab[4] = { -1, -2, 1, 2 };
3072
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
3073

    
3074
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3075
        if (get_bits1(&s->gb)) {
3076
            /* skip mb */
3077
            s->mb_intra = 0;
3078
            for(i=0;i<6;i++)
3079
                s->block_last_index[i] = -1;
3080
            s->mv_dir = MV_DIR_FORWARD;
3081
            s->mv_type = MV_TYPE_16X16;
3082
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3083
                s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
3084
                s->mcsel=1;
3085
                s->mv[0][0][0]= get_amv(s, 0);
3086
                s->mv[0][0][1]= get_amv(s, 1);
3087

    
3088
                s->mb_skiped = 0;
3089
            }else{
3090
                s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3091
                s->mcsel=0;
3092
                s->mv[0][0][0] = 0;
3093
                s->mv[0][0][1] = 0;
3094
                s->mb_skiped = 1;
3095
            }
3096
            goto end;
3097
        }
3098
        cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3099
        //fprintf(stderr, "\tCBPC: %d", cbpc);
3100
        if (cbpc < 0)
3101
            return -1;
3102
        if (cbpc > 20)
3103
            cbpc+=3;
3104
        else if (cbpc == 20)
3105
            fprintf(stderr, "Stuffing !");
3106
        
3107
        dquant = cbpc & 8;
3108
        s->mb_intra = ((cbpc & 4) != 0);
3109
        if (s->mb_intra) goto intra;
3110
        
3111
        if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
3112
            s->mcsel= get_bits1(&s->gb);
3113
        else s->mcsel= 0;
3114
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3115
        cbp = (cbpc & 3) | ((cbpy ^ 0xf) << 2);
3116
        if (dquant) {
3117
            change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3118
        }
3119
        if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
3120
            s->interlaced_dct= get_bits1(&s->gb);
3121
        
3122
        s->mv_dir = MV_DIR_FORWARD;
3123
        if ((cbpc & 16) == 0) {
3124
            if(s->mcsel){
3125
                s->current_picture.mb_type[xy]= MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
3126
                /* 16x16 global motion prediction */
3127
                s->mv_type = MV_TYPE_16X16;
3128
                mx= get_amv(s, 0);
3129
                my= get_amv(s, 1);
3130
                s->mv[0][0][0] = mx;
3131
                s->mv[0][0][1] = my;
3132
            }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
3133
                s->current_picture.mb_type[xy]= MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; 
3134
                /* 16x8 field motion prediction */
3135
                s->mv_type= MV_TYPE_FIELD;
3136

    
3137
                s->field_select[0][0]= get_bits1(&s->gb);
3138
                s->field_select[0][1]= get_bits1(&s->gb);
3139

    
3140
                h263_pred_motion(s, 0, &pred_x, &pred_y);
3141
                
3142
                for(i=0; i<2; i++){
3143
                    mx = h263_decode_motion(s, pred_x, s->f_code);
3144
                    if (mx >= 0xffff)
3145
                        return -1;
3146
            
3147
                    my = h263_decode_motion(s, pred_y/2, s->f_code);
3148
                    if (my >= 0xffff)
3149
                        return -1;
3150

    
3151
                    s->mv[0][i][0] = mx;
3152
                    s->mv[0][i][1] = my;
3153
                }
3154
            }else{
3155
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
3156
                /* 16x16 motion prediction */
3157
                s->mv_type = MV_TYPE_16X16;
3158
                h263_pred_motion(s, 0, &pred_x, &pred_y);
3159
                if (s->umvplus)
3160
                   mx = h263p_decode_umotion(s, pred_x);
3161
                else
3162
                   mx = h263_decode_motion(s, pred_x, s->f_code);
3163
            
3164
                if (mx >= 0xffff)
3165
                    return -1;
3166
            
3167
                if (s->umvplus)
3168
                   my = h263p_decode_umotion(s, pred_y);
3169
                else
3170
                   my = h263_decode_motion(s, pred_y, s->f_code);
3171
            
3172
                if (my >= 0xffff)
3173
                    return -1;
3174
                s->mv[0][0][0] = mx;
3175
                s->mv[0][0][1] = my;
3176

    
3177
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3178
                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */                   
3179
            }
3180
        } else {
3181
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
3182
            s->mv_type = MV_TYPE_8X8;
3183
            for(i=0;i<4;i++) {
3184
                mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
3185
                if (s->umvplus)
3186
                  mx = h263p_decode_umotion(s, pred_x);
3187
                else
3188
                  mx = h263_decode_motion(s, pred_x, s->f_code);
3189
                if (mx >= 0xffff)
3190
                    return -1;
3191
                
3192
                if (s->umvplus)
3193
                  my = h263p_decode_umotion(s, pred_y);
3194
                else    
3195
                  my = h263_decode_motion(s, pred_y, s->f_code);
3196
                if (my >= 0xffff)
3197
                    return -1;
3198
                s->mv[0][i][0] = mx;
3199
                s->mv[0][i][1] = my;
3200
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3201
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3202
                mot_val[0] = mx;
3203
                mot_val[1] = my;
3204
            }
3205
        }
3206
    } else if(s->pict_type==B_TYPE) {
3207
        int modb1; // first bit of modb
3208
        int modb2; // second bit of modb
3209
        int mb_type;
3210

    
3211
        s->mb_intra = 0; //B-frames never contain intra blocks
3212
        s->mcsel=0;      //     ...               true gmc blocks
3213

    
3214
        if(s->mb_x==0){
3215
            for(i=0; i<2; i++){
3216
                s->last_mv[i][0][0]= 
3217
                s->last_mv[i][0][1]= 
3218
                s->last_mv[i][1][0]= 
3219
                s->last_mv[i][1][1]= 0;
3220
            }
3221
        }
3222

    
3223
        /* if we skipped it in the future P Frame than skip it now too */
3224
        s->mb_skiped= s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC
3225

    
3226
        if(s->mb_skiped){
3227
                /* skip mb */
3228
            for(i=0;i<6;i++)
3229
                s->block_last_index[i] = -1;
3230

    
3231
            s->mv_dir = MV_DIR_FORWARD;
3232
            s->mv_type = MV_TYPE_16X16;
3233
            s->mv[0][0][0] = 0;
3234
            s->mv[0][0][1] = 0;
3235
            s->mv[1][0][0] = 0;
3236
            s->mv[1][0][1] = 0;
3237
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; 
3238
            goto end;
3239
        }
3240

    
3241
        modb1= get_bits1(&s->gb); 
3242
        if(modb1){
3243
            mb_type= MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; //like MB_TYPE_B_DIRECT but no vectors coded
3244
            cbp=0;
3245
        }else{
3246
            modb2= get_bits1(&s->gb);
3247
            mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
3248
            if(mb_type<0){
3249
                printf("illegal MB_type\n");
3250
                return -1;
3251
            }
3252
            mb_type= mb_type_b_map[ mb_type ];
3253
            if(modb2) cbp= 0;
3254
            else      cbp= get_bits(&s->gb, 6);
3255

    
3256
            if ((!IS_DIRECT(mb_type)) && cbp) {
3257
                if(get_bits1(&s->gb)){
3258
                    change_qscale(s, get_bits1(&s->gb)*4 - 2);
3259
                }
3260
            }
3261

    
3262
            if(!s->progressive_sequence){
3263
                if(cbp)
3264
                    s->interlaced_dct= get_bits1(&s->gb);
3265

    
3266
                if(!IS_DIRECT(mb_type) && get_bits1(&s->gb)){
3267
                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
3268
                    mb_type &= ~MB_TYPE_16x16;
3269

    
3270
                    if(USES_LIST(mb_type, 0)){
3271
                        s->field_select[0][0]= get_bits1(&s->gb);
3272
                        s->field_select[0][1]= get_bits1(&s->gb);
3273
                    }
3274
                    if(USES_LIST(mb_type, 1)){
3275
                        s->field_select[1][0]= get_bits1(&s->gb);
3276
                        s->field_select[1][1]= get_bits1(&s->gb);
3277
                    }
3278
                }
3279
            }
3280

    
3281
            s->mv_dir = 0;
3282
            if((mb_type & (MB_TYPE_DIRECT2|MB_TYPE_INTERLACED)) == 0){
3283
                s->mv_type= MV_TYPE_16X16;
3284

    
3285
                if(USES_LIST(mb_type, 0)){
3286
                    s->mv_dir = MV_DIR_FORWARD;
3287

    
3288
                    mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
3289
                    my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
3290
                    s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
3291
                    s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
3292
                }
3293
    
3294
                if(USES_LIST(mb_type, 1)){
3295
                    s->mv_dir |= MV_DIR_BACKWARD;
3296

    
3297
                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
3298
                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
3299
                    s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
3300
                    s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
3301
                }
3302
            }else if(!IS_DIRECT(mb_type)){
3303
                s->mv_type= MV_TYPE_FIELD;
3304

    
3305
                if(USES_LIST(mb_type, 0)){
3306
                    s->mv_dir = MV_DIR_FORWARD;
3307
                
3308
                    for(i=0; i<2; i++){
3309
                        mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
3310
                        my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
3311
                        s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
3312
                        s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
3313
                    }
3314
                }
3315
    
3316
                if(USES_LIST(mb_type, 1)){
3317
                    s->mv_dir |= MV_DIR_BACKWARD;
3318

    
3319
                    for(i=0; i<2; i++){
3320
                        mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
3321
                        my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
3322
                        s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
3323
                        s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
3324
                    }
3325
                }
3326
            }
3327
        }
3328
          
3329
        if(IS_DIRECT(mb_type)){
3330
            if(IS_SKIP(mb_type))
3331
                mx=my=0;
3332
            else{
3333
                mx = h263_decode_motion(s, 0, 1);
3334
                my = h263_decode_motion(s, 0, 1);
3335
            }
3336
 
3337
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3338
            mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
3339
        }
3340
        s->current_picture.mb_type[xy]= mb_type;
3341
    } else { /* I-Frame */
3342
        cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
3343
        if (cbpc < 0)
3344
            return -1;
3345
        dquant = cbpc & 4;
3346
        s->mb_intra = 1;
3347
intra:
3348
        s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3349
        if (s->h263_pred || s->h263_aic) {
3350
            s->ac_pred = get_bits1(&s->gb);
3351
            if(s->ac_pred){
3352
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
3353
            
3354
                if (s->h263_aic)
3355
                    s->h263_aic_dir = get_bits1(&s->gb);
3356
            }
3357
        }else
3358
            s->ac_pred = 0;
3359
        
3360
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3361
        if(cbpy<0) return -1;
3362
        cbp = (cbpc & 3) | (cbpy << 2);
3363
        if (dquant) {
3364
            change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3365
        }
3366
        
3367
        if(!s->progressive_sequence)
3368
            s->interlaced_dct= get_bits1(&s->gb);
3369

    
3370
        /* decode each block */
3371
        if (s->h263_pred) {
3372
            for (i = 0; i < 6; i++) {
3373
                if (mpeg4_decode_block(s, block[i], i, cbp&32, 1, 0) < 0)
3374
                    return -1;
3375
                cbp+=cbp;
3376
            }
3377
        } else {
3378
            for (i = 0; i < 6; i++) {
3379
                if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3380
                    return -1;
3381
                cbp+=cbp;
3382
            }
3383
        }
3384
        goto end;
3385
    }
3386

    
3387
    /* decode each block */
3388
    if (s->h263_pred) {
3389
        for (i = 0; i < 6; i++) {
3390
            if (mpeg4_decode_block(s, block[i], i, cbp&32, 0, 0) < 0)
3391
                return -1;
3392
            cbp+=cbp;
3393
        }
3394
    } else {
3395
        for (i = 0; i < 6; i++) {
3396
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3397
                return -1;
3398
            cbp+=cbp;
3399
        }
3400
    }
3401
end:
3402

    
3403
        /* per-MB end of slice check */
3404
    if(s->codec_id==CODEC_ID_MPEG4){
3405
        if(mpeg4_is_resync(s)){
3406
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
3407
            if(s->pict_type==B_TYPE && s->next_picture.mbskip_table[xy + delta])
3408
                return SLICE_OK;
3409
            return SLICE_END;
3410
        }
3411
    }else{
3412
        int v= show_bits(&s->gb, 16);
3413
    
3414
        if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
3415
            v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
3416
        }
3417

    
3418
        if(v==0)
3419
            return SLICE_END;
3420
    }
3421

    
3422
    return SLICE_OK;     
3423
}
3424

    
3425
static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
3426
{
3427
    int code, val, sign, shift, l;
3428
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
3429

    
3430
    if (code == 0)
3431
        return pred;
3432
    if (code < 0)
3433
        return 0xffff;
3434

    
3435
    sign = get_bits1(&s->gb);
3436
    shift = f_code - 1;
3437
    val = code;
3438
    if (shift) {
3439
        val = (val - 1) << shift;
3440
        val |= get_bits(&s->gb, shift);
3441
        val++;
3442
    }
3443
    if (sign)
3444
        val = -val;
3445
    val += pred;
3446

    
3447
    /* modulo decoding */
3448
    if (!s->h263_long_vectors) {
3449
        l = 1 << (f_code + 4);
3450
        val = ((val + l)&(l*2-1)) - l;
3451
    } else {
3452
        /* horrible h263 long vector mode */
3453
        if (pred < -31 && val < -63)
3454
            val += 64;
3455
        if (pred > 32 && val > 63)
3456
            val -= 64;
3457
        
3458
    }
3459
    return val;
3460
}
3461

    
3462
/* Decodes RVLC of H.263+ UMV */
3463
static int h263p_decode_umotion(MpegEncContext * s, int pred)
3464
{
3465
   int code = 0, sign;
3466
   
3467
   if (get_bits1(&s->gb)) /* Motion difference = 0 */
3468
      return pred;
3469
   
3470
   code = 2 + get_bits1(&s->gb);
3471
   
3472
   while (get_bits1(&s->gb))
3473
   {
3474
      code <<= 1;
3475
      code += get_bits1(&s->gb);
3476
   }
3477
   sign = code & 1;
3478
   code >>= 1;
3479
   
3480
   code = (sign) ? (pred - code) : (pred + code);
3481
#ifdef DEBUG
3482
   fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
3483
#endif
3484
   return code;   
3485

    
3486
}
3487

    
3488
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
3489
                             int n, int coded)
3490
{
3491
    int code, level, i, j, last, run;
3492
    RLTable *rl = &rl_inter;
3493
    const uint8_t *scan_table;
3494

    
3495
    scan_table = s->intra_scantable.permutated;
3496
    if (s->h263_aic && s->mb_intra) {
3497
        rl = &rl_intra_aic;
3498
        i = 0;
3499
        if (s->ac_pred) {
3500
            if (s->h263_aic_dir) 
3501
                scan_table = s->intra_v_scantable.permutated; /* left */
3502
            else
3503
                scan_table = s->intra_h_scantable.permutated; /* top */
3504
        }
3505
    } else if (s->mb_intra) {
3506
        /* DC coef */
3507
        if(s->h263_rv10){
3508
          if (s->rv10_version == 3 && s->pict_type == I_TYPE) {
3509
            int component, diff;
3510
            component = (n <= 3 ? 0 : n - 4 + 1);
3511
            level = s->last_dc[component];
3512
            if (s->rv10_first_dc_coded[component]) {
3513
                diff = rv_decode_dc(s, n);
3514
                if (diff == 0xffff)
3515
                    return -1;
3516
                level += diff;
3517
                level = level & 0xff; /* handle wrap round */
3518
                s->last_dc[component] = level;
3519
            } else {
3520
                s->rv10_first_dc_coded[component] = 1;
3521
            }
3522
          } else {
3523
                level = get_bits(&s->gb, 8);
3524
          }
3525
        }else{
3526
            level = get_bits(&s->gb, 8);
3527
            if((level&0x7F) == 0){
3528
                fprintf(stderr, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);
3529
                return -1;
3530
            }
3531
            if (level == 255)
3532
                level = 128;
3533
        }
3534
        block[0] = level;
3535
        i = 1;
3536
    } else {
3537
        i = 0;
3538
    }
3539
    if (!coded) {
3540
        if (s->mb_intra && s->h263_aic)
3541
            goto not_coded;
3542
        s->block_last_index[n] = i - 1;
3543
        return 0;
3544
    }
3545

    
3546
    for(;;) {
3547
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
3548
        if (code < 0){
3549
            fprintf(stderr, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
3550
            return -1;
3551
        }
3552
        if (code == rl->n) {
3553
            /* escape */
3554
            last = get_bits1(&s->gb);
3555
            run = get_bits(&s->gb, 6);
3556
            level = (int8_t)get_bits(&s->gb, 8);
3557
            if(level == -128){
3558
                if (s->h263_rv10) {
3559
                    /* XXX: should patch encoder too */
3560
                    level = get_sbits(&s->gb, 12);
3561
                }else{
3562
                    level = get_bits(&s->gb, 5);
3563
                    level |= get_sbits(&s->gb, 6)<<5;
3564
                }
3565
            }
3566
        } else {
3567
            run = rl->table_run[code];
3568
            level = rl->table_level[code];
3569
            last = code >= rl->last;
3570
            if (get_bits1(&s->gb))
3571
                level = -level;
3572
        }
3573
        i += run;
3574
        if (i >= 64){
3575
            fprintf(stderr, "run overflow at %dx%d\n", s->mb_x, s->mb_y);
3576
            return -1;
3577
        }
3578
        j = scan_table[i];
3579
        block[j] = level;
3580
        if (last)
3581
            break;
3582
        i++;
3583
    }
3584
not_coded:    
3585
    if (s->mb_intra && s->h263_aic) {
3586
        h263_pred_acdc(s, block, n);
3587
        i = 63;
3588
    }
3589
    s->block_last_index[n] = i;
3590
    return 0;
3591
}
3592

    
3593
/**
3594
 * decodes the dc value.
3595
 * @param n block index (0-3 are luma, 4-5 are chroma)
3596
 * @param dir_ptr the prediction direction will be stored here
3597
 * @return the quantized dc
3598
 */
3599
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
3600
{
3601
    int level, pred, code;
3602
    uint16_t *dc_val;
3603

    
3604
    if (n < 4) 
3605
        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
3606
    else 
3607
        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
3608
    if (code < 0 || code > 9 /* && s->nbit<9 */){
3609
        fprintf(stderr, "illegal dc vlc\n");
3610
        return -1;
3611
    }
3612
    if (code == 0) {
3613
        level = 0;
3614
    } else {
3615
        if(IS_3IV1){
3616
            if(code==1)
3617
                level= 2*get_bits1(&s->gb)-1;
3618
            else{
3619
                if(get_bits1(&s->gb))
3620
                    level = get_bits(&s->gb, code-1) + (1<<(code-1));
3621
                else
3622
                    level = -get_bits(&s->gb, code-1) - (1<<(code-1));
3623
            }
3624
        }else{
3625
            level = get_xbits(&s->gb, code);
3626
        }
3627

    
3628
        if (code > 8){
3629
            if(get_bits1(&s->gb)==0){ /* marker */
3630
                if(s->error_resilience>=2){
3631
                    fprintf(stderr, "dc marker bit missing\n");
3632
                    return -1;
3633
                }
3634
            }
3635
        }
3636
    }
3637
    pred = ff_mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
3638
    level += pred;
3639
    if (level < 0){
3640
        if(s->error_resilience>=3){
3641
            fprintf(stderr, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
3642
            return -1;
3643
        }
3644
        level = 0;
3645
    }
3646
    if (n < 4) {
3647
        *dc_val = level * s->y_dc_scale;
3648
    } else {
3649
        *dc_val = level * s->c_dc_scale;
3650
    }
3651
    if(IS_3IV1)
3652
        *dc_val = level * 8;
3653
    
3654
    if(s->error_resilience>=3){
3655
        if(*dc_val > 2048 + s->y_dc_scale + s->c_dc_scale){
3656
            fprintf(stderr, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
3657
            return -1;
3658
        }
3659
    }
3660
    return level;
3661
}
3662

    
3663
/**
3664
 * decodes a block.
3665
 * @return <0 if an error occured
3666
 */
3667
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
3668
                              int n, int coded, int intra, int rvlc)
3669
{
3670
    int level, i, last, run;
3671
    int dc_pred_dir;
3672
    RLTable * rl;
3673
    RL_VLC_ELEM * rl_vlc;
3674
    const uint8_t * scan_table;
3675
    int qmul, qadd;
3676

    
3677
    //Note intra & rvlc should be optimized away if this is inlined
3678
    
3679
    if(intra) {
3680
        /* DC coef */
3681
        if(s->partitioned_frame){
3682
            level = s->dc_val[0][ s->block_index[n] ];
3683
            if(n<4) level= FASTDIV((level + (s->y_dc_scale>>1)), s->y_dc_scale);
3684
            else    level= FASTDIV((level + (s->c_dc_scale>>1)), s->c_dc_scale);
3685
            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_stride]<<n)&32;
3686
        }else{
3687
            level = mpeg4_decode_dc(s, n, &dc_pred_dir);
3688
            if (level < 0)
3689
                return -1;
3690
        }
3691
        block[0] = level;
3692
        i = 0;
3693
        if (!coded) 
3694
            goto not_coded;
3695
        
3696
        if(rvlc){        
3697
            rl = &rvlc_rl_intra;
3698
            rl_vlc = rvlc_rl_intra.rl_vlc[0];
3699
        }else{
3700
            rl = &rl_intra;
3701
            rl_vlc = rl_intra.rl_vlc[0];
3702
        }
3703
        if (s->ac_pred) {
3704
            if (dc_pred_dir == 0) 
3705
                scan_table = s->intra_v_scantable.permutated; /* left */
3706
            else
3707
                scan_table = s->intra_h_scantable.permutated; /* top */
3708
        } else {
3709
            scan_table = s->intra_scantable.permutated;
3710
        }
3711
        qmul=1;
3712
        qadd=0;
3713
    } else {
3714
        i = -1;
3715
        if (!coded) {
3716
            s->block_last_index[n] = i;
3717
            return 0;
3718
        }
3719
        if(rvlc) rl = &rvlc_rl_inter;
3720
        else     rl = &rl_inter;
3721
   
3722
        scan_table = s->intra_scantable.permutated;
3723

    
3724
        if(s->mpeg_quant){
3725
            qmul=1;
3726
            qadd=0;
3727
            if(rvlc){        
3728
                rl_vlc = rvlc_rl_inter.rl_vlc[0];        
3729
            }else{
3730
                rl_vlc = rl_inter.rl_vlc[0];        
3731
            }
3732
        }else{
3733
            qmul = s->qscale << 1;
3734
            qadd = (s->qscale - 1) | 1;
3735
            if(rvlc){        
3736
                rl_vlc = rvlc_rl_inter.rl_vlc[s->qscale];        
3737
            }else{
3738
                rl_vlc = rl_inter.rl_vlc[s->qscale];        
3739
            }
3740
        }
3741
    }
3742
  {
3743
    OPEN_READER(re, &s->gb);
3744
    for(;;) {
3745
        UPDATE_CACHE(re, &s->gb);
3746
        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3747
        if (level==0) {
3748
          /* escape */                
3749
          if(rvlc){
3750
                if(SHOW_UBITS(re, &s->gb, 1)==0){
3751
                    fprintf(stderr, "1. marker bit missing in rvlc esc\n");
3752
                    return -1;
3753
                }; SKIP_CACHE(re, &s->gb, 1);
3754
 
3755
                last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
3756
                run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
3757
                SKIP_COUNTER(re, &s->gb, 1+1+6);
3758
                UPDATE_CACHE(re, &s->gb);
3759
              
3760
                if(SHOW_UBITS(re, &s->gb, 1)==0){
3761
                    fprintf(stderr, "2. marker bit missing in rvlc esc\n");
3762
                    return -1;
3763
                }; SKIP_CACHE(re, &s->gb, 1);
3764
 
3765
                level= SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11);
3766
 
3767
                if(SHOW_UBITS(re, &s->gb, 5)!=0x10){
3768
                    fprintf(stderr, "reverse esc missing\n");
3769
                    return -1;
3770
                }; SKIP_CACHE(re, &s->gb, 5);
3771

    
3772
                level=  level * qmul + qadd;
3773
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1);
3774
                SKIP_COUNTER(re, &s->gb, 1+11+5+1);
3775

    
3776
                i+= run + 1;
3777
                if(last) i+=192;
3778
          }else{
3779
            int cache;
3780
            cache= GET_CACHE(re, &s->gb);
3781

    
3782
            if(IS_3IV1) 
3783
                cache ^= 0xC0000000;
3784

    
3785
            if (cache&0x80000000) {
3786
                if (cache&0x40000000) {
3787
                    /* third escape */
3788
                    SKIP_CACHE(re, &s->gb, 2);
3789
                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
3790
                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
3791
                    SKIP_COUNTER(re, &s->gb, 2+1+6);
3792
                    UPDATE_CACHE(re, &s->gb);
3793

    
3794
                    if(IS_3IV1){
3795
                        level= SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12);
3796
                    }else{
3797
                        if(SHOW_UBITS(re, &s->gb, 1)==0){
3798
                            fprintf(stderr, "1. marker bit missing in 3. esc\n");
3799
                            return -1;
3800
                        }; SKIP_CACHE(re, &s->gb, 1);
3801

    
3802
                        level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
3803

    
3804
                        if(SHOW_UBITS(re, &s->gb, 1)==0){
3805
                            fprintf(stderr, "2. marker bit missing in 3. esc\n");
3806
                            return -1;
3807
                        }; LAST_SKIP_CACHE(re, &s->gb, 1);
3808

    
3809
                        SKIP_COUNTER(re, &s->gb, 1+12+1);
3810
                    }
3811
 
3812
                    if(level*s->qscale>1024 || level*s->qscale<-1024){
3813
                        fprintf(stderr, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
3814
                        return -1;
3815
                    }
3816
#if 1 
3817
                    {
3818
                        const int abs_level= ABS(level);
3819
                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN && !(s->workaround_bugs&FF_BUG_AC_VLC)){
3820
                            const int run1= run - rl->max_run[last][abs_level] - 1;
3821
                            if(abs_level <= rl->max_level[last][run]){
3822
                                fprintf(stderr, "illegal 3. esc, vlc encoding possible\n");
3823
                                return -1;
3824
                            }
3825
                            if(s->error_resilience > FF_ER_COMPLIANT){
3826
                                if(abs_level <= rl->max_level[last][run]*2){
3827
                                    fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");
3828
                                    return -1;
3829
                                }
3830
                                if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
3831
                                    fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");
3832
                                    return -1;
3833
                                }
3834
                            }
3835
                        }
3836
                    }
3837
#endif
3838
                    if (level>0) level= level * qmul + qadd;
3839
                    else         level= level * qmul - qadd;
3840

    
3841
                    i+= run + 1;
3842
                    if(last) i+=192;
3843
                } else {
3844
                    /* second escape */
3845
#if MIN_CACHE_BITS < 20
3846
                    LAST_SKIP_BITS(re, &s->gb, 2);
3847
                    UPDATE_CACHE(re, &s->gb);
3848
#else
3849
                    SKIP_BITS(re, &s->gb, 2);
3850
#endif
3851
                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3852
                    i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
3853
                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3854
                    LAST_SKIP_BITS(re, &s->gb, 1);
3855
                }
3856
            } else {
3857
                /* first escape */
3858
#if MIN_CACHE_BITS < 19
3859
                LAST_SKIP_BITS(re, &s->gb, 1);
3860
                UPDATE_CACHE(re, &s->gb);
3861
#else
3862
                SKIP_BITS(re, &s->gb, 1);
3863
#endif
3864
                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3865
                i+= run;
3866
                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
3867
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3868
                LAST_SKIP_BITS(re, &s->gb, 1);
3869
            }
3870
          }
3871
        } else {
3872
            i+= run;
3873
            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3874
            LAST_SKIP_BITS(re, &s->gb, 1);
3875
        }
3876
        if (i > 62){
3877
            i-= 192;
3878
            if(i&(~63)){
3879
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
3880
                return -1;
3881
            }
3882

    
3883
            block[scan_table[i]] = level;
3884
            break;
3885
        }
3886

    
3887
        block[scan_table[i]] = level;
3888
    }
3889
    CLOSE_READER(re, &s->gb);
3890
  }
3891
 not_coded:
3892
    if (s->mb_intra) {
3893
        mpeg4_pred_ac(s, block, n, dc_pred_dir);
3894
        if (s->ac_pred) {
3895
            i = 63; /* XXX: not optimal */
3896
        }
3897
    }
3898
    s->block_last_index[n] = i;
3899
    return 0;
3900
}
3901

    
3902
/* most is hardcoded. should extend to handle all h263 streams */
3903
int h263_decode_picture_header(MpegEncContext *s)
3904
{
3905
    int format, width, height, i;
3906
    uint32_t startcode;
3907
    
3908
    align_get_bits(&s->gb);
3909

    
3910
    startcode= get_bits(&s->gb, 22-8);
3911

    
3912
    for(i= s->gb.size_in_bits - get_bits_count(&s->gb); i>0; i--) {
3913
        startcode = ((startcode << 8) | get_bits(&s->gb, 8)) & 0x003FFFFF;
3914
        
3915
        if(startcode == 0x20)
3916
            break;
3917
    }
3918
        
3919
    if (startcode != 0x20) {
3920
        fprintf(stderr, "Bad picture start code\n");
3921
        return -1;
3922
    }
3923
    /* temporal reference */
3924
    s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
3925

    
3926
    /* PTYPE starts here */    
3927
    if (get_bits1(&s->gb) != 1) {
3928
        /* marker */
3929
        fprintf(stderr, "Bad marker\n");
3930
        return -1;
3931
    }
3932
    if (get_bits1(&s->gb) != 0) {
3933
        fprintf(stderr, "Bad H263 id\n");
3934
        return -1;        /* h263 id */
3935
    }
3936
    skip_bits1(&s->gb);        /* split screen off */
3937
    skip_bits1(&s->gb);        /* camera  off */
3938
    skip_bits1(&s->gb);        /* freeze picture release off */
3939

    
3940
    /* Reset GOB number */
3941
    s->gob_number = 0;
3942
        
3943
    format = get_bits(&s->gb, 3);
3944
    /*
3945
        0    forbidden
3946
        1    sub-QCIF
3947
        10   QCIF
3948
        7        extended PTYPE (PLUSPTYPE)
3949
    */
3950

    
3951
    if (format != 7 && format != 6) {
3952
        s->h263_plus = 0;
3953
        /* H.263v1 */
3954
        width = h263_format[format][0];
3955
        height = h263_format[format][1];
3956
        if (!width)
3957
            return -1;
3958
        
3959
        s->width = width;
3960
        s->height = height;
3961
        s->pict_type = I_TYPE + get_bits1(&s->gb);
3962

    
3963
        s->unrestricted_mv = get_bits1(&s->gb); 
3964
        s->h263_long_vectors = s->unrestricted_mv;
3965

    
3966
        if (get_bits1(&s->gb) != 0) {
3967
            fprintf(stderr, "H263 SAC not supported\n");
3968
            return -1;        /* SAC: off */
3969
        }
3970
        if (get_bits1(&s->gb) != 0) {
3971
            s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3972
        }   
3973
        
3974
        if (get_bits1(&s->gb) != 0) {
3975
            fprintf(stderr, "H263 PB frame not supported\n");
3976
            return -1;        /* not PB frame */
3977
        }
3978
        s->qscale = get_bits(&s->gb, 5);
3979
        skip_bits1(&s->gb);        /* Continuous Presence Multipoint mode: off */
3980
    } else {
3981
        int ufep;
3982
        
3983
        /* H.263v2 */
3984
        s->h263_plus = 1;
3985
        ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
3986

    
3987
        /* ufep other than 0 and 1 are reserved */        
3988
        if (ufep == 1) {
3989
            /* OPPTYPE */       
3990
            format = get_bits(&s->gb, 3);
3991
            dprintf("ufep=1, format: %d\n", format);
3992
            skip_bits(&s->gb,1); /* Custom PCF */
3993
            s->umvplus = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */
3994
            skip_bits1(&s->gb); /* Syntax-based Arithmetic Coding (SAC) */
3995
            if (get_bits1(&s->gb) != 0) {
3996
                s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3997
            }
3998
            if (get_bits1(&s->gb) != 0) { /* Advanced Intra Coding (AIC) */
3999
                s->h263_aic = 1;
4000
            }
4001
            
4002
            if (get_bits1(&s->gb) != 0) {
4003
                fprintf(stderr, "Deblocking Filter not supported\n");
4004
            }
4005
            if (get_bits1(&s->gb) != 0) {
4006
                fprintf(stderr, "Slice Structured not supported\n");
4007
            }
4008
            if (get_bits1(&s->gb) != 0) {
4009
                fprintf(stderr, "Reference Picture Selection not supported\n");
4010
            }
4011
            if (get_bits1(&s->gb) != 0) {
4012
                fprintf(stderr, "Independent Segment Decoding not supported\n");
4013
            }
4014
            if (get_bits1(&s->gb) != 0) {
4015
                fprintf(stderr, "Alternative Inter VLC not supported\n");
4016
            }
4017
            if (get_bits1(&s->gb) != 0) {
4018
                fprintf(stderr, "Modified Quantization not supported\n");
4019
            }
4020
            
4021
            skip_bits(&s->gb, 1); /* Prevent start code emulation */
4022

    
4023
            skip_bits(&s->gb, 3); /* Reserved */
4024
        } else if (ufep != 0) {
4025
            fprintf(stderr, "Bad UFEP type (%d)\n", ufep);
4026
            return -1;
4027
        }
4028
            
4029
        /* MPPTYPE */
4030
        s->pict_type = get_bits(&s->gb, 3) + I_TYPE;
4031
        dprintf("pict_type: %d\n", s->pict_type);
4032
        if (s->pict_type != I_TYPE &&
4033
            s->pict_type != P_TYPE)
4034
            return -1;
4035
        skip_bits(&s->gb, 2);
4036
        s->no_rounding = get_bits1(&s->gb);
4037
        dprintf("RTYPE: %d\n", s->no_rounding);
4038
        skip_bits(&s->gb, 4);
4039
        
4040
        /* Get the picture dimensions */
4041
        if (ufep) {
4042
            if (format == 6) {
4043
                /* Custom Picture Format (CPFMT) */
4044
                s->aspect_ratio_info = get_bits(&s->gb, 4);
4045
                dprintf("aspect: %d\n", s->aspect_ratio_info);
4046
                /* aspect ratios:
4047
                0 - forbidden
4048
                1 - 1:1
4049
                2 - 12:11 (CIF 4:3)
4050
                3 - 10:11 (525-type 4:3)
4051
                4 - 16:11 (CIF 16:9)
4052
                5 - 40:33 (525-type 16:9)
4053
                6-14 - reserved
4054
                */
4055
                width = (get_bits(&s->gb, 9) + 1) * 4;
4056
                skip_bits1(&s->gb);
4057
                height = get_bits(&s->gb, 9) * 4;
4058
                dprintf("\nH.263+ Custom picture: %dx%d\n",width,height);
4059
                if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
4060
                    /* aspected dimensions */
4061
                    s->aspected_width = get_bits(&s->gb, 8);
4062
                    s->aspected_height = get_bits(&s->gb, 8);
4063
                }else{
4064
                    s->aspected_width = pixel_aspect[s->aspect_ratio_info][0];
4065
                    s->aspected_height= pixel_aspect[s->aspect_ratio_info][1];
4066
                }
4067
            } else {
4068
                width = h263_format[format][0];
4069
                height = h263_format[format][1];
4070
            }
4071
            if ((width == 0) || (height == 0))
4072
                return -1;
4073
            s->width = width;
4074
            s->height = height;
4075
            if (s->umvplus) {
4076
                if(get_bits1(&s->gb)==0) /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
4077
                    skip_bits1(&s->gb); 
4078
            }
4079
        }
4080
            
4081
        s->qscale = get_bits(&s->gb, 5);
4082
    }
4083
    /* PEI */
4084
    while (get_bits1(&s->gb) != 0) {
4085
        skip_bits(&s->gb, 8);
4086
    }
4087
    s->f_code = 1;
4088
    
4089
    if(s->h263_aic){
4090
         s->y_dc_scale_table= 
4091
         s->c_dc_scale_table= h263_aic_dc_scale_table;
4092
    }else{
4093
        s->y_dc_scale_table=
4094
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
4095
    }
4096

    
4097
     if(s->avctx->debug&FF_DEBUG_PICT_INFO){
4098
         printf("qp:%d %c size:%d rnd:%d %s %s %s %s\n", 
4099
         s->qscale, av_get_pict_type_char(s->pict_type),
4100
         s->gb.size_in_bits, 1-s->no_rounding,
4101
         s->mv_type == MV_TYPE_8X8 ? "ADV" : "",
4102
         s->umvplus ? "UMV" : "",
4103
         s->h263_long_vectors ? "LONG" : "",
4104
         s->h263_plus ? "+" : ""
4105
         ); 
4106
     }
4107

    
4108
    
4109
    return 0;
4110
}
4111

    
4112
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
4113
{
4114
    int i;
4115
    int a= 2<<s->sprite_warping_accuracy;
4116
    int rho= 3-s->sprite_warping_accuracy;
4117
    int r=16/a;
4118
    const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
4119
    int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
4120
    int sprite_ref[4][2];
4121
    int virtual_ref[2][2];
4122
    int w2, h2, w3, h3;
4123
    int alpha=0, beta=0;
4124
    int w= s->width;
4125
    int h= s->height;
4126
    int min_ab;
4127

    
4128
    for(i=0; i<s->num_sprite_warping_points; i++){
4129
        int length;
4130
        int x=0, y=0;
4131

    
4132
        length= get_vlc(&s->gb, &sprite_trajectory);
4133
        if(length){
4134
            x= get_xbits(&s->gb, length);
4135
        }
4136
        if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
4137
        
4138
        length= get_vlc(&s->gb, &sprite_trajectory);
4139
        if(length){
4140
            y=get_xbits(&s->gb, length);
4141
        }
4142
        skip_bits1(&s->gb); /* marker bit */
4143
//printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
4144
        d[i][0]= x;
4145
        d[i][1]= y;
4146
    }
4147

    
4148
    while((1<<alpha)<w) alpha++;
4149
    while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
4150
    w2= 1<<alpha;
4151
    h2= 1<<beta;
4152

    
4153
// Note, the 4th point isnt used for GMC
4154
    if(s->divx_version==500 && s->divx_build==413){
4155
        sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
4156
        sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
4157
        sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
4158
        sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
4159
        sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
4160
        sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
4161
    } else {
4162
        sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
4163
        sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
4164
        sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
4165
        sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
4166
        sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
4167
        sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
4168
    }
4169
/*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
4170
    sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
4171
    
4172
// this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
4173
// perhaps it should be reordered to be more readable ...
4174
// the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
4175
// so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
4176
    virtual_ref[0][0]= 16*(vop_ref[0][0] + w2) 
4177
        + ROUNDED_DIV(((w - w2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + w2*(r*sprite_ref[1][0] - 16*vop_ref[1][0])),w);
4178
    virtual_ref[0][1]= 16*vop_ref[0][1] 
4179
        + ROUNDED_DIV(((w - w2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + w2*(r*sprite_ref[1][1] - 16*vop_ref[1][1])),w);
4180
    virtual_ref[1][0]= 16*vop_ref[0][0] 
4181
        + ROUNDED_DIV(((h - h2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + h2*(r*sprite_ref[2][0] - 16*vop_ref[2][0])),h);
4182
    virtual_ref[1][1]= 16*(vop_ref[0][1] + h2) 
4183
        + ROUNDED_DIV(((h - h2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + h2*(r*sprite_ref[2][1] - 16*vop_ref[2][1])),h);
4184
        
4185
    switch(s->num_sprite_warping_points)
4186
    {
4187
        case 0:
4188
            s->sprite_offset[0][0]= 0;
4189
            s->sprite_offset[0][1]= 0;
4190
            s->sprite_offset[1][0]= 0;
4191
            s->sprite_offset[1][1]= 0;
4192
            s->sprite_delta[0][0]= a;
4193
            s->sprite_delta[0][1]= 0;
4194
            s->sprite_delta[1][0]= 0;
4195
            s->sprite_delta[1][1]= a;
4196
            s->sprite_shift[0]= 0;
4197
            s->sprite_shift[1]= 0;
4198
            break;
4199
        case 1: //GMC only
4200
            s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
4201
            s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
4202
            s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
4203
            s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
4204
            s->sprite_delta[0][0]= a;
4205
            s->sprite_delta[0][1]= 0;
4206
            s->sprite_delta[1][0]= 0;
4207
            s->sprite_delta[1][1]= a;
4208
            s->sprite_shift[0]= 0;
4209
            s->sprite_shift[1]= 0;
4210
            break;
4211
        case 2:
4212
            s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
4213
                                                  + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
4214
                                                  + ( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1])
4215
                                                  + (1<<(alpha+rho-1));
4216
            s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
4217
                                                  + (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
4218
                                                  + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1])
4219
                                                  + (1<<(alpha+rho-1));
4220
            s->sprite_offset[1][0]= ( (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)
4221
                                     +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)
4222
                                     +2*w2*r*sprite_ref[0][0] 
4223
                                     - 16*w2 
4224
                                     + (1<<(alpha+rho+1)));
4225
            s->sprite_offset[1][1]= ( (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1) 
4226
                                     +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)
4227
                                     +2*w2*r*sprite_ref[0][1] 
4228
                                     - 16*w2
4229
                                     + (1<<(alpha+rho+1)));
4230
            s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
4231
            s->sprite_delta[0][1]=   (+r*sprite_ref[0][1] - virtual_ref[0][1]);
4232
            s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);
4233
            s->sprite_delta[1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
4234
            
4235
            s->sprite_shift[0]= alpha+rho;
4236
            s->sprite_shift[1]= alpha+rho+2;
4237
            break;
4238
        case 3:
4239
            min_ab= FFMIN(alpha, beta);
4240
            w3= w2>>min_ab;
4241
            h3= h2>>min_ab;
4242
            s->sprite_offset[0][0]=  (sprite_ref[0][0]<<(alpha+beta+rho-min_ab))
4243
                                   + (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-vop_ref[0][0])
4244
                                   + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-vop_ref[0][1])
4245
                                   + (1<<(alpha+beta+rho-min_ab-1));
4246
            s->sprite_offset[0][1]=  (sprite_ref[0][1]<<(alpha+beta+rho-min_ab))
4247
                                   + (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-vop_ref[0][0])
4248
                                   + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-vop_ref[0][1])
4249
                                   + (1<<(alpha+beta+rho-min_ab-1));
4250
            s->sprite_offset[1][0]=  (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-2*vop_ref[0][0] + 1)
4251
                                   + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-2*vop_ref[0][1] + 1)
4252
                                   + 2*w2*h3*r*sprite_ref[0][0]
4253
                                   - 16*w2*h3
4254
                                   + (1<<(alpha+beta+rho-min_ab+1));
4255
            s->sprite_offset[1][1]=  (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-2*vop_ref[0][0] + 1)
4256
                                   + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-2*vop_ref[0][1] + 1)
4257
                                   + 2*w2*h3*r*sprite_ref[0][1]
4258
                                   - 16*w2*h3
4259
                                   + (1<<(alpha+beta+rho-min_ab+1));
4260
            s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3;
4261
            s->sprite_delta[0][1]=   (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3;
4262
            s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3;
4263
            s->sprite_delta[1][1]=   (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3;
4264
                                   
4265
            s->sprite_shift[0]= alpha + beta + rho - min_ab;
4266
            s->sprite_shift[1]= alpha + beta + rho - min_ab + 2;
4267
            break;
4268
    }
4269
    /* try to simplify the situation */ 
4270
    if(   s->sprite_delta[0][0] == a<<s->sprite_shift[0]
4271
       && s->sprite_delta[0][1] == 0
4272
       && s->sprite_delta[1][0] == 0
4273
       && s->sprite_delta[1][1] == a<<s->sprite_shift[0])
4274
    {
4275
        s->sprite_offset[0][0]>>=s->sprite_shift[0];
4276
        s->sprite_offset[0][1]>>=s->sprite_shift[0];
4277
        s->sprite_offset[1][0]>>=s->sprite_shift[1];
4278
        s->sprite_offset[1][1]>>=s->sprite_shift[1];
4279
        s->sprite_delta[0][0]= a;
4280
        s->sprite_delta[0][1]= 0;
4281
        s->sprite_delta[1][0]= 0;
4282
        s->sprite_delta[1][1]= a;
4283
        s->sprite_shift[0]= 0;
4284
        s->sprite_shift[1]= 0;
4285
        s->real_sprite_warping_points=1;
4286
    }
4287
    else{
4288
        int shift_y= 16 - s->sprite_shift[0];
4289
        int shift_c= 16 - s->sprite_shift[1];
4290
//printf("shifts %d %d\n", shift_y, shift_c);
4291
        for(i=0; i<2; i++){
4292
            s->sprite_offset[0][i]<<= shift_y;
4293
            s->sprite_offset[1][i]<<= shift_c;
4294
            s->sprite_delta[0][i]<<= shift_y;
4295
            s->sprite_delta[1][i]<<= shift_y;
4296
            s->sprite_shift[i]= 16;
4297
        }
4298
        s->real_sprite_warping_points= s->num_sprite_warping_points;
4299
    }
4300
#if 0
4301
printf("vop:%d:%d %d:%d %d:%d, sprite:%d:%d %d:%d %d:%d, virtual: %d:%d %d:%d\n",
4302
    vop_ref[0][0], vop_ref[0][1],
4303
    vop_ref[1][0], vop_ref[1][1],
4304
    vop_ref[2][0], vop_ref[2][1],
4305
    sprite_ref[0][0], sprite_ref[0][1], 
4306
    sprite_ref[1][0], sprite_ref[1][1], 
4307
    sprite_ref[2][0], sprite_ref[2][1], 
4308
    virtual_ref[0][0], virtual_ref[0][1], 
4309
    virtual_ref[1][0], virtual_ref[1][1]
4310
    );
4311
    
4312
printf("offset: %d:%d , delta: %d %d %d %d, shift %d\n",
4313
    s->sprite_offset[0][0], s->sprite_offset[0][1],
4314
    s->sprite_delta[0][0], s->sprite_delta[0][1],
4315
    s->sprite_delta[1][0], s->sprite_delta[1][1],
4316
    s->sprite_shift[0]
4317
    );
4318
#endif
4319
}
4320

    
4321
static int mpeg4_decode_gop_header(MpegEncContext * s, GetBitContext *gb){
4322
    int hours, minutes, seconds;
4323

    
4324
    hours= get_bits(gb, 5);
4325
    minutes= get_bits(gb, 6);
4326
    skip_bits1(gb);
4327
    seconds= get_bits(gb, 6);
4328

    
4329
    s->time_base= seconds + 60*(minutes + 60*hours);
4330

    
4331
    skip_bits1(gb);
4332
    skip_bits1(gb);
4333
    
4334
    return 0;
4335
}
4336

    
4337
static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){
4338
    int width, height, vo_ver_id;
4339

    
4340
    /* vol header */
4341
    skip_bits(gb, 1); /* random access */
4342
    s->vo_type= get_bits(gb, 8);
4343
    if (get_bits1(gb) != 0) { /* is_ol_id */
4344
        vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
4345
        skip_bits(gb, 3); /* vo_priority */
4346
    } else {
4347
        vo_ver_id = 1;
4348
    }
4349
//printf("vo type:%d\n",s->vo_type);
4350
    s->aspect_ratio_info= get_bits(gb, 4);
4351
    if(s->aspect_ratio_info == FF_ASPECT_EXTENDED){            
4352
        s->aspected_width = get_bits(gb, 8); // par_width
4353
        s->aspected_height = get_bits(gb, 8); // par_height
4354
    }else{
4355
        s->aspected_width = pixel_aspect[s->aspect_ratio_info][0];
4356
        s->aspected_height= pixel_aspect[s->aspect_ratio_info][1];
4357
    }
4358

    
4359
    if ((s->vol_control_parameters=get_bits1(gb))) { /* vol control parameter */
4360
        int chroma_format= get_bits(gb, 2);
4361
        if(chroma_format!=1){
4362
            printf("illegal chroma format\n");
4363
        }
4364
        s->low_delay= get_bits1(gb);
4365
        if(get_bits1(gb)){ /* vbv parameters */
4366
            get_bits(gb, 15);        /* first_half_bitrate */
4367
            skip_bits1(gb);        /* marker */
4368
            get_bits(gb, 15);        /* latter_half_bitrate */
4369
            skip_bits1(gb);        /* marker */
4370
            get_bits(gb, 15);        /* first_half_vbv_buffer_size */
4371
            skip_bits1(gb);        /* marker */
4372
            get_bits(gb, 3);        /* latter_half_vbv_buffer_size */
4373
            get_bits(gb, 11);        /* first_half_vbv_occupancy */
4374
            skip_bits1(gb);        /* marker */
4375
            get_bits(gb, 15);        /* latter_half_vbv_occupancy */
4376
            skip_bits1(gb);        /* marker */               
4377
        }
4378
    }else{
4379
        // set low delay flag only once so the smart? low delay detection wont be overriden
4380
        if(s->picture_number==0)
4381
            s->low_delay=0;
4382
    }
4383

    
4384
    s->shape = get_bits(gb, 2); /* vol shape */
4385
    if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");
4386
    if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
4387
        printf("Gray shape not supported\n");
4388
        skip_bits(gb, 4);  //video_object_layer_shape_extension
4389
    }
4390

    
4391
    skip_bits1(gb);   /* marker */
4392
    
4393
    s->time_increment_resolution = get_bits(gb, 16);
4394
    
4395
    s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
4396
    if (s->time_increment_bits < 1)
4397
        s->time_increment_bits = 1;
4398
    skip_bits1(gb);   /* marker */
4399

    
4400
    if (get_bits1(gb) != 0) {   /* fixed_vop_rate  */
4401
        skip_bits(gb, s->time_increment_bits);
4402
    }
4403

    
4404
    if (s->shape != BIN_ONLY_SHAPE) {
4405
        if (s->shape == RECT_SHAPE) {
4406
            skip_bits1(gb);   /* marker */
4407
            width = get_bits(gb, 13);
4408
            skip_bits1(gb);   /* marker */
4409
            height = get_bits(gb, 13);
4410
            skip_bits1(gb);   /* marker */
4411
            if(width && height){ /* they should be non zero but who knows ... */
4412
                s->width = width;
4413
                s->height = height;
4414
//                printf("width/height: %d %d\n", width, height);
4415
            }
4416
        }
4417
        
4418
        s->progressive_sequence= get_bits1(gb)^1;
4419
        if(!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO)) 
4420
            printf("OBMC not supported (very likely buggy encoder)\n");   /* OBMC Disable */
4421
        if (vo_ver_id == 1) {
4422
            s->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
4423
        } else {
4424
            s->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
4425
        }
4426
        if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");
4427
        if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
4428
            if(s->vol_sprite_usage==STATIC_SPRITE){
4429
                s->sprite_width = get_bits(gb, 13);
4430
                skip_bits1(gb); /* marker */
4431
                s->sprite_height= get_bits(gb, 13);
4432
                skip_bits1(gb); /* marker */
4433
                s->sprite_left  = get_bits(gb, 13);
4434
                skip_bits1(gb); /* marker */
4435
                s->sprite_top   = get_bits(gb, 13);
4436
                skip_bits1(gb); /* marker */
4437
            }
4438
            s->num_sprite_warping_points= get_bits(gb, 6);
4439
            s->sprite_warping_accuracy = get_bits(gb, 2);
4440
            s->sprite_brightness_change= get_bits1(gb);
4441
            if(s->vol_sprite_usage==STATIC_SPRITE)
4442
                s->low_latency_sprite= get_bits1(gb);            
4443
        }
4444
        // FIXME sadct disable bit if verid!=1 && shape not rect
4445
        
4446
        if (get_bits1(gb) == 1) {   /* not_8_bit */
4447
            s->quant_precision = get_bits(gb, 4); /* quant_precision */
4448
            if(get_bits(gb, 4)!=8) printf("N-bit not supported\n"); /* bits_per_pixel */
4449
            if(s->quant_precision!=5) printf("quant precission %d\n", s->quant_precision);
4450
        } else {
4451
            s->quant_precision = 5;
4452
        }
4453
        
4454
        // FIXME a bunch of grayscale shape things
4455

    
4456
        if((s->mpeg_quant=get_bits1(gb))){ /* vol_quant_type */
4457
            int i, v;
4458
            
4459
            /* load default matrixes */
4460
            for(i=0; i<64; i++){
4461
                int j= s->dsp.idct_permutation[i];
4462
                v= ff_mpeg4_default_intra_matrix[i];
4463
                s->intra_matrix[j]= v;
4464
                s->chroma_intra_matrix[j]= v;
4465
                
4466
                v= ff_mpeg4_default_non_intra_matrix[i];
4467
                s->inter_matrix[j]= v;
4468
                s->chroma_inter_matrix[j]= v;
4469
            }
4470

    
4471
            /* load custom intra matrix */
4472
            if(get_bits1(gb)){
4473
                int last=0;
4474
                for(i=0; i<64; i++){
4475
                    int j;
4476
                    v= get_bits(gb, 8);
4477
                    if(v==0) break;
4478
                    
4479
                    last= v;
4480
                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
4481
                    s->intra_matrix[j]= v;
4482
                    s->chroma_intra_matrix[j]= v;
4483
                }
4484

    
4485
                /* replicate last value */
4486
                for(; i<64; i++){
4487
                    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
4488
                    s->intra_matrix[j]= v;
4489
                    s->chroma_intra_matrix[j]= v;
4490
                }
4491
            }
4492

    
4493
            /* load custom non intra matrix */
4494
            if(get_bits1(gb)){
4495
                int last=0;
4496
                for(i=0; i<64; i++){
4497
                    int j;
4498
                    v= get_bits(gb, 8);
4499
                    if(v==0) break;
4500

    
4501
                    last= v;
4502
                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
4503
                    s->inter_matrix[j]= v;
4504
                    s->chroma_inter_matrix[j]= v;
4505
                }
4506

    
4507
                /* replicate last value */
4508
                for(; i<64; i++){
4509
                    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
4510
                    s->inter_matrix[j]= last;
4511
                    s->chroma_inter_matrix[j]= last;
4512
                }
4513
            }
4514

    
4515
            // FIXME a bunch of grayscale shape things
4516
        }
4517

    
4518
        if(vo_ver_id != 1)
4519
             s->quarter_sample= get_bits1(gb);
4520
        else s->quarter_sample=0;
4521

    
4522
        if(!get_bits1(gb)) printf("Complexity estimation not supported\n");
4523

    
4524
        s->resync_marker= !get_bits1(gb); /* resync_marker_disabled */
4525

    
4526
        s->data_partitioning= get_bits1(gb);
4527
        if(s->data_partitioning){
4528
            s->rvlc= get_bits1(gb);
4529
        }
4530
        
4531
        if(vo_ver_id != 1) {
4532
            s->new_pred= get_bits1(gb);
4533
            if(s->new_pred){
4534
                printf("new pred not supported\n");
4535
                skip_bits(gb, 2); /* requested upstream message type */
4536
                skip_bits1(gb); /* newpred segment type */
4537
            }
4538
            s->reduced_res_vop= get_bits1(gb);
4539
            if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");
4540
        }
4541
        else{
4542
            s->new_pred=0;
4543
            s->reduced_res_vop= 0;
4544
        }
4545

    
4546
        s->scalability= get_bits1(gb);
4547

    
4548
        if (s->scalability) {
4549
            GetBitContext bak= *gb;
4550
            int ref_layer_id;
4551
            int ref_layer_sampling_dir;
4552
            int h_sampling_factor_n;
4553
            int h_sampling_factor_m;
4554
            int v_sampling_factor_n;
4555
            int v_sampling_factor_m;
4556
            
4557
            s->hierachy_type= get_bits1(gb);
4558
            ref_layer_id= get_bits(gb, 4);
4559
            ref_layer_sampling_dir= get_bits1(gb);
4560
            h_sampling_factor_n= get_bits(gb, 5);
4561
            h_sampling_factor_m= get_bits(gb, 5);
4562
            v_sampling_factor_n= get_bits(gb, 5);
4563
            v_sampling_factor_m= get_bits(gb, 5);
4564
            s->enhancement_type= get_bits1(gb);
4565
            
4566
            if(   h_sampling_factor_n==0 || h_sampling_factor_m==0 
4567
               || v_sampling_factor_n==0 || v_sampling_factor_m==0){
4568
               
4569
//                fprintf(stderr, "illegal scalability header (VERY broken encoder), trying to workaround\n");
4570
                s->scalability=0;
4571
               
4572
                *gb= bak;
4573
            }else
4574
                printf("scalability not supported\n");
4575
            
4576
            // bin shape stuff FIXME
4577
        }
4578
    }
4579
    return 0;
4580
}
4581

    
4582
/**
4583
 * decodes the user data stuff in the header.
4584
 * allso inits divx/xvid/lavc_version/build
4585
 */
4586
static int decode_user_data(MpegEncContext *s, GetBitContext *gb){
4587
    char buf[256];
4588
    int i;
4589
    int e;
4590
    int ver, build, ver2, ver3;
4591
    char last;
4592

    
4593
    buf[0]= show_bits(gb, 8);
4594
    for(i=1; i<256; i++){
4595
        buf[i]= show_bits(gb, 16)&0xFF;
4596
        if(buf[i]==0) break;
4597
        skip_bits(gb, 8);
4598
    }
4599
    buf[255]=0;
4600

    
4601
    /* divx detection */
4602
    e=sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
4603
    if(e<2)
4604
        e=sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
4605
    if(e>=2){
4606
        s->divx_version= ver;
4607
        s->divx_build= build;
4608
        s->divx_packed= e==3 && last=='p';
4609
        if(s->picture_number==0){
4610
            printf("This file was encoded with DivX%d Build%d", ver, build);
4611
            if(s->divx_packed)
4612
                printf("p\n");
4613
            else
4614
                printf("\n");
4615
        }
4616
    }
4617
    
4618
    /* ffmpeg detection */
4619
    e=sscanf(buf, "FFmpeg%d.%d.%db%d", &ver, &ver2, &ver3, &build);
4620
    if(e!=4)
4621
        e=sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); 
4622
    if(e!=4){
4623
        if(strcmp(buf, "ffmpeg")==0){
4624
            s->ffmpeg_version= 0x000406;
4625
            s->lavc_build= 4600;
4626
        }
4627
    }
4628
    if(e==4){
4629
        s->ffmpeg_version= ver*256*256 + ver2*256 + ver3;
4630
        s->lavc_build= build;
4631
        if(s->picture_number==0)
4632
            printf("This file was encoded with libavcodec build %d\n", build);
4633
    }
4634
    
4635
    /* xvid detection */
4636
    e=sscanf(buf, "XviD%d", &build);
4637
    if(e==1){
4638
        s->xvid_build= build;
4639
        if(s->picture_number==0)
4640
            printf("This file was encoded with XviD build %d\n", build);
4641
    }
4642

    
4643
//printf("User Data: %s\n", buf);
4644
    return 0;
4645
}
4646

    
4647
static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){
4648
    int time_incr, time_increment;
4649

    
4650
    s->pict_type = get_bits(gb, 2) + I_TYPE;        /* pict type: I = 0 , P = 1 */
4651
    if(s->pict_type==B_TYPE && s->low_delay && s->vol_control_parameters==0 && !(s->flags & CODEC_FLAG_LOW_DELAY)){
4652
        printf("low_delay flag set, but shouldnt, clearing it\n");
4653
        s->low_delay=0;
4654
    }
4655
 
4656
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
4657
    if(s->partitioned_frame)
4658
        s->decode_mb= mpeg4_decode_partitioned_mb;
4659
    else
4660
        s->decode_mb= ff_h263_decode_mb;
4661

    
4662
    if(s->time_increment_resolution==0){
4663
        s->time_increment_resolution=1;
4664
//        fprintf(stderr, "time_increment_resolution is illegal\n");
4665
    }
4666
    time_incr=0;
4667
    while (get_bits1(gb) != 0) 
4668
        time_incr++;
4669

    
4670
    check_marker(gb, "before time_increment");
4671
    
4672
    if(s->picture_number==0 && (show_bits(gb, s->time_increment_bits+1)&1)==0){
4673
        printf("hmm, seems the headers arnt complete, trying to guess time_increment_bits\n");
4674
        
4675

    
4676
        for(s->time_increment_bits=1 ;s->time_increment_bits<16; s->time_increment_bits++){
4677
            if(show_bits(gb, s->time_increment_bits+1)&1) break;
4678
        }
4679
        printf("my guess is %d bits ;)\n",s->time_increment_bits);
4680
    }
4681
    
4682
    time_increment= get_bits(gb, s->time_increment_bits);
4683
//printf(" type:%d modulo_time_base:%d increment:%d\n", s->pict_type, time_incr, time_increment);
4684
    if(s->pict_type!=B_TYPE){
4685
        s->last_time_base= s->time_base;
4686
        s->time_base+= time_incr;
4687
        s->time= s->time_base*s->time_increment_resolution + time_increment;
4688
        if(s->workaround_bugs&FF_BUG_UMP4){
4689
            if(s->time < s->last_non_b_time){
4690
//                fprintf(stderr, "header is not mpeg4 compatible, broken encoder, trying to workaround\n");
4691
                s->time_base++;
4692
                s->time+= s->time_increment_resolution;
4693
            }
4694
        }
4695
        s->pp_time= s->time - s->last_non_b_time;
4696
        s->last_non_b_time= s->time;
4697
    }else{
4698
        s->time= (s->last_time_base + time_incr)*s->time_increment_resolution + time_increment;
4699
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
4700
        if(s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0){
4701
//            printf("messed up order, seeking?, skiping current b frame\n");