Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h263.c @ 983e3246

History | View | Annotate | Download (164 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
#if 1
43
#define PRINT_MB_TYPE(a) {}
44
#else
45
#define PRINT_MB_TYPE(a) printf(a)
46
#endif
47

    
48
#define INTRA_MCBPC_VLC_BITS 6
49
#define INTER_MCBPC_VLC_BITS 6
50
#define CBPY_VLC_BITS 6
51
#define MV_VLC_BITS 9
52
#define DC_VLC_BITS 9
53
#define SPRITE_TRAJ_VLC_BITS 6
54
#define MB_TYPE_B_VLC_BITS 4
55
#define TEX_VLC_BITS 9
56

    
57
#ifdef CONFIG_ENCODERS
58
static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
59
                              int n);
60
static void h263_encode_motion(MpegEncContext * s, int val, int fcode);
61
static void h263p_encode_umotion(MpegEncContext * s, int val);
62
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
63
                               int n, int dc, uint8_t *scan_table, 
64
                               PutBitContext *dc_pb, PutBitContext *ac_pb);
65
#endif
66

    
67
static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
68
static int h263p_decode_umotion(MpegEncContext * s, int pred);
69
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
70
                             int n, int coded);
71
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr);
72
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
73
                              int n, int coded, int intra);
74
static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr);
75
#ifdef CONFIG_ENCODERS
76
static void mpeg4_inv_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
77
                              int dir);
78
#endif //CONFIG_ENCODERS
79
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s);
80
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr);
81

    
82
extern uint32_t inverse[256];
83

    
84
#ifdef CONFIG_ENCODERS
85
static uint8_t uni_DCtab_lum_len[512];
86
static uint8_t uni_DCtab_chrom_len[512];
87
static uint16_t uni_DCtab_lum_bits[512];
88
static uint16_t uni_DCtab_chrom_bits[512];
89

    
90
static uint16_t (*mv_penalty)[MAX_MV*2+1]= NULL;
91
static uint8_t fcode_tab[MAX_MV*2+1];
92
static uint8_t umv_fcode_tab[MAX_MV*2+1];
93

    
94
static uint32_t uni_mpeg4_intra_rl_bits[64*64*2*2];
95
static uint8_t  uni_mpeg4_intra_rl_len [64*64*2*2];
96
static uint32_t uni_mpeg4_inter_rl_bits[64*64*2*2];
97
static uint8_t  uni_mpeg4_inter_rl_len [64*64*2*2];
98
//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
99
//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
100
#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
101

    
102
/* mpeg4
103
inter
104
max level: 24/6
105
max run: 53/63
106

107
intra
108
max level: 53/16
109
max run: 29/41
110
*/
111
#endif
112

    
113

    
114
int h263_get_picture_format(int width, int height)
115
{
116
    int format;
117

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

    
133
#ifdef CONFIG_ENCODERS
134

    
135
static void float_aspect_to_info(MpegEncContext * s, float aspect){
136
    int i;
137

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

    
143
    ff_float2fraction(&s->aspected_width, &s->aspected_height, aspect, 255);
144

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

    
156
void h263_encode_picture_header(MpegEncContext * s, int picture_number)
157
{
158
    int format;
159

    
160
    align_put_bits(&s->pb);
161

    
162
    /* Update the pointer to last GOB */
163
    s->ptr_lastgob = pbBufPtr(&s->pb);
164
    s->gob_number = 0;
165

    
166
    put_bits(&s->pb, 22, 0x20); /* PSC */
167
    put_bits(&s->pb, 8, (((int64_t)s->picture_number * 30 * FRAME_RATE_BASE) / 
168
                         s->frame_rate) & 0xff);
169

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

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

    
246
        put_bits(&s->pb, 5, s->qscale);
247
    }
248

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

    
251
    if(s->h263_aic){
252
         s->y_dc_scale_table= 
253
         s->c_dc_scale_table= h263_aic_dc_scale_table;
254
    }else{
255
        s->y_dc_scale_table=
256
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
257
    }
258
}
259

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

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

    
287
    for(n=0; n<6; n++){
288
        int16_t *ac_val, *ac_val1;
289

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

    
341
    return score0 > score1 ? 1 : 0;    
342
}
343

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

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

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

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

    
405
#endif //CONFIG_ENCODERS
406

    
407
void ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
408
    const int mb_index= s->mb_x + s->mb_y*s->mb_width;
409
    int xy= s->block_index[0];
410
    uint16_t time_pp= s->pp_time;
411
    uint16_t time_pb= s->pb_time;
412
    int i;
413
    
414
    //FIXME avoid divides
415
    switch(s->co_located_type_table[mb_index]){
416
    case 0:
417
        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;
418
        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;
419
        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]
420
                            : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
421
        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] 
422
                            : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
423
        if((s->avctx->workaround_bugs & FF_BUG_DIRECT_BLOCKSIZE) || !s->quarter_sample)
424
            s->mv_type= MV_TYPE_16X16;
425
        else
426
            s->mv_type= MV_TYPE_8X8;
427
        break;
428
    case CO_LOCATED_TYPE_4MV:
429
        s->mv_type = MV_TYPE_8X8;
430
        for(i=0; i<4; i++){
431
            xy= s->block_index[i];
432
            s->mv[0][i][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
433
            s->mv[0][i][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
434
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->motion_val[xy][0]
435
                                : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
436
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->motion_val[xy][1] 
437
                                : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
438
        }
439
        break;
440
    case CO_LOCATED_TYPE_FIELDMV:
441
        s->mv_type = MV_TYPE_FIELD;
442
        for(i=0; i<2; i++){
443
            if(s->top_field_first){
444
                time_pp= s->pp_field_time - s->field_select_table[mb_index][i] + i;
445
                time_pb= s->pb_field_time - s->field_select_table[mb_index][i] + i;
446
            }else{
447
                time_pp= s->pp_field_time + s->field_select_table[mb_index][i] - i;
448
                time_pb= s->pb_field_time + s->field_select_table[mb_index][i] - i;
449
            }
450
            s->mv[0][i][0] = s->field_mv_table[mb_index][i][0]*time_pb/time_pp + mx;
451
            s->mv[0][i][1] = s->field_mv_table[mb_index][i][1]*time_pb/time_pp + my;
452
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->field_mv_table[mb_index][i][0]
453
                                : s->field_mv_table[mb_index][i][0]*(time_pb - time_pp)/time_pp;
454
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->field_mv_table[mb_index][i][1] 
455
                                : s->field_mv_table[mb_index][i][1]*(time_pb - time_pp)/time_pp;
456
        }
457
        break;
458
    }
459
}
460

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

    
483
        if(s->pict_type==B_TYPE){
484
            static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
485
            int mb_type=  mb_type_table[s->mv_dir];
486
            
487
            if(s->mb_x==0){
488
                s->last_mv[0][0][0]= 
489
                s->last_mv[0][0][1]= 
490
                s->last_mv[1][0][0]= 
491
                s->last_mv[1][0][1]= 0;
492
            }
493
            
494
            assert(s->dquant>=-2 && s->dquant<=2);
495
            assert((s->dquant&1)==0);
496
            assert(mb_type>=0);
497

    
498
            /* nothing to do if this MB was skiped in the next P Frame */
499
            if(s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x]){ //FIXME avoid DCT & ...
500
                s->skip_count++;
501
                s->mv[0][0][0]= 
502
                s->mv[0][0][1]= 
503
                s->mv[1][0][0]= 
504
                s->mv[1][0][1]= 0;
505
                s->mv_dir= MV_DIR_FORWARD; //doesnt matter
506
                s->qscale -= s->dquant;
507
//                s->mb_skiped=1;
508

    
509
                return;
510
            }
511
            
512
            if ((cbp | motion_x | motion_y | mb_type) ==0) {
513
                /* direct MB with MV={0,0} */
514
                assert(s->dquant==0);
515
                
516
                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
517

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

    
546
            if(interleaved_stats){
547
                bits= get_bit_count(&s->pb);
548
                s->misc_bits+= bits - s->last_bits;
549
                s->last_bits=bits;
550
            }
551

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

    
591
            if(interleaved_stats){
592
                bits= get_bit_count(&s->pb);
593
                s->mv_bits+= bits - s->last_bits;
594
                s->last_bits=bits;
595
            }
596

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

    
602
            if(interleaved_stats){
603
                bits= get_bit_count(&s->pb);
604
                s->p_tex_bits+= bits - s->last_bits;
605
                s->last_bits=bits;
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
                    return;
652
                }
653
            }
654

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

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

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

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

    
695
                if(!s->progressive_sequence){
696
                    if(cbp)
697
                        put_bits(pb2, 1, s->interlaced_dct);
698
                }
699
    
700
                if(interleaved_stats){
701
                    bits= get_bit_count(&s->pb);
702
                    s->misc_bits+= bits - s->last_bits;
703
                    s->last_bits=bits;
704
                }
705

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

    
710
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x, s->f_code);
711
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y, s->f_code);
712
                }
713
            }
714

    
715
            if(interleaved_stats){ 
716
                bits= get_bit_count(&s->pb);
717
                s->mv_bits+= bits - s->last_bits;
718
                s->last_bits=bits;
719
            }
720

    
721
            /* encode each block */
722
            for (i = 0; i < 6; i++) {
723
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, tex_pb);
724
            }
725

    
726
            if(interleaved_stats){
727
                bits= get_bit_count(&s->pb);
728
                s->p_tex_bits+= bits - s->last_bits;
729
                s->last_bits=bits;
730
            }
731
            s->f_count++;
732
        }
733
    } else {
734
        int cbp;
735
        int dc_diff[6];   //dc values with the dc prediction subtracted 
736
        int dir[6];  //prediction direction
737
        int zigzag_last_index[6];
738
        uint8_t *scan_table[6];
739
        int i;
740

    
741
        for(i=0; i<6; i++){
742
            const int level= block[i][0];
743
            uint16_t *dc_ptr;
744

    
745
            dc_diff[i]= level - ff_mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
746
            if (i < 4) {
747
                *dc_ptr = level * s->y_dc_scale;
748
            } else {
749
                *dc_ptr = level * s->c_dc_scale;
750
            }
751
        }
752

    
753
        s->ac_pred= decide_ac_pred(s, block, dir);
754

    
755
        if(s->ac_pred){
756
            for(i=0; i<6; i++){
757
                uint8_t *st;
758
                int last_index;
759

    
760
                mpeg4_inv_pred_ac(s, block[i], i, dir[i]);
761
                if (dir[i]==0) st = s->intra_v_scantable.permutated; /* left */
762
                else           st = s->intra_h_scantable.permutated; /* top */
763

    
764
                for(last_index=63; last_index>=0; last_index--) //FIXME optimize
765
                    if(block[i][st[last_index]]) break;
766
                zigzag_last_index[i]= s->block_last_index[i];
767
                s->block_last_index[i]= last_index;
768
                scan_table[i]= st;
769
            }
770
        }else{
771
            for(i=0; i<6; i++)
772
                scan_table[i]= s->intra_scantable.permutated;
773
        }
774

    
775
        /* compute cbp */
776
        cbp = 0;
777
        for (i = 0; i < 6; i++) {
778
            if (s->block_last_index[i] >= 1)
779
                cbp |= 1 << (5 - i);
780
        }
781

    
782
        cbpc = cbp & 3;
783
        if (s->pict_type == I_TYPE) {
784
            if(s->dquant) cbpc+=4;
785
            put_bits(&s->pb,
786
                intra_MCBPC_bits[cbpc],
787
                intra_MCBPC_code[cbpc]);
788
        } else {
789
            if(s->dquant) cbpc+=8;
790
            put_bits(&s->pb, 1, 0);        /* mb coded */
791
            put_bits(&s->pb,
792
                inter_MCBPC_bits[cbpc + 4],
793
                inter_MCBPC_code[cbpc + 4]);
794
        }
795
        put_bits(pb2, 1, s->ac_pred);
796
        cbpy = cbp >> 2;
797
        put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
798
        if(s->dquant)
799
            put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
800

    
801
        if(!s->progressive_sequence){
802
            put_bits(dc_pb, 1, s->interlaced_dct);
803
        }
804

    
805
        if(interleaved_stats){
806
            bits= get_bit_count(&s->pb);
807
            s->misc_bits+= bits - s->last_bits;
808
            s->last_bits=bits;
809
        }
810

    
811
        /* encode each block */
812
        for (i = 0; i < 6; i++) {
813
            mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
814
        }
815

    
816
        if(interleaved_stats){
817
            bits= get_bit_count(&s->pb);
818
            s->i_tex_bits+= bits - s->last_bits;
819
            s->last_bits=bits;
820
        }
821
        s->i_count++;
822

    
823
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
824
        if(s->ac_pred){
825
            for(i=0; i<6; i++){
826
                int j;    
827
                int16_t *ac_val;
828

    
829
                ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
830

    
831
                if(dir[i]){
832
                    for(j=1; j<8; j++) 
833
                        block[i][s->dsp.idct_permutation[j   ]]= ac_val[j+8];
834
                }else{
835
                    for(j=1; j<8; j++) 
836
                        block[i][s->dsp.idct_permutation[j<<3]]= ac_val[j  ];
837
                }
838
                s->block_last_index[i]= zigzag_last_index[i];
839
            }
840
        }
841
    }
842
}
843

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

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

    
939
        cbpc = cbp & 3;
940
        if (s->pict_type == I_TYPE) {
941
            if(s->dquant) cbpc+=4;
942
            put_bits(&s->pb,
943
                intra_MCBPC_bits[cbpc],
944
                intra_MCBPC_code[cbpc]);
945
        } else {
946
            if(s->dquant) cbpc+=8;
947
            put_bits(&s->pb, 1, 0);        /* mb coded */
948
            put_bits(&s->pb,
949
                inter_MCBPC_bits[cbpc + 4],
950
                inter_MCBPC_code[cbpc + 4]);
951
        }
952
        if (s->h263_aic) {
953
            /* XXX: currently, we do not try to use ac prediction */
954
            put_bits(&s->pb, 1, 0);        /* no AC prediction */
955
        }
956
        cbpy = cbp >> 2;
957
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
958
        if(s->dquant)
959
            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
960
    }
961

    
962
    for(i=0; i<6; i++) {
963
        /* encode each block */
964
        h263_encode_block(s, block[i], i);
965
    
966
        /* Update INTRADC for decoding */
967
        if (s->h263_aic && s->mb_intra) {
968
            block[i][0] = rec_intradc[i];
969
            
970
        }
971
    }
972
}
973
#endif
974

    
975
static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr)
976
{
977
    int x, y, wrap, a, c, pred_dc, scale;
978
    int16_t *dc_val, *ac_val;
979

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

    
1020
static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1021
{
1022
    int x, y, wrap, a, c, pred_dc, scale, i;
1023
    int16_t *dc_val, *ac_val, *ac_val1;
1024

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

    
1104
int16_t *h263_pred_motion(MpegEncContext * s, int block, 
1105
                        int *px, int *py)
1106
{
1107
    int xy, wrap;
1108
    int16_t *A, *B, *C, *mot_val;
1109
    static const int off[4]= {2, 1, 1, -1};
1110

    
1111
    wrap = s->block_wrap[0];
1112
    xy = s->block_index[block];
1113

    
1114
    mot_val = s->motion_val[xy];
1115

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

    
1164
#ifdef CONFIG_ENCODERS
1165
static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
1166
{
1167
    int range, l, bit_size, sign, code, bits;
1168

    
1169
    if (val == 0) {
1170
        /* zero vector */
1171
        code = 0;
1172
        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1173
    } else {
1174
        bit_size = f_code - 1;
1175
        range = 1 << bit_size;
1176
        /* modulo encoding */
1177
        l = range * 32;
1178
#if 1
1179
        val+= l;
1180
        val&= 2*l-1;
1181
        val-= l;
1182
        sign = val>>31;
1183
        val= (val^sign)-sign;
1184
        sign&=1;
1185
#else
1186
        if (val < -l) {
1187
            val += 2*l;
1188
        } else if (val >= l) {
1189
            val -= 2*l;
1190
        }
1191

    
1192
        assert(val>=-l && val<l);
1193

    
1194
        if (val >= 0) {
1195
            sign = 0;
1196
        } else {
1197
            val = -val;
1198
            sign = 1;
1199
        }
1200
#endif
1201
        val--;
1202
        code = (val >> bit_size) + 1;
1203
        bits = val & (range - 1);
1204

    
1205
        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
1206
        if (bit_size > 0) {
1207
            put_bits(&s->pb, bit_size, bits);
1208
        }
1209
    }
1210

    
1211
}
1212

    
1213
/* Encode MV differences on H.263+ with Unrestricted MV mode */
1214
static void h263p_encode_umotion(MpegEncContext * s, int val)
1215
{
1216
    short sval = 0; 
1217
    short i = 0;
1218
    short n_bits = 0;
1219
    short temp_val;
1220
    int code = 0;
1221
    int tcode;
1222
    
1223
    if ( val == 0)
1224
        put_bits(&s->pb, 1, 1);
1225
    else if (val == 1)
1226
        put_bits(&s->pb, 3, 0);
1227
    else if (val == -1)
1228
        put_bits(&s->pb, 3, 2);
1229
    else {
1230
        
1231
        sval = ((val < 0) ? (short)(-val):(short)val);
1232
        temp_val = sval;
1233
        
1234
        while (temp_val != 0) {
1235
            temp_val = temp_val >> 1;
1236
            n_bits++;
1237
        }
1238
        
1239
        i = n_bits - 1;
1240
        while (i > 0) {
1241
            tcode = (sval & (1 << (i-1))) >> (i-1);
1242
            tcode = (tcode << 1) | 1;
1243
            code = (code << 2) | tcode;
1244
            i--;
1245
        }
1246
        code = ((code << 1) | (val < 0)) << 1;
1247
        put_bits(&s->pb, (2*n_bits)+1, code);
1248
        //printf("\nVal = %d\tCode = %d", sval, code);
1249
    }
1250
}
1251

    
1252
static void init_mv_penalty_and_fcode(MpegEncContext *s)
1253
{
1254
    int f_code;
1255
    int mv;
1256
    
1257
    if(mv_penalty==NULL)
1258
        mv_penalty= av_mallocz( sizeof(uint16_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1259
    
1260
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
1261
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1262
            int len;
1263

    
1264
            if(mv==0) len= mvtab[0][1];
1265
            else{
1266
                int val, bit_size, range, code;
1267

    
1268
                bit_size = s->f_code - 1;
1269
                range = 1 << bit_size;
1270

    
1271
                val=mv;
1272
                if (val < 0) 
1273
                    val = -val;
1274
                val--;
1275
                code = (val >> bit_size) + 1;
1276
                if(code<33){
1277
                    len= mvtab[code][1] + 1 + bit_size;
1278
                }else{
1279
                    len= mvtab[32][1] + 2 + bit_size;
1280
                }
1281
            }
1282

    
1283
            mv_penalty[f_code][mv+MAX_MV]= len;
1284
        }
1285
    }
1286

    
1287
    for(f_code=MAX_FCODE; f_code>0; f_code--){
1288
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1289
            fcode_tab[mv+MAX_MV]= f_code;
1290
        }
1291
    }
1292

    
1293
    for(mv=0; mv<MAX_MV*2+1; mv++){
1294
        umv_fcode_tab[mv]= 1;
1295
    }
1296
}
1297
#endif
1298

    
1299
#ifdef CONFIG_ENCODERS
1300

    
1301
static void init_uni_dc_tab(void)
1302
{
1303
    int level, uni_code, uni_len;
1304

    
1305
    for(level=-256; level<256; level++){
1306
        int size, v, l;
1307
        /* find number of bits */
1308
        size = 0;
1309
        v = abs(level);
1310
        while (v) {
1311
            v >>= 1;
1312
            size++;
1313
        }
1314

    
1315
        if (level < 0)
1316
            l= (-level) ^ ((1 << size) - 1);
1317
        else
1318
            l= level;
1319

    
1320
        /* luminance */
1321
        uni_code= DCtab_lum[size][0];
1322
        uni_len = DCtab_lum[size][1];
1323

    
1324
        if (size > 0) {
1325
            uni_code<<=size; uni_code|=l;
1326
            uni_len+=size;
1327
            if (size > 8){
1328
                uni_code<<=1; uni_code|=1;
1329
                uni_len++;
1330
            }
1331
        }
1332
        uni_DCtab_lum_bits[level+256]= uni_code;
1333
        uni_DCtab_lum_len [level+256]= uni_len;
1334

    
1335
        /* chrominance */
1336
        uni_code= DCtab_chrom[size][0];
1337
        uni_len = DCtab_chrom[size][1];
1338
        
1339
        if (size > 0) {
1340
            uni_code<<=size; uni_code|=l;
1341
            uni_len+=size;
1342
            if (size > 8){
1343
                uni_code<<=1; uni_code|=1;
1344
                uni_len++;
1345
            }
1346
        }
1347
        uni_DCtab_chrom_bits[level+256]= uni_code;
1348
        uni_DCtab_chrom_len [level+256]= uni_len;
1349

    
1350
    }
1351
}
1352

    
1353
#endif //CONFIG_ENCODERS
1354

    
1355
#ifdef CONFIG_ENCODERS
1356
static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1357
    int slevel, run, last;
1358
    
1359
    assert(MAX_LEVEL >= 64);
1360
    assert(MAX_RUN   >= 63);
1361

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

    
1441
void h263_encode_init(MpegEncContext *s)
1442
{
1443
    static int done = 0;
1444

    
1445
    if (!done) {
1446
        done = 1;
1447

    
1448
        init_uni_dc_tab();
1449

    
1450
        init_rl(&rl_inter);
1451
        init_rl(&rl_intra);
1452
        init_rl(&rl_intra_aic);
1453
        
1454
        init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1455
        init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1456

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

    
1488
    if(s->mpeg_quant){
1489
        s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
1490
        s->inter_quant_bias= 0;
1491
    }else{
1492
        s->intra_quant_bias=0;
1493
        s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
1494
    }
1495
}
1496

    
1497
/**
1498
 * encodes a 8x8 block.
1499
 * @param block the 8x8 block
1500
 * @param n block index (0-3 are luma, 4-5 are chroma)
1501
 */
1502
static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
1503
{
1504
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
1505
    RLTable *rl;
1506

    
1507
    rl = &rl_inter;
1508
    if (s->mb_intra && !s->h263_aic) {
1509
        /* DC coef */
1510
        level = block[0];
1511
        /* 255 cannot be represented, so we clamp */
1512
        if (level > 254) {
1513
            level = 254;
1514
            block[0] = 254;
1515
        }
1516
        /* 0 cannot be represented also */
1517
        else if (level < 1) {
1518
            level = 1;
1519
            block[0] = 1;
1520
        }
1521
        if (level == 128) //FIXME check rv10
1522
            put_bits(&s->pb, 8, 0xff);
1523
        else
1524
            put_bits(&s->pb, 8, level & 0xff);
1525
        i = 1;
1526
    } else {
1527
        i = 0;
1528
        if (s->h263_aic && s->mb_intra)
1529
            rl = &rl_intra_aic;
1530
    }
1531
   
1532
    /* AC coefs */
1533
    last_index = s->block_last_index[n];
1534
    last_non_zero = i - 1;
1535
    for (; i <= last_index; i++) {
1536
        j = s->intra_scantable.permutated[i];
1537
        level = block[j];
1538
        if (level) {
1539
            run = i - last_non_zero - 1;
1540
            last = (i == last_index);
1541
            sign = 0;
1542
            slevel = level;
1543
            if (level < 0) {
1544
                sign = 1;
1545
                level = -level;
1546
            }
1547
            code = get_rl_index(rl, last, run, level);
1548
            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1549
            if (code == rl->n) {
1550
                put_bits(&s->pb, 1, last);
1551
                put_bits(&s->pb, 6, run);
1552
                
1553
                assert(slevel != 0);
1554

    
1555
                if(slevel < 128 && slevel > -128) 
1556
                    put_bits(&s->pb, 8, slevel & 0xff);
1557
                else{
1558
                    put_bits(&s->pb, 8, 128);
1559
                    put_bits(&s->pb, 5, slevel & 0x1f);
1560
                    put_bits(&s->pb, 6, (slevel>>5)&0x3f);
1561
                }
1562
            } else {
1563
                put_bits(&s->pb, 1, sign);
1564
            }
1565
                last_non_zero = i;
1566
            }
1567
    }
1568
}
1569
#endif
1570

    
1571
#ifdef CONFIG_ENCODERS
1572

    
1573
/***************************************************/
1574
/**
1575
 * add mpeg4 stuffing bits (01...1)
1576
 */
1577
void ff_mpeg4_stuffing(PutBitContext * pbc)
1578
{
1579
    int length;
1580
    put_bits(pbc, 1, 0);
1581
    length= (-get_bit_count(pbc))&7;
1582
    if(length) put_bits(pbc, length, (1<<length)-1);
1583
}
1584

    
1585
/* must be called before writing the header */
1586
void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
1587
    int time_div, time_mod;
1588

    
1589
    if(s->pict_type==I_TYPE){ //we will encode a vol header
1590
        s->time_increment_resolution= s->frame_rate/ff_gcd(s->frame_rate, FRAME_RATE_BASE);
1591
        if(s->time_increment_resolution>=256*256) s->time_increment_resolution= 256*128;
1592

    
1593
        s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
1594
    }
1595
    
1596
    if(s->current_picture.pts)
1597
        s->time= (s->current_picture.pts*s->time_increment_resolution + 500*1000)/(1000*1000);
1598
    else
1599
        s->time= picture_number*(int64_t)FRAME_RATE_BASE*s->time_increment_resolution/s->frame_rate;
1600
    time_div= s->time/s->time_increment_resolution;
1601
    time_mod= s->time%s->time_increment_resolution;
1602

    
1603
    if(s->pict_type==B_TYPE){
1604
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
1605
    }else{
1606
        s->last_time_base= s->time_base;
1607
        s->time_base= time_div;
1608
        s->pp_time= s->time - s->last_non_b_time;
1609
        s->last_non_b_time= s->time;
1610
    }
1611
}
1612

    
1613
static void mpeg4_encode_gop_header(MpegEncContext * s){
1614
    int hours, minutes, seconds;
1615
    
1616
    put_bits(&s->pb, 16, 0);
1617
    put_bits(&s->pb, 16, GOP_STARTCODE);
1618
    
1619
    seconds= s->time/s->time_increment_resolution;
1620
    minutes= seconds/60; seconds %= 60;
1621
    hours= minutes/60; minutes %= 60;
1622
    hours%=24;
1623

    
1624
    put_bits(&s->pb, 5, hours);
1625
    put_bits(&s->pb, 6, minutes);
1626
    put_bits(&s->pb, 1, 1);
1627
    put_bits(&s->pb, 6, seconds);
1628
    
1629
    put_bits(&s->pb, 1, 0); //closed gov == NO
1630
    put_bits(&s->pb, 1, 0); //broken link == NO
1631

    
1632
    ff_mpeg4_stuffing(&s->pb);
1633
}
1634

    
1635
static void mpeg4_encode_visual_object_header(MpegEncContext * s){
1636
    int profile_and_level_indication;
1637
    int vo_ver_id;
1638
    
1639
    if(s->max_b_frames || s->quarter_sample){
1640
        profile_and_level_indication= 0xF1; // adv simple level 1
1641
        vo_ver_id= 5;
1642
    }else{
1643
        profile_and_level_indication= 0x01; // simple level 1
1644
        vo_ver_id= 1;
1645
    }
1646
    //FIXME levels
1647

    
1648
    put_bits(&s->pb, 16, 0);
1649
    put_bits(&s->pb, 16, VOS_STARTCODE);
1650
    
1651
    put_bits(&s->pb, 8, profile_and_level_indication);
1652
    
1653
    put_bits(&s->pb, 16, 0);
1654
    put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
1655
    
1656
    put_bits(&s->pb, 1, 1);
1657
        put_bits(&s->pb, 4, vo_ver_id);
1658
        put_bits(&s->pb, 3, 1); //priority
1659
 
1660
    put_bits(&s->pb, 4, 1); //visual obj type== video obj
1661
    
1662
    put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
1663

    
1664
    ff_mpeg4_stuffing(&s->pb);
1665
}
1666

    
1667
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
1668
{
1669
    int vo_ver_id;
1670
    char buf[255];
1671

    
1672
    if(s->max_b_frames || s->quarter_sample){
1673
        vo_ver_id= 5;
1674
        s->vo_type= ADV_SIMPLE_VO_TYPE;
1675
    }else{
1676
        vo_ver_id= 1;
1677
        s->vo_type= SIMPLE_VO_TYPE;
1678
    }
1679

    
1680
    put_bits(&s->pb, 16, 0);
1681
    put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
1682
    put_bits(&s->pb, 16, 0);
1683
    put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
1684

    
1685
    put_bits(&s->pb, 1, 0);                /* random access vol */
1686
    put_bits(&s->pb, 8, s->vo_type);        /* video obj type indication */
1687
    put_bits(&s->pb, 1, 1);                /* is obj layer id= yes */
1688
      put_bits(&s->pb, 4, vo_ver_id);        /* is obj layer ver id */
1689
      put_bits(&s->pb, 3, 1);                /* is obj layer priority */
1690
    
1691
    float_aspect_to_info(s, s->avctx->aspect_ratio);
1692

    
1693
    put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
1694
    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
1695
    {
1696
        put_bits(&s->pb, 8, s->aspected_width);
1697
        put_bits(&s->pb, 8, s->aspected_height);
1698
    }
1699

    
1700
    if(s->low_delay){
1701
        put_bits(&s->pb, 1, 1);                /* vol control parameters= yes */
1702
        put_bits(&s->pb, 2, 1);                /* chroma format YUV 420/YV12 */
1703
        put_bits(&s->pb, 1, s->low_delay);
1704
        put_bits(&s->pb, 1, 0);                /* vbv parameters= no */
1705
    }else{
1706
        put_bits(&s->pb, 1, 0);                /* vol control parameters= no */
1707
    }
1708

    
1709
    put_bits(&s->pb, 2, RECT_SHAPE);        /* vol shape= rectangle */
1710
    put_bits(&s->pb, 1, 1);                /* marker bit */
1711
    
1712
    put_bits(&s->pb, 16, s->time_increment_resolution);
1713
    if (s->time_increment_bits < 1)
1714
        s->time_increment_bits = 1;
1715
    put_bits(&s->pb, 1, 1);                /* marker bit */
1716
    put_bits(&s->pb, 1, 0);                /* fixed vop rate=no */
1717
    put_bits(&s->pb, 1, 1);                /* marker bit */
1718
    put_bits(&s->pb, 13, s->width);        /* vol width */
1719
    put_bits(&s->pb, 1, 1);                /* marker bit */
1720
    put_bits(&s->pb, 13, s->height);        /* vol height */
1721
    put_bits(&s->pb, 1, 1);                /* marker bit */
1722
    put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1723
    put_bits(&s->pb, 1, 1);                /* obmc disable */
1724
    if (vo_ver_id == 1) {
1725
        put_bits(&s->pb, 1, s->vol_sprite_usage=0);                /* sprite enable */
1726
    }else{
1727
        put_bits(&s->pb, 2, s->vol_sprite_usage=0);                /* sprite enable */
1728
    }
1729
    
1730
    s->quant_precision=5;
1731
    put_bits(&s->pb, 1, 0);                /* not 8 bit == false */
1732
    put_bits(&s->pb, 1, s->mpeg_quant);        /* quant type= (0=h263 style)*/
1733
    if(s->mpeg_quant) put_bits(&s->pb, 2, 0); /* no custom matrixes */
1734

    
1735
    if (vo_ver_id != 1)
1736
        put_bits(&s->pb, 1, s->quarter_sample);
1737
    put_bits(&s->pb, 1, 1);                /* complexity estimation disable */
1738
    s->resync_marker= s->rtp_mode;
1739
    put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
1740
    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1741
    if(s->data_partitioning){
1742
        put_bits(&s->pb, 1, 0);                /* no rvlc */
1743
    }
1744

    
1745
    if (vo_ver_id != 1){
1746
        put_bits(&s->pb, 1, 0);                /* newpred */
1747
        put_bits(&s->pb, 1, 0);                /* reduced res vop */
1748
    }
1749
    put_bits(&s->pb, 1, 0);                /* scalability */
1750
    
1751
    ff_mpeg4_stuffing(&s->pb);
1752

    
1753
    /* user data */
1754
    if(!(s->flags & CODEC_FLAG_BITEXACT)){
1755
        put_bits(&s->pb, 16, 0);
1756
        put_bits(&s->pb, 16, 0x1B2);        /* user_data */
1757
        sprintf(buf, "FFmpeg%sb%s", FFMPEG_VERSION, LIBAVCODEC_BUILD_STR);
1758
        put_string(&s->pb, buf);
1759
        ff_mpeg4_stuffing(&s->pb);
1760
    }
1761
}
1762

    
1763
/* write mpeg4 VOP header */
1764
void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
1765
{
1766
    int time_incr;
1767
    int time_div, time_mod;
1768
    
1769
    if(s->pict_type==I_TYPE){
1770
        if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
1771
            mpeg4_encode_visual_object_header(s);
1772
            mpeg4_encode_vol_header(s, 0, 0);
1773
        }
1774
        mpeg4_encode_gop_header(s);
1775
    }
1776
    
1777
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
1778

    
1779
//printf("num:%d rate:%d base:%d\n", s->picture_number, s->frame_rate, FRAME_RATE_BASE);
1780
    
1781
    put_bits(&s->pb, 16, 0);                /* vop header */
1782
    put_bits(&s->pb, 16, VOP_STARTCODE);        /* vop header */
1783
    put_bits(&s->pb, 2, s->pict_type - 1);        /* pict type: I = 0 , P = 1 */
1784

    
1785
    time_div= s->time/s->time_increment_resolution;
1786
    time_mod= s->time%s->time_increment_resolution;
1787
    time_incr= time_div - s->last_time_base;
1788
    while(time_incr--)
1789
        put_bits(&s->pb, 1, 1);
1790
        
1791
    put_bits(&s->pb, 1, 0);
1792

    
1793
    put_bits(&s->pb, 1, 1);        /* marker */
1794
    put_bits(&s->pb, s->time_increment_bits, time_mod);        /* time increment */
1795
    put_bits(&s->pb, 1, 1);        /* marker */
1796
    put_bits(&s->pb, 1, 1);        /* vop coded */
1797
    if (    s->pict_type == P_TYPE 
1798
        || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
1799
        put_bits(&s->pb, 1, s->no_rounding);        /* rounding type */
1800
    }
1801
    put_bits(&s->pb, 3, 0);        /* intra dc VLC threshold */
1802
    if(!s->progressive_sequence){
1803
         put_bits(&s->pb, 1, s->top_field_first);
1804
         put_bits(&s->pb, 1, s->alternate_scan);
1805
    }
1806
    //FIXME sprite stuff
1807

    
1808
    put_bits(&s->pb, 5, s->qscale);
1809

    
1810
    if (s->pict_type != I_TYPE)
1811
        put_bits(&s->pb, 3, s->f_code);        /* fcode_for */
1812
    if (s->pict_type == B_TYPE)
1813
        put_bits(&s->pb, 3, s->b_code);        /* fcode_back */
1814
    //    printf("****frame %d\n", picture_number);
1815

    
1816
     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support 
1817
     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
1818
     s->h_edge_pos= s->width;
1819
     s->v_edge_pos= s->height;
1820
}
1821

    
1822
#endif //CONFIG_ENCODERS
1823

    
1824
/**
1825
 * change qscale by given dquant and update qscale dependant variables.
1826
 */
1827
static void change_qscale(MpegEncContext * s, int dquant)
1828
{
1829
    s->qscale += dquant;
1830

    
1831
    if (s->qscale < 1)
1832
        s->qscale = 1;
1833
    else if (s->qscale > 31)
1834
        s->qscale = 31;
1835

    
1836
    s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
1837
    s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
1838
}
1839

    
1840
/**
1841
 * predicts the dc.
1842
 * @param n block index (0-3 are luma, 4-5 are chroma)
1843
 * @param dc_val_ptr a pointer to the dc_val entry for the current MB will be stored here
1844
 * @param dir_ptr pointer to an integer where the prediction direction will be stored
1845
 * @return the quantized predicted dc
1846
 */
1847
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr)
1848
{
1849
    int a, b, c, wrap, pred, scale;
1850
    uint16_t *dc_val;
1851
    int dummy;
1852

    
1853
    /* find prediction */
1854
    if (n < 4) {
1855
        scale = s->y_dc_scale;
1856
    } else {
1857
        scale = s->c_dc_scale;
1858
    }
1859
    wrap= s->block_wrap[n];
1860
    dc_val = s->dc_val[0] + s->block_index[n];
1861

    
1862
    /* B C
1863
     * A X 
1864
     */
1865
    a = dc_val[ - 1];
1866
    b = dc_val[ - 1 - wrap];
1867
    c = dc_val[ - wrap];
1868

    
1869
    /* outside slice handling (we cant do that by memset as we need the dc for error resilience) */
1870
    if(s->first_slice_line && n!=3){
1871
        if(n!=2) b=c= 1024;
1872
        if(n!=1 && s->mb_x == s->resync_mb_x) b=a= 1024;
1873
    }
1874
    if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1){
1875
        if(n==0 || n==4 || n==5)
1876
            b=1024;
1877
    }
1878

    
1879
    if (abs(a - b) < abs(b - c)) {
1880
        pred = c;
1881
        *dir_ptr = 1; /* top */
1882
    } else {
1883
        pred = a;
1884
        *dir_ptr = 0; /* left */
1885
    }
1886
    /* we assume pred is positive */
1887
#ifdef ARCH_X86
1888
        asm volatile (
1889
                "xorl %%edx, %%edx        \n\t"
1890
                "mul %%ecx                \n\t"
1891
                : "=d" (pred), "=a"(dummy)
1892
                : "a" (pred + (scale >> 1)), "c" (inverse[scale])
1893
        );
1894
#else
1895
    pred = (pred + (scale >> 1)) / scale;
1896
#endif
1897

    
1898
    /* prepare address for prediction update */
1899
    *dc_val_ptr = &dc_val[0];
1900

    
1901
    return pred;
1902
}
1903

    
1904
/**
1905
 * predicts the ac.
1906
 * @param n block index (0-3 are luma, 4-5 are chroma)
1907
 * @param dir the ac prediction direction
1908
 */
1909
void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
1910
                   int dir)
1911
{
1912
    int i;
1913
    int16_t *ac_val, *ac_val1;
1914
    int8_t * const qscale_table= s->current_picture.qscale_table;
1915

    
1916
    /* find prediction */
1917
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1918
    ac_val1 = ac_val;
1919
    if (s->ac_pred) {
1920
        if (dir == 0) {
1921
            const int xy= s->mb_x-1 + s->mb_y*s->mb_width;
1922
            /* left prediction */
1923
            ac_val -= 16;
1924
            
1925
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
1926
                /* same qscale */
1927
                for(i=1;i<8;i++) {
1928
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1929
                }
1930
            }else{
1931
                /* different qscale, we must rescale */
1932
                for(i=1;i<8;i++) {
1933
                    block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
1934
                }
1935
            }
1936
        } else {
1937
            const int xy= s->mb_x + s->mb_y*s->mb_width - s->mb_width;
1938
            /* top prediction */
1939
            ac_val -= 16 * s->block_wrap[n];
1940

    
1941
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
1942
                /* same qscale */
1943
                for(i=1;i<8;i++) {
1944
                    block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
1945
                }
1946
            }else{
1947
                /* different qscale, we must rescale */
1948
                for(i=1;i<8;i++) {
1949
                    block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
1950
                }
1951
            }
1952
        }
1953
    }
1954
    /* left copy */
1955
    for(i=1;i<8;i++)
1956
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1957

    
1958
    /* top copy */
1959
    for(i=1;i<8;i++)
1960
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1961

    
1962
}
1963

    
1964
#ifdef CONFIG_ENCODERS
1965

    
1966
static void mpeg4_inv_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
1967
                              int dir)
1968
{
1969
    int i;
1970
    int16_t *ac_val;
1971
    int8_t * const qscale_table= s->current_picture.qscale_table;
1972

    
1973
    /* find prediction */
1974
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1975
 
1976
    if (dir == 0) {
1977
        const int xy= s->mb_x-1 + s->mb_y*s->mb_width;
1978
        /* left prediction */
1979
        ac_val -= 16;
1980
        if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
1981
            /* same qscale */
1982
            for(i=1;i<8;i++) {
1983
                block[s->dsp.idct_permutation[i<<3]] -= ac_val[i];
1984
            }
1985
        }else{
1986
            /* different qscale, we must rescale */
1987
            for(i=1;i<8;i++) {
1988
                block[s->dsp.idct_permutation[i<<3]] -= ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
1989
            }
1990
        }
1991
    } else {
1992
        const int xy= s->mb_x + s->mb_y*s->mb_width - s->mb_width;
1993
        /* top prediction */
1994
        ac_val -= 16 * s->block_wrap[n];
1995
        if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
1996
            /* same qscale */
1997
            for(i=1;i<8;i++) {
1998
                block[s->dsp.idct_permutation[i]] -= ac_val[i + 8];
1999
            }
2000
        }else{
2001
            /* different qscale, we must rescale */
2002
            for(i=1;i<8;i++) {
2003
                block[s->dsp.idct_permutation[i]] -= ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
2004
            }
2005
        }
2006
    }
2007
}
2008

    
2009
/**
2010
 * encodes the dc value.
2011
 * @param n block index (0-3 are luma, 4-5 are chroma)
2012
 */
2013
static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
2014
{
2015
#if 1
2016
//    if(level<-255 || level>255) printf("dc overflow\n");
2017
    level+=256;
2018
    if (n < 4) {
2019
        /* luminance */
2020
        put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
2021
    } else {
2022
        /* chrominance */
2023
        put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
2024
    }
2025
#else
2026
    int size, v;
2027
    /* find number of bits */
2028
    size = 0;
2029
    v = abs(level);
2030
    while (v) {
2031
        v >>= 1;
2032
        size++;
2033
    }
2034

    
2035
    if (n < 4) {
2036
        /* luminance */
2037
        put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
2038
    } else {
2039
        /* chrominance */
2040
        put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
2041
    }
2042

    
2043
    /* encode remaining bits */
2044
    if (size > 0) {
2045
        if (level < 0)
2046
            level = (-level) ^ ((1 << size) - 1);
2047
        put_bits(&s->pb, size, level);
2048
        if (size > 8)
2049
            put_bits(&s->pb, 1, 1);
2050
    }
2051
#endif
2052
}
2053

    
2054
/**
2055
 * encodes a 8x8 block
2056
 * @param n block index (0-3 are luma, 4-5 are chroma)
2057
 */
2058
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2059
                               uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
2060
{
2061
    int i, last_non_zero;
2062
#if 0 //variables for the outcommented version
2063
    int code, sign, last;
2064
#endif
2065
    const RLTable *rl;
2066
    uint32_t *bits_tab;
2067
    uint8_t *len_tab;
2068
    const int last_index = s->block_last_index[n];
2069

    
2070
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2071
        /* mpeg4 based DC predictor */
2072
        mpeg4_encode_dc(dc_pb, intra_dc, n);
2073
        if(last_index<1) return;
2074
        i = 1;
2075
        rl = &rl_intra;
2076
        bits_tab= uni_mpeg4_intra_rl_bits;
2077
        len_tab = uni_mpeg4_intra_rl_len;
2078
    } else {
2079
        if(last_index<0) return;
2080
        i = 0;
2081
        rl = &rl_inter;
2082
        bits_tab= uni_mpeg4_inter_rl_bits;
2083
        len_tab = uni_mpeg4_inter_rl_len;
2084
    }
2085

    
2086
    /* AC coefs */
2087
    last_non_zero = i - 1;
2088
#if 1
2089
    for (; i < last_index; i++) {
2090
        int level = block[ scan_table[i] ];
2091
        if (level) {
2092
            int run = i - last_non_zero - 1;
2093
            level+=64;
2094
            if((level&(~127)) == 0){
2095
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2096
                put_bits(ac_pb, len_tab[index], bits_tab[index]);
2097
            }else{ //ESC3
2098
                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);
2099
            }
2100
            last_non_zero = i;
2101
        }
2102
    }
2103
    /*if(i<=last_index)*/{
2104
        int level = block[ scan_table[i] ];
2105
        int run = i - last_non_zero - 1;
2106
        level+=64;
2107
        if((level&(~127)) == 0){
2108
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2109
            put_bits(ac_pb, len_tab[index], bits_tab[index]);
2110
        }else{ //ESC3
2111
            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);
2112
        }
2113
    }
2114
#else
2115
    for (; i <= last_index; i++) {
2116
        const int slevel = block[ scan_table[i] ];
2117
        if (slevel) {
2118
            int level;
2119
            int run = i - last_non_zero - 1;
2120
            last = (i == last_index);
2121
            sign = 0;
2122
            level = slevel;
2123
            if (level < 0) {
2124
                sign = 1;
2125
                level = -level;
2126
            }
2127
            code = get_rl_index(rl, last, run, level);
2128
            put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2129
            if (code == rl->n) {
2130
                int level1, run1;
2131
                level1 = level - rl->max_level[last][run];
2132
                if (level1 < 1) 
2133
                    goto esc2;
2134
                code = get_rl_index(rl, last, run, level1);
2135
                if (code == rl->n) {
2136
                esc2:
2137
                    put_bits(ac_pb, 1, 1);
2138
                    if (level > MAX_LEVEL)
2139
                        goto esc3;
2140
                    run1 = run - rl->max_run[last][level] - 1;
2141
                    if (run1 < 0)
2142
                        goto esc3;
2143
                    code = get_rl_index(rl, last, run1, level);
2144
                    if (code == rl->n) {
2145
                    esc3:
2146
                        /* third escape */
2147
                        put_bits(ac_pb, 1, 1);
2148
                        put_bits(ac_pb, 1, last);
2149
                        put_bits(ac_pb, 6, run);
2150
                        put_bits(ac_pb, 1, 1);
2151
                        put_bits(ac_pb, 12, slevel & 0xfff);
2152
                        put_bits(ac_pb, 1, 1);
2153
                    } else {
2154
                        /* second escape */
2155
                        put_bits(ac_pb, 1, 0);
2156
                        put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2157
                        put_bits(ac_pb, 1, sign);
2158
                    }
2159
                } else {
2160
                    /* first escape */
2161
                    put_bits(ac_pb, 1, 0);
2162
                    put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2163
                    put_bits(ac_pb, 1, sign);
2164
                }
2165
            } else {
2166
                put_bits(ac_pb, 1, sign);
2167
            }
2168
            last_non_zero = i;
2169
        }
2170
    }
2171
#endif
2172
}
2173

    
2174
static inline int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2175
                               uint8_t *scan_table)
2176
{
2177
    int i, last_non_zero;
2178
    const RLTable *rl;
2179
    uint8_t *len_tab;
2180
    const int last_index = s->block_last_index[n];
2181
    int len=0;
2182

    
2183
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2184
        /* mpeg4 based DC predictor */
2185
        //mpeg4_encode_dc(dc_pb, intra_dc, n); //FIXME
2186
        if(last_index<1) return len;
2187
        i = 1;
2188
        rl = &rl_intra;
2189
        len_tab = uni_mpeg4_intra_rl_len;
2190
    } else {
2191
        if(last_index<0) return 0;
2192
        i = 0;
2193
        rl = &rl_inter;
2194
        len_tab = uni_mpeg4_inter_rl_len;
2195
    }
2196

    
2197
    /* AC coefs */
2198
    last_non_zero = i - 1;
2199
    for (; i < last_index; i++) {
2200
        int level = block[ scan_table[i] ];
2201
        if (level) {
2202
            int run = i - last_non_zero - 1;
2203
            level+=64;
2204
            if((level&(~127)) == 0){
2205
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2206
                len += len_tab[index];
2207
            }else{ //ESC3
2208
                len += 7+2+1+6+1+12+1;
2209
            }
2210
            last_non_zero = i;
2211
        }
2212
    }
2213
    /*if(i<=last_index)*/{
2214
        int level = block[ scan_table[i] ];
2215
        int run = i - last_non_zero - 1;
2216
        level+=64;
2217
        if((level&(~127)) == 0){
2218
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2219
            len += len_tab[index];
2220
        }else{ //ESC3
2221
            len += 7+2+1+6+1+12+1;
2222
        }
2223
    }
2224
    
2225
    return len;
2226
}
2227

    
2228
#endif
2229

    
2230

    
2231
/***********************************************/
2232
/* decoding */
2233

    
2234
static VLC intra_MCBPC_vlc;
2235
static VLC inter_MCBPC_vlc;
2236
static VLC cbpy_vlc;
2237
static VLC mv_vlc;
2238
static VLC dc_lum, dc_chrom;
2239
static VLC sprite_trajectory;
2240
static VLC mb_type_b_vlc;
2241

    
2242
void init_vlc_rl(RLTable *rl)
2243
{
2244
    int i, q;
2245
    
2246
    init_vlc(&rl->vlc, 9, rl->n + 1, 
2247
             &rl->table_vlc[0][1], 4, 2,
2248
             &rl->table_vlc[0][0], 4, 2);
2249

    
2250
    
2251
    for(q=0; q<32; q++){
2252
        int qmul= q*2;
2253
        int qadd= (q-1)|1;
2254
        
2255
        if(q==0){
2256
            qmul=1;
2257
            qadd=0;
2258
        }
2259
        
2260
        rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2261
        for(i=0; i<rl->vlc.table_size; i++){
2262
            int code= rl->vlc.table[i][0];
2263
            int len = rl->vlc.table[i][1];
2264
            int level, run;
2265
        
2266
            if(len==0){ // illegal code
2267
                run= 66;
2268
                level= MAX_LEVEL;
2269
            }else if(len<0){ //more bits needed
2270
                run= 0;
2271
                level= code;
2272
            }else{
2273
                if(code==rl->n){ //esc
2274
                    run= 66;
2275
                    level= 0;
2276
                }else{
2277
                    run=   rl->table_run  [code] + 1;
2278
                    level= rl->table_level[code] * qmul + qadd;
2279
                    if(code >= rl->last) run+=192;
2280
                }
2281
            }
2282
            rl->rl_vlc[q][i].len= len;
2283
            rl->rl_vlc[q][i].level= level;
2284
            rl->rl_vlc[q][i].run= run;
2285
        }
2286
    }
2287
}
2288

    
2289
/* init vlcs */
2290

    
2291
/* XXX: find a better solution to handle static init */
2292
void h263_decode_init_vlc(MpegEncContext *s)
2293
{
2294
    static int done = 0;
2295

    
2296
    if (!done) {
2297
        done = 1;
2298

    
2299
        init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 8, 
2300
                 intra_MCBPC_bits, 1, 1,
2301
                 intra_MCBPC_code, 1, 1);
2302
        init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 25, 
2303
                 inter_MCBPC_bits, 1, 1,
2304
                 inter_MCBPC_code, 1, 1);
2305
        init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,
2306
                 &cbpy_tab[0][1], 2, 1,
2307
                 &cbpy_tab[0][0], 2, 1);
2308
        init_vlc(&mv_vlc, MV_VLC_BITS, 33,
2309
                 &mvtab[0][1], 2, 1,
2310
                 &mvtab[0][0], 2, 1);
2311
        init_rl(&rl_inter);
2312
        init_rl(&rl_intra);
2313
        init_rl(&rl_intra_aic);
2314
        init_vlc_rl(&rl_inter);
2315
        init_vlc_rl(&rl_intra);
2316
        init_vlc_rl(&rl_intra_aic);
2317
        init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2318
                 &DCtab_lum[0][1], 2, 1,
2319
                 &DCtab_lum[0][0], 2, 1);
2320
        init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2321
                 &DCtab_chrom[0][1], 2, 1,
2322
                 &DCtab_chrom[0][0], 2, 1);
2323
        init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2324
                 &sprite_trajectory_tab[0][1], 4, 2,
2325
                 &sprite_trajectory_tab[0][0], 4, 2);
2326
        init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2327
                 &mb_type_b_tab[0][1], 2, 1,
2328
                 &mb_type_b_tab[0][0], 2, 1);
2329
    }
2330
}
2331

    
2332
/**
2333
 * Get the GOB height based on picture height.
2334
 */
2335
int ff_h263_get_gob_height(MpegEncContext *s){
2336
    if (s->height <= 400)
2337
        return 1;
2338
    else if (s->height <= 800)
2339
        return  2;
2340
    else
2341
        return 4;
2342
}
2343

    
2344
/**
2345
 * decodes the group of blocks header.
2346
 * @return <0 if an error occured
2347
 */
2348
static int h263_decode_gob_header(MpegEncContext *s)
2349
{
2350
    unsigned int val, gfid;
2351
    int left;
2352
    
2353
    /* Check for GOB Start Code */
2354
    val = show_bits(&s->gb, 16);
2355
    if(val)
2356
        return -1;
2357

    
2358
        /* We have a GBSC probably with GSTUFF */
2359
    skip_bits(&s->gb, 16); /* Drop the zeros */
2360
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
2361
    //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2362
    for(;left>13; left--){
2363
        if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2364
    }
2365
    if(left<=13) 
2366
        return -1;
2367

    
2368
#ifdef DEBUG
2369
    fprintf(stderr,"\nGOB Start Code at MB %d\n", (s->mb_y * s->mb_width) + s->mb_x);
2370
#endif
2371
    s->gob_number = get_bits(&s->gb, 5); /* GN */
2372
    gfid = get_bits(&s->gb, 2); /* GFID */
2373
    s->qscale = get_bits(&s->gb, 5); /* GQUANT */
2374
    if(s->qscale==0) 
2375
        return -1;
2376
    s->mb_x= 0;
2377
    s->mb_y= s->gob_index* s->gob_number;
2378
#ifdef DEBUG
2379
    fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", s->gob_number, gfid, s->qscale);
2380
#endif
2381
    return 0;
2382
}
2383

    
2384
static inline void memsetw(short *tab, int val, int n)
2385
{
2386
    int i;
2387
    for(i=0;i<n;i++)
2388
        tab[i] = val;
2389
}
2390

    
2391
#ifdef CONFIG_ENCODERS
2392

    
2393
void ff_mpeg4_init_partitions(MpegEncContext *s)
2394
{
2395
    init_put_bits(&s->tex_pb, s->tex_pb_buffer, PB_BUFFER_SIZE, NULL, NULL);
2396
    init_put_bits(&s->pb2   , s->pb2_buffer   , PB_BUFFER_SIZE, NULL, NULL);
2397
}
2398

    
2399
void ff_mpeg4_merge_partitions(MpegEncContext *s)
2400
{
2401
    const int pb2_len   = get_bit_count(&s->pb2   );
2402
    const int tex_pb_len= get_bit_count(&s->tex_pb);
2403
    const int bits= get_bit_count(&s->pb);
2404

    
2405
    if(s->pict_type==I_TYPE){
2406
        put_bits(&s->pb, 19, DC_MARKER);
2407
        s->misc_bits+=19 + pb2_len + bits - s->last_bits;
2408
        s->i_tex_bits+= tex_pb_len;
2409
    }else{
2410
        put_bits(&s->pb, 17, MOTION_MARKER);
2411
        s->misc_bits+=17 + pb2_len;
2412
        s->mv_bits+= bits - s->last_bits;
2413
        s->p_tex_bits+= tex_pb_len;
2414
    }
2415

    
2416
    flush_put_bits(&s->pb2);
2417
    flush_put_bits(&s->tex_pb);
2418

    
2419
    ff_copy_bits(&s->pb, s->pb2_buffer   , pb2_len);
2420
    ff_copy_bits(&s->pb, s->tex_pb_buffer, tex_pb_len);
2421
    s->last_bits= get_bit_count(&s->pb);
2422
}
2423

    
2424
#endif //CONFIG_ENCODERS
2425

    
2426
int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
2427
    switch(s->pict_type){
2428
        case I_TYPE:
2429
            return 16;
2430
        case P_TYPE:
2431
        case S_TYPE:
2432
            return s->f_code+15;
2433
        case B_TYPE:
2434
            return FFMAX(FFMAX(s->f_code, s->b_code)+15, 17);
2435
        default:
2436
            return -1;
2437
    }
2438
}
2439

    
2440
#ifdef CONFIG_ENCODERS
2441

    
2442
void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
2443
{
2444
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2445

    
2446
    ff_mpeg4_stuffing(&s->pb);
2447
    put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
2448
    put_bits(&s->pb, 1, 1);
2449
    
2450
    put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
2451
    put_bits(&s->pb, s->quant_precision, s->qscale);
2452
    put_bits(&s->pb, 1, 0); /* no HEC */
2453
}
2454

    
2455
#endif //CONFIG_ENCODERS
2456

    
2457
/**
2458
 * check if the next stuff is a resync marker or the end.
2459
 * @return 0 if not
2460
 */
2461
static inline int mpeg4_is_resync(MpegEncContext *s){
2462
    const int bits_count= get_bits_count(&s->gb);
2463
    
2464
    if(s->workaround_bugs&FF_BUG_NO_PADDING){
2465
        return 0;
2466
    }
2467

    
2468
    if(bits_count + 8 >= s->gb.size_in_bits){
2469
        int v= show_bits(&s->gb, 8);
2470
        v|= 0x7F >> (7-(bits_count&7));
2471
                
2472
        if(v==0x7F)
2473
            return 1;
2474
    }else{
2475
        if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){
2476
            int len;
2477
            GetBitContext gb= s->gb;
2478
        
2479
            skip_bits(&s->gb, 1);
2480
            align_get_bits(&s->gb);
2481
        
2482
            for(len=0; len<32; len++){
2483
                if(get_bits1(&s->gb)) break;
2484
            }
2485

    
2486
            s->gb= gb;
2487

    
2488
            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
2489
                return 1;
2490
        }
2491
    }
2492
    return 0;
2493
}
2494

    
2495
/**
2496
 * decodes the next video packet.
2497
 * @return <0 if something went wrong
2498
 */
2499
static int mpeg4_decode_video_packet_header(MpegEncContext *s)
2500
{
2501
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2502
    int header_extension=0, mb_num, len;
2503
    
2504
    /* is there enough space left for a video packet + header */
2505
    if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
2506

    
2507
    for(len=0; len<32; len++){
2508
        if(get_bits1(&s->gb)) break;
2509
    }
2510

    
2511
    if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
2512
        printf("marker does not match f_code\n");
2513
        return -1;
2514
    }
2515
    
2516
    if(s->shape != RECT_SHAPE){
2517
        header_extension= get_bits1(&s->gb);
2518
        //FIXME more stuff here
2519
    }
2520

    
2521
    mb_num= get_bits(&s->gb, mb_num_bits);
2522
    if(mb_num>=s->mb_num){
2523
        fprintf(stderr, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
2524
        return -1;
2525
    }
2526
    s->mb_x= mb_num % s->mb_width;
2527
    s->mb_y= mb_num / s->mb_width;
2528

    
2529
    if(s->shape != BIN_ONLY_SHAPE){
2530
        int qscale= get_bits(&s->gb, s->quant_precision); 
2531
        if(qscale)
2532
            s->qscale= qscale;
2533
    }
2534

    
2535
    if(s->shape == RECT_SHAPE){
2536
        header_extension= get_bits1(&s->gb);
2537
    }
2538
    if(header_extension){
2539
        int time_increment;
2540
        int time_incr=0;
2541

    
2542
        while (get_bits1(&s->gb) != 0) 
2543
            time_incr++;
2544

    
2545
        check_marker(&s->gb, "before time_increment in video packed header");
2546
        time_increment= get_bits(&s->gb, s->time_increment_bits);
2547
        check_marker(&s->gb, "before vop_coding_type in video packed header");
2548
        
2549
        skip_bits(&s->gb, 2); /* vop coding type */
2550
        //FIXME not rect stuff here
2551

    
2552
        if(s->shape != BIN_ONLY_SHAPE){
2553
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
2554
//FIXME dont just ignore everything
2555
            if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2556
                mpeg4_decode_sprite_trajectory(s);
2557
                fprintf(stderr, "untested\n");
2558
            }
2559

    
2560
            //FIXME reduced res stuff here
2561
            
2562
            if (s->pict_type != I_TYPE) {
2563
                int f_code = get_bits(&s->gb, 3);        /* fcode_for */
2564
                if(f_code==0){
2565
                    printf("Error, video packet header damaged (f_code=0)\n");
2566
                }
2567
            }
2568
            if (s->pict_type == B_TYPE) {
2569
                int b_code = get_bits(&s->gb, 3);
2570
                if(b_code==0){
2571
                    printf("Error, video packet header damaged (b_code=0)\n");
2572
                }
2573
            }       
2574
        }
2575
    }
2576
    //FIXME new-pred stuff
2577
    
2578
//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));
2579

    
2580
    return 0;
2581
}
2582

    
2583
void ff_mpeg4_clean_buffers(MpegEncContext *s)
2584
{
2585
    int c_wrap, c_xy, l_wrap, l_xy;
2586

    
2587
    l_wrap= s->block_wrap[0];
2588
    l_xy= s->mb_y*l_wrap*2 + s->mb_x*2;
2589
    c_wrap= s->block_wrap[4];
2590
    c_xy= s->mb_y*c_wrap + s->mb_x;
2591

    
2592
#if 0
2593
    /* clean DC */
2594
    memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
2595
    memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
2596
    memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
2597
#endif
2598

    
2599
    /* clean AC */
2600
    memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(int16_t));
2601
    memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
2602
    memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
2603

    
2604
    /* clean MV */
2605
    // we cant clear the MVs as they might be needed by a b frame
2606
//    memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(int16_t));
2607
//    memset(s->motion_val, 0, 2*sizeof(int16_t)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
2608
    s->last_mv[0][0][0]=
2609
    s->last_mv[0][0][1]=
2610
    s->last_mv[1][0][0]=
2611
    s->last_mv[1][0][1]= 0;
2612
}
2613

    
2614
/**
2615
 * decodes the group of blocks / video packet header.
2616
 * @return <0 if no resync found
2617
 */
2618
int ff_h263_resync(MpegEncContext *s){
2619
    int left, ret;
2620
    
2621
    if(s->codec_id==CODEC_ID_MPEG4)
2622
        skip_bits1(&s->gb);
2623
    
2624
    align_get_bits(&s->gb);
2625

    
2626
    if(show_bits(&s->gb, 16)==0){
2627
        if(s->codec_id==CODEC_ID_MPEG4)
2628
            ret= mpeg4_decode_video_packet_header(s);
2629
        else
2630
            ret= h263_decode_gob_header(s);
2631
        if(ret>=0)
2632
            return 0;
2633
    }
2634
    //ok, its not where its supposed to be ...
2635
    s->gb= s->last_resync_gb;
2636
    align_get_bits(&s->gb);
2637
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
2638
    
2639
    for(;left>16+1+5+5; left-=8){ 
2640
        if(show_bits(&s->gb, 16)==0){
2641
            GetBitContext bak= s->gb;
2642

    
2643
            if(s->codec_id==CODEC_ID_MPEG4)
2644
                ret= mpeg4_decode_video_packet_header(s);
2645
            else
2646
                ret= h263_decode_gob_header(s);
2647
            if(ret>=0)
2648
                return 0;
2649

    
2650
            s->gb= bak;
2651
        }
2652
        skip_bits(&s->gb, 8);
2653
    }
2654
    
2655
    return -1;
2656
}
2657

    
2658
/**
2659
 * gets the average motion vector for a GMC MB.
2660
 * @param n either 0 for the x component or 1 for y
2661
 * @returns the average MV for a GMC MB
2662
 */
2663
static inline int get_amv(MpegEncContext *s, int n){
2664
    int x, y, mb_v, sum, dx, dy, shift;
2665
    int len = 1 << (s->f_code + 4);
2666
    const int a= s->sprite_warping_accuracy;
2667

    
2668
    if(s->real_sprite_warping_points==1){
2669
        if(s->divx_version==500 && s->divx_build==413)
2670
            sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
2671
        else
2672
            sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
2673
    }else{
2674
        dx= s->sprite_delta[n][0];
2675
        dy= s->sprite_delta[n][1];
2676
        shift= s->sprite_shift[0];
2677
        if(n) dy -= 1<<(shift + a + 1);
2678
        else  dx -= 1<<(shift + a + 1);
2679
        mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
2680

    
2681
        sum=0;
2682
        for(y=0; y<16; y++){
2683
            int v;
2684
        
2685
            v= mb_v + dy*y;
2686
            //XXX FIXME optimize
2687
            for(x=0; x<16; x++){
2688
                sum+= v>>shift;
2689
                v+= dx;
2690
            }
2691
        }
2692
        sum= RSHIFT(sum, a+8-s->quarter_sample);
2693
    }
2694

    
2695
    if      (sum < -len) sum= -len;
2696
    else if (sum >= len) sum= len-1;
2697

    
2698
    return sum;
2699
}
2700

    
2701
/**
2702
 * decodes first partition.
2703
 * @return number of MBs decoded or <0 if an error occured
2704
 */
2705
static int mpeg4_decode_partition_a(MpegEncContext *s){
2706
    int mb_num;
2707
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
2708
    
2709
    /* decode first partition */
2710
    mb_num=0;
2711
    s->first_slice_line=1;
2712
    for(; s->mb_y<s->mb_height; s->mb_y++){
2713
        ff_init_block_index(s);
2714
        for(; s->mb_x<s->mb_width; s->mb_x++){
2715
            const int xy= s->mb_x + s->mb_y*s->mb_width;
2716
            int cbpc;
2717
            int dir=0;
2718
            
2719
            mb_num++;
2720
            ff_update_block_index(s);
2721
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2722
                s->first_slice_line=0;
2723
            
2724
            if(s->mb_x==0) PRINT_MB_TYPE("\n");
2725

    
2726
            if(s->pict_type==I_TYPE){
2727
                int i;
2728

    
2729
                if(show_bits(&s->gb, 19)==DC_MARKER){
2730
                    return mb_num-1;
2731
                }
2732

    
2733
                PRINT_MB_TYPE("I");
2734
                cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
2735
                if (cbpc < 0){
2736

    
2737
                    fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2738
                    return -1;
2739
                }
2740
                s->cbp_table[xy]= cbpc & 3;
2741
                s->mb_type[xy]= MB_TYPE_INTRA;
2742
                s->mb_intra = 1;
2743

    
2744
                if(cbpc & 4) {
2745
                    change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2746
                }
2747
                s->current_picture.qscale_table[xy]= s->qscale;
2748

    
2749
                s->mbintra_table[xy]= 1;
2750
                for(i=0; i<6; i++){
2751
                    int dc_pred_dir;
2752
                    int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2753
                    if(dc < 0){
2754
                        fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2755
                        return -1;
2756
                    }
2757
                    dir<<=1;
2758
                    if(dc_pred_dir) dir|=1;
2759
                }
2760
                s->pred_dir_table[xy]= dir;
2761
                
2762
                s->error_status_table[xy]= AC_ERROR;
2763
            }else{ /* P/S_TYPE */
2764
                int mx, my, pred_x, pred_y, bits;
2765
                int16_t * const mot_val= s->motion_val[s->block_index[0]];
2766
                const int stride= s->block_wrap[0]*2;
2767

    
2768
                bits= show_bits(&s->gb, 17);
2769
                if(bits==MOTION_MARKER){
2770
                    return mb_num-1;
2771
                }
2772
                skip_bits1(&s->gb);
2773
                if(bits&0x10000){
2774
                    /* skip mb */
2775
                    s->mb_type[xy]= MB_TYPE_SKIPED;
2776
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2777
                        PRINT_MB_TYPE("G");
2778
                        mx= get_amv(s, 0);
2779
                        my= get_amv(s, 1);
2780
                    }else{
2781
                        PRINT_MB_TYPE("S");
2782
                        mx=my=0;
2783
                    }
2784
                    mot_val[0       ]= mot_val[2       ]=
2785
                    mot_val[0+stride]= mot_val[2+stride]= mx;
2786
                    mot_val[1       ]= mot_val[3       ]=
2787
                    mot_val[1+stride]= mot_val[3+stride]= my;
2788

    
2789
                    if(s->mbintra_table[xy])
2790
                        ff_clean_intra_table_entries(s);
2791

    
2792
                    s->error_status_table[xy]= AC_ERROR;
2793
                    continue;
2794
                }
2795
                cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
2796
                if (cbpc < 0){
2797
                    fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2798
                    return -1;
2799
                }
2800
                if (cbpc > 20)
2801
                    cbpc+=3;
2802
                else if (cbpc == 20)
2803
                    fprintf(stderr, "Stuffing !");
2804
                s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
2805
    
2806
                s->mb_intra = ((cbpc & 4) != 0);
2807
        
2808
                if(s->mb_intra){
2809
                    PRINT_MB_TYPE("I");
2810
                    s->mbintra_table[xy]= 1;
2811
                    s->mb_type[xy]= MB_TYPE_INTRA;
2812
                    mot_val[0       ]= mot_val[2       ]= 
2813
                    mot_val[0+stride]= mot_val[2+stride]= 0;
2814
                    mot_val[1       ]= mot_val[3       ]=
2815
                    mot_val[1+stride]= mot_val[3+stride]= 0;
2816
                    s->error_status_table[xy]= DC_ERROR|AC_ERROR;
2817
                }else{
2818
                    if(s->mbintra_table[xy])
2819
                        ff_clean_intra_table_entries(s);
2820

    
2821
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
2822
                        s->mcsel= get_bits1(&s->gb);
2823
                    else s->mcsel= 0;
2824
        
2825
                    if ((cbpc & 16) == 0) {
2826
                        PRINT_MB_TYPE("P");
2827
                        /* 16x16 motion prediction */
2828
                        s->mb_type[xy]= MB_TYPE_INTER;
2829

    
2830
                        h263_pred_motion(s, 0, &pred_x, &pred_y);
2831
                        if(!s->mcsel){
2832
                            mx = h263_decode_motion(s, pred_x, s->f_code);
2833
                            if (mx >= 0xffff)
2834
                                return -1;
2835

    
2836
                            my = h263_decode_motion(s, pred_y, s->f_code);
2837
                            if (my >= 0xffff)
2838
                                return -1;
2839
                        } else {
2840
                            mx = get_amv(s, 0);
2841
                            my = get_amv(s, 1);
2842
                        }
2843

    
2844
                        mot_val[0       ]= mot_val[2       ] =
2845
                        mot_val[0+stride]= mot_val[2+stride]= mx;
2846
                        mot_val[1       ]= mot_val[3       ]=
2847
                        mot_val[1+stride]= mot_val[3+stride]= my;
2848
                    } else {
2849
                        int i;
2850
                        PRINT_MB_TYPE("4");
2851
                        s->mb_type[xy]= MB_TYPE_INTER4V;
2852
                        for(i=0;i<4;i++) {
2853
                            int16_t *mot_val= h263_pred_motion(s, i, &pred_x, &pred_y);
2854
                            mx = h263_decode_motion(s, pred_x, s->f_code);
2855
                            if (mx >= 0xffff)
2856
                                return -1;
2857
                
2858
                            my = h263_decode_motion(s, pred_y, s->f_code);
2859
                            if (my >= 0xffff)
2860
                                return -1;
2861
                            mot_val[0] = mx;
2862
                            mot_val[1] = my;
2863
                        }
2864
                    }
2865
                    s->error_status_table[xy]= AC_ERROR;
2866
                }
2867
            }
2868
        }
2869
        s->mb_x= 0;
2870
    }
2871

    
2872
    return mb_num;
2873
}
2874

    
2875
/**
2876
 * decode second partition.
2877
 * @return <0 if an error occured
2878
 */
2879
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
2880
    int mb_num=0;
2881
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
2882

    
2883
    s->mb_x= s->resync_mb_x;
2884
    s->first_slice_line=1;
2885
    for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
2886
        ff_init_block_index(s);
2887
        for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
2888
            const int xy= s->mb_x + s->mb_y*s->mb_width;
2889

    
2890
            mb_num++;
2891
            ff_update_block_index(s);
2892
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2893
                s->first_slice_line=0;
2894
            
2895
            if(s->pict_type==I_TYPE){
2896
                int ac_pred= get_bits1(&s->gb);
2897
                int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2898
                if(cbpy<0){
2899
                    fprintf(stderr, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2900
                    return -1;
2901
                }
2902
                
2903
                s->cbp_table[xy]|= cbpy<<2;
2904
                s->pred_dir_table[xy]|= ac_pred<<7;
2905
            }else{ /* P || S_TYPE */
2906
                if(s->mb_type[xy]&MB_TYPE_INTRA){          
2907
                    int dir=0,i;
2908
                    int ac_pred = get_bits1(&s->gb);
2909
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2910

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

    
2921
                    for(i=0; i<6; i++){
2922
                        int dc_pred_dir;
2923
                        int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2924
                        if(dc < 0){
2925
                            fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2926
                            return -1;
2927
                        }
2928
                        dir<<=1;
2929
                        if(dc_pred_dir) dir|=1;
2930
                    }
2931
                    s->cbp_table[xy]&= 3; //remove dquant
2932
                    s->cbp_table[xy]|= cbpy<<2;
2933
                    s->pred_dir_table[xy]= dir | (ac_pred<<7);
2934
                    s->error_status_table[xy]&= ~DC_ERROR;
2935
                }else if(s->mb_type[xy]&MB_TYPE_SKIPED){
2936
                    s->current_picture.qscale_table[xy]= s->qscale;
2937
                    s->cbp_table[xy]= 0;
2938
                }else{
2939
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2940

    
2941
                    if(cbpy<0){
2942
                        fprintf(stderr, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2943
                        return -1;
2944
                    }
2945
                    
2946
                    if(s->cbp_table[xy] & 8) {
2947
                        change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2948
                    }
2949
                    s->current_picture.qscale_table[xy]= s->qscale;
2950

    
2951
                    s->cbp_table[xy]&= 3; //remove dquant
2952
                    s->cbp_table[xy]|= (cbpy^0xf)<<2;
2953
                }
2954
            }
2955
        }
2956
        if(mb_num >= mb_count) return 0;
2957
        s->mb_x= 0;
2958
    }
2959
    return 0;
2960
}
2961

    
2962
/**
2963
 * decodes the first & second partition
2964
 * @return <0 if error (and sets error type in the error_status_table)
2965
 */
2966
int ff_mpeg4_decode_partitions(MpegEncContext *s)
2967
{
2968
    int mb_num;
2969
    
2970
    mb_num= mpeg4_decode_partition_a(s);    
2971
    if(mb_num<0)
2972
        return -1;
2973
    
2974
    if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
2975
        fprintf(stderr, "slice below monitor ...\n");
2976
        return -1;
2977
    }
2978

    
2979
    s->mb_num_left= mb_num;
2980
        
2981
    if(s->pict_type==I_TYPE){
2982
        if(get_bits(&s->gb, 19)!=DC_MARKER){
2983
            fprintf(stderr, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
2984
            return -1;
2985
        }else
2986
            s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= MV_END|DC_END;
2987
    }else{
2988
        if(get_bits(&s->gb, 17)!=MOTION_MARKER){
2989
            fprintf(stderr, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
2990
            return -1;
2991
        }else
2992
            s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= MV_END;
2993
    }
2994
    
2995
    if( mpeg4_decode_partition_b(s, mb_num) < 0){
2996
        return -1;
2997
    }
2998
    
2999
    s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= DC_END;
3000

    
3001
    return 0;        
3002
}
3003

    
3004
/**
3005
 * decode partition C of one MB.
3006
 * @return <0 if an error occured
3007
 */
3008
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
3009
{
3010
    int cbp, mb_type;
3011
    const int xy= s->mb_x + s->mb_y*s->mb_width;
3012

    
3013
    mb_type= s->mb_type[xy];
3014
    cbp = s->cbp_table[xy];
3015

    
3016
    if(s->current_picture.qscale_table[xy] != s->qscale){
3017
        s->qscale= s->current_picture.qscale_table[xy];
3018
        s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
3019
        s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
3020
    }
3021
    
3022
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3023
        int i;
3024
        for(i=0; i<4; i++){
3025
            s->mv[0][i][0] = s->motion_val[ s->block_index[i] ][0];
3026
            s->mv[0][i][1] = s->motion_val[ s->block_index[i] ][1];
3027
        }
3028
        s->mb_intra = mb_type&MB_TYPE_INTRA;
3029

    
3030
        if (mb_type&MB_TYPE_SKIPED) {
3031
            /* skip mb */
3032
            for(i=0;i<6;i++)
3033
                s->block_last_index[i] = -1;
3034
            s->mv_dir = MV_DIR_FORWARD;
3035
            s->mv_type = MV_TYPE_16X16;
3036
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3037
                s->mcsel=1;
3038
                s->mb_skiped = 0;
3039
            }else{
3040
                s->mcsel=0;
3041
                s->mb_skiped = 1;
3042
            }
3043
        }else if(s->mb_intra){
3044
            s->ac_pred = s->pred_dir_table[xy]>>7;
3045

    
3046
            /* decode each block */
3047
            for (i = 0; i < 6; i++) {
3048
                if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){
3049
                    fprintf(stderr, "texture corrupted at %d %d\n", s->mb_x, s->mb_y);
3050
                    return -1;
3051
                }
3052
                cbp+=cbp;
3053
            }
3054
        }else if(!s->mb_intra){
3055
//            s->mcsel= 0; //FIXME do we need to init that
3056
            
3057
            s->mv_dir = MV_DIR_FORWARD;
3058
            if (mb_type&MB_TYPE_INTER4V) {
3059
                s->mv_type = MV_TYPE_8X8;
3060
            } else {
3061
                s->mv_type = MV_TYPE_16X16;
3062
            }
3063
            /* decode each block */
3064
            for (i = 0; i < 6; i++) {
3065
                if(mpeg4_decode_block(s, block[i], i, cbp&32, 0) < 0){
3066
                    fprintf(stderr, "texture corrupted at %d %d (trying to continue with mc/dc only)\n", s->mb_x, s->mb_y);
3067
                    return -1;
3068
                }
3069
                cbp+=cbp;
3070
            }
3071
        }
3072
    } else { /* I-Frame */
3073
        int i;
3074
        s->mb_intra = 1;
3075
        s->ac_pred = s->pred_dir_table[xy]>>7;
3076
        
3077
        /* decode each block */
3078
        for (i = 0; i < 6; i++) {
3079
            if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){
3080
                fprintf(stderr, "texture corrupted at %d %d (trying to continue with dc only)\n", s->mb_x, s->mb_y);
3081
                return -1;
3082
            }
3083
            cbp+=cbp;
3084
        }
3085
    }
3086

    
3087
    s->error_status_table[xy]&= ~AC_ERROR;
3088

    
3089
    /* per-MB end of slice check */
3090

    
3091
    if(--s->mb_num_left <= 0){
3092
//printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size_in_bits - get_bits_count(&s->gb));
3093
        if(mpeg4_is_resync(s))
3094
            return SLICE_END;
3095
        else
3096
            return SLICE_NOEND;     
3097
    }else{
3098
        if(s->cbp_table[xy+1] && mpeg4_is_resync(s))
3099
            return SLICE_END;
3100
        else
3101
            return SLICE_OK;
3102
    }
3103
}
3104

    
3105
int ff_h263_decode_mb(MpegEncContext *s,
3106
                      DCTELEM block[6][64])
3107
{
3108
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
3109
    int16_t *mot_val;
3110
    static int8_t quant_tab[4] = { -1, -2, 1, 2 };
3111

    
3112
    s->error_status_table[s->mb_x + s->mb_y*s->mb_width]= 0;
3113

    
3114
    if(s->mb_x==0) PRINT_MB_TYPE("\n");
3115

    
3116
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3117
        if (get_bits1(&s->gb)) {
3118
            /* skip mb */
3119
            s->mb_intra = 0;
3120
            for(i=0;i<6;i++)
3121
                s->block_last_index[i] = -1;
3122
            s->mv_dir = MV_DIR_FORWARD;
3123
            s->mv_type = MV_TYPE_16X16;
3124
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3125
                PRINT_MB_TYPE("G");
3126
                s->mcsel=1;
3127
                s->mv[0][0][0]= get_amv(s, 0);
3128
                s->mv[0][0][1]= get_amv(s, 1);
3129

    
3130
                s->mb_skiped = 0;
3131
            }else{
3132
                PRINT_MB_TYPE("S");
3133
                s->mcsel=0;
3134
                s->mv[0][0][0] = 0;
3135
                s->mv[0][0][1] = 0;
3136
                s->mb_skiped = 1;
3137
            }
3138
            goto end;
3139
        }
3140
        cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3141
        //fprintf(stderr, "\tCBPC: %d", cbpc);
3142
        if (cbpc < 0)
3143
            return -1;
3144
        if (cbpc > 20)
3145
            cbpc+=3;
3146
        else if (cbpc == 20)
3147
            fprintf(stderr, "Stuffing !");
3148
        
3149
        dquant = cbpc & 8;
3150
        s->mb_intra = ((cbpc & 4) != 0);
3151
        if (s->mb_intra) goto intra;
3152
        
3153
        if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
3154
            s->mcsel= get_bits1(&s->gb);
3155
        else s->mcsel= 0;
3156
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3157
        cbp = (cbpc & 3) | ((cbpy ^ 0xf) << 2);
3158
        if (dquant) {
3159
            change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3160
        }
3161
        if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
3162
            s->interlaced_dct= get_bits1(&s->gb);
3163
        
3164
        s->mv_dir = MV_DIR_FORWARD;
3165
        if ((cbpc & 16) == 0) {
3166
            if(s->mcsel){
3167
                PRINT_MB_TYPE("G");
3168
                /* 16x16 global motion prediction */
3169
                s->mv_type = MV_TYPE_16X16;
3170
                mx= get_amv(s, 0);
3171
                my= get_amv(s, 1);
3172
                s->mv[0][0][0] = mx;
3173
                s->mv[0][0][1] = my;
3174
            }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
3175
                PRINT_MB_TYPE("f");
3176
                /* 16x8 field motion prediction */
3177
                s->mv_type= MV_TYPE_FIELD;
3178

    
3179
                s->field_select[0][0]= get_bits1(&s->gb);
3180
                s->field_select[0][1]= get_bits1(&s->gb);
3181

    
3182
                h263_pred_motion(s, 0, &pred_x, &pred_y);
3183
                
3184
                for(i=0; i<2; i++){
3185
                    mx = h263_decode_motion(s, pred_x, s->f_code);
3186
                    if (mx >= 0xffff)
3187
                        return -1;
3188
            
3189
                    my = h263_decode_motion(s, pred_y/2, s->f_code);
3190
                    if (my >= 0xffff)
3191
                        return -1;
3192

    
3193
                    s->mv[0][i][0] = mx;
3194
                    s->mv[0][i][1] = my;
3195
                }
3196
            }else{
3197
                PRINT_MB_TYPE("P");
3198
                /* 16x16 motion prediction */
3199
                s->mv_type = MV_TYPE_16X16;
3200
                h263_pred_motion(s, 0, &pred_x, &pred_y);
3201
                if (s->umvplus)
3202
                   mx = h263p_decode_umotion(s, pred_x);
3203
                else
3204
                   mx = h263_decode_motion(s, pred_x, s->f_code);
3205
            
3206
                if (mx >= 0xffff)
3207
                    return -1;
3208
            
3209
                if (s->umvplus)
3210
                   my = h263p_decode_umotion(s, pred_y);
3211
                else
3212
                   my = h263_decode_motion(s, pred_y, s->f_code);
3213
            
3214
                if (my >= 0xffff)
3215
                    return -1;
3216
                s->mv[0][0][0] = mx;
3217
                s->mv[0][0][1] = my;
3218

    
3219
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3220
                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */                   
3221
            }
3222
        } else {
3223
            PRINT_MB_TYPE("4");
3224
            s->mv_type = MV_TYPE_8X8;
3225
            for(i=0;i<4;i++) {
3226
                mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
3227
                if (s->umvplus)
3228
                  mx = h263p_decode_umotion(s, pred_x);
3229
                else
3230
                  mx = h263_decode_motion(s, pred_x, s->f_code);
3231
                if (mx >= 0xffff)
3232
                    return -1;
3233
                
3234
                if (s->umvplus)
3235
                  my = h263p_decode_umotion(s, pred_y);
3236
                else    
3237
                  my = h263_decode_motion(s, pred_y, s->f_code);
3238
                if (my >= 0xffff)
3239
                    return -1;
3240
                s->mv[0][i][0] = mx;
3241
                s->mv[0][i][1] = my;
3242
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3243
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3244
                mot_val[0] = mx;
3245
                mot_val[1] = my;
3246
            }
3247
        }
3248
    } else if(s->pict_type==B_TYPE) {
3249
        int modb1; // first bit of modb
3250
        int modb2; // second bit of modb
3251
        int mb_type;
3252

    
3253
        s->mb_intra = 0; //B-frames never contain intra blocks
3254
        s->mcsel=0;      //     ...               true gmc blocks
3255

    
3256
        if(s->mb_x==0){
3257
            for(i=0; i<2; i++){
3258
                s->last_mv[i][0][0]= 
3259
                s->last_mv[i][0][1]= 
3260
                s->last_mv[i][1][0]= 
3261
                s->last_mv[i][1][1]= 0;
3262
            }
3263
        }
3264

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

    
3268
        if(s->mb_skiped){
3269
                /* skip mb */
3270
            for(i=0;i<6;i++)
3271
                s->block_last_index[i] = -1;
3272

    
3273
            s->mv_dir = MV_DIR_FORWARD;
3274
            s->mv_type = MV_TYPE_16X16;
3275
            s->mv[0][0][0] = 0;
3276
            s->mv[0][0][1] = 0;
3277
            s->mv[1][0][0] = 0;
3278
            s->mv[1][0][1] = 0;
3279
            PRINT_MB_TYPE("s");
3280
            goto end;
3281
        }
3282

    
3283
        modb1= get_bits1(&s->gb); 
3284
        if(modb1){
3285
            mb_type=4; //like MB_TYPE_B_DIRECT but no vectors coded
3286
            cbp=0;
3287
        }else{
3288
            int field_mv;
3289
        
3290
            modb2= get_bits1(&s->gb);
3291
            mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
3292
            if(modb2) cbp= 0;
3293
            else      cbp= get_bits(&s->gb, 6);
3294

    
3295
            if (mb_type!=MB_TYPE_B_DIRECT && cbp) {
3296
                if(get_bits1(&s->gb)){
3297
                    change_qscale(s, get_bits1(&s->gb)*4 - 2);
3298
                }
3299
            }
3300
            field_mv=0;
3301

    
3302
            if(!s->progressive_sequence){
3303
                if(cbp)
3304
                    s->interlaced_dct= get_bits1(&s->gb);
3305

    
3306
                if(mb_type!=MB_TYPE_B_DIRECT && get_bits1(&s->gb)){
3307
                    field_mv=1;
3308

    
3309
                    if(mb_type!=MB_TYPE_B_BACKW){
3310
                        s->field_select[0][0]= get_bits1(&s->gb);
3311
                        s->field_select[0][1]= get_bits1(&s->gb);
3312
                    }
3313
                    if(mb_type!=MB_TYPE_B_FORW){
3314
                        s->field_select[1][0]= get_bits1(&s->gb);
3315
                        s->field_select[1][1]= get_bits1(&s->gb);
3316
                    }
3317
                }
3318
            }
3319

    
3320
            s->mv_dir = 0;
3321
            if(mb_type!=MB_TYPE_B_DIRECT && !field_mv){
3322
                s->mv_type= MV_TYPE_16X16;
3323
                if(mb_type!=MB_TYPE_B_BACKW){
3324
                    s->mv_dir = MV_DIR_FORWARD;
3325

    
3326
                    mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
3327
                    my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
3328
                    s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
3329
                    s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
3330
                }
3331
    
3332
                if(mb_type!=MB_TYPE_B_FORW){
3333
                    s->mv_dir |= MV_DIR_BACKWARD;
3334

    
3335
                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
3336
                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
3337
                    s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
3338
                    s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
3339
                }
3340
                if(mb_type!=MB_TYPE_B_DIRECT)
3341
                    PRINT_MB_TYPE(mb_type==MB_TYPE_B_FORW ? "F" : (mb_type==MB_TYPE_B_BACKW ? "B" : "T"));
3342
            }else if(mb_type!=MB_TYPE_B_DIRECT){
3343
                s->mv_type= MV_TYPE_FIELD;
3344

    
3345
                if(mb_type!=MB_TYPE_B_BACKW){
3346
                    s->mv_dir = MV_DIR_FORWARD;
3347
                
3348
                    for(i=0; i<2; i++){
3349
                        mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
3350
                        my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
3351
                        s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
3352
                        s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
3353
                    }
3354
                }
3355
    
3356
                if(mb_type!=MB_TYPE_B_FORW){
3357
                    s->mv_dir |= MV_DIR_BACKWARD;
3358

    
3359
                    for(i=0; i<2; i++){
3360
                        mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
3361
                        my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
3362
                        s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
3363
                        s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
3364
                    }
3365
                }
3366
                if(mb_type!=MB_TYPE_B_DIRECT)
3367
                    PRINT_MB_TYPE(mb_type==MB_TYPE_B_FORW ? "f" : (mb_type==MB_TYPE_B_BACKW ? "b" : "t"));
3368
            }
3369
        }
3370
          
3371
        if(mb_type==4 || mb_type==MB_TYPE_B_DIRECT){
3372
            if(mb_type==4)
3373
                mx=my=0;
3374
            else{
3375
                mx = h263_decode_motion(s, 0, 1);
3376
                my = h263_decode_motion(s, 0, 1);
3377
            }
3378
 
3379
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3380
            ff_mpeg4_set_direct_mv(s, mx, my);
3381
        }
3382
        
3383
        if(mb_type<0 || mb_type>4){
3384
            printf("illegal MB_type\n");
3385
            return -1;
3386
        }
3387
    } else { /* I-Frame */
3388
        cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
3389
        if (cbpc < 0)
3390
            return -1;
3391
        dquant = cbpc & 4;
3392
        s->mb_intra = 1;
3393
intra:
3394
        s->ac_pred = 0;
3395
        if (s->h263_pred || s->h263_aic) {
3396
            s->ac_pred = get_bits1(&s->gb);
3397
            if (s->ac_pred && s->h263_aic)
3398
                s->h263_aic_dir = get_bits1(&s->gb);
3399
        }
3400
        PRINT_MB_TYPE(s->ac_pred ? "A" : "I");
3401
        
3402
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3403
        if(cbpy<0) return -1;
3404
        cbp = (cbpc & 3) | (cbpy << 2);
3405
        if (dquant) {
3406
            change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3407
        }
3408
        
3409
        if(!s->progressive_sequence)
3410
            s->interlaced_dct= get_bits1(&s->gb);
3411

    
3412
        /* decode each block */
3413
        if (s->h263_pred) {
3414
            for (i = 0; i < 6; i++) {
3415
                if (mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0)
3416
                    return -1;
3417
                cbp+=cbp;
3418
            }
3419
        } else {
3420
            for (i = 0; i < 6; i++) {
3421
                if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3422
                    return -1;
3423
                cbp+=cbp;
3424
            }
3425
        }
3426
        goto end;
3427
    }
3428

    
3429
    /* decode each block */
3430
    if (s->h263_pred) {
3431
        for (i = 0; i < 6; i++) {
3432
            if (mpeg4_decode_block(s, block[i], i, cbp&32, 0) < 0)
3433
                return -1;
3434
            cbp+=cbp;
3435
        }
3436
    } else {
3437
        for (i = 0; i < 6; i++) {
3438
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3439
                return -1;
3440
            cbp+=cbp;
3441
        }
3442
    }
3443
end:
3444

    
3445
        /* per-MB end of slice check */
3446
    if(s->codec_id==CODEC_ID_MPEG4){
3447
        if(mpeg4_is_resync(s)){
3448
            if(s->pict_type==B_TYPE && s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x+1])
3449
                return SLICE_OK;
3450
            return SLICE_END;
3451
        }
3452
    }else{
3453
        int v= show_bits(&s->gb, 16);
3454
    
3455
        if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
3456
            v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
3457
        }
3458

    
3459
        if(v==0)
3460
            return SLICE_END;
3461
    }
3462

    
3463
    return SLICE_OK;     
3464
}
3465

    
3466
static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
3467
{
3468
    int code, val, sign, shift, l;
3469
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
3470
    if (code < 0)
3471
        return 0xffff;
3472

    
3473
    if (code == 0)
3474
        return pred;
3475

    
3476
    sign = get_bits1(&s->gb);
3477
    shift = f_code - 1;
3478
    val = (code - 1) << shift;
3479
    if (shift > 0)
3480
        val |= get_bits(&s->gb, shift);
3481
    val++;
3482
    if (sign)
3483
        val = -val;
3484
    val += pred;
3485

    
3486
    /* modulo decoding */
3487
    if (!s->h263_long_vectors) {
3488
        l = 1 << (f_code + 4);
3489
        if (val < -l) {
3490
            val += l<<1;
3491
        } else if (val >= l) {
3492
            val -= l<<1;
3493
        }
3494
    } else {
3495
        /* horrible h263 long vector mode */
3496
        if (pred < -31 && val < -63)
3497
            val += 64;
3498
        if (pred > 32 && val > 63)
3499
            val -= 64;
3500
        
3501
    }
3502
    return val;
3503
}
3504

    
3505
/* Decodes RVLC of H.263+ UMV */
3506
static int h263p_decode_umotion(MpegEncContext * s, int pred)
3507
{
3508
   int code = 0, sign;
3509
   
3510
   if (get_bits1(&s->gb)) /* Motion difference = 0 */
3511
      return pred;
3512
   
3513
   code = 2 + get_bits1(&s->gb);
3514
   
3515
   while (get_bits1(&s->gb))
3516
   {
3517
      code <<= 1;
3518
      code += get_bits1(&s->gb);
3519
   }
3520
   sign = code & 1;
3521
   code >>= 1;
3522
   
3523
   code = (sign) ? (pred - code) : (pred + code);
3524
#ifdef DEBUG
3525
   fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
3526
#endif
3527
   return code;   
3528

    
3529
}
3530

    
3531
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
3532
                             int n, int coded)
3533
{
3534
    int code, level, i, j, last, run;
3535
    RLTable *rl = &rl_inter;
3536
    const uint8_t *scan_table;
3537

    
3538
    scan_table = s->intra_scantable.permutated;
3539
    if (s->h263_aic && s->mb_intra) {
3540
        rl = &rl_intra_aic;
3541
        i = 0;
3542
        if (s->ac_pred) {
3543
            if (s->h263_aic_dir) 
3544
                scan_table = s->intra_v_scantable.permutated; /* left */
3545
            else
3546
                scan_table = s->intra_h_scantable.permutated; /* top */
3547
        }
3548
    } else if (s->mb_intra) {
3549
        /* DC coef */
3550
        if(s->h263_rv10){
3551
          if (s->rv10_version == 3 && s->pict_type == I_TYPE) {
3552
            int component, diff;
3553
            component = (n <= 3 ? 0 : n - 4 + 1);
3554
            level = s->last_dc[component];
3555
            if (s->rv10_first_dc_coded[component]) {
3556
                diff = rv_decode_dc(s, n);
3557
                if (diff == 0xffff)
3558
                    return -1;
3559
                level += diff;
3560
                level = level & 0xff; /* handle wrap round */
3561
                s->last_dc[component] = level;
3562
            } else {
3563
                s->rv10_first_dc_coded[component] = 1;
3564
            }
3565
          } else {
3566
                level = get_bits(&s->gb, 8);
3567
          }
3568
        }else{
3569
            level = get_bits(&s->gb, 8);
3570
            if((level&0x7F) == 0){
3571
                fprintf(stderr, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);
3572
                return -1;
3573
            }
3574
            if (level == 255)
3575
                level = 128;
3576
        }
3577
        block[0] = level;
3578
        i = 1;
3579
    } else {
3580
        i = 0;
3581
    }
3582
    if (!coded) {
3583
        if (s->mb_intra && s->h263_aic)
3584
            goto not_coded;
3585
        s->block_last_index[n] = i - 1;
3586
        return 0;
3587
    }
3588

    
3589
    for(;;) {
3590
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
3591
        if (code < 0){
3592
            fprintf(stderr, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
3593
            return -1;
3594
        }
3595
        if (code == rl->n) {
3596
            /* escape */
3597
            last = get_bits1(&s->gb);
3598
            run = get_bits(&s->gb, 6);
3599
            level = (int8_t)get_bits(&s->gb, 8);
3600
            if(level == -128){
3601
                if (s->h263_rv10) {
3602
                    /* XXX: should patch encoder too */
3603
                    level = get_bits(&s->gb, 12);
3604
                    level= (level + ((-1)<<11)) ^ ((-1)<<11); //sign extension
3605
                }else{
3606
                    level = get_bits(&s->gb, 5);
3607
                    level += get_bits(&s->gb, 6)<<5;
3608
                    level= (level + ((-1)<<10)) ^ ((-1)<<10); //sign extension
3609
                }
3610
            }
3611
        } else {
3612
            run = rl->table_run[code];
3613
            level = rl->table_level[code];
3614
            last = code >= rl->last;
3615
            if (get_bits1(&s->gb))
3616
                level = -level;
3617
        }
3618
        i += run;
3619
        if (i >= 64){
3620
            fprintf(stderr, "run overflow at %dx%d\n", s->mb_x, s->mb_y);
3621
            return -1;
3622
        }
3623
        j = scan_table[i];
3624
        block[j] = level;
3625
        if (last)
3626
            break;
3627
        i++;
3628
    }
3629
not_coded:    
3630
    if (s->mb_intra && s->h263_aic) {
3631
        h263_pred_acdc(s, block, n);
3632
        i = 63;
3633
    }
3634
    s->block_last_index[n] = i;
3635
    return 0;
3636
}
3637

    
3638
/**
3639
 * decodes the dc value.
3640
 * @param n block index (0-3 are luma, 4-5 are chroma)
3641
 * @param dir_ptr the prediction direction will be stored here
3642
 * @return the quantized dc
3643
 */
3644
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
3645
{
3646
    int level, pred, code;
3647
    uint16_t *dc_val;
3648

    
3649
    if (n < 4) 
3650
        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
3651
    else 
3652
        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
3653
    if (code < 0 || code > 9 /* && s->nbit<9 */){
3654
        fprintf(stderr, "illegal dc vlc\n");
3655
        return -1;
3656
    }
3657
    if (code == 0) {
3658
        level = 0;
3659
    } else {
3660
        level = get_bits(&s->gb, code);
3661
        if ((level >> (code - 1)) == 0) /* if MSB not set it is negative*/
3662
            level = - (level ^ ((1 << code) - 1));
3663
        if (code > 8){
3664
            if(get_bits1(&s->gb)==0){ /* marker */
3665
                if(s->error_resilience>=2){
3666
                    fprintf(stderr, "dc marker bit missing\n");
3667
                    return -1;
3668
                }
3669
            }
3670
        }
3671
    }
3672
    pred = ff_mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
3673
    level += pred;
3674
    if (level < 0){
3675
        if(s->error_resilience>=3){
3676
            fprintf(stderr, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
3677
            return -1;
3678
        }
3679
        level = 0;
3680
    }
3681
    if (n < 4) {
3682
        *dc_val = level * s->y_dc_scale;
3683
    } else {
3684
        *dc_val = level * s->c_dc_scale;
3685
    }
3686
    if(s->error_resilience>=3){
3687
        if(*dc_val > 2048 + s->y_dc_scale + s->c_dc_scale){
3688
            fprintf(stderr, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
3689
            return -1;
3690
        }
3691
    }
3692
    return level;
3693
}
3694

    
3695
/**
3696
 * decodes a block.
3697
 * @return <0 if an error occured
3698
 */
3699
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
3700
                              int n, int coded, int intra)
3701
{
3702
    int level, i, last, run;
3703
    int dc_pred_dir;
3704
    RLTable * rl;
3705
    RL_VLC_ELEM * rl_vlc;
3706
    const uint8_t * scan_table;
3707
    int qmul, qadd;
3708

    
3709
    if(intra) {
3710
        /* DC coef */
3711
        if(s->partitioned_frame){
3712
            level = s->dc_val[0][ s->block_index[n] ];
3713
            if(n<4) level= (level + (s->y_dc_scale>>1))/s->y_dc_scale; //FIXME optimizs
3714
            else    level= (level + (s->c_dc_scale>>1))/s->c_dc_scale;
3715
            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_width]<<n)&32;
3716
        }else{
3717
            level = mpeg4_decode_dc(s, n, &dc_pred_dir);
3718
            if (level < 0)
3719
                return -1;
3720
        }
3721
        block[0] = level;
3722
        i = 0;
3723
        if (!coded) 
3724
            goto not_coded;
3725
        rl = &rl_intra;
3726
        rl_vlc = rl_intra.rl_vlc[0];
3727
        if (s->ac_pred) {
3728
            if (dc_pred_dir == 0) 
3729
                scan_table = s->intra_v_scantable.permutated; /* left */
3730
            else
3731
                scan_table = s->intra_h_scantable.permutated; /* top */
3732
        } else {
3733
            scan_table = s->intra_scantable.permutated;
3734
        }
3735
        qmul=1;
3736
        qadd=0;
3737
    } else {
3738
        i = -1;
3739
        if (!coded) {
3740
            s->block_last_index[n] = i;
3741
            return 0;
3742
        }
3743
        rl = &rl_inter;
3744
   
3745
        scan_table = s->intra_scantable.permutated;
3746

    
3747
        if(s->mpeg_quant){
3748
            qmul=1;
3749
            qadd=0;
3750
            rl_vlc = rl_inter.rl_vlc[0];        
3751
        }else{
3752
            qmul = s->qscale << 1;
3753
            qadd = (s->qscale - 1) | 1;
3754
            rl_vlc = rl_inter.rl_vlc[s->qscale];
3755
        }
3756
    }
3757
  {
3758
    OPEN_READER(re, &s->gb);
3759
    for(;;) {
3760
        UPDATE_CACHE(re, &s->gb);
3761
        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3762
        if (level==0) {
3763
            int cache;
3764
            cache= GET_CACHE(re, &s->gb);
3765
            /* escape */
3766
            if (cache&0x80000000) {
3767
                if (cache&0x40000000) {
3768
                    /* third escape */
3769
                    SKIP_CACHE(re, &s->gb, 2);
3770
                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
3771
                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
3772
                    SKIP_COUNTER(re, &s->gb, 2+1+6);
3773
                    UPDATE_CACHE(re, &s->gb);
3774

    
3775
                    if(SHOW_UBITS(re, &s->gb, 1)==0){
3776
                        fprintf(stderr, "1. marker bit missing in 3. esc\n");
3777
                        return -1;
3778
                    }; SKIP_CACHE(re, &s->gb, 1);
3779
                    
3780
                    level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
3781
 
3782
                    if(SHOW_UBITS(re, &s->gb, 1)==0){
3783
                        fprintf(stderr, "2. marker bit missing in 3. esc\n");
3784
                        return -1;
3785
                    }; LAST_SKIP_CACHE(re, &s->gb, 1);
3786
                    
3787
                    SKIP_COUNTER(re, &s->gb, 1+12+1);
3788
                    
3789
                    if(level*s->qscale>1024 || level*s->qscale<-1024){
3790
                        fprintf(stderr, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
3791
                        return -1;
3792
                    }
3793
#if 1 
3794
                    {
3795
                        const int abs_level= ABS(level);
3796
                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN && !(s->workaround_bugs&FF_BUG_AC_VLC)){
3797
                            const int run1= run - rl->max_run[last][abs_level] - 1;
3798
                            if(abs_level <= rl->max_level[last][run]){
3799
                                fprintf(stderr, "illegal 3. esc, vlc encoding possible\n");
3800
                                return -1;
3801
                            }
3802
                            if(s->error_resilience > FF_ER_COMPLIANT){
3803
                                if(abs_level <= rl->max_level[last][run]*2){
3804
                                    fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");
3805
                                    return -1;
3806
                                }
3807
                                if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
3808
                                    fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");
3809
                                    return -1;
3810
                                }
3811
                            }
3812
                        }
3813
                    }
3814
#endif
3815
                    if (level>0) level= level * qmul + qadd;
3816
                    else         level= level * qmul - qadd;
3817

    
3818
                    i+= run + 1;
3819
                    if(last) i+=192;
3820
                } else {
3821
                    /* second escape */
3822
#if MIN_CACHE_BITS < 20
3823
                    LAST_SKIP_BITS(re, &s->gb, 2);
3824
                    UPDATE_CACHE(re, &s->gb);
3825
#else
3826
                    SKIP_BITS(re, &s->gb, 2);
3827
#endif
3828
                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3829
                    i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
3830
                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3831
                    LAST_SKIP_BITS(re, &s->gb, 1);
3832
                }
3833
            } else {
3834
                /* first escape */
3835
#if MIN_CACHE_BITS < 19
3836
                LAST_SKIP_BITS(re, &s->gb, 1);
3837
                UPDATE_CACHE(re, &s->gb);
3838
#else
3839
                SKIP_BITS(re, &s->gb, 1);
3840
#endif
3841
                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3842
                i+= run;
3843
                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
3844
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3845
                LAST_SKIP_BITS(re, &s->gb, 1);
3846
            }
3847
        } else {
3848
            i+= run;
3849
            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3850
            LAST_SKIP_BITS(re, &s->gb, 1);
3851
        }
3852
        if (i > 62){
3853
            i-= 192;
3854
            if(i&(~63)){
3855
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
3856
                return -1;
3857
            }
3858

    
3859
            block[scan_table[i]] = level;
3860
            break;
3861
        }
3862

    
3863
        block[scan_table[i]] = level;
3864
    }
3865
    CLOSE_READER(re, &s->gb);
3866
  }
3867
 not_coded:
3868
    if (s->mb_intra) {
3869
        mpeg4_pred_ac(s, block, n, dc_pred_dir);
3870
        if (s->ac_pred) {
3871
            i = 63; /* XXX: not optimal */
3872
        }
3873
    }
3874
    s->block_last_index[n] = i;
3875
    return 0;
3876
}
3877

    
3878
/* most is hardcoded. should extend to handle all h263 streams */
3879
int h263_decode_picture_header(MpegEncContext *s)
3880
{
3881
    int format, width, height;
3882

    
3883
    /* picture start code */
3884
    if (get_bits(&s->gb, 22) != 0x20) {
3885
        fprintf(stderr, "Bad picture start code\n");
3886
        return -1;
3887
    }
3888
    /* temporal reference */
3889
    s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
3890

    
3891
    /* PTYPE starts here */    
3892
    if (get_bits1(&s->gb) != 1) {
3893
        /* marker */
3894
        fprintf(stderr, "Bad marker\n");
3895
        return -1;
3896
    }
3897
    if (get_bits1(&s->gb) != 0) {
3898
        fprintf(stderr, "Bad H263 id\n");
3899
        return -1;        /* h263 id */
3900
    }
3901
    skip_bits1(&s->gb);        /* split screen off */
3902
    skip_bits1(&s->gb);        /* camera  off */
3903
    skip_bits1(&s->gb);        /* freeze picture release off */
3904

    
3905
    /* Reset GOB number */
3906
    s->gob_number = 0;
3907
        
3908
    format = get_bits(&s->gb, 3);
3909
    /*
3910
        0    forbidden
3911
        1    sub-QCIF
3912
        10   QCIF
3913
        7        extended PTYPE (PLUSPTYPE)
3914
    */
3915

    
3916
    if (format != 7 && format != 6) {
3917
        s->h263_plus = 0;
3918
        /* H.263v1 */
3919
        width = h263_format[format][0];
3920
        height = h263_format[format][1];
3921
        if (!width)
3922
            return -1;
3923
        
3924
        s->width = width;
3925
        s->height = height;
3926
        s->pict_type = I_TYPE + get_bits1(&s->gb);
3927

    
3928
        s->unrestricted_mv = get_bits1(&s->gb); 
3929
        s->h263_long_vectors = s->unrestricted_mv;
3930

    
3931
        if (get_bits1(&s->gb) != 0) {
3932
            fprintf(stderr, "H263 SAC not supported\n");
3933
            return -1;        /* SAC: off */
3934
        }
3935
        if (get_bits1(&s->gb) != 0) {
3936
            s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3937
        }   
3938
        
3939
        if (get_bits1(&s->gb) != 0) {
3940
            fprintf(stderr, "H263 PB frame not supported\n");
3941
            return -1;        /* not PB frame */
3942
        }
3943
        s->qscale = get_bits(&s->gb, 5);
3944
        skip_bits1(&s->gb);        /* Continuous Presence Multipoint mode: off */
3945
    } else {
3946
        int ufep;
3947
        
3948
        /* H.263v2 */
3949
        s->h263_plus = 1;
3950
        ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
3951

    
3952
        /* ufep other than 0 and 1 are reserved */        
3953
        if (ufep == 1) {
3954
            /* OPPTYPE */       
3955
            format = get_bits(&s->gb, 3);
3956
            dprintf("ufep=1, format: %d\n", format);
3957
            skip_bits(&s->gb,1); /* Custom PCF */
3958
            s->umvplus = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */
3959
            skip_bits1(&s->gb); /* Syntax-based Arithmetic Coding (SAC) */
3960
            if (get_bits1(&s->gb) != 0) {
3961
                s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3962
            }
3963
            if (get_bits1(&s->gb) != 0) { /* Advanced Intra Coding (AIC) */
3964
                s->h263_aic = 1;
3965
            }
3966
            
3967
            skip_bits(&s->gb, 7);
3968
            /* these are the 7 bits: (in order of appearence  */
3969
            /* Deblocking Filter */
3970
            /* Slice Structured */
3971
            /* Reference Picture Selection */
3972
            /* Independent Segment Decoding */
3973
            /* Alternative Inter VLC */
3974
            /* Modified Quantization */
3975
            /* Prevent start code emulation */
3976

    
3977
            skip_bits(&s->gb, 3); /* Reserved */
3978
        } else if (ufep != 0) {
3979
            fprintf(stderr, "Bad UFEP type (%d)\n", ufep);
3980
            return -1;
3981
        }
3982
            
3983
        /* MPPTYPE */
3984
        s->pict_type = get_bits(&s->gb, 3) + I_TYPE;
3985
        dprintf("pict_type: %d\n", s->pict_type);
3986
        if (s->pict_type != I_TYPE &&
3987
            s->pict_type != P_TYPE)
3988
            return -1;
3989
        skip_bits(&s->gb, 2);
3990
        s->no_rounding = get_bits1(&s->gb);
3991
        dprintf("RTYPE: %d\n", s->no_rounding);
3992
        skip_bits(&s->gb, 4);
3993
        
3994
        /* Get the picture dimensions */
3995
        if (ufep) {
3996
            if (format == 6) {
3997
                /* Custom Picture Format (CPFMT) */
3998
                s->aspect_ratio_info = get_bits(&s->gb, 4);
3999
                dprintf("aspect: %d\n", s->aspect_ratio_info);
4000
                /* aspect ratios:
4001
                0 - forbidden
4002
                1 - 1:1
4003
                2 - 12:11 (CIF 4:3)
4004
                3 - 10:11 (525-type 4:3)
4005
                4 - 16:11 (CIF 16:9)
4006
                5 - 40:33 (525-type 16:9)
4007
                6-14 - reserved
4008
                */
4009
                width = (get_bits(&s->gb, 9) + 1) * 4;
4010
                skip_bits1(&s->gb);
4011
                height = get_bits(&s->gb, 9) * 4;
4012
                dprintf("\nH.263+ Custom picture: %dx%d\n",width,height);
4013
                if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
4014
                    /* aspected dimensions */
4015
                    s->aspected_width = get_bits(&s->gb, 8);
4016
                    s->aspected_height = get_bits(&s->gb, 8);
4017
                }else{
4018
                    s->aspected_width = pixel_aspect[s->aspect_ratio_info][0];
4019
                    s->aspected_height= pixel_aspect[s->aspect_ratio_info][1];
4020
                }
4021
            } else {
4022
                width = h263_format[format][0];
4023
                height = h263_format[format][1];
4024
            }
4025
            if ((width == 0) || (height == 0))
4026
                return -1;
4027
            s->width = width;
4028
            s->height = height;
4029
            if (s->umvplus) {
4030
                if(get_bits1(&s->gb)==0) /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
4031
                    skip_bits1(&s->gb); 
4032
            }
4033
        }
4034
            
4035
        s->qscale = get_bits(&s->gb, 5);
4036
    }
4037
    /* PEI */
4038
    while (get_bits1(&s->gb) != 0) {
4039
        skip_bits(&s->gb, 8);
4040
    }
4041
    s->f_code = 1;
4042
    
4043
    if(s->h263_aic){
4044
         s->y_dc_scale_table= 
4045
         s->c_dc_scale_table= h263_aic_dc_scale_table;
4046
    }else{
4047
        s->y_dc_scale_table=
4048
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
4049
    }
4050

    
4051
    return 0;
4052
}
4053

    
4054
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
4055
{
4056
    int i;
4057
    int a= 2<<s->sprite_warping_accuracy;
4058
    int rho= 3-s->sprite_warping_accuracy;
4059
    int r=16/a;
4060
    const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
4061
    int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
4062
    int sprite_ref[4][2];
4063
    int virtual_ref[2][2];
4064
    int w2, h2, w3, h3;
4065
    int alpha=0, beta=0;
4066
    int w= s->width;
4067
    int h= s->height;
4068
    int min_ab;
4069

    
4070
    for(i=0; i<s->num_sprite_warping_points; i++){
4071
        int length;
4072
        int x=0, y=0;
4073

    
4074
        length= get_vlc(&s->gb, &sprite_trajectory);
4075
        if(length){
4076
            x= get_bits(&s->gb, length);
4077

    
4078
            if ((x >> (length - 1)) == 0) /* if MSB not set it is negative*/
4079
                x = - (x ^ ((1 << length) - 1));
4080
        }
4081
        if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
4082
        
4083
        length= get_vlc(&s->gb, &sprite_trajectory);
4084
        if(length){
4085
            y=get_bits(&s->gb, length);
4086

    
4087
            if ((y >> (length - 1)) == 0) /* if MSB not set it is negative*/
4088
                y = - (y ^ ((1 << length) - 1));
4089
        }
4090
        skip_bits1(&s->gb); /* marker bit */
4091
//printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
4092
        d[i][0]= x;
4093
        d[i][1]= y;
4094
    }
4095

    
4096
    while((1<<alpha)<w) alpha++;
4097
    while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
4098
    w2= 1<<alpha;
4099
    h2= 1<<beta;
4100

    
4101
// Note, the 4th point isnt used for GMC
4102
    if(s->divx_version==500 && s->divx_build==413){
4103
        sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
4104
        sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
4105
        sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
4106
        sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
4107
        sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
4108
        sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
4109
    } else {
4110
        sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
4111
        sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
4112
        sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
4113
        sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
4114
        sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
4115
        sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
4116
    }
4117
/*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
4118
    sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
4119
    
4120
// this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
4121
// perhaps it should be reordered to be more readable ...
4122
// the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
4123
// so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
4124
    virtual_ref[0][0]= 16*(vop_ref[0][0] + w2) 
4125
        + 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);
4126
    virtual_ref[0][1]= 16*vop_ref[0][1] 
4127
        + 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);
4128
    virtual_ref[1][0]= 16*vop_ref[0][0] 
4129
        + 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);
4130
    virtual_ref[1][1]= 16*(vop_ref[0][1] + h2) 
4131
        + 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);
4132
        
4133
    switch(s->num_sprite_warping_points)
4134
    {
4135
        case 0:
4136
            s->sprite_offset[0][0]= 0;
4137
            s->sprite_offset[0][1]= 0;
4138
            s->sprite_offset[1][0]= 0;
4139
            s->sprite_offset[1][1]= 0;
4140
            s->sprite_delta[0][0]= a;
4141
            s->sprite_delta[0][1]= 0;
4142
            s->sprite_delta[1][0]= 0;
4143
            s->sprite_delta[1][1]= a;
4144
            s->sprite_shift[0]= 0;
4145
            s->sprite_shift[1]= 0;
4146
            break;
4147
        case 1: //GMC only
4148
            s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
4149
            s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
4150
            s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
4151
            s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
4152
            s->sprite_delta[0][0]= a;
4153
            s->sprite_delta[0][1]= 0;
4154
            s->sprite_delta[1][0]= 0;
4155
            s->sprite_delta[1][1]= a;
4156
            s->sprite_shift[0]= 0;
4157
            s->sprite_shift[1]= 0;
4158
            break;
4159
        case 2:
4160
            s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
4161
                                                  + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
4162
                                                  + ( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1])
4163
                                                  + (1<<(alpha+rho-1));
4164
            s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
4165
                                                  + (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
4166
                                                  + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1])
4167
                                                  + (1<<(alpha+rho-1));
4168
            s->sprite_offset[1][0]= ( (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)
4169
                                     +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)
4170
                                     +2*w2*r*sprite_ref[0][0] 
4171
                                     - 16*w2 
4172
                                     + (1<<(alpha+rho+1)));
4173
            s->sprite_offset[1][1]= ( (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1) 
4174
                                     +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)
4175
                                     +2*w2*r*sprite_ref[0][1] 
4176
                                     - 16*w2
4177
                                     + (1<<(alpha+rho+1)));
4178
            s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
4179
            s->sprite_delta[0][1]=   (+r*sprite_ref[0][1] - virtual_ref[0][1]);
4180
            s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);
4181
            s->sprite_delta[1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
4182
            
4183
            s->sprite_shift[0]= alpha+rho;
4184
            s->sprite_shift[1]= alpha+rho+2;
4185
            break;
4186
        case 3:
4187
            min_ab= FFMIN(alpha, beta);
4188
            w3= w2>>min_ab;
4189
            h3= h2>>min_ab;
4190
            s->sprite_offset[0][0]=  (sprite_ref[0][0]<<(alpha+beta+rho-min_ab))
4191
                                   + (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-vop_ref[0][0])
4192
                                   + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-vop_ref[0][1])
4193
                                   + (1<<(alpha+beta+rho-min_ab-1));
4194
            s->sprite_offset[0][1]=  (sprite_ref[0][1]<<(alpha+beta+rho-min_ab))
4195
                                   + (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-vop_ref[0][0])
4196
                                   + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-vop_ref[0][1])
4197
                                   + (1<<(alpha+beta+rho-min_ab-1));
4198
            s->sprite_offset[1][0]=  (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-2*vop_ref[0][0] + 1)
4199
                                   + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-2*vop_ref[0][1] + 1)
4200
                                   + 2*w2*h3*r*sprite_ref[0][0]
4201
                                   - 16*w2*h3
4202
                                   + (1<<(alpha+beta+rho-min_ab+1));
4203
            s->sprite_offset[1][1]=  (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-2*vop_ref[0][0] + 1)
4204
                                   + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-2*vop_ref[0][1] + 1)
4205
                                   + 2*w2*h3*r*sprite_ref[0][1]
4206
                                   - 16*w2*h3
4207
                                   + (1<<(alpha+beta+rho-min_ab+1));
4208
            s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3;
4209
            s->sprite_delta[0][1]=   (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3;
4210
            s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3;
4211
            s->sprite_delta[1][1]=   (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3;
4212
                                   
4213
            s->sprite_shift[0]= alpha + beta + rho - min_ab;
4214
            s->sprite_shift[1]= alpha + beta + rho - min_ab + 2;
4215
            break;
4216
    }
4217
    /* try to simplify the situation */ 
4218
    if(   s->sprite_delta[0][0] == a<<s->sprite_shift[0]
4219
       && s->sprite_delta[0][1] == 0
4220
       && s->sprite_delta[1][0] == 0
4221
       && s->sprite_delta[1][1] == a<<s->sprite_shift[0])
4222
    {
4223
        s->sprite_offset[0][0]>>=s->sprite_shift[0];
4224
        s->sprite_offset[0][1]>>=s->sprite_shift[0];
4225
        s->sprite_offset[1][0]>>=s->sprite_shift[1];
4226
        s->sprite_offset[1][1]>>=s->sprite_shift[1];
4227
        s->sprite_delta[0][0]= a;
4228
        s->sprite_delta[0][1]= 0;
4229
        s->sprite_delta[1][0]= 0;
4230
        s->sprite_delta[1][1]= a;
4231
        s->sprite_shift[0]= 0;
4232
        s->sprite_shift[1]= 0;
4233
        s->real_sprite_warping_points=1;
4234
    }
4235
    else{
4236
        int shift_y= 16 - s->sprite_shift[0];
4237
        int shift_c= 16 - s->sprite_shift[1];
4238
//printf("shifts %d %d\n", shift_y, shift_c);
4239
        for(i=0; i<2; i++){
4240
            s->sprite_offset[0][i]<<= shift_y;
4241
            s->sprite_offset[1][i]<<= shift_c;
4242
            s->sprite_delta[0][i]<<= shift_y;
4243
            s->sprite_delta[1][i]<<= shift_y;
4244
            s->sprite_shift[i]= 16;
4245
        }
4246
        s->real_sprite_warping_points= s->num_sprite_warping_points;
4247
    }
4248
#if 0
4249
printf("vop:%d:%d %d:%d %d:%d, sprite:%d:%d %d:%d %d:%d, virtual: %d:%d %d:%d\n",
4250
    vop_ref[0][0], vop_ref[0][1],
4251
    vop_ref[1][0], vop_ref[1][1],
4252
    vop_ref[2][0], vop_ref[2][1],
4253
    sprite_ref[0][0], sprite_ref[0][1], 
4254
    sprite_ref[1][0], sprite_ref[1][1], 
4255
    sprite_ref[2][0], sprite_ref[2][1], 
4256
    virtual_ref[0][0], virtual_ref[0][1], 
4257
    virtual_ref[1][0], virtual_ref[1][1]
4258
    );
4259
    
4260
printf("offset: %d:%d , delta: %d %d %d %d, shift %d\n",
4261
    s->sprite_offset[0][0], s->sprite_offset[0][1],
4262
    s->sprite_delta[0][0], s->sprite_delta[0][1],
4263
    s->sprite_delta[1][0], s->sprite_delta[1][1],
4264
    s->sprite_shift[0]
4265
    );
4266
#endif
4267
}
4268

    
4269
static int mpeg4_decode_gop_header(MpegEncContext * s, GetBitContext *gb){
4270
    int hours, minutes, seconds;
4271

    
4272
    hours= get_bits(gb, 5);
4273
    minutes= get_bits(gb, 6);
4274
    skip_bits1(gb);
4275
    seconds= get_bits(gb, 6);
4276

    
4277
    s->time_base= seconds + 60*(minutes + 60*hours);
4278

    
4279
    skip_bits1(gb);
4280
    skip_bits1(gb);
4281
    
4282
    return 0;
4283
}
4284

    
4285
static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){
4286
    int width, height, vo_ver_id;
4287

    
4288
    /* vol header */
4289
    skip_bits(gb, 1); /* random access */
4290
    s->vo_type= get_bits(gb, 8);
4291
    if (get_bits1(gb) != 0) { /* is_ol_id */
4292
        vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
4293
        skip_bits(gb, 3); /* vo_priority */
4294
    } else {
4295
        vo_ver_id = 1;
4296
    }
4297
//printf("vo type:%d\n",s->vo_type);
4298
    s->aspect_ratio_info= get_bits(gb, 4);
4299
    if(s->aspect_ratio_info == FF_ASPECT_EXTENDED){            
4300
        s->aspected_width = get_bits(gb, 8); // par_width
4301
        s->aspected_height = get_bits(gb, 8); // par_height
4302
    }else{
4303
        s->aspected_width = pixel_aspect[s->aspect_ratio_info][0];
4304
        s->aspected_height= pixel_aspect[s->aspect_ratio_info][1];
4305
    }
4306

    
4307
    if ((s->vol_control_parameters=get_bits1(gb))) { /* vol control parameter */
4308
        int chroma_format= get_bits(gb, 2);
4309
        if(chroma_format!=1){
4310
            printf("illegal chroma format\n");
4311
        }
4312
        s->low_delay= get_bits1(gb);
4313
        if(get_bits1(gb)){ /* vbv parameters */
4314
            get_bits(gb, 15);        /* first_half_bitrate */
4315
            skip_bits1(gb);        /* marker */
4316
            get_bits(gb, 15);        /* latter_half_bitrate */
4317
            skip_bits1(gb);        /* marker */
4318
            get_bits(gb, 15);        /* first_half_vbv_buffer_size */
4319
            skip_bits1(gb);        /* marker */
4320
            get_bits(gb, 3);        /* latter_half_vbv_buffer_size */
4321
            get_bits(gb, 11);        /* first_half_vbv_occupancy */
4322
            skip_bits1(gb);        /* marker */
4323
            get_bits(gb, 15);        /* latter_half_vbv_occupancy */
4324
            skip_bits1(gb);        /* marker */               
4325
        }
4326
    }else{
4327
        // set low delay flag only once so the smart? low delay detection wont be overriden
4328
        if(s->picture_number==0)
4329
            s->low_delay=0;
4330
    }
4331

    
4332
    s->shape = get_bits(gb, 2); /* vol shape */
4333
    if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");
4334
    if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
4335
        printf("Gray shape not supported\n");
4336
        skip_bits(gb, 4);  //video_object_layer_shape_extension
4337
    }
4338

    
4339
    skip_bits1(gb);   /* marker */
4340
    
4341
    s->time_increment_resolution = get_bits(gb, 16);
4342
    
4343
    s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
4344
    if (s->time_increment_bits < 1)
4345
        s->time_increment_bits = 1;
4346
    skip_bits1(gb);   /* marker */
4347

    
4348
    if (get_bits1(gb) != 0) {   /* fixed_vop_rate  */
4349
        skip_bits(gb, s->time_increment_bits);
4350
    }
4351

    
4352
    if (s->shape != BIN_ONLY_SHAPE) {
4353
        if (s->shape == RECT_SHAPE) {
4354
            skip_bits1(gb);   /* marker */
4355
            width = get_bits(gb, 13);
4356
            skip_bits1(gb);   /* marker */
4357
            height = get_bits(gb, 13);
4358
            skip_bits1(gb);   /* marker */
4359
            if(width && height){ /* they should be non zero but who knows ... */
4360
                s->width = width;
4361
                s->height = height;
4362
//                printf("width/height: %d %d\n", width, height);
4363
            }
4364
        }
4365
        
4366
        s->progressive_sequence= get_bits1(gb)^1;
4367
        if(!get_bits1(gb)) printf("OBMC not supported (very likely buggy encoder)\n");   /* OBMC Disable */
4368
        if (vo_ver_id == 1) {
4369
            s->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
4370
        } else {
4371
            s->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
4372
        }
4373
        if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");
4374
        if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
4375
            if(s->vol_sprite_usage==STATIC_SPRITE){
4376
                s->sprite_width = get_bits(gb, 13);
4377
                skip_bits1(gb); /* marker */
4378
                s->sprite_height= get_bits(gb, 13);
4379
                skip_bits1(gb); /* marker */
4380
                s->sprite_left  = get_bits(gb, 13);
4381
                skip_bits1(gb); /* marker */
4382
                s->sprite_top   = get_bits(gb, 13);
4383
                skip_bits1(gb); /* marker */
4384
            }
4385
            s->num_sprite_warping_points= get_bits(gb, 6);
4386
            s->sprite_warping_accuracy = get_bits(gb, 2);
4387
            s->sprite_brightness_change= get_bits1(gb);
4388
            if(s->vol_sprite_usage==STATIC_SPRITE)
4389
                s->low_latency_sprite= get_bits1(gb);            
4390
        }
4391
        // FIXME sadct disable bit if verid!=1 && shape not rect
4392
        
4393
        if (get_bits1(gb) == 1) {   /* not_8_bit */
4394
            s->quant_precision = get_bits(gb, 4); /* quant_precision */
4395
            if(get_bits(gb, 4)!=8) printf("N-bit not supported\n"); /* bits_per_pixel */
4396
            if(s->quant_precision!=5) printf("quant precission %d\n", s->quant_precision);
4397
        } else {
4398
            s->quant_precision = 5;
4399
        }
4400
        
4401
        // FIXME a bunch of grayscale shape things
4402

    
4403
        if((s->mpeg_quant=get_bits1(gb))){ /* vol_quant_type */
4404
            int i, v;
4405
            
4406
            /* load default matrixes */
4407
            for(i=0; i<64; i++){
4408
                int j= s->dsp.idct_permutation[i];
4409
                v= ff_mpeg4_default_intra_matrix[i];
4410
                s->intra_matrix[j]= v;
4411
                s->chroma_intra_matrix[j]= v;
4412
                
4413
                v= ff_mpeg4_default_non_intra_matrix[i];
4414
                s->inter_matrix[j]= v;
4415
                s->chroma_inter_matrix[j]= v;
4416
            }
4417

    
4418
            /* load custom intra matrix */
4419
            if(get_bits1(gb)){
4420
                int last=0;
4421
                for(i=0; i<64; i++){
4422
                    int j;
4423
                    v= get_bits(gb, 8);
4424
                    if(v==0) break;
4425
                    
4426
                    last= v;
4427
                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
4428
                    s->intra_matrix[j]= v;
4429
                    s->chroma_intra_matrix[j]= v;
4430
                }
4431

    
4432
                /* replicate last value */
4433
                for(; i<64; i++){
4434
                    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
4435
                    s->intra_matrix[j]= v;
4436
                    s->chroma_intra_matrix[j]= v;
4437
                }
4438
            }
4439

    
4440
            /* load custom non intra matrix */
4441
            if(get_bits1(gb)){
4442
                int last=0;
4443
                for(i=0; i<64; i++){
4444
                    int j;
4445
                    v= get_bits(gb, 8);
4446
                    if(v==0) break;
4447

    
4448
                    last= v;
4449
                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
4450
                    s->inter_matrix[j]= v;
4451
                    s->chroma_inter_matrix[j]= v;
4452
                }
4453

    
4454
                /* replicate last value */
4455
                for(; i<64; i++){
4456
                    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
4457
                    s->inter_matrix[j]= last;
4458
                    s->chroma_inter_matrix[j]= last;
4459
                }
4460
            }
4461

    
4462
            // FIXME a bunch of grayscale shape things
4463
        }
4464

    
4465
        if(vo_ver_id != 1)
4466
             s->quarter_sample= get_bits1(gb);
4467
        else s->quarter_sample=0;
4468

    
4469
        if(!get_bits1(gb)) printf("Complexity estimation not supported\n");
4470

    
4471
        s->resync_marker= !get_bits1(gb); /* resync_marker_disabled */
4472

    
4473
        s->data_partitioning= get_bits1(gb);
4474
        if(s->data_partitioning){
4475
            s->rvlc= get_bits1(gb);
4476
            if(s->rvlc){
4477
                printf("reversible vlc not supported\n");
4478
            }
4479
        }
4480
        
4481
        if(vo_ver_id != 1) {
4482
            s->new_pred= get_bits1(gb);
4483
            if(s->new_pred){
4484
                printf("new pred not supported\n");
4485
                skip_bits(gb, 2); /* requested upstream message type */
4486
                skip_bits1(gb); /* newpred segment type */
4487
            }
4488
            s->reduced_res_vop= get_bits1(gb);
4489
            if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");
4490
        }
4491
        else{
4492
            s->new_pred=0;
4493
            s->reduced_res_vop= 0;
4494
        }
4495

    
4496
        s->scalability= get_bits1(gb);
4497

    
4498
        if (s->scalability) {
4499
            GetBitContext bak= *gb;
4500
            int ref_layer_id;
4501
            int ref_layer_sampling_dir;
4502
            int h_sampling_factor_n;
4503
            int h_sampling_factor_m;
4504
            int v_sampling_factor_n;
4505
            int v_sampling_factor_m;
4506
            
4507
            s->hierachy_type= get_bits1(gb);
4508
            ref_layer_id= get_bits(gb, 4);
4509
            ref_layer_sampling_dir= get_bits1(gb);
4510
            h_sampling_factor_n= get_bits(gb, 5);
4511
            h_sampling_factor_m= get_bits(gb, 5);
4512
            v_sampling_factor_n= get_bits(gb, 5);
4513
            v_sampling_factor_m= get_bits(gb, 5);
4514
            s->enhancement_type= get_bits1(gb);
4515
            
4516
            if(   h_sampling_factor_n==0 || h_sampling_factor_m==0 
4517
               || v_sampling_factor_n==0 || v_sampling_factor_m==0){
4518
               
4519
//                fprintf(stderr, "illegal scalability header (VERY broken encoder), trying to workaround\n");
4520
                s->scalability=0;
4521
               
4522
                *gb= bak;
4523
            }else
4524
                printf("scalability not supported\n");
4525
            
4526
            // bin shape stuff FIXME
4527
        }
4528
    }
4529
    return 0;
4530
}
4531

    
4532
/**
4533
 * decodes the user data stuff in the header.
4534
 * allso inits divx/xvid/lavc_version/build
4535
 */
4536
static int decode_user_data(MpegEncContext *s, GetBitContext *gb){
4537
    char buf[256];
4538
    int i;
4539
    int e;
4540
    int ver, build, ver2, ver3;
4541

    
4542
    buf[0]= show_bits(gb, 8);
4543
    for(i=1; i<256; i++){
4544
        buf[i]= show_bits(gb, 16)&0xFF;
4545
        if(buf[i]==0) break;
4546
        skip_bits(gb, 8);
4547
    }
4548
    buf[255]=0;
4549
    
4550
    /* divx detection */
4551
    e=sscanf(buf, "DivX%dBuild%d", &ver, &build);
4552
    if(e!=2)
4553
        e=sscanf(buf, "DivX%db%d", &ver, &build);
4554
    if(e==2){
4555
        s->divx_version= ver;
4556
        s->divx_build= build;
4557
        if(s->picture_number==0){
4558
            printf("This file was encoded with DivX%d Build%d\n", ver, build);
4559
        }
4560
    }
4561
    
4562
    /* ffmpeg detection */
4563
    e=sscanf(buf, "FFmpeg%d.%d.%db%d", &ver, &ver2, &ver3, &build);
4564
    if(e!=4)
4565
        e=sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); 
4566
    if(e!=4){
4567
        if(strcmp(buf, "ffmpeg")==0){
4568
            s->ffmpeg_version= 0x000406;
4569
            s->lavc_build= 4600;
4570
        }
4571
    }
4572
    if(e==4){
4573
        s->ffmpeg_version= ver*256*256 + ver2*256 + ver3;
4574
        s->lavc_build= build;
4575
        if(s->picture_number==0)
4576
            printf("This file was encoded with libavcodec build %d\n", build);
4577
    }
4578
    
4579
    /* xvid detection */
4580
    e=sscanf(buf, "XviD%d", &build);
4581
    if(e==1){
4582
        s->xvid_build= build;
4583
        if(s->picture_number==0)
4584
            printf("This file was encoded with XviD build %d\n", build);
4585
    }
4586

    
4587
//printf("User Data: %s\n", buf);
4588
    return 0;
4589
}
4590

    
4591
static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){
4592
    int time_incr, time_increment;
4593

    
4594
    s->pict_type = get_bits(gb, 2) + I_TYPE;        /* pict type: I = 0 , P = 1 */
4595
    if(s->pict_type==B_TYPE && s->low_delay && s->vol_control_parameters==0){
4596
        printf("low_delay flag set, but shouldnt, clearing it\n");
4597
        s->low_delay=0;
4598
    }
4599
 
4600
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
4601
    if(s->partitioned_frame)
4602
        s->decode_mb= mpeg4_decode_partitioned_mb;
4603
    else
4604
        s->decode_mb= ff_h263_decode_mb;
4605

    
4606
    if(s->time_increment_resolution==0){
4607
        s->time_increment_resolution=1;
4608
//        fprintf(stderr, "time_increment_resolution is illegal\n");
4609
    }
4610
    time_incr=0;
4611
    while (get_bits1(gb) != 0) 
4612
        time_incr++;
4613

    
4614
    check_marker(gb, "before time_increment");
4615
    
4616
    if(s->picture_number==0 && (show_bits(gb, s->time_increment_bits+1)&1)==0){
4617
        printf("hmm, seems the headers arnt complete, trying to guess time_increment_bits\n");
4618
        
4619

    
4620
        for(s->time_increment_bits=1 ;s->time_increment_bits<16; s->time_increment_bits++){
4621
            if(show_bits(gb, s->time_increment_bits+1)&1) break;
4622
        }
4623
        printf("my guess is %d bits ;)\n",s->time_increment_bits);
4624
    }
4625
    
4626
    time_increment= get_bits(gb, s->time_increment_bits);
4627
//printf(" type:%d modulo_time_base:%d increment:%d\n", s->pict_type, time_incr, time_increment);
4628
    if(s->pict_type!=B_TYPE){
4629
        s->last_time_base= s->time_base;
4630
        s->time_base+= time_incr;
4631
        s->time= s->time_base*s->time_increment_resolution + time_increment;
4632
        if(s->workaround_bugs&FF_BUG_UMP4){
4633
            if(s->time < s->last_non_b_time){
4634
//                fprintf(stderr, "header is not mpeg4 compatible, broken encoder, trying to workaround\n");
4635
                s->time_base++;
4636
                s->time+= s->time_increment_resolution;
4637
            }
4638
        }
4639
        s->pp_time= s->time - s->last_non_b_time;
4640
        s->last_non_b_time= s->time;
4641
    }else{
4642
        s->time= (s->last_time_base + time_incr)*s->time_increment_resolution + time_increment;
4643
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
4644
        if(s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0){
4645
//            printf("messed up order, seeking?, skiping current b frame\n");
4646
            return FRAME_SKIPED;
4647
        }
4648
        
4649
        if(s->t_frame==0) s->t_frame= s->time - s->last_time_base;
4650
        if(s->t_frame==0) s->t_frame=1; // 1/0 protection
4651
//printf("%Ld %Ld %d %d\n", s->last_non_b_time, s->time, s->pp_time, s->t_frame); fflush(stdout);
4652
        s->pp_field_time= (  ROUNDED_DIV(s->last_non_b_time, s->t_frame) 
4653
                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
4654
        s->pb_field_time= (  ROUNDED_DIV(s->time, s->t_frame) 
4655
                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
4656
    }
4657
    
4658
    s->current_picture.pts= s->time*1000LL*1000LL / s->time_increment_resolution;
4659
    if(s->avctx->debug&FF_DEBUG_PTS)
4660
        printf("MPEG4 PTS: %f\n", s->current_picture.pts/(1000.0*1000.0));
4661
    
4662
    check_marker(gb, "before vop_coded");
4663
    
4664
    /* vop coded */
4665
    if (get_bits1(gb) != 1){
4666
        printf("vop not coded\n");
4667
        return FRAME_SKIPED;
4668
    }
4669
//printf("time %d %d %d || %Ld %Ld %Ld\n", s->time_increment_bits, s->time_increment_resolution, s->time_base,
4670
//s->time, s->last_non_b_time, s->last_non_b_time - s->pp_time);  
4671
    if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == P_TYPE
4672
                          || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {
4673
        /* rounding type for motion estimation */
4674
        s->no_rounding = get_bits1(gb);
4675
    } else {
4676
        s->no_rounding = 0;
4677
    }
4678
//FIXME reduced res stuff
4679

    
4680
     if (s->shape != RECT_SHAPE) {
4681
         if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {
4682
             int width, height, hor_spat_ref, ver_spat_ref;
4683
 
4684
             width = get_bits(gb, 13);
4685
             skip_bits1(gb);   /* marker */
4686
             height = get_bits(gb, 13);
4687
             skip_bits1(gb);   /* marker */
4688
             hor_spat_ref = get_bits(gb, 13); /* hor_spat_ref */
4689
             skip_bits1(gb);   /* marker */
4690
             ver_spat_ref = get_bits(gb, 13); /* ver_spat_ref */
4691
         }
4692
         skip_bits1(gb); /* change_CR_disable */
4693
 
4694
         if (get_bits1(gb) != 0) {