Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h263.c @ d2975f8d

History | View | Annotate | Download (156 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
//#define DEBUG
27
#include "common.h"
28
#include "dsputil.h"
29
#include "avcodec.h"
30
#include "mpegvideo.h"
31
#include "h263data.h"
32
#include "mpeg4data.h"
33

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

    
37
//rounded divison & shift
38
#define RSHIFT(a,b) ((a) > 0 ? ((a) + (1<<((b)-1)))>>(b) : ((a) + (1<<((b)-1))-1)>>(b))
39

    
40
#if 1
41
#define PRINT_MB_TYPE(a) {}
42
#else
43
#define PRINT_MB_TYPE(a) printf(a)
44
#endif
45

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

    
55
static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
56
                              int n);
57
static void h263_encode_motion(MpegEncContext * s, int val, int fcode);
58
static void h263p_encode_umotion(MpegEncContext * s, int val);
59
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
60
                               int n, int dc, UINT8 *scan_table, 
61
                               PutBitContext *dc_pb, PutBitContext *ac_pb);
62
static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
63
static int h263p_decode_umotion(MpegEncContext * s, int pred);
64
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
65
                             int n, int coded);
66
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr);
67
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
68
                              int n, int coded, int intra);
69
static int h263_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr);
70
static void mpeg4_inv_pred_ac(MpegEncContext * s, INT16 *block, int n,
71
                              int dir);
72
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s);
73
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr, int *dir_ptr);
74

    
75

    
76
extern UINT32 inverse[256];
77

    
78
static UINT16 mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
79
static UINT8 fcode_tab[MAX_MV*2+1];
80
static UINT8 umv_fcode_tab[MAX_MV*2+1];
81

    
82
static UINT16 uni_DCtab_lum  [512][2];
83
static UINT16 uni_DCtab_chrom[512][2];
84
static UINT32 uni_mpeg4_intra_rl_bits[64*64*2*2];
85
static UINT8  uni_mpeg4_intra_rl_len [64*64*2*2];
86
static UINT32 uni_mpeg4_inter_rl_bits[64*64*2*2];
87
static UINT8  uni_mpeg4_inter_rl_len [64*64*2*2];
88
#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
89
//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
90

    
91
/* mpeg4
92
inter
93
max level: 24/6
94
max run: 53/63
95

96
intra
97
max level: 53/16
98
max run: 29/41
99
*/
100

    
101
int h263_get_picture_format(int width, int height)
102
{
103
    int format;
104

    
105
    if (width == 128 && height == 96)
106
        format = 1;
107
    else if (width == 176 && height == 144)
108
        format = 2;
109
    else if (width == 352 && height == 288)
110
        format = 3;
111
    else if (width == 704 && height == 576)
112
        format = 4;
113
    else if (width == 1408 && height == 1152)
114
        format = 5;
115
    else
116
        format = 7;
117
    return format;
118
}
119

    
120
void h263_encode_picture_header(MpegEncContext * s, int picture_number)
121
{
122
    int format;
123

    
124
    align_put_bits(&s->pb);
125

    
126
    /* Update the pointer to last GOB */
127
    s->ptr_lastgob = pbBufPtr(&s->pb);
128
    s->gob_number = 0;
129

    
130
    put_bits(&s->pb, 22, 0x20); /* PSC */
131
    put_bits(&s->pb, 8, (((INT64)s->picture_number * 30 * FRAME_RATE_BASE) / 
132
                         s->frame_rate) & 0xff);
133

    
134
    put_bits(&s->pb, 1, 1);        /* marker */
135
    put_bits(&s->pb, 1, 0);        /* h263 id */
136
    put_bits(&s->pb, 1, 0);        /* split screen off */
137
    put_bits(&s->pb, 1, 0);        /* camera  off */
138
    put_bits(&s->pb, 1, 0);        /* freeze picture release off */
139
    
140
    format = h263_get_picture_format(s->width, s->height);
141
    if (!s->h263_plus) {
142
        /* H.263v1 */
143
        put_bits(&s->pb, 3, format);
144
        put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
145
        /* By now UMV IS DISABLED ON H.263v1, since the restrictions
146
        of H.263v1 UMV implies to check the predicted MV after
147
        calculation of the current MB to see if we're on the limits */
148
        put_bits(&s->pb, 1, 0);        /* unrestricted motion vector: off */
149
        put_bits(&s->pb, 1, 0);        /* SAC: off */
150
        put_bits(&s->pb, 1, 0);        /* advanced prediction mode: off */
151
        put_bits(&s->pb, 1, 0);        /* not PB frame */
152
        put_bits(&s->pb, 5, s->qscale);
153
        put_bits(&s->pb, 1, 0);        /* Continuous Presence Multipoint mode: off */
154
    } else {
155
        /* H.263v2 */
156
        /* H.263 Plus PTYPE */
157
        put_bits(&s->pb, 3, 7);
158
        put_bits(&s->pb,3,1); /* Update Full Extended PTYPE */
159
        if (format == 7)
160
            put_bits(&s->pb,3,6); /* Custom Source Format */
161
        else
162
            put_bits(&s->pb, 3, format);
163
            
164
        put_bits(&s->pb,1,0); /* Custom PCF: off */
165
        s->umvplus = (s->pict_type == P_TYPE) && s->unrestricted_mv;
166
        put_bits(&s->pb, 1, s->umvplus); /* Unrestricted Motion Vector */
167
        put_bits(&s->pb,1,0); /* SAC: off */
168
        put_bits(&s->pb,1,0); /* Advanced Prediction Mode: off */
169
        put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
170
        put_bits(&s->pb,1,0); /* Deblocking Filter: off */
171
        put_bits(&s->pb,1,0); /* Slice Structured: off */
172
        put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
173
        put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
174
        put_bits(&s->pb,1,0); /* Alternative Inter VLC: off */
175
        put_bits(&s->pb,1,0); /* Modified Quantization: off */
176
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
177
        put_bits(&s->pb,3,0); /* Reserved */
178
                
179
        put_bits(&s->pb, 3, s->pict_type == P_TYPE);
180
                
181
        put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
182
        put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
183
        if (s->pict_type == I_TYPE)
184
            s->no_rounding = 0;
185
        else
186
            s->no_rounding ^= 1;
187
        put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
188
        put_bits(&s->pb,2,0); /* Reserved */
189
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
190
                
191
        /* This should be here if PLUSPTYPE */
192
        put_bits(&s->pb, 1, 0);        /* Continuous Presence Multipoint mode: off */
193
                
194
                if (format == 7) {
195
            /* Custom Picture Format (CPFMT) */
196
                
197
            if (s->aspect_ratio_info)
198
                put_bits(&s->pb,4,s->aspect_ratio_info);
199
            else
200
                put_bits(&s->pb,4,2); /* Aspect ratio: CIF 12:11 (4:3) picture */
201
            put_bits(&s->pb,9,(s->width >> 2) - 1);
202
            put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
203
            put_bits(&s->pb,9,(s->height >> 2));
204
            if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
205
            {
206
                put_bits(&s->pb, 8, s->aspected_width);
207
                put_bits(&s->pb, 8, s->aspected_height);
208
            }
209
        }
210
        
211
        /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
212
        if (s->umvplus)
213
            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
214
        put_bits(&s->pb, 5, s->qscale);
215
    }
216

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

    
219
    if(s->h263_aic){
220
         s->y_dc_scale_table= 
221
         s->c_dc_scale_table= h263_aic_dc_scale_table;
222
    }else{
223
        s->y_dc_scale_table=
224
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
225
    }
226
}
227

    
228
int h263_encode_gob_header(MpegEncContext * s, int mb_line)
229
{
230
    int pdif=0;
231
    
232
    /* Check to see if we need to put a new GBSC */
233
    /* for RTP packetization                    */
234
    if (s->rtp_mode) {
235
        pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
236
        if (pdif >= s->rtp_payload_size) {
237
            /* Bad luck, packet must be cut before */
238
            align_put_bits(&s->pb);
239
            flush_put_bits(&s->pb);
240
            /* Call the RTP callback to send the last GOB */
241
            if (s->rtp_callback) {
242
                pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
243
                s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
244
            }
245
            s->ptr_lastgob = pbBufPtr(&s->pb);
246
            put_bits(&s->pb, 17, 1); /* GBSC */
247
            s->gob_number = mb_line / s->gob_index;
248
            put_bits(&s->pb, 5, s->gob_number); /* GN */
249
            put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
250
            put_bits(&s->pb, 5, s->qscale); /* GQUANT */
251
            //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
252
            return pdif;
253
       } else if (pdif + s->mb_line_avgsize >= s->rtp_payload_size) {
254
           /* Cut the packet before we can't */
255
           align_put_bits(&s->pb);
256
           flush_put_bits(&s->pb);
257
           /* Call the RTP callback to send the last GOB */
258
           if (s->rtp_callback) {
259
               pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
260
               s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
261
           }
262
           s->ptr_lastgob = pbBufPtr(&s->pb);
263
           put_bits(&s->pb, 17, 1); /* GBSC */
264
           s->gob_number = mb_line / s->gob_index;
265
           put_bits(&s->pb, 5, s->gob_number); /* GN */
266
           put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
267
           put_bits(&s->pb, 5, s->qscale); /* GQUANT */
268
           //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
269
           return pdif;
270
       }
271
   }
272
   return 0;
273
}
274

    
275
static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6])
276
{
277
    int score0=0, score1=0;
278
    int i, n;
279

    
280
    for(n=0; n<6; n++){
281
        INT16 *ac_val, *ac_val1;
282

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

    
334
    return score0 > score1 ? 1 : 0;    
335
}
336

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

    
353
/**
354
 * modify mb_type & qscale so that encoding is acually possible in mpeg4
355
 */
356
void ff_clean_mpeg4_qscales(MpegEncContext *s){
357
    int i;
358
    
359
    ff_clean_h263_qscales(s);
360
    
361
    for(i=1; i<s->mb_num; i++){
362
        if(s->qscale_table[i] != s->qscale_table[i-1] && (s->mb_type[i]&MB_TYPE_INTER4V)){
363
            s->mb_type[i]&= ~MB_TYPE_INTER4V;
364
            s->mb_type[i]|= MB_TYPE_INTER;
365
        }
366
    }
367

    
368
    if(s->pict_type== B_TYPE){
369
        int odd=0;
370
        /* ok, come on, this isnt funny anymore, theres more code for handling this mpeg4 mess than
371
           for the actual adaptive quantization */
372
        
373
        for(i=0; i<s->mb_num; i++){
374
            odd += s->qscale_table[i]&1;
375
        }
376
        
377
        if(2*odd > s->mb_num) odd=1;
378
        else                  odd=0;
379
        
380
        for(i=0; i<s->mb_num; i++){
381
            if((s->qscale_table[i]&1) != odd)
382
                s->qscale_table[i]++;
383
            if(s->qscale_table[i] > 31)
384
                s->qscale_table[i]= 31;
385
        }            
386
    
387
        for(i=1; i<s->mb_num; i++){
388
            if(s->qscale_table[i] != s->qscale_table[i-1] && (s->mb_type[i]&MB_TYPE_DIRECT)){
389
                s->mb_type[i]&= ~MB_TYPE_DIRECT;
390
                s->mb_type[i]|= MB_TYPE_BIDIR;
391
            }
392
        }
393
    }
394
}
395

    
396
void mpeg4_encode_mb(MpegEncContext * s,
397
                    DCTELEM block[6][64],
398
                    int motion_x, int motion_y)
399
{
400
    int cbpc, cbpy, i, pred_x, pred_y;
401
    int bits;
402
    PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
403
    PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=B_TYPE ? &s->tex_pb : &s->pb;
404
    PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=I_TYPE ? &s->pb2    : &s->pb;
405
    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
406
    const int dquant_code[5]= {1,0,9,2,3};
407
    
408
    //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
409
    if (!s->mb_intra) {
410
        /* compute cbp */
411
        int cbp = 0;
412
        for (i = 0; i < 6; i++) {
413
            if (s->block_last_index[i] >= 0)
414
                cbp |= 1 << (5 - i);
415
        }
416

    
417
        if(s->pict_type==B_TYPE){
418
            static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
419
            int mb_type=  mb_type_table[s->mv_dir];
420
            
421
            if(s->mb_x==0){
422
                s->last_mv[0][0][0]= 
423
                s->last_mv[0][0][1]= 
424
                s->last_mv[1][0][0]= 
425
                s->last_mv[1][0][1]= 0;
426
            }
427
            
428
            assert(s->dquant>=-2 && s->dquant<=2);
429
            assert((s->dquant&1)==0);
430
            assert(mb_type>=0);
431

    
432
            /* nothing to do if this MB was skiped in the next P Frame */
433
            if(s->mbskip_table[s->mb_y * s->mb_width + s->mb_x]){ //FIXME avoid DCT & ...
434
                s->skip_count++;
435
                s->mv[0][0][0]= 
436
                s->mv[0][0][1]= 
437
                s->mv[1][0][0]= 
438
                s->mv[1][0][1]= 0;
439
                s->mv_dir= MV_DIR_FORWARD; //doesnt matter
440
                s->qscale -= s->dquant;
441
                return;
442
            }
443

    
444
            if ((cbp | motion_x | motion_y | mb_type) ==0) {
445
                /* direct MB with MV={0,0} */
446
                assert(s->dquant==0);
447
                
448
                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
449

    
450
                if(interleaved_stats){
451
                    s->misc_bits++;
452
                    s->last_bits++;
453
                }
454
                s->skip_count++;
455
                return;
456
            }
457
            put_bits(&s->pb, 1, 0);        /* mb coded modb1=0 */
458
            put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
459
            put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we dont need it :)
460
            if(cbp) put_bits(&s->pb, 6, cbp);
461
            
462
            if(cbp && mb_type){
463
                if(s->dquant)
464
                    put_bits(&s->pb, 2, (s->dquant>>2)+3);
465
                else
466
                    put_bits(&s->pb, 1, 0);
467
            }else
468
                s->qscale -= s->dquant;
469
            
470
            if(!s->progressive_sequence){
471
                if(cbp)
472
                    put_bits(&s->pb, 1, s->interlaced_dct);
473
                if(mb_type) // not diect mode
474
                    put_bits(&s->pb, 1, 0); // no interlaced ME yet
475
            }
476

    
477
            if(interleaved_stats){
478
                bits= get_bit_count(&s->pb);
479
                s->misc_bits+= bits - s->last_bits;
480
                s->last_bits=bits;
481
            }
482

    
483
            switch(mb_type)
484
            {
485
            case 0: /* direct */
486
                h263_encode_motion(s, motion_x, 1);
487
                h263_encode_motion(s, motion_y, 1);                
488
                s->b_count++;
489
                s->f_count++;
490
                break;
491
            case 1: /* bidir */
492
                h263_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
493
                h263_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
494
                h263_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
495
                h263_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
496
                s->last_mv[0][0][0]= s->mv[0][0][0];
497
                s->last_mv[0][0][1]= s->mv[0][0][1];
498
                s->last_mv[1][0][0]= s->mv[1][0][0];
499
                s->last_mv[1][0][1]= s->mv[1][0][1];
500
                s->b_count++;
501
                s->f_count++;
502
                break;
503
            case 2: /* backward */
504
                h263_encode_motion(s, motion_x - s->last_mv[1][0][0], s->b_code);
505
                h263_encode_motion(s, motion_y - s->last_mv[1][0][1], s->b_code);
506
                s->last_mv[1][0][0]= motion_x;
507
                s->last_mv[1][0][1]= motion_y;
508
                s->b_count++;
509
                break;
510
            case 3: /* forward */
511
                h263_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);
512
                h263_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);
513
                s->last_mv[0][0][0]= motion_x;
514
                s->last_mv[0][0][1]= motion_y;
515
                s->f_count++;
516
                break;
517
            default:
518
                printf("unknown mb type\n");
519
                return;
520
            }
521

    
522
            if(interleaved_stats){
523
                bits= get_bit_count(&s->pb);
524
                s->mv_bits+= bits - s->last_bits;
525
                s->last_bits=bits;
526
            }
527

    
528
            /* encode each block */
529
            for (i = 0; i < 6; i++) {
530
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, &s->pb);
531
            }
532

    
533
            if(interleaved_stats){
534
                bits= get_bit_count(&s->pb);
535
                s->p_tex_bits+= bits - s->last_bits;
536
                s->last_bits=bits;
537
            }
538
        }else{ /* s->pict_type==B_TYPE */
539
            if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
540
                /* check if the B frames can skip it too, as we must skip it if we skip here 
541
                   why didnt they just compress the skip-mb bits instead of reusing them ?! */
542
                if(s->max_b_frames>0){
543
                    int i;
544
                    int x,y, offset;
545
                    uint8_t *p_pic;
546

    
547
                    x= s->mb_x*16;
548
                    y= s->mb_y*16;
549
                    if(x+16 > s->width)  x= s->width-16;
550
                    if(y+16 > s->height) y= s->height-16;
551

    
552
                    offset= x + y*s->linesize;
553
                    p_pic= s->new_picture[0] + offset;
554
                    
555
                    s->mb_skiped=1;
556
                    for(i=0; i<s->max_b_frames; i++){
557
                        uint8_t *b_pic;
558
                        int diff;
559

    
560
                        if(s->coded_order[i+1].pict_type!=B_TYPE) break;
561

    
562
                        b_pic= s->coded_order[i+1].picture[0] + offset;
563
                        diff= pix_abs16x16(p_pic, b_pic, s->linesize);
564
                        if(diff>s->qscale*70){ //FIXME check that 70 is optimal
565
                            s->mb_skiped=0;
566
                            break;
567
                        }
568
                    }
569
                }else
570
                    s->mb_skiped=1; 
571

    
572
                if(s->mb_skiped==1){
573
                    /* skip macroblock */
574
                    put_bits(&s->pb, 1, 1);
575

    
576
                    if(interleaved_stats){
577
                        s->misc_bits++;
578
                        s->last_bits++;
579
                    }
580
                    s->skip_count++;
581
                    return;
582
                }
583
            }
584

    
585
            put_bits(&s->pb, 1, 0);        /* mb coded */
586
            if(s->mv_type==MV_TYPE_16X16){
587
                cbpc = cbp & 3;
588
                if(s->dquant) cbpc+= 8;
589
                put_bits(&s->pb,
590
                        inter_MCBPC_bits[cbpc],
591
                        inter_MCBPC_code[cbpc]);
592

    
593
                cbpy = cbp >> 2;
594
                cbpy ^= 0xf;
595
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
596
                if(s->dquant)
597
                    put_bits(pb2, 2, dquant_code[s->dquant+2]);
598

    
599
                if(!s->progressive_sequence){
600
                    if(cbp)
601
                        put_bits(pb2, 1, s->interlaced_dct);
602
                    put_bits(pb2, 1, 0); // no interlaced ME yet
603
                }
604
                    
605
                if(interleaved_stats){
606
                    bits= get_bit_count(&s->pb);
607
                    s->misc_bits+= bits - s->last_bits;
608
                    s->last_bits=bits;
609
                }
610

    
611
                /* motion vectors: 16x16 mode */
612
                h263_pred_motion(s, 0, &pred_x, &pred_y);
613
            
614
                h263_encode_motion(s, motion_x - pred_x, s->f_code);
615
                h263_encode_motion(s, motion_y - pred_y, s->f_code);
616
            }else{
617
                cbpc = (cbp & 3)+16;
618
                put_bits(&s->pb,
619
                        inter_MCBPC_bits[cbpc],
620
                        inter_MCBPC_code[cbpc]);
621
                cbpy = cbp >> 2;
622
                cbpy ^= 0xf;
623
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
624

    
625
                if(interleaved_stats){
626
                    bits= get_bit_count(&s->pb);
627
                    s->misc_bits+= bits - s->last_bits;
628
                    s->last_bits=bits;
629
                }
630

    
631
                for(i=0; i<4; i++){
632
                    /* motion vectors: 8x8 mode*/
633
                    h263_pred_motion(s, i, &pred_x, &pred_y);
634

    
635
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x, s->f_code);
636
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y, s->f_code);
637
                }
638
            }
639

    
640
            if(interleaved_stats){ 
641
                bits= get_bit_count(&s->pb);
642
                s->mv_bits+= bits - s->last_bits;
643
                s->last_bits=bits;
644
            }
645

    
646
            /* encode each block */
647
            for (i = 0; i < 6; i++) {
648
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, tex_pb);
649
            }
650

    
651
            if(interleaved_stats){
652
                bits= get_bit_count(&s->pb);
653
                s->p_tex_bits+= bits - s->last_bits;
654
                s->last_bits=bits;
655
            }
656
            s->f_count++;
657
        }
658
    } else {
659
        int cbp;
660
        int dc_diff[6];   //dc values with the dc prediction subtracted 
661
        int dir[6];  //prediction direction
662
        int zigzag_last_index[6];
663
        UINT8 *scan_table[6];
664

    
665
        for(i=0; i<6; i++){
666
            const int level= block[i][0];
667
            UINT16 *dc_ptr;
668

    
669
            dc_diff[i]= level - ff_mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
670
            if (i < 4) {
671
                *dc_ptr = level * s->y_dc_scale;
672
            } else {
673
                *dc_ptr = level * s->c_dc_scale;
674
            }
675
        }
676

    
677
        s->ac_pred= decide_ac_pred(s, block, dir);
678

    
679
        if(s->ac_pred){
680
            for(i=0; i<6; i++){
681
                UINT8 *st;
682
                int last_index;
683

    
684
                mpeg4_inv_pred_ac(s, block[i], i, dir[i]);
685
                if (dir[i]==0) st = s->intra_v_scantable.permutated; /* left */
686
                else           st = s->intra_h_scantable.permutated; /* top */
687

    
688
                for(last_index=63; last_index>=0; last_index--) //FIXME optimize
689
                    if(block[i][st[last_index]]) break;
690
                zigzag_last_index[i]= s->block_last_index[i];
691
                s->block_last_index[i]= last_index;
692
                scan_table[i]= st;
693
            }
694
        }else{
695
            for(i=0; i<6; i++)
696
                scan_table[i]= s->intra_scantable.permutated;
697
        }
698

    
699
        /* compute cbp */
700
        cbp = 0;
701
        for (i = 0; i < 6; i++) {
702
            if (s->block_last_index[i] >= 1)
703
                cbp |= 1 << (5 - i);
704
        }
705

    
706
        cbpc = cbp & 3;
707
        if (s->pict_type == I_TYPE) {
708
            if(s->dquant) cbpc+=4;
709
            put_bits(&s->pb,
710
                intra_MCBPC_bits[cbpc],
711
                intra_MCBPC_code[cbpc]);
712
        } else {
713
            if(s->dquant) cbpc+=8;
714
            put_bits(&s->pb, 1, 0);        /* mb coded */
715
            put_bits(&s->pb,
716
                inter_MCBPC_bits[cbpc + 4],
717
                inter_MCBPC_code[cbpc + 4]);
718
        }
719
        put_bits(pb2, 1, s->ac_pred);
720
        cbpy = cbp >> 2;
721
        put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
722
        if(s->dquant)
723
            put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
724

    
725
        if(!s->progressive_sequence){
726
            put_bits(dc_pb, 1, s->interlaced_dct);
727
        }
728

    
729
        if(interleaved_stats){
730
            bits= get_bit_count(&s->pb);
731
            s->misc_bits+= bits - s->last_bits;
732
            s->last_bits=bits;
733
        }
734

    
735
        /* encode each block */
736
        for (i = 0; i < 6; i++) {
737
            mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
738
        }
739

    
740
        if(interleaved_stats){
741
            bits= get_bit_count(&s->pb);
742
            s->i_tex_bits+= bits - s->last_bits;
743
            s->last_bits=bits;
744
        }
745
        s->i_count++;
746

    
747
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
748
        if(s->ac_pred){
749
            for(i=0; i<6; i++){
750
                int j;    
751
                INT16 *ac_val;
752

    
753
                ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
754

    
755
                if(dir[i]){
756
                    for(j=1; j<8; j++) 
757
                        block[i][s->idct_permutation[j   ]]= ac_val[j+8];
758
                }else{
759
                    for(j=1; j<8; j++) 
760
                        block[i][s->idct_permutation[j<<3]]= ac_val[j  ];
761
                }
762
                s->block_last_index[i]= zigzag_last_index[i];
763
            }
764
        }
765
    }
766
}
767

    
768
void h263_encode_mb(MpegEncContext * s,
769
                    DCTELEM block[6][64],
770
                    int motion_x, int motion_y)
771
{
772
    int cbpc, cbpy, i, cbp, pred_x, pred_y;
773
    INT16 pred_dc;
774
    INT16 rec_intradc[6];
775
    UINT16 *dc_ptr[6];
776
    const int dquant_code[5]= {1,0,9,2,3};
777
           
778
    //printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
779
    if (!s->mb_intra) {
780
        /* compute cbp */
781
        cbp = 0;
782
        for (i = 0; i < 6; i++) {
783
            if (s->block_last_index[i] >= 0)
784
                cbp |= 1 << (5 - i);
785
        }
786
        if ((cbp | motion_x | motion_y | s->dquant) == 0) {
787
            /* skip macroblock */
788
            put_bits(&s->pb, 1, 1);
789
            return;
790
        }
791
        put_bits(&s->pb, 1, 0);        /* mb coded */
792
        cbpc = cbp & 3;
793
        if(s->dquant) cbpc+= 8;
794
        put_bits(&s->pb,
795
                    inter_MCBPC_bits[cbpc],
796
                    inter_MCBPC_code[cbpc]);
797
        cbpy = cbp >> 2;
798
        cbpy ^= 0xf;
799
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
800
        if(s->dquant)
801
            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
802

    
803
        /* motion vectors: 16x16 mode only now */
804
        h263_pred_motion(s, 0, &pred_x, &pred_y);
805
      
806
        if (!s->umvplus) {  
807
            h263_encode_motion(s, motion_x - pred_x, s->f_code);
808
            h263_encode_motion(s, motion_y - pred_y, s->f_code);
809
        }
810
        else {
811
            h263p_encode_umotion(s, motion_x - pred_x);
812
            h263p_encode_umotion(s, motion_y - pred_y);
813
            if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
814
                /* To prevent Start Code emulation */
815
                put_bits(&s->pb,1,1);
816
        }
817
    } else {
818
        int li = s->h263_aic ? 0 : 1;
819
        
820
        cbp = 0;
821
        for(i=0; i<6; i++) {
822
            /* Predict DC */
823
            if (s->h263_aic && s->mb_intra) {
824
                INT16 level = block[i][0];
825
            
826
                pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
827
                level -= pred_dc;
828
                /* Quant */
829
                if (level < 0)
830
                    level = (level + (s->qscale >> 1))/(s->y_dc_scale);
831
                else
832
                    level = (level - (s->qscale >> 1))/(s->y_dc_scale);
833
                    
834
                /* AIC can change CBP */
835
                if (level == 0 && s->block_last_index[i] == 0)
836
                    s->block_last_index[i] = -1;
837
                else if (level < -127)
838
                    level = -127;
839
                else if (level > 127)
840
                    level = 127;
841
                
842
                block[i][0] = level;
843
                /* Reconstruction */ 
844
                rec_intradc[i] = (s->y_dc_scale*level) + pred_dc;
845
                /* Oddify */
846
                rec_intradc[i] |= 1;
847
                //if ((rec_intradc[i] % 2) == 0)
848
                //    rec_intradc[i]++;
849
                /* Clipping */
850
                if (rec_intradc[i] < 0)
851
                    rec_intradc[i] = 0;
852
                else if (rec_intradc[i] > 2047)
853
                    rec_intradc[i] = 2047;
854
                                
855
                /* Update AC/DC tables */
856
                *dc_ptr[i] = rec_intradc[i];
857
            }
858
            /* compute cbp */
859
            if (s->block_last_index[i] >= li)
860
                cbp |= 1 << (5 - i);
861
        }
862

    
863
        cbpc = cbp & 3;
864
        if (s->pict_type == I_TYPE) {
865
            if(s->dquant) cbpc+=4;
866
            put_bits(&s->pb,
867
                intra_MCBPC_bits[cbpc],
868
                intra_MCBPC_code[cbpc]);
869
        } else {
870
            if(s->dquant) cbpc+=8;
871
            put_bits(&s->pb, 1, 0);        /* mb coded */
872
            put_bits(&s->pb,
873
                inter_MCBPC_bits[cbpc + 4],
874
                inter_MCBPC_code[cbpc + 4]);
875
        }
876
        if (s->h263_aic) {
877
            /* XXX: currently, we do not try to use ac prediction */
878
            put_bits(&s->pb, 1, 0);        /* no AC prediction */
879
        }
880
        cbpy = cbp >> 2;
881
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
882
        if(s->dquant)
883
            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
884
    }
885

    
886
    for(i=0; i<6; i++) {
887
        /* encode each block */
888
        h263_encode_block(s, block[i], i);
889
    
890
        /* Update INTRADC for decoding */
891
        if (s->h263_aic && s->mb_intra) {
892
            block[i][0] = rec_intradc[i];
893
            
894
        }
895
    }
896
}
897

    
898
static int h263_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr)
899
{
900
    int x, y, wrap, a, c, pred_dc, scale;
901
    INT16 *dc_val, *ac_val;
902

    
903
    /* find prediction */
904
    if (n < 4) {
905
        x = 2 * s->mb_x + 1 + (n & 1);
906
        y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
907
        wrap = s->mb_width * 2 + 2;
908
        dc_val = s->dc_val[0];
909
        ac_val = s->ac_val[0][0];
910
        scale = s->y_dc_scale;
911
    } else {
912
        x = s->mb_x + 1;
913
        y = s->mb_y + 1;
914
        wrap = s->mb_width + 2;
915
        dc_val = s->dc_val[n - 4 + 1];
916
        ac_val = s->ac_val[n - 4 + 1][0];
917
        scale = s->c_dc_scale;
918
    }
919
    /* B C
920
     * A X 
921
     */
922
    a = dc_val[(x - 1) + (y) * wrap];
923
    c = dc_val[(x) + (y - 1) * wrap];
924
    
925
    /* No prediction outside GOB boundary */
926
    if (s->first_slice_line && ((n < 2) || (n > 3)))
927
        c = 1024;
928
    pred_dc = 1024;
929
    /* just DC prediction */
930
    if (a != 1024 && c != 1024)
931
        pred_dc = (a + c) >> 1;
932
    else if (a != 1024)
933
        pred_dc = a;
934
    else
935
        pred_dc = c;
936
    
937
    /* we assume pred is positive */
938
    //pred_dc = (pred_dc + (scale >> 1)) / scale;
939
    *dc_val_ptr = &dc_val[x + y * wrap];
940
    return pred_dc;
941
}
942

    
943

    
944
void h263_pred_acdc(MpegEncContext * s, INT16 *block, int n)
945
{
946
    int x, y, wrap, a, c, pred_dc, scale, i;
947
    INT16 *dc_val, *ac_val, *ac_val1;
948

    
949
    /* find prediction */
950
    if (n < 4) {
951
        x = 2 * s->mb_x + 1 + (n & 1);
952
        y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
953
        wrap = s->mb_width * 2 + 2;
954
        dc_val = s->dc_val[0];
955
        ac_val = s->ac_val[0][0];
956
        scale = s->y_dc_scale;
957
    } else {
958
        x = s->mb_x + 1;
959
        y = s->mb_y + 1;
960
        wrap = s->mb_width + 2;
961
        dc_val = s->dc_val[n - 4 + 1];
962
        ac_val = s->ac_val[n - 4 + 1][0];
963
        scale = s->c_dc_scale;
964
    }
965
    
966
    ac_val += ((y) * wrap + (x)) * 16;
967
    ac_val1 = ac_val;
968
    
969
    /* B C
970
     * A X 
971
     */
972
    a = dc_val[(x - 1) + (y) * wrap];
973
    c = dc_val[(x) + (y - 1) * wrap];
974
    
975
    /* No prediction outside GOB boundary */
976
    if (s->first_slice_line && ((n < 2) || (n > 3)))
977
        c = 1024;
978
    pred_dc = 1024;
979
    if (s->ac_pred) {
980
        if (s->h263_aic_dir) {
981
            /* left prediction */
982
            if (a != 1024) {
983
                ac_val -= 16;
984
                for(i=1;i<8;i++) {
985
                    block[s->idct_permutation[i<<3]] += ac_val[i];
986
                }
987
                pred_dc = a;
988
            }
989
        } else {
990
            /* top prediction */
991
            if (c != 1024) {
992
                ac_val -= 16 * wrap;
993
                for(i=1;i<8;i++) {
994
                    block[s->idct_permutation[i   ]] += ac_val[i + 8];
995
                }
996
                pred_dc = c;
997
            }
998
        }
999
    } else {
1000
        /* just DC prediction */
1001
        if (a != 1024 && c != 1024)
1002
            pred_dc = (a + c) >> 1;
1003
        else if (a != 1024)
1004
            pred_dc = a;
1005
        else
1006
            pred_dc = c;
1007
    }
1008
    
1009
    /* we assume pred is positive */
1010
    block[0]=block[0]*scale + pred_dc;
1011
    
1012
    if (block[0] < 0)
1013
        block[0] = 0;
1014
    else if (!(block[0] & 1))
1015
        block[0]++;
1016
    
1017
    /* Update AC/DC tables */
1018
    dc_val[(x) + (y) * wrap] = block[0];
1019
    
1020
    /* left copy */
1021
    for(i=1;i<8;i++)
1022
        ac_val1[i    ] = block[s->idct_permutation[i<<3]];
1023
    /* top copy */
1024
    for(i=1;i<8;i++)
1025
        ac_val1[8 + i] = block[s->idct_permutation[i   ]];
1026
}
1027

    
1028
INT16 *h263_pred_motion(MpegEncContext * s, int block, 
1029
                        int *px, int *py)
1030
{
1031
    int xy, wrap;
1032
    INT16 *A, *B, *C, *mot_val;
1033
    static const int off[4]= {2, 1, 1, -1};
1034

    
1035
    wrap = s->block_wrap[0];
1036
    xy = s->block_index[block];
1037

    
1038
    mot_val = s->motion_val[xy];
1039

    
1040
    A = s->motion_val[xy - 1];
1041
    /* special case for first (slice) line */
1042
    if (s->first_slice_line && block<3) {
1043
        // we cant just change some MVs to simulate that as we need them for the B frames (and ME)
1044
        // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1045
        if(block==0){ //most common case
1046
            if(s->mb_x  == s->resync_mb_x){ //rare
1047
                *px= *py = 0;
1048
            }else if(s->mb_x + 1 == s->resync_mb_x){ //rare
1049
                C = s->motion_val[xy + off[block] - wrap];
1050
                if(s->mb_x==0){
1051
                    *px = C[0];
1052
                    *py = C[1];
1053
                }else{
1054
                    *px = mid_pred(A[0], 0, C[0]);
1055
                    *py = mid_pred(A[1], 0, C[1]);
1056
                }
1057
            }else{
1058
                *px = A[0];
1059
                *py = A[1];
1060
            }
1061
        }else if(block==1){
1062
            if(s->mb_x + 1 == s->resync_mb_x){ //rare
1063
                C = s->motion_val[xy + off[block] - wrap];
1064
                *px = mid_pred(A[0], 0, C[0]);
1065
                *py = mid_pred(A[1], 0, C[1]);
1066
            }else{
1067
                *px = A[0];
1068
                *py = A[1];
1069
            }
1070
        }else{ /* block==2*/
1071
            B = s->motion_val[xy - wrap];
1072
            C = s->motion_val[xy + off[block] - wrap];
1073
            if(s->mb_x == s->resync_mb_x) //rare
1074
                A[0]=A[1]=0;
1075
    
1076
            *px = mid_pred(A[0], B[0], C[0]);
1077
            *py = mid_pred(A[1], B[1], C[1]);
1078
        }
1079
    } else {
1080
        B = s->motion_val[xy - wrap];
1081
        C = s->motion_val[xy + off[block] - wrap];
1082
        *px = mid_pred(A[0], B[0], C[0]);
1083
        *py = mid_pred(A[1], B[1], C[1]);
1084
    }
1085
    return mot_val;
1086
}
1087

    
1088
static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
1089
{
1090
    int range, l, bit_size, sign, code, bits;
1091

    
1092
    if (val == 0) {
1093
        /* zero vector */
1094
        code = 0;
1095
        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1096
    } else {
1097
        bit_size = f_code - 1;
1098
        range = 1 << bit_size;
1099
        /* modulo encoding */
1100
        l = range * 32;
1101
#if 1
1102
        val+= l;
1103
        val&= 2*l-1;
1104
        val-= l;
1105
        sign = val>>31;
1106
        val= (val^sign)-sign;
1107
        sign&=1;
1108
#else
1109
        if (val < -l) {
1110
            val += 2*l;
1111
        } else if (val >= l) {
1112
            val -= 2*l;
1113
        }
1114

    
1115
        assert(val>=-l && val<l);
1116

    
1117
        if (val >= 0) {
1118
            sign = 0;
1119
        } else {
1120
            val = -val;
1121
            sign = 1;
1122
        }
1123
#endif
1124
        val--;
1125
        code = (val >> bit_size) + 1;
1126
        bits = val & (range - 1);
1127

    
1128
        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
1129
        if (bit_size > 0) {
1130
            put_bits(&s->pb, bit_size, bits);
1131
        }
1132
    }
1133

    
1134
}
1135

    
1136
/* Encode MV differences on H.263+ with Unrestricted MV mode */
1137
static void h263p_encode_umotion(MpegEncContext * s, int val)
1138
{
1139
    short sval = 0; 
1140
    short i = 0;
1141
    short n_bits = 0;
1142
    short temp_val;
1143
    int code = 0;
1144
    int tcode;
1145
    
1146
    if ( val == 0)
1147
        put_bits(&s->pb, 1, 1);
1148
    else if (val == 1)
1149
        put_bits(&s->pb, 3, 0);
1150
    else if (val == -1)
1151
        put_bits(&s->pb, 3, 2);
1152
    else {
1153
        
1154
        sval = ((val < 0) ? (short)(-val):(short)val);
1155
        temp_val = sval;
1156
        
1157
        while (temp_val != 0) {
1158
            temp_val = temp_val >> 1;
1159
            n_bits++;
1160
        }
1161
        
1162
        i = n_bits - 1;
1163
        while (i > 0) {
1164
            tcode = (sval & (1 << (i-1))) >> (i-1);
1165
            tcode = (tcode << 1) | 1;
1166
            code = (code << 2) | tcode;
1167
            i--;
1168
        }
1169
        code = ((code << 1) | (val < 0)) << 1;
1170
        put_bits(&s->pb, (2*n_bits)+1, code);
1171
        //printf("\nVal = %d\tCode = %d", sval, code);
1172
    }
1173
}
1174

    
1175
static void init_mv_penalty_and_fcode(MpegEncContext *s)
1176
{
1177
    int f_code;
1178
    int mv;
1179
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
1180
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1181
            int len;
1182

    
1183
            if(mv==0) len= mvtab[0][1];
1184
            else{
1185
                int val, bit_size, range, code;
1186

    
1187
                bit_size = s->f_code - 1;
1188
                range = 1 << bit_size;
1189

    
1190
                val=mv;
1191
                if (val < 0) 
1192
                    val = -val;
1193
                val--;
1194
                code = (val >> bit_size) + 1;
1195
                if(code<33){
1196
                    len= mvtab[code][1] + 1 + bit_size;
1197
                }else{
1198
                    len= mvtab[32][1] + 2 + bit_size;
1199
                }
1200
            }
1201

    
1202
            mv_penalty[f_code][mv+MAX_MV]= len;
1203
        }
1204
    }
1205

    
1206
    for(f_code=MAX_FCODE; f_code>0; f_code--){
1207
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1208
            fcode_tab[mv+MAX_MV]= f_code;
1209
        }
1210
    }
1211

    
1212
    for(mv=0; mv<MAX_MV*2+1; mv++){
1213
        umv_fcode_tab[mv]= 1;
1214
    }
1215
}
1216

    
1217
static void init_uni_dc_tab(void)
1218
{
1219
    int level, uni_code, uni_len;
1220

    
1221
    for(level=-256; level<256; level++){
1222
        int size, v, l;
1223
        /* find number of bits */
1224
        size = 0;
1225
        v = abs(level);
1226
        while (v) {
1227
            v >>= 1;
1228
            size++;
1229
        }
1230

    
1231
        if (level < 0)
1232
            l= (-level) ^ ((1 << size) - 1);
1233
        else
1234
            l= level;
1235

    
1236
        /* luminance */
1237
        uni_code= DCtab_lum[size][0];
1238
        uni_len = DCtab_lum[size][1];
1239

    
1240
        if (size > 0) {
1241
            uni_code<<=size; uni_code|=l;
1242
            uni_len+=size;
1243
            if (size > 8){
1244
                uni_code<<=1; uni_code|=1;
1245
                uni_len++;
1246
            }
1247
        }
1248
        uni_DCtab_lum[level+256][0]= uni_code;
1249
        uni_DCtab_lum[level+256][1]= uni_len;
1250

    
1251
        /* chrominance */
1252
        uni_code= DCtab_chrom[size][0];
1253
        uni_len = DCtab_chrom[size][1];
1254
        
1255
        if (size > 0) {
1256
            uni_code<<=size; uni_code|=l;
1257
            uni_len+=size;
1258
            if (size > 8){
1259
                uni_code<<=1; uni_code|=1;
1260
                uni_len++;
1261
            }
1262
        }
1263
        uni_DCtab_chrom[level+256][0]= uni_code;
1264
        uni_DCtab_chrom[level+256][1]= uni_len;
1265

    
1266
    }
1267
}
1268

    
1269
static void init_uni_mpeg4_rl_tab(RLTable *rl, UINT32 *bits_tab, UINT8 *len_tab){
1270
    int slevel, run, last;
1271
    
1272
    assert(MAX_LEVEL >= 64);
1273
    assert(MAX_RUN   >= 63);
1274

    
1275
    for(slevel=-64; slevel<64; slevel++){
1276
        if(slevel==0) continue;
1277
        for(run=0; run<64; run++){
1278
            for(last=0; last<=1; last++){
1279
                const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1280
                int level= slevel < 0 ? -slevel : slevel;
1281
                int sign= slevel < 0 ? 1 : 0;
1282
                int bits, len, code;
1283
                int level1, run1;
1284
                
1285
                len_tab[index]= 100;
1286
                     
1287
                /* ESC0 */
1288
                code= get_rl_index(rl, last, run, level);
1289
                bits= rl->table_vlc[code][0];
1290
                len=  rl->table_vlc[code][1];
1291
                bits=bits*2+sign; len++;
1292
                
1293
                if(code!=rl->n && len < len_tab[index]){
1294
                    bits_tab[index]= bits;
1295
                    len_tab [index]= len;
1296
                }
1297
#if 1
1298
                /* ESC1 */
1299
                bits= rl->table_vlc[rl->n][0];
1300
                len=  rl->table_vlc[rl->n][1];
1301
                bits=bits*2;    len++; //esc1
1302
                level1= level - rl->max_level[last][run];
1303
                if(level1>0){
1304
                    code= get_rl_index(rl, last, run, level1);
1305
                    bits<<= rl->table_vlc[code][1];
1306
                    len  += rl->table_vlc[code][1];
1307
                    bits += rl->table_vlc[code][0];
1308
                    bits=bits*2+sign; len++;
1309
                
1310
                    if(code!=rl->n && len < len_tab[index]){
1311
                        bits_tab[index]= bits;
1312
                        len_tab [index]= len;
1313
                    }
1314
                }
1315
#endif 
1316
#if 1
1317
                /* ESC2 */
1318
                bits= rl->table_vlc[rl->n][0];
1319
                len=  rl->table_vlc[rl->n][1];
1320
                bits=bits*4+2;    len+=2; //esc2
1321
                run1 = run - rl->max_run[last][level] - 1;
1322
                if(run1>=0){
1323
                    code= get_rl_index(rl, last, run1, level);
1324
                    bits<<= rl->table_vlc[code][1];
1325
                    len  += rl->table_vlc[code][1];
1326
                    bits += rl->table_vlc[code][0];
1327
                    bits=bits*2+sign; len++;
1328
                
1329
                    if(code!=rl->n && len < len_tab[index]){
1330
                        bits_tab[index]= bits;
1331
                        len_tab [index]= len;
1332
                    }
1333
                }
1334
#endif           
1335
                /* ESC3 */        
1336
                bits= rl->table_vlc[rl->n][0];
1337
                len = rl->table_vlc[rl->n][1];
1338
                bits=bits*4+3;    len+=2; //esc3
1339
                bits=bits*2+last; len++;
1340
                bits=bits*64+run; len+=6;
1341
                bits=bits*2+1;    len++;  //marker
1342
                bits=bits*4096+(slevel&0xfff); len+=12;
1343
                bits=bits*2+1;    len++;  //marker
1344
                
1345
                if(len < len_tab[index]){
1346
                    bits_tab[index]= bits;
1347
                    len_tab [index]= len;
1348
                }
1349
            }
1350
        }
1351
    }
1352
}
1353

    
1354
void h263_encode_init(MpegEncContext *s)
1355
{
1356
    static int done = 0;
1357

    
1358
    if (!done) {
1359
        done = 1;
1360

    
1361
        init_uni_dc_tab();
1362

    
1363
        init_rl(&rl_inter);
1364
        init_rl(&rl_intra);
1365
        init_rl(&rl_intra_aic);
1366
        
1367
        init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1368
        init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1369

    
1370
        init_mv_penalty_and_fcode(s);
1371
    }
1372
    s->mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
1373
    
1374
    // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
1375
    switch(s->codec_id){
1376
    case CODEC_ID_MPEG4:
1377
        s->fcode_tab= fcode_tab;
1378
        s->min_qcoeff= -2048;
1379
        s->max_qcoeff=  2047;
1380
        break;
1381
    case CODEC_ID_H263P:
1382
        s->fcode_tab= umv_fcode_tab;
1383
        s->min_qcoeff= -128;
1384
        s->max_qcoeff=  127;
1385
        break;
1386
        //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later 
1387
    default: //nothing needed default table allready set in mpegvideo.c
1388
        s->min_qcoeff= -128;
1389
        s->max_qcoeff=  127;
1390
        s->y_dc_scale_table=
1391
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1392
    }
1393

    
1394
    if(s->mpeg_quant){
1395
        s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
1396
        s->inter_quant_bias= 0;
1397
    }else{
1398
        s->intra_quant_bias=0;
1399
        s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
1400
    }
1401
}
1402

    
1403
static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
1404
{
1405
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
1406
    RLTable *rl;
1407

    
1408
    rl = &rl_inter;
1409
    if (s->mb_intra && !s->h263_aic) {
1410
        /* DC coef */
1411
            level = block[0];
1412
        /* 255 cannot be represented, so we clamp */
1413
        if (level > 254) {
1414
            level = 254;
1415
            block[0] = 254;
1416
        }
1417
        /* 0 cannot be represented also */
1418
        else if (!level) {
1419
            level = 1;
1420
            block[0] = 1;
1421
        }
1422
            if (level == 128)
1423
                put_bits(&s->pb, 8, 0xff);
1424
            else
1425
                put_bits(&s->pb, 8, level & 0xff);
1426
            i = 1;
1427
    } else {
1428
            i = 0;
1429
            if (s->h263_aic && s->mb_intra)
1430
                rl = &rl_intra_aic;
1431
    }
1432
   
1433
    /* AC coefs */
1434
    last_index = s->block_last_index[n];
1435
    last_non_zero = i - 1;
1436
    for (; i <= last_index; i++) {
1437
        j = s->intra_scantable.permutated[i];
1438
        level = block[j];
1439
        if (level) {
1440
            run = i - last_non_zero - 1;
1441
            last = (i == last_index);
1442
            sign = 0;
1443
            slevel = level;
1444
            if (level < 0) {
1445
                sign = 1;
1446
                level = -level;
1447
            }
1448
            code = get_rl_index(rl, last, run, level);
1449
            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1450
            if (code == rl->n) {
1451
                put_bits(&s->pb, 1, last);
1452
                put_bits(&s->pb, 6, run);
1453
                put_bits(&s->pb, 8, slevel & 0xff);
1454
            } else {
1455
                put_bits(&s->pb, 1, sign);
1456
            }
1457
                last_non_zero = i;
1458
            }
1459
    }
1460
}
1461

    
1462
/***************************************************/
1463
/**
1464
 * add mpeg4 stuffing bits (01...1)
1465
 */
1466
void ff_mpeg4_stuffing(PutBitContext * pbc)
1467
{
1468
    int length;
1469
    put_bits(pbc, 1, 0);
1470
    length= (-get_bit_count(pbc))&7;
1471
    if(length) put_bits(pbc, length, (1<<length)-1);
1472
}
1473

    
1474
/* must be called before writing the header */
1475
void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
1476
    int time_div, time_mod;
1477

    
1478
    if(s->pict_type==I_TYPE){ //we will encode a vol header
1479
        s->time_increment_resolution= s->frame_rate/ff_gcd(s->frame_rate, FRAME_RATE_BASE);
1480
        if(s->time_increment_resolution>=256*256) s->time_increment_resolution= 256*128;
1481

    
1482
        s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
1483
    }
1484
    
1485
    if(s->avctx->pts)
1486
        s->time= (s->avctx->pts*s->time_increment_resolution + 500*1000)/(1000*1000);
1487
    else
1488
        s->time= picture_number*(INT64)FRAME_RATE_BASE*s->time_increment_resolution/s->frame_rate;
1489
    time_div= s->time/s->time_increment_resolution;
1490
    time_mod= s->time%s->time_increment_resolution;
1491

    
1492
    if(s->pict_type==B_TYPE){
1493
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
1494
    }else{
1495
        s->last_time_base= s->time_base;
1496
        s->time_base= time_div;
1497
        s->pp_time= s->time - s->last_non_b_time;
1498
        s->last_non_b_time= s->time;
1499
    }
1500
}
1501

    
1502
static void mpeg4_encode_vol_header(MpegEncContext * s)
1503
{
1504
    int vo_ver_id=1; //must be 2 if we want GMC or q-pel
1505
    char buf[255];
1506

    
1507
    s->vo_type= s->has_b_frames ? CORE_VO_TYPE : SIMPLE_VO_TYPE;
1508

    
1509
    put_bits(&s->pb, 16, 0);
1510
    put_bits(&s->pb, 16, 0x100);        /* video obj */
1511
    put_bits(&s->pb, 16, 0);
1512
    put_bits(&s->pb, 16, 0x120);        /* video obj layer */
1513

    
1514
    put_bits(&s->pb, 1, 0);                /* random access vol */
1515
    put_bits(&s->pb, 8, s->vo_type);        /* video obj type indication */
1516
    put_bits(&s->pb, 1, 1);                /* is obj layer id= yes */
1517
      put_bits(&s->pb, 4, vo_ver_id);        /* is obj layer ver id */
1518
      put_bits(&s->pb, 3, 1);                /* is obj layer priority */
1519
    if(s->aspect_ratio_info) 
1520
        put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
1521
    else
1522
        put_bits(&s->pb, 4, 1);                /* aspect ratio info= sqare pixel */
1523
    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
1524
    {
1525
        put_bits(&s->pb, 8, s->aspected_width);
1526
        put_bits(&s->pb, 8, s->aspected_height);
1527
    }
1528

    
1529
    if(s->low_delay){
1530
        put_bits(&s->pb, 1, 1);                /* vol control parameters= yes */
1531
        put_bits(&s->pb, 2, 1);                /* chroma format YUV 420/YV12 */
1532
        put_bits(&s->pb, 1, s->low_delay);
1533
        put_bits(&s->pb, 1, 0);                /* vbv parameters= no */
1534
    }else{
1535
        put_bits(&s->pb, 1, 0);                /* vol control parameters= no */
1536
    }
1537

    
1538
    put_bits(&s->pb, 2, RECT_SHAPE);        /* vol shape= rectangle */
1539
    put_bits(&s->pb, 1, 1);                /* marker bit */
1540
    
1541
    put_bits(&s->pb, 16, s->time_increment_resolution);
1542
    if (s->time_increment_bits < 1)
1543
        s->time_increment_bits = 1;
1544
    put_bits(&s->pb, 1, 1);                /* marker bit */
1545
    put_bits(&s->pb, 1, 0);                /* fixed vop rate=no */
1546
    put_bits(&s->pb, 1, 1);                /* marker bit */
1547
    put_bits(&s->pb, 13, s->width);        /* vol width */
1548
    put_bits(&s->pb, 1, 1);                /* marker bit */
1549
    put_bits(&s->pb, 13, s->height);        /* vol height */
1550
    put_bits(&s->pb, 1, 1);                /* marker bit */
1551
    put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1552
    put_bits(&s->pb, 1, 1);                /* obmc disable */
1553
    if (vo_ver_id == 1) {
1554
        put_bits(&s->pb, 1, s->vol_sprite_usage=0);                /* sprite enable */
1555
    }else{ /* vo_ver_id == 2 */
1556
        put_bits(&s->pb, 2, s->vol_sprite_usage=0);                /* sprite enable */
1557
    }
1558
    
1559
    s->quant_precision=5;
1560
    put_bits(&s->pb, 1, 0);                /* not 8 bit == false */
1561
    put_bits(&s->pb, 1, s->mpeg_quant);        /* quant type= (0=h263 style)*/
1562
    if(s->mpeg_quant) put_bits(&s->pb, 2, 0); /* no custom matrixes */
1563

    
1564
    if (vo_ver_id != 1)
1565
        put_bits(&s->pb, 1, s->quarter_sample=0);
1566
    put_bits(&s->pb, 1, 1);                /* complexity estimation disable */
1567
    s->resync_marker= s->rtp_mode;
1568
    put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
1569
    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1570
    if(s->data_partitioning){
1571
        put_bits(&s->pb, 1, 0);                /* no rvlc */
1572
    }
1573

    
1574
    if (vo_ver_id != 1){
1575
        put_bits(&s->pb, 1, 0);                /* newpred */
1576
        put_bits(&s->pb, 1, 0);                /* reduced res vop */
1577
    }
1578
    put_bits(&s->pb, 1, 0);                /* scalability */
1579
    
1580
    ff_mpeg4_stuffing(&s->pb);
1581

    
1582
    /* user data */
1583
    if(!ff_bit_exact){
1584
        put_bits(&s->pb, 16, 0);
1585
        put_bits(&s->pb, 16, 0x1B2);        /* user_data */
1586
        sprintf(buf, "FFmpeg%sb%s", FFMPEG_VERSION, LIBAVCODEC_BUILD_STR);
1587
        put_string(&s->pb, buf);
1588
        ff_mpeg4_stuffing(&s->pb);
1589
    }
1590
}
1591

    
1592
/* write mpeg4 VOP header */
1593
void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
1594
{
1595
    int time_incr;
1596
    int time_div, time_mod;
1597
    
1598
    if(s->pict_type==I_TYPE){
1599
        s->no_rounding=0;
1600
        if(picture_number==0 || !s->strict_std_compliance)
1601
            mpeg4_encode_vol_header(s);
1602
    }
1603
    
1604
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
1605

    
1606
//printf("num:%d rate:%d base:%d\n", s->picture_number, s->frame_rate, FRAME_RATE_BASE);
1607
    
1608
    put_bits(&s->pb, 16, 0);                /* vop header */
1609
    put_bits(&s->pb, 16, 0x1B6);        /* vop header */
1610
    put_bits(&s->pb, 2, s->pict_type - 1);        /* pict type: I = 0 , P = 1 */
1611

    
1612
    time_div= s->time/s->time_increment_resolution;
1613
    time_mod= s->time%s->time_increment_resolution;
1614
    time_incr= time_div - s->last_time_base;
1615
    while(time_incr--)
1616
        put_bits(&s->pb, 1, 1);
1617
        
1618
    put_bits(&s->pb, 1, 0);
1619

    
1620
    put_bits(&s->pb, 1, 1);        /* marker */
1621
    put_bits(&s->pb, s->time_increment_bits, time_mod);        /* time increment */
1622
    put_bits(&s->pb, 1, 1);        /* marker */
1623
    put_bits(&s->pb, 1, 1);        /* vop coded */
1624
    if (    s->pict_type == P_TYPE 
1625
        || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
1626
        s->no_rounding ^= 1;
1627
        put_bits(&s->pb, 1, s->no_rounding);        /* rounding type */
1628
    }
1629
    put_bits(&s->pb, 3, 0);        /* intra dc VLC threshold */
1630
    if(!s->progressive_sequence){
1631
         put_bits(&s->pb, 1, s->top_field_first);
1632
         put_bits(&s->pb, 1, s->alternate_scan);
1633
    }
1634
    //FIXME sprite stuff
1635

    
1636
    put_bits(&s->pb, 5, s->qscale);
1637

    
1638
    if (s->pict_type != I_TYPE)
1639
        put_bits(&s->pb, 3, s->f_code);        /* fcode_for */
1640
    if (s->pict_type == B_TYPE)
1641
        put_bits(&s->pb, 3, s->b_code);        /* fcode_back */
1642
    //    printf("****frame %d\n", picture_number);
1643

    
1644
     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support 
1645
     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
1646
     s->h_edge_pos= s->width;
1647
     s->v_edge_pos= s->height;
1648
}
1649

    
1650
/**
1651
 * change qscale by given dquant and update qscale dependant variables.
1652
 */
1653
static void change_qscale(MpegEncContext * s, int dquant)
1654
{
1655
    s->qscale += dquant;
1656

    
1657
    if (s->qscale < 1)
1658
        s->qscale = 1;
1659
    else if (s->qscale > 31)
1660
        s->qscale = 31;
1661

    
1662
    s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
1663
    s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
1664
}
1665

    
1666
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr, int *dir_ptr)
1667
{
1668
    int a, b, c, wrap, pred, scale;
1669
    UINT16 *dc_val;
1670
    int dummy;
1671

    
1672
    /* find prediction */
1673
    if (n < 4) {
1674
        scale = s->y_dc_scale;
1675
    } else {
1676
        scale = s->c_dc_scale;
1677
    }
1678
    wrap= s->block_wrap[n];
1679
    dc_val = s->dc_val[0] + s->block_index[n];
1680

    
1681
    /* B C
1682
     * A X 
1683
     */
1684
    a = dc_val[ - 1];
1685
    b = dc_val[ - 1 - wrap];
1686
    c = dc_val[ - wrap];
1687

    
1688
    /* outside slice handling (we cant do that by memset as we need the dc for error resilience) */
1689
    if(s->first_slice_line && n!=3){
1690
        if(n!=2) b=c= 1024;
1691
        if(n!=1 && s->mb_x == s->resync_mb_x) b=a= 1024;
1692
    }
1693
    if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1){
1694
        if(n==0 || n==4 || n==5)
1695
            b=1024;
1696
    }
1697

    
1698
    if (abs(a - b) < abs(b - c)) {
1699
        pred = c;
1700
        *dir_ptr = 1; /* top */
1701
    } else {
1702
        pred = a;
1703
        *dir_ptr = 0; /* left */
1704
    }
1705
    /* we assume pred is positive */
1706
#ifdef ARCH_X86
1707
        asm volatile (
1708
                "xorl %%edx, %%edx        \n\t"
1709
                "mul %%ecx                \n\t"
1710
                : "=d" (pred), "=a"(dummy)
1711
                : "a" (pred + (scale >> 1)), "c" (inverse[scale])
1712
        );
1713
#else
1714
    pred = (pred + (scale >> 1)) / scale;
1715
#endif
1716

    
1717
    /* prepare address for prediction update */
1718
    *dc_val_ptr = &dc_val[0];
1719

    
1720
    return pred;
1721
}
1722

    
1723
void mpeg4_pred_ac(MpegEncContext * s, INT16 *block, int n,
1724
                   int dir)
1725
{
1726
    int i;
1727
    INT16 *ac_val, *ac_val1;
1728

    
1729
    /* find prediction */
1730
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1731
    ac_val1 = ac_val;
1732
    if (s->ac_pred) {
1733
        if (dir == 0) {
1734
            const int xy= s->mb_x-1 + s->mb_y*s->mb_width;
1735
            /* left prediction */
1736
            ac_val -= 16;
1737
            
1738
            if(s->mb_x==0 || s->qscale == s->qscale_table[xy] || n==1 || n==3){
1739
                /* same qscale */
1740
                for(i=1;i<8;i++) {
1741
                    block[s->idct_permutation[i<<3]] += ac_val[i];
1742
                }
1743
            }else{
1744
                /* different qscale, we must rescale */
1745
                for(i=1;i<8;i++) {
1746
                    block[s->idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*s->qscale_table[xy], s->qscale);
1747
                }
1748
            }
1749
        } else {
1750
            const int xy= s->mb_x + s->mb_y*s->mb_width - s->mb_width;
1751
            /* top prediction */
1752
            ac_val -= 16 * s->block_wrap[n];
1753

    
1754
            if(s->mb_y==0 || s->qscale == s->qscale_table[xy] || n==2 || n==3){
1755
                /* same qscale */
1756
                for(i=1;i<8;i++) {
1757
                    block[s->idct_permutation[i]] += ac_val[i + 8];
1758
                }
1759
            }else{
1760
                /* different qscale, we must rescale */
1761
                for(i=1;i<8;i++) {
1762
                    block[s->idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*s->qscale_table[xy], s->qscale);
1763
                }
1764
            }
1765
        }
1766
    }
1767
    /* left copy */
1768
    for(i=1;i<8;i++)
1769
        ac_val1[i    ] = block[s->idct_permutation[i<<3]];
1770

    
1771
    /* top copy */
1772
    for(i=1;i<8;i++)
1773
        ac_val1[8 + i] = block[s->idct_permutation[i   ]];
1774

    
1775
}
1776

    
1777
static void mpeg4_inv_pred_ac(MpegEncContext * s, INT16 *block, int n,
1778
                              int dir)
1779
{
1780
    int i;
1781
    INT16 *ac_val;
1782

    
1783
    /* find prediction */
1784
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1785
 
1786
    if (dir == 0) {
1787
        const int xy= s->mb_x-1 + s->mb_y*s->mb_width;
1788
        /* left prediction */
1789
        ac_val -= 16;
1790
        if(s->mb_x==0 || s->qscale == s->qscale_table[xy] || n==1 || n==3){
1791
            /* same qscale */
1792
            for(i=1;i<8;i++) {
1793
                block[s->idct_permutation[i<<3]] -= ac_val[i];
1794
            }
1795
        }else{
1796
            /* different qscale, we must rescale */
1797
            for(i=1;i<8;i++) {
1798
                block[s->idct_permutation[i<<3]] -= ROUNDED_DIV(ac_val[i]*s->qscale_table[xy], s->qscale);
1799
            }
1800
        }
1801
    } else {
1802
        const int xy= s->mb_x + s->mb_y*s->mb_width - s->mb_width;
1803
        /* top prediction */
1804
        ac_val -= 16 * s->block_wrap[n];
1805
        if(s->mb_y==0 || s->qscale == s->qscale_table[xy] || n==2 || n==3){
1806
            /* same qscale */
1807
            for(i=1;i<8;i++) {
1808
                block[s->idct_permutation[i]] -= ac_val[i + 8];
1809
            }
1810
        }else{
1811
            /* different qscale, we must rescale */
1812
            for(i=1;i<8;i++) {
1813
                block[s->idct_permutation[i]] -= ROUNDED_DIV(ac_val[i + 8]*s->qscale_table[xy], s->qscale);
1814
            }
1815
        }
1816
    }
1817
}
1818

    
1819
static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
1820
{
1821
#if 1
1822
//    if(level<-255 || level>255) printf("dc overflow\n");
1823
    level+=256;
1824
    if (n < 4) {
1825
        /* luminance */
1826
        put_bits(s, uni_DCtab_lum[level][1], uni_DCtab_lum[level][0]);
1827
    } else {
1828
        /* chrominance */
1829
        put_bits(s, uni_DCtab_chrom[level][1], uni_DCtab_chrom[level][0]);
1830
    }
1831
#else
1832
    int size, v;
1833
    /* find number of bits */
1834
    size = 0;
1835
    v = abs(level);
1836
    while (v) {
1837
        v >>= 1;
1838
        size++;
1839
    }
1840

    
1841
    if (n < 4) {
1842
        /* luminance */
1843
        put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
1844
    } else {
1845
        /* chrominance */
1846
        put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
1847
    }
1848

    
1849
    /* encode remaining bits */
1850
    if (size > 0) {
1851
        if (level < 0)
1852
            level = (-level) ^ ((1 << size) - 1);
1853
        put_bits(&s->pb, size, level);
1854
        if (size > 8)
1855
            put_bits(&s->pb, 1, 1);
1856
    }
1857
#endif
1858
}
1859

    
1860
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
1861
                               UINT8 *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
1862
{
1863
    int i, last_non_zero;
1864
#if 0 //variables for the outcommented version
1865
    int code, sign, last;
1866
#endif
1867
    const RLTable *rl;
1868
    UINT32 *bits_tab;
1869
    UINT8 *len_tab;
1870
    const int last_index = s->block_last_index[n];
1871

    
1872
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
1873
        /* mpeg4 based DC predictor */
1874
        mpeg4_encode_dc(dc_pb, intra_dc, n);
1875
        if(last_index<1) return;
1876
        i = 1;
1877
        rl = &rl_intra;
1878
        bits_tab= uni_mpeg4_intra_rl_bits;
1879
        len_tab = uni_mpeg4_intra_rl_len;
1880
    } else {
1881
        if(last_index<0) return;
1882
        i = 0;
1883
        rl = &rl_inter;
1884
        bits_tab= uni_mpeg4_inter_rl_bits;
1885
        len_tab = uni_mpeg4_inter_rl_len;
1886
    }
1887

    
1888
    /* AC coefs */
1889
    last_non_zero = i - 1;
1890
#if 1
1891
    for (; i < last_index; i++) {
1892
        int level = block[ scan_table[i] ];
1893
        if (level) {
1894
            int run = i - last_non_zero - 1;
1895
            level+=64;
1896
            if((level&(~127)) == 0){
1897
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
1898
                put_bits(ac_pb, len_tab[index], bits_tab[index]);
1899
            }else{ //ESC3
1900
                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);
1901
            }
1902
            last_non_zero = i;
1903
        }
1904
    }
1905
    /*if(i<=last_index)*/{
1906
        int level = block[ scan_table[i] ];
1907
        int run = i - last_non_zero - 1;
1908
        level+=64;
1909
        if((level&(~127)) == 0){
1910
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
1911
            put_bits(ac_pb, len_tab[index], bits_tab[index]);
1912
        }else{ //ESC3
1913
            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);
1914
        }
1915
    }
1916
#else
1917
    for (; i <= last_index; i++) {
1918
        const int slevel = block[ scan_table[i] ];
1919
        if (slevel) {
1920
            int level;
1921
            int run = i - last_non_zero - 1;
1922
            last = (i == last_index);
1923
            sign = 0;
1924
            level = slevel;
1925
            if (level < 0) {
1926
                sign = 1;
1927
                level = -level;
1928
            }
1929
            code = get_rl_index(rl, last, run, level);
1930
            put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1931
            if (code == rl->n) {
1932
                int level1, run1;
1933
                level1 = level - rl->max_level[last][run];
1934
                if (level1 < 1) 
1935
                    goto esc2;
1936
                code = get_rl_index(rl, last, run, level1);
1937
                if (code == rl->n) {
1938
                esc2:
1939
                    put_bits(ac_pb, 1, 1);
1940
                    if (level > MAX_LEVEL)
1941
                        goto esc3;
1942
                    run1 = run - rl->max_run[last][level] - 1;
1943
                    if (run1 < 0)
1944
                        goto esc3;
1945
                    code = get_rl_index(rl, last, run1, level);
1946
                    if (code == rl->n) {
1947
                    esc3:
1948
                        /* third escape */
1949
                        put_bits(ac_pb, 1, 1);
1950
                        put_bits(ac_pb, 1, last);
1951
                        put_bits(ac_pb, 6, run);
1952
                        put_bits(ac_pb, 1, 1);
1953
                        put_bits(ac_pb, 12, slevel & 0xfff);
1954
                        put_bits(ac_pb, 1, 1);
1955
                    } else {
1956
                        /* second escape */
1957
                        put_bits(ac_pb, 1, 0);
1958
                        put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1959
                        put_bits(ac_pb, 1, sign);
1960
                    }
1961
                } else {
1962
                    /* first escape */
1963
                    put_bits(ac_pb, 1, 0);
1964
                    put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1965
                    put_bits(ac_pb, 1, sign);
1966
                }
1967
            } else {
1968
                put_bits(ac_pb, 1, sign);
1969
            }
1970
            last_non_zero = i;
1971
        }
1972
    }
1973
#endif
1974
}
1975

    
1976

    
1977

    
1978
/***********************************************/
1979
/* decoding */
1980

    
1981
static VLC intra_MCBPC_vlc;
1982
static VLC inter_MCBPC_vlc;
1983
static VLC cbpy_vlc;
1984
static VLC mv_vlc;
1985
static VLC dc_lum, dc_chrom;
1986
static VLC sprite_trajectory;
1987
static VLC mb_type_b_vlc;
1988

    
1989
void init_rl(RLTable *rl)
1990
{
1991
    INT8 max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
1992
    UINT8 index_run[MAX_RUN+1];
1993
    int last, run, level, start, end, i;
1994

    
1995
    /* compute max_level[], max_run[] and index_run[] */
1996
    for(last=0;last<2;last++) {
1997
        if (last == 0) {
1998
            start = 0;
1999
            end = rl->last;
2000
        } else {
2001
            start = rl->last;
2002
            end = rl->n;
2003
        }
2004

    
2005
        memset(max_level, 0, MAX_RUN + 1);
2006
        memset(max_run, 0, MAX_LEVEL + 1);
2007
        memset(index_run, rl->n, MAX_RUN + 1);
2008
        for(i=start;i<end;i++) {
2009
            run = rl->table_run[i];
2010
            level = rl->table_level[i];
2011
            if (index_run[run] == rl->n)
2012
                index_run[run] = i;
2013
            if (level > max_level[run])
2014
                max_level[run] = level;
2015
            if (run > max_run[level])
2016
                max_run[level] = run;
2017
        }
2018
        rl->max_level[last] = av_malloc(MAX_RUN + 1);
2019
        memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
2020
        rl->max_run[last] = av_malloc(MAX_LEVEL + 1);
2021
        memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
2022
        rl->index_run[last] = av_malloc(MAX_RUN + 1);
2023
        memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
2024
    }
2025
}
2026

    
2027
void init_vlc_rl(RLTable *rl)
2028
{
2029
    int i, q;
2030
    
2031
    init_vlc(&rl->vlc, 9, rl->n + 1, 
2032
             &rl->table_vlc[0][1], 4, 2,
2033
             &rl->table_vlc[0][0], 4, 2);
2034

    
2035
    
2036
    for(q=0; q<32; q++){
2037
        int qmul= q*2;
2038
        int qadd= (q-1)|1;
2039
        
2040
        if(q==0){
2041
            qmul=1;
2042
            qadd=0;
2043
        }
2044
        
2045
        rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2046
        for(i=0; i<rl->vlc.table_size; i++){
2047
            int code= rl->vlc.table[i][0];
2048
            int len = rl->vlc.table[i][1];
2049
            int level, run;
2050
        
2051
            if(len==0){ // illegal code
2052
                run= 66;
2053
                level= MAX_LEVEL;
2054
            }else if(len<0){ //more bits needed
2055
                run= 0;
2056
                level= code;
2057
            }else{
2058
                if(code==rl->n){ //esc
2059
                    run= 66;
2060
                    level= 0;
2061
                }else{
2062
                    run=   rl->table_run  [code] + 1;
2063
                    level= rl->table_level[code] * qmul + qadd;
2064
                    if(code >= rl->last) run+=192;
2065
                }
2066
            }
2067
            rl->rl_vlc[q][i].len= len;
2068
            rl->rl_vlc[q][i].level= level;
2069
            rl->rl_vlc[q][i].run= run;
2070
        }
2071
    }
2072
}
2073

    
2074
/* init vlcs */
2075

    
2076
/* XXX: find a better solution to handle static init */
2077
void h263_decode_init_vlc(MpegEncContext *s)
2078
{
2079
    static int done = 0;
2080

    
2081
    if (!done) {
2082
        done = 1;
2083

    
2084
        init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 8, 
2085
                 intra_MCBPC_bits, 1, 1,
2086
                 intra_MCBPC_code, 1, 1);
2087
        init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 25, 
2088
                 inter_MCBPC_bits, 1, 1,
2089
                 inter_MCBPC_code, 1, 1);
2090
        init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,
2091
                 &cbpy_tab[0][1], 2, 1,
2092
                 &cbpy_tab[0][0], 2, 1);
2093
        init_vlc(&mv_vlc, MV_VLC_BITS, 33,
2094
                 &mvtab[0][1], 2, 1,
2095
                 &mvtab[0][0], 2, 1);
2096
        init_rl(&rl_inter);
2097
        init_rl(&rl_intra);
2098
        init_rl(&rl_intra_aic);
2099
        init_vlc_rl(&rl_inter);
2100
        init_vlc_rl(&rl_intra);
2101
        init_vlc_rl(&rl_intra_aic);
2102
        init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2103
                 &DCtab_lum[0][1], 2, 1,
2104
                 &DCtab_lum[0][0], 2, 1);
2105
        init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2106
                 &DCtab_chrom[0][1], 2, 1,
2107
                 &DCtab_chrom[0][0], 2, 1);
2108
        init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2109
                 &sprite_trajectory_tab[0][1], 4, 2,
2110
                 &sprite_trajectory_tab[0][0], 4, 2);
2111
        init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2112
                 &mb_type_b_tab[0][1], 2, 1,
2113
                 &mb_type_b_tab[0][0], 2, 1);
2114
    }
2115
}
2116

    
2117
/**
2118
 * Get the GOB height based on picture height.
2119
 */
2120
int ff_h263_get_gob_height(MpegEncContext *s){
2121
    if (s->height <= 400)
2122
        return 1;
2123
    else if (s->height <= 800)
2124
        return  2;
2125
    else
2126
        return 4;
2127
}
2128

    
2129
/**
2130
 * decodes the group of blocks header.
2131
 * @return <0 if an error occured
2132
 */
2133
static int h263_decode_gob_header(MpegEncContext *s)
2134
{
2135
    unsigned int val, gfid;
2136
    int left;
2137
    
2138
    /* Check for GOB Start Code */
2139
    val = show_bits(&s->gb, 16);
2140
    if(val)
2141
        return -1;
2142

    
2143
        /* We have a GBSC probably with GSTUFF */
2144
    skip_bits(&s->gb, 16); /* Drop the zeros */
2145
    left= s->gb.size*8 - get_bits_count(&s->gb);
2146
    //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2147
    for(;left>13; left--){
2148
        if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2149
    }
2150
    if(left<=13) 
2151
        return -1;
2152

    
2153
#ifdef DEBUG
2154
    fprintf(stderr,"\nGOB Start Code at MB %d\n", (s->mb_y * s->mb_width) + s->mb_x);
2155
#endif
2156
    s->gob_number = get_bits(&s->gb, 5); /* GN */
2157
    gfid = get_bits(&s->gb, 2); /* GFID */
2158
    s->qscale = get_bits(&s->gb, 5); /* GQUANT */
2159
    if(s->qscale==0) 
2160
        return -1;
2161
    s->mb_x= 0;
2162
    s->mb_y= s->gob_index* s->gob_number;
2163
#ifdef DEBUG
2164
    fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", s->gob_number, gfid, s->qscale);
2165
#endif
2166
    return 0;
2167
}
2168

    
2169
static inline void memsetw(short *tab, int val, int n)
2170
{
2171
    int i;
2172
    for(i=0;i<n;i++)
2173
        tab[i] = val;
2174
}
2175

    
2176
void ff_mpeg4_init_partitions(MpegEncContext *s)
2177
{
2178
    init_put_bits(&s->tex_pb, s->tex_pb_buffer, PB_BUFFER_SIZE, NULL, NULL);
2179
    init_put_bits(&s->pb2   , s->pb2_buffer   , PB_BUFFER_SIZE, NULL, NULL);
2180
}
2181

    
2182
void ff_mpeg4_merge_partitions(MpegEncContext *s)
2183
{
2184
    const int pb2_len   = get_bit_count(&s->pb2   );
2185
    const int tex_pb_len= get_bit_count(&s->tex_pb);
2186
    const int bits= get_bit_count(&s->pb);
2187

    
2188
    if(s->pict_type==I_TYPE){
2189
        put_bits(&s->pb, 19, DC_MARKER);
2190
        s->misc_bits+=19 + pb2_len + bits - s->last_bits;
2191
        s->i_tex_bits+= tex_pb_len;
2192
    }else{
2193
        put_bits(&s->pb, 17, MOTION_MARKER);
2194
        s->misc_bits+=17 + pb2_len;
2195
        s->mv_bits+= bits - s->last_bits;
2196
        s->p_tex_bits+= tex_pb_len;
2197
    }
2198

    
2199
    flush_put_bits(&s->pb2);
2200
    flush_put_bits(&s->tex_pb);
2201

    
2202
    ff_copy_bits(&s->pb, s->pb2_buffer   , pb2_len);
2203
    ff_copy_bits(&s->pb, s->tex_pb_buffer, tex_pb_len);
2204
    s->last_bits= get_bit_count(&s->pb);
2205
}
2206

    
2207
int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
2208
    switch(s->pict_type){
2209
        case I_TYPE:
2210
            return 16;
2211
        case P_TYPE:
2212
        case S_TYPE:
2213
            return s->f_code+15;
2214
        case B_TYPE:
2215
            return MAX(MAX(s->f_code, s->b_code)+15, 17);
2216
        default:
2217
            return -1;
2218
    }
2219
}
2220

    
2221
void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
2222
{
2223
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2224

    
2225
    ff_mpeg4_stuffing(&s->pb);
2226
    put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
2227
    put_bits(&s->pb, 1, 1);
2228
    
2229
    put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
2230
    put_bits(&s->pb, s->quant_precision, s->qscale);
2231
    put_bits(&s->pb, 1, 0); /* no HEC */
2232
}
2233

    
2234
/**
2235
 * check if the next stuff is a resync marker or the end.
2236
 * @return 0 if not
2237
 */
2238
static inline int mpeg4_is_resync(MpegEncContext *s){
2239
    const int bits_count= get_bits_count(&s->gb);
2240
    
2241
    if(s->workaround_bugs&FF_BUG_NO_PADDING){
2242
        return 0;
2243
    }
2244

    
2245
    if(bits_count + 8 >= s->gb.size*8){
2246
        int v= show_bits(&s->gb, 8);
2247
        v|= 0x7F >> (7-(bits_count&7));
2248
                
2249
        if(v==0x7F)
2250
            return 1;
2251
    }else{
2252
        if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){
2253
            int len;
2254
            GetBitContext gb= s->gb;
2255
        
2256
            skip_bits(&s->gb, 1);
2257
            align_get_bits(&s->gb);
2258
        
2259
            for(len=0; len<32; len++){
2260
                if(get_bits1(&s->gb)) break;
2261
            }
2262

    
2263
            s->gb= gb;
2264

    
2265
            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
2266
                return 1;
2267
        }
2268
    }
2269
    return 0;
2270
}
2271

    
2272
/**
2273
 * decodes the next video packet.
2274
 * @return <0 if something went wrong
2275
 */
2276
static int mpeg4_decode_video_packet_header(MpegEncContext *s)
2277
{
2278
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2279
    int header_extension=0, mb_num, len;
2280
    
2281
    /* is there enough space left for a video packet + header */
2282
    if( get_bits_count(&s->gb) > s->gb.size*8-20) return -1;
2283

    
2284
    for(len=0; len<32; len++){
2285
        if(get_bits1(&s->gb)) break;
2286
    }
2287

    
2288
    if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
2289
        printf("marker does not match f_code\n");
2290
        return -1;
2291
    }
2292
    
2293
    if(s->shape != RECT_SHAPE){
2294
        header_extension= get_bits1(&s->gb);
2295
        //FIXME more stuff here
2296
    }
2297

    
2298
    mb_num= get_bits(&s->gb, mb_num_bits);
2299
    if(mb_num>=s->mb_num){
2300
        fprintf(stderr, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
2301
        return -1;
2302
    }
2303
    s->mb_x= mb_num % s->mb_width;
2304
    s->mb_y= mb_num / s->mb_width;
2305

    
2306
    if(s->shape != BIN_ONLY_SHAPE){
2307
        int qscale= get_bits(&s->gb, s->quant_precision); 
2308
        if(qscale)
2309
            s->qscale= qscale;
2310
    }
2311

    
2312
    if(s->shape == RECT_SHAPE){
2313
        header_extension= get_bits1(&s->gb);
2314
    }
2315
    if(header_extension){
2316
        int time_increment;
2317
        int time_incr=0;
2318

    
2319
        while (get_bits1(&s->gb) != 0) 
2320
            time_incr++;
2321

    
2322
        check_marker(&s->gb, "before time_increment in video packed header");
2323
        time_increment= get_bits(&s->gb, s->time_increment_bits);
2324
        check_marker(&s->gb, "before vop_coding_type in video packed header");
2325
        
2326
        skip_bits(&s->gb, 2); /* vop coding type */
2327
        //FIXME not rect stuff here
2328

    
2329
        if(s->shape != BIN_ONLY_SHAPE){
2330
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
2331
//FIXME dont just ignore everything
2332
            if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE && s->num_sprite_warping_points){
2333
                mpeg4_decode_sprite_trajectory(s);
2334
                fprintf(stderr, "untested\n");
2335
            }
2336

    
2337
            //FIXME reduced res stuff here
2338
            
2339
            if (s->pict_type != I_TYPE) {
2340
                int f_code = get_bits(&s->gb, 3);        /* fcode_for */
2341
                if(f_code==0){
2342
                    printf("Error, video packet header damaged (f_code=0)\n");
2343
                }
2344
            }
2345
            if (s->pict_type == B_TYPE) {
2346
                int b_code = get_bits(&s->gb, 3);
2347
                if(b_code==0){
2348
                    printf("Error, video packet header damaged (b_code=0)\n");
2349
                }
2350
            }       
2351
        }
2352
    }
2353
    //FIXME new-pred stuff
2354
    
2355
//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));
2356

    
2357
    return 0;
2358
}
2359

    
2360
void ff_mpeg4_clean_buffers(MpegEncContext *s)
2361
{
2362
    int c_wrap, c_xy, l_wrap, l_xy;
2363

    
2364
    l_wrap= s->block_wrap[0];
2365
    l_xy= s->mb_y*l_wrap*2 + s->mb_x*2;
2366
    c_wrap= s->block_wrap[4];
2367
    c_xy= s->mb_y*c_wrap + s->mb_x;
2368

    
2369
#if 0
2370
    /* clean DC */
2371
    memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
2372
    memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
2373
    memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
2374
#endif
2375

    
2376
    /* clean AC */
2377
    memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(INT16));
2378
    memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(INT16));
2379
    memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(INT16));
2380

    
2381
    /* clean MV */
2382
    // we cant clear the MVs as they might be needed by a b frame
2383
//    memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(INT16));
2384
//    memset(s->motion_val, 0, 2*sizeof(INT16)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
2385
    s->last_mv[0][0][0]=
2386
    s->last_mv[0][0][1]=
2387
    s->last_mv[1][0][0]=
2388
    s->last_mv[1][0][1]= 0;
2389
}
2390

    
2391
/**
2392
 * decodes the group of blocks / video packet header.
2393
 * @return <0 if no resync found
2394
 */
2395
int ff_h263_resync(MpegEncContext *s){
2396
    int left, ret;
2397
    
2398
    if(s->codec_id==CODEC_ID_MPEG4)
2399
        skip_bits1(&s->gb);
2400
    
2401
    align_get_bits(&s->gb);
2402

    
2403
    if(show_bits(&s->gb, 16)==0){
2404
        if(s->codec_id==CODEC_ID_MPEG4)
2405
            ret= mpeg4_decode_video_packet_header(s);
2406
        else
2407
            ret= h263_decode_gob_header(s);
2408
        if(ret>=0)
2409
            return 0;
2410
    }
2411
    //ok, its not where its supposed to be ...
2412
    s->gb= s->last_resync_gb;
2413
    align_get_bits(&s->gb);
2414
    left= s->gb.size*8 - get_bits_count(&s->gb);
2415
    
2416
    for(;left>16+1+5+5; left-=8){ 
2417
        if(show_bits(&s->gb, 16)==0){
2418
            GetBitContext bak= s->gb;
2419

    
2420
            if(s->codec_id==CODEC_ID_MPEG4)
2421
                ret= mpeg4_decode_video_packet_header(s);
2422
            else
2423
                ret= h263_decode_gob_header(s);
2424
            if(ret>=0)
2425
                return 0;
2426

    
2427
            s->gb= bak;
2428
        }
2429
        skip_bits(&s->gb, 8);
2430
    }
2431
    
2432
    return -1;
2433
}
2434

    
2435
/**
2436
 * decodes first partition.
2437
 * @return number of MBs decoded or <0 if an error occured
2438
 */
2439
static int mpeg4_decode_partition_a(MpegEncContext *s){
2440
    int mb_num;
2441
    static const INT8 quant_tab[4] = { -1, -2, 1, 2 };
2442
    
2443
    /* decode first partition */
2444
    mb_num=0;
2445
    s->first_slice_line=1;
2446
    for(; s->mb_y<s->mb_height; s->mb_y++){
2447
        ff_init_block_index(s);
2448
        for(; s->mb_x<s->mb_width; s->mb_x++){
2449
            const int xy= s->mb_x + s->mb_y*s->mb_width;
2450
            int cbpc;
2451
            int dir=0;
2452
            
2453
            mb_num++;
2454
            ff_update_block_index(s);
2455
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2456
                s->first_slice_line=0;
2457
            
2458
            if(s->mb_x==0) PRINT_MB_TYPE("\n");
2459

    
2460
            if(s->pict_type==I_TYPE){
2461
                int i;
2462

    
2463
                if(show_bits(&s->gb, 19)==DC_MARKER){
2464
                    return mb_num-1;
2465
                }
2466

    
2467
                PRINT_MB_TYPE("I");
2468
                cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
2469
                if (cbpc < 0){
2470

    
2471
                    fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2472
                    return -1;
2473
                }
2474
                s->cbp_table[xy]= cbpc & 3;
2475
                s->mb_type[xy]= MB_TYPE_INTRA;
2476
                s->mb_intra = 1;
2477

    
2478
                if(cbpc & 4) {
2479
                    change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2480
                }
2481
                s->qscale_table[xy]= s->qscale;
2482

    
2483
                s->mbintra_table[xy]= 1;
2484
                for(i=0; i<6; i++){
2485
                    int dc_pred_dir;
2486
                    int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2487
                    if(dc < 0){
2488
                        fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2489
                        return -1;
2490
                    }
2491
                    dir<<=1;
2492
                    if(dc_pred_dir) dir|=1;
2493
                }
2494
                s->pred_dir_table[xy]= dir;
2495
                
2496
                s->error_status_table[xy]= AC_ERROR;
2497
            }else{ /* P/S_TYPE */
2498
                int mx, my, pred_x, pred_y, bits;
2499
                INT16 * const mot_val= s->motion_val[s->block_index[0]];
2500
                const int stride= s->block_wrap[0]*2;
2501

    
2502
                bits= show_bits(&s->gb, 17);
2503
                if(bits==MOTION_MARKER){
2504
                    return mb_num-1;
2505
                }
2506
                skip_bits1(&s->gb);
2507
                if(bits&0x10000){
2508
                    /* skip mb */
2509
                    s->mb_type[xy]= MB_TYPE_SKIPED;
2510
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2511
                        const int a= s->sprite_warping_accuracy;
2512
                        PRINT_MB_TYPE("G");
2513
                        if(s->divx_version==500 && s->divx_build==413){
2514
                            mx = s->sprite_offset[0][0] / (1<<(a-s->quarter_sample));
2515
                            my = s->sprite_offset[0][1] / (1<<(a-s->quarter_sample));
2516
                        }else{
2517
                            mx = RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
2518
                            my = RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
2519
                            s->mb_type[xy]= MB_TYPE_GMC | MB_TYPE_SKIPED;
2520
                        }
2521
                    }else{
2522
                        PRINT_MB_TYPE("S");
2523
                        mx = 0;
2524
                        my = 0;
2525
                    }
2526
                    mot_val[0       ]= mot_val[2       ]=
2527
                    mot_val[0+stride]= mot_val[2+stride]= mx;
2528
                    mot_val[1       ]= mot_val[3       ]=
2529
                    mot_val[1+stride]= mot_val[3+stride]= my;
2530

    
2531
                    if(s->mbintra_table[xy])
2532
                        ff_clean_intra_table_entries(s);
2533

    
2534
                    s->error_status_table[xy]= AC_ERROR;
2535
                    continue;
2536
                }
2537
                cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
2538
                if (cbpc < 0){
2539
                    fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2540
                    return -1;
2541
                }
2542
                if (cbpc > 20)
2543
                    cbpc+=3;
2544
                else if (cbpc == 20)
2545
                    fprintf(stderr, "Stuffing !");
2546
                s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
2547
    
2548
                s->mb_intra = ((cbpc & 4) != 0);
2549
        
2550
                if(s->mb_intra){
2551
                    PRINT_MB_TYPE("I");
2552
                    s->mbintra_table[xy]= 1;
2553
                    s->mb_type[xy]= MB_TYPE_INTRA;
2554
                    mot_val[0       ]= mot_val[2       ]= 
2555
                    mot_val[0+stride]= mot_val[2+stride]= 0;
2556
                    mot_val[1       ]= mot_val[3       ]=
2557
                    mot_val[1+stride]= mot_val[3+stride]= 0;
2558
                    s->error_status_table[xy]= DC_ERROR|AC_ERROR;
2559
                }else{
2560
                    if(s->mbintra_table[xy])
2561
                        ff_clean_intra_table_entries(s);
2562

    
2563
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
2564
                        s->mcsel= get_bits1(&s->gb);
2565
                    else s->mcsel= 0;
2566
        
2567
                    if ((cbpc & 16) == 0) {
2568
                        PRINT_MB_TYPE("P");
2569
                        /* 16x16 motion prediction */
2570
                        s->mb_type[xy]= MB_TYPE_INTER;
2571

    
2572
                        h263_pred_motion(s, 0, &pred_x, &pred_y);
2573
                        if(!s->mcsel)
2574
                           mx = h263_decode_motion(s, pred_x, s->f_code);
2575
                        else {
2576
                            const int a= s->sprite_warping_accuracy;
2577
                            if(s->divx_version==500 && s->divx_build==413){
2578
                                mx = s->sprite_offset[0][0] / (1<<(a-s->quarter_sample));
2579
                            }else{
2580
                                mx = RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
2581
                            }
2582
                        }
2583
                        if (mx >= 0xffff)
2584
                            return -1;
2585
            
2586
                        if(!s->mcsel)
2587
                           my = h263_decode_motion(s, pred_y, s->f_code);
2588
                        else{
2589
                           const int a= s->sprite_warping_accuracy;
2590
                            if(s->divx_version==500 && s->divx_build==413){
2591
                                my = s->sprite_offset[0][1] / (1<<(a-s->quarter_sample));
2592
                            }else{
2593
                                my = RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
2594
                            }
2595
                        }
2596
                        if (my >= 0xffff)
2597
                            return -1;
2598
                        mot_val[0       ]= mot_val[2       ] =
2599
                        mot_val[0+stride]= mot_val[2+stride]= mx;
2600
                        mot_val[1       ]= mot_val[3       ]=
2601
                        mot_val[1+stride]= mot_val[3+stride]= my;
2602
                    } else {
2603
                        int i;
2604
                        PRINT_MB_TYPE("4");
2605
                        s->mb_type[xy]= MB_TYPE_INTER4V;
2606
                        for(i=0;i<4;i++) {
2607
                            INT16 *mot_val= h263_pred_motion(s, i, &pred_x, &pred_y);
2608
                            mx = h263_decode_motion(s, pred_x, s->f_code);
2609
                            if (mx >= 0xffff)
2610
                                return -1;
2611
                
2612
                            my = h263_decode_motion(s, pred_y, s->f_code);
2613
                            if (my >= 0xffff)
2614
                                return -1;
2615
                            mot_val[0] = mx;
2616
                            mot_val[1] = my;
2617
                        }
2618
                    }
2619
                    s->error_status_table[xy]= AC_ERROR;
2620
                }
2621
            }
2622
        }
2623
        s->mb_x= 0;
2624
    }
2625

    
2626
    return mb_num;
2627
}
2628

    
2629
/**
2630
 * decode second partition.
2631
 * @return <0 if an error occured
2632
 */
2633
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
2634
    int mb_num=0;
2635
    static const INT8 quant_tab[4] = { -1, -2, 1, 2 };
2636

    
2637
    s->mb_x= s->resync_mb_x;
2638
    s->first_slice_line=1;
2639
    for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
2640
        ff_init_block_index(s);
2641
        for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
2642
            const int xy= s->mb_x + s->mb_y*s->mb_width;
2643

    
2644
            mb_num++;
2645
            ff_update_block_index(s);
2646
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2647
                s->first_slice_line=0;
2648
            
2649
            if(s->pict_type==I_TYPE){
2650
                int ac_pred= get_bits1(&s->gb);
2651
                int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2652
                if(cbpy<0){
2653
                    fprintf(stderr, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2654
                    return -1;
2655
                }
2656
                
2657
                s->cbp_table[xy]|= cbpy<<2;
2658
                s->pred_dir_table[xy]|= ac_pred<<7;
2659
            }else{ /* P || S_TYPE */
2660
                if(s->mb_type[xy]&MB_TYPE_INTRA){          
2661
                    int dir=0,i;
2662
                    int ac_pred = get_bits1(&s->gb);
2663
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2664

    
2665
                    if(cbpy<0){
2666
                        fprintf(stderr, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2667
                        return -1;
2668
                    }
2669
                    
2670
                    if(s->cbp_table[xy] & 8) {
2671
                        change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2672
                    }
2673
                    s->qscale_table[xy]= s->qscale;
2674

    
2675
                    for(i=0; i<6; i++){
2676
                        int dc_pred_dir;
2677
                        int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2678
                        if(dc < 0){
2679
                            fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2680
                            return -1;
2681
                        }
2682
                        dir<<=1;
2683
                        if(dc_pred_dir) dir|=1;
2684
                    }
2685
                    s->cbp_table[xy]&= 3; //remove dquant
2686
                    s->cbp_table[xy]|= cbpy<<2;
2687
                    s->pred_dir_table[xy]= dir | (ac_pred<<7);
2688
                    s->error_status_table[xy]&= ~DC_ERROR;
2689
                }else if(s->mb_type[xy]&MB_TYPE_SKIPED){
2690
                    s->qscale_table[xy]= s->qscale;
2691
                    s->cbp_table[xy]= 0;
2692
                }else{
2693
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2694

    
2695
                    if(cbpy<0){
2696
                        fprintf(stderr, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2697
                        return -1;
2698
                    }
2699
                    
2700
                    if(s->cbp_table[xy] & 8) {
2701
                        change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2702
                    }
2703
                    s->qscale_table[xy]= s->qscale;
2704

    
2705
                    s->cbp_table[xy]&= 3; //remove dquant
2706
                    s->cbp_table[xy]|= (cbpy^0xf)<<2;
2707
                }
2708
            }
2709
        }
2710
        if(mb_num >= mb_count) return 0;
2711
        s->mb_x= 0;
2712
    }
2713
    return 0;
2714
}
2715

    
2716
/**
2717
 * decodes the first & second partition
2718
 * @return <0 if error (and sets error type in the error_status_table)
2719
 */
2720
int ff_mpeg4_decode_partitions(MpegEncContext *s)
2721
{
2722
    int mb_num;
2723
    
2724
    mb_num= mpeg4_decode_partition_a(s);    
2725
    if(mb_num<0)
2726
        return -1;
2727
    
2728
    if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
2729
        fprintf(stderr, "slice below monitor ...\n");
2730
        return -1;
2731
    }
2732

    
2733
    s->mb_num_left= mb_num;
2734
        
2735
    if(s->pict_type==I_TYPE){
2736
        if(get_bits(&s->gb, 19)!=DC_MARKER){
2737
            fprintf(stderr, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
2738
            return -1;
2739
        }else
2740
            s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= MV_END|DC_END;
2741
    }else{
2742
        if(get_bits(&s->gb, 17)!=MOTION_MARKER){
2743
            fprintf(stderr, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
2744
            return -1;
2745
        }else
2746
            s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= MV_END;
2747
    }
2748
    
2749
    if( mpeg4_decode_partition_b(s, mb_num) < 0){
2750
        return -1;
2751
    }
2752
    
2753
    s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= DC_END;
2754

    
2755
    return 0;        
2756
}
2757

    
2758
/**
2759
 * decode partition C of one MB.
2760
 * @return <0 if an error occured
2761
 */
2762
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
2763
{
2764
    int cbp, mb_type;
2765
    const int xy= s->mb_x + s->mb_y*s->mb_width;
2766

    
2767
    mb_type= s->mb_type[xy];
2768
    cbp = s->cbp_table[xy];
2769

    
2770
    if(s->qscale_table[xy] != s->qscale){
2771
        s->qscale= s->qscale_table[xy];
2772
        s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
2773
        s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
2774
    }
2775
    
2776
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
2777
        int i;
2778
        for(i=0; i<4; i++){
2779
            s->mv[0][i][0] = s->motion_val[ s->block_index[i] ][0];
2780
            s->mv[0][i][1] = s->motion_val[ s->block_index[i] ][1];
2781
        }
2782
        s->mb_intra = mb_type&MB_TYPE_INTRA;
2783

    
2784
        if (mb_type&MB_TYPE_SKIPED) {
2785
            /* skip mb */
2786
            for(i=0;i<6;i++)
2787
                s->block_last_index[i] = -1;
2788
            s->mv_dir = MV_DIR_FORWARD;
2789
            s->mv_type = MV_TYPE_16X16;
2790
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2791
                s->mcsel=1;
2792
                s->mb_skiped = 0;
2793
            }else{
2794
                s->mcsel=0;
2795
                s->mb_skiped = 1;
2796
            }
2797
        }else if(s->mb_intra){
2798
            s->ac_pred = s->pred_dir_table[xy]>>7;
2799

    
2800
            /* decode each block */
2801
            for (i = 0; i < 6; i++) {
2802
                if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){
2803
                    fprintf(stderr, "texture corrupted at %d %d\n", s->mb_x, s->mb_y);
2804
                    return -1;
2805
                }
2806
                cbp+=cbp;
2807
            }
2808
        }else if(!s->mb_intra){
2809
//            s->mcsel= 0; //FIXME do we need to init that
2810
            
2811
            s->mv_dir = MV_DIR_FORWARD;
2812
            if (mb_type&MB_TYPE_INTER4V) {
2813
                s->mv_type = MV_TYPE_8X8;
2814
            } else {
2815
                s->mv_type = MV_TYPE_16X16;
2816
            }
2817
            /* decode each block */
2818
            for (i = 0; i < 6; i++) {
2819
                if(mpeg4_decode_block(s, block[i], i, cbp&32, 0) < 0){
2820
                    fprintf(stderr, "texture corrupted at %d %d (trying to continue with mc/dc only)\n", s->mb_x, s->mb_y);
2821
                    return -1;
2822
                }
2823
                cbp+=cbp;
2824
            }
2825
        }
2826
    } else { /* I-Frame */
2827
        int i;
2828
        s->mb_intra = 1;
2829
        s->ac_pred = s->pred_dir_table[xy]>>7;
2830
        
2831
        /* decode each block */
2832
        for (i = 0; i < 6; i++) {
2833
            if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){
2834
                fprintf(stderr, "texture corrupted at %d %d (trying to continue with dc only)\n", s->mb_x, s->mb_y);
2835
                return -1;
2836
            }
2837
            cbp+=cbp;
2838
        }
2839
    }
2840

    
2841
    s->error_status_table[xy]&= ~AC_ERROR;
2842

    
2843
    /* per-MB end of slice check */
2844

    
2845
    if(--s->mb_num_left <= 0){
2846
//printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size*8 - get_bits_count(&s->gb));
2847
        if(mpeg4_is_resync(s))
2848
            return SLICE_END;
2849
        else
2850
            return SLICE_NOEND;     
2851
    }else{
2852
        if(s->cbp_table[xy+1] && mpeg4_is_resync(s))
2853
            return SLICE_END;
2854
        else
2855
            return SLICE_OK;
2856
    }
2857
}
2858

    
2859
int ff_h263_decode_mb(MpegEncContext *s,
2860
                      DCTELEM block[6][64])
2861
{
2862
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
2863
    INT16 *mot_val;
2864
    static INT8 quant_tab[4] = { -1, -2, 1, 2 };
2865

    
2866
    s->error_status_table[s->mb_x + s->mb_y*s->mb_width]= 0;
2867

    
2868
    if(s->mb_x==0) PRINT_MB_TYPE("\n");
2869

    
2870
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
2871
        if (get_bits1(&s->gb)) {
2872
            /* skip mb */
2873
            s->mb_intra = 0;
2874
            for(i=0;i<6;i++)
2875
                s->block_last_index[i] = -1;
2876
            s->mv_dir = MV_DIR_FORWARD;
2877
            s->mv_type = MV_TYPE_16X16;
2878
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2879
                const int a= s->sprite_warping_accuracy;
2880
//                int l = (1 << (s->f_code - 1)) * 32;
2881
                PRINT_MB_TYPE("G");
2882
                s->mcsel=1;
2883
                if(s->divx_version==500 && s->divx_build==413){
2884
                    s->mv[0][0][0] = s->sprite_offset[0][0] / (1<<(a-s->quarter_sample));
2885
                    s->mv[0][0][1] = s->sprite_offset[0][1] / (1<<(a-s->quarter_sample));
2886
                }else{
2887
                    s->mv[0][0][0] = RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
2888
                    s->mv[0][0][1] = RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
2889
                }
2890
/*                if (s->mv[0][0][0] < -l) s->mv[0][0][0]= -l;
2891
                else if (s->mv[0][0][0] >= l) s->mv[0][0][0]= l-1;
2892
                if (s->mv[0][0][1] < -l) s->mv[0][0][1]= -l;
2893
                else if (s->mv[0][0][1] >= l) s->mv[0][0][1]= l-1;*/
2894

    
2895
                s->mb_skiped = 0;
2896
            }else{
2897
                PRINT_MB_TYPE("S");
2898
                s->mcsel=0;
2899
                s->mv[0][0][0] = 0;
2900
                s->mv[0][0][1] = 0;
2901
                s->mb_skiped = 1;
2902
            }
2903
            goto end;
2904
        }
2905
        cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
2906
        //fprintf(stderr, "\tCBPC: %d", cbpc);
2907
        if (cbpc < 0)
2908
            return -1;
2909
        if (cbpc > 20)
2910
            cbpc+=3;
2911
        else if (cbpc == 20)
2912
            fprintf(stderr, "Stuffing !");
2913
        
2914
        dquant = cbpc & 8;
2915
        s->mb_intra = ((cbpc & 4) != 0);
2916
        if (s->mb_intra) goto intra;
2917
        
2918
        if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
2919
            s->mcsel= get_bits1(&s->gb);
2920
        else s->mcsel= 0;
2921
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2922
        cbp = (cbpc & 3) | ((cbpy ^ 0xf) << 2);
2923
        if (dquant) {
2924
            change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2925
        }
2926
        if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
2927
            s->interlaced_dct= get_bits1(&s->gb);
2928
        
2929
        s->mv_dir = MV_DIR_FORWARD;
2930
        if ((cbpc & 16) == 0) {
2931
            if(s->mcsel){
2932
                const int a= s->sprite_warping_accuracy;
2933
                PRINT_MB_TYPE("G");
2934
                /* 16x16 global motion prediction */
2935
                s->mv_type = MV_TYPE_16X16;
2936
//        int l = (1 << (s->f_code - 1)) * 32;
2937
                if(s->divx_version==500 && s->divx_build==413){
2938
                    mx = s->sprite_offset[0][0] / (1<<(a-s->quarter_sample));
2939
                    my = s->sprite_offset[0][1] / (1<<(a-s->quarter_sample));
2940
                }else{
2941
                    mx = RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
2942
                    my = RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
2943
                }
2944
//       int l = (1 << (s->f_code - 1)) * 32;
2945
                s->mv[0][0][0] = mx;
2946
                s->mv[0][0][1] = my;
2947
            }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
2948
                PRINT_MB_TYPE("f");
2949
                /* 16x8 field motion prediction */
2950
                s->mv_type= MV_TYPE_FIELD;
2951

    
2952
                s->field_select[0][0]= get_bits1(&s->gb);
2953
                s->field_select[0][1]= get_bits1(&s->gb);
2954

    
2955
                h263_pred_motion(s, 0, &pred_x, &pred_y);
2956
                
2957
                for(i=0; i<2; i++){
2958
                    mx = h263_decode_motion(s, pred_x, s->f_code);
2959
                    if (mx >= 0xffff)
2960
                        return -1;
2961
            
2962
                    my = h263_decode_motion(s, pred_y/2, s->f_code);
2963
                    if (my >= 0xffff)
2964
                        return -1;
2965

    
2966
                    s->mv[0][i][0] = mx;
2967
                    s->mv[0][i][1] = my;
2968
                }
2969
            }else{
2970
                PRINT_MB_TYPE("P");
2971
                /* 16x16 motion prediction */
2972
                s->mv_type = MV_TYPE_16X16;
2973
                h263_pred_motion(s, 0, &pred_x, &pred_y);
2974
                if (s->umvplus_dec)
2975
                   mx = h263p_decode_umotion(s, pred_x);
2976
                else
2977
                   mx = h263_decode_motion(s, pred_x, s->f_code);
2978
            
2979
                if (mx >= 0xffff)
2980
                    return -1;
2981
            
2982
                if (s->umvplus_dec)
2983
                   my = h263p_decode_umotion(s, pred_y);
2984
                else
2985
                   my = h263_decode_motion(s, pred_y, s->f_code);
2986
            
2987
                if (my >= 0xffff)
2988
                    return -1;
2989
                s->mv[0][0][0] = mx;
2990
                s->mv[0][0][1] = my;
2991

    
2992
                if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
2993
                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */                   
2994
            }
2995
        } else {
2996
            PRINT_MB_TYPE("4");
2997
            s->mv_type = MV_TYPE_8X8;
2998
            for(i=0;i<4;i++) {
2999
                mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
3000
                if (s->umvplus_dec)
3001
                  mx = h263p_decode_umotion(s, pred_x);
3002
                else
3003
                  mx = h263_decode_motion(s, pred_x, s->f_code);
3004
                if (mx >= 0xffff)
3005
                    return -1;
3006
                
3007
                if (s->umvplus_dec)
3008
                  my = h263p_decode_umotion(s, pred_y);
3009
                else    
3010
                  my = h263_decode_motion(s, pred_y, s->f_code);
3011
                if (my >= 0xffff)
3012
                    return -1;
3013
                s->mv[0][i][0] = mx;
3014
                s->mv[0][i][1] = my;
3015
                if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
3016
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3017
                mot_val[0] = mx;
3018
                mot_val[1] = my;
3019
            }
3020
        }
3021
    } else if(s->pict_type==B_TYPE) {
3022
        int modb1; // first bit of modb
3023
        int modb2; // second bit of modb
3024
        int mb_type;
3025
        uint16_t time_pp;
3026
        uint16_t time_pb;
3027
        int xy;
3028

    
3029
        s->mb_intra = 0; //B-frames never contain intra blocks
3030
        s->mcsel=0;      //     ...               true gmc blocks
3031

    
3032
        if(s->mb_x==0){
3033
            for(i=0; i<2; i++){
3034
                s->last_mv[i][0][0]= 
3035
                s->last_mv[i][0][1]= 
3036
                s->last_mv[i][1][0]= 
3037
                s->last_mv[i][1][1]= 0;
3038
            }
3039
        }
3040

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

    
3044
        if(s->mb_skiped){
3045
                /* skip mb */
3046
            for(i=0;i<6;i++)
3047
                s->block_last_index[i] = -1;
3048

    
3049
            s->mv_dir = MV_DIR_FORWARD;
3050
            s->mv_type = MV_TYPE_16X16;
3051
            s->mv[0][0][0] = 0;
3052
            s->mv[0][0][1] = 0;
3053
            s->mv[1][0][0] = 0;
3054
            s->mv[1][0][1] = 0;
3055
            PRINT_MB_TYPE("s");
3056
            goto end;
3057
        }
3058

    
3059
        modb1= get_bits1(&s->gb); 
3060
        if(modb1){
3061
            mb_type=4; //like MB_TYPE_B_DIRECT but no vectors coded
3062
            cbp=0;
3063
        }else{
3064
            int field_mv;
3065
        
3066
            modb2= get_bits1(&s->gb);
3067
            mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
3068
            if(modb2) cbp= 0;
3069
            else      cbp= get_bits(&s->gb, 6);
3070

    
3071
            if (mb_type!=MB_TYPE_B_DIRECT && cbp) {
3072
                if(get_bits1(&s->gb)){
3073
                    change_qscale(s, get_bits1(&s->gb)*4 - 2);
3074
                }
3075
            }
3076
            field_mv=0;
3077

    
3078
            if(!s->progressive_sequence){
3079
                if(cbp)
3080
                    s->interlaced_dct= get_bits1(&s->gb);
3081

    
3082
                if(mb_type!=MB_TYPE_B_DIRECT && get_bits1(&s->gb)){
3083
                    field_mv=1;
3084

    
3085
                    if(mb_type!=MB_TYPE_B_BACKW){
3086
                        s->field_select[0][0]= get_bits1(&s->gb);
3087
                        s->field_select[0][1]= get_bits1(&s->gb);
3088
                    }
3089
                    if(mb_type!=MB_TYPE_B_FORW){
3090
                        s->field_select[1][0]= get_bits1(&s->gb);
3091
                        s->field_select[1][1]= get_bits1(&s->gb);
3092
                    }
3093
                }
3094
            }
3095

    
3096
            s->mv_dir = 0;
3097
            if(mb_type!=MB_TYPE_B_DIRECT && !field_mv){
3098
                s->mv_type= MV_TYPE_16X16;
3099
                if(mb_type!=MB_TYPE_B_BACKW){
3100
                    s->mv_dir = MV_DIR_FORWARD;
3101

    
3102
                    mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
3103
                    my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
3104
                    s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
3105
                    s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
3106
                }
3107
    
3108
                if(mb_type!=MB_TYPE_B_FORW){
3109
                    s->mv_dir |= MV_DIR_BACKWARD;
3110

    
3111
                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
3112
                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
3113
                    s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
3114
                    s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
3115
                }
3116
                if(mb_type!=MB_TYPE_B_DIRECT)
3117
                    PRINT_MB_TYPE(mb_type==MB_TYPE_B_FORW ? "F" : (mb_type==MB_TYPE_B_BACKW ? "B" : "T"));
3118
            }else if(mb_type!=MB_TYPE_B_DIRECT){
3119
                s->mv_type= MV_TYPE_FIELD;
3120

    
3121
                if(mb_type!=MB_TYPE_B_BACKW){
3122
                    s->mv_dir = MV_DIR_FORWARD;
3123
                
3124
                    for(i=0; i<2; i++){
3125
                        mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
3126
                        my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
3127
                        s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
3128
                        s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
3129
                    }
3130
                }
3131
    
3132
                if(mb_type!=MB_TYPE_B_FORW){
3133
                    s->mv_dir |= MV_DIR_BACKWARD;
3134

    
3135
                    for(i=0; i<2; i++){
3136
                        mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
3137
                        my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
3138
                        s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
3139
                        s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
3140
                    }
3141
                }
3142
                if(mb_type!=MB_TYPE_B_DIRECT)
3143
                    PRINT_MB_TYPE(mb_type==MB_TYPE_B_FORW ? "f" : (mb_type==MB_TYPE_B_BACKW ? "b" : "t"));
3144
            }
3145
        }
3146
          
3147
        if(mb_type==4 || mb_type==MB_TYPE_B_DIRECT){
3148
            int mb_index= s->mb_x + s->mb_y*s->mb_width;
3149
            int i;
3150
            
3151
            if(mb_type==4)
3152
                mx=my=0;
3153
            else{
3154
                mx = h263_decode_motion(s, 0, 1);
3155
                my = h263_decode_motion(s, 0, 1);
3156
            }
3157
 
3158
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3159
            xy= s->block_index[0];
3160
            time_pp= s->pp_time;
3161
            time_pb= s->pb_time;
3162
            
3163
            //FIXME avoid divides
3164
            switch(s->co_located_type_table[mb_index]){
3165
            case 0:
3166
                s->mv_type= MV_TYPE_16X16;
3167
                s->mv[0][0][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
3168
                s->mv[0][0][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
3169
                s->mv[1][0][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
3170
                                    : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
3171
                s->mv[1][0][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1] 
3172
                                    : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
3173
                PRINT_MB_TYPE(mb_type==4 ? "D" : "S");
3174
                break;
3175
            case CO_LOCATED_TYPE_4MV:
3176
                s->mv_type = MV_TYPE_8X8;
3177
                for(i=0; i<4; i++){
3178
                    xy= s->block_index[i];
3179
                    s->mv[0][i][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
3180
                    s->mv[0][i][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
3181
                    s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->motion_val[xy][0]
3182
                                        : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
3183
                    s->mv[1][i][1] = my ? s->mv[0][i][1] - s->motion_val[xy][1] 
3184
                                        : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
3185
                }
3186
                PRINT_MB_TYPE("4");
3187
                break;
3188
            case CO_LOCATED_TYPE_FIELDMV:
3189
                s->mv_type = MV_TYPE_FIELD;
3190
                for(i=0; i<2; i++){
3191
                    if(s->top_field_first){
3192
                        time_pp= s->pp_field_time - s->field_select_table[mb_index][i] + i;
3193
                        time_pb= s->pb_field_time - s->field_select_table[mb_index][i] + i;
3194
                    }else{
3195
                        time_pp= s->pp_field_time + s->field_select_table[mb_index][i] - i;
3196
                        time_pb= s->pb_field_time + s->field_select_table[mb_index][i] - i;
3197
                    }
3198
                    s->mv[0][i][0] = s->field_mv_table[mb_index][i][0]*time_pb/time_pp + mx;
3199
                    s->mv[0][i][1] = s->field_mv_table[mb_index][i][1]*time_pb/time_pp + my;
3200
                    s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->field_mv_table[mb_index][i][0]
3201
                                        : s->field_mv_table[mb_index][i][0]*(time_pb - time_pp)/time_pp;
3202
                    s->mv[1][i][1] = my ? s->mv[0][i][1] - s->field_mv_table[mb_index][i][1] 
3203
                                        : s->field_mv_table[mb_index][i][1]*(time_pb - time_pp)/time_pp;
3204
                }
3205
                PRINT_MB_TYPE("=");
3206
                break;
3207
            }
3208
        }
3209
        
3210
        if(mb_type<0 || mb_type>4){
3211
            printf("illegal MB_type\n");
3212
            return -1;
3213
        }
3214
    } else { /* I-Frame */
3215
        cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
3216
        if (cbpc < 0)
3217
            return -1;
3218
        dquant = cbpc & 4;
3219
        s->mb_intra = 1;
3220
intra:
3221
        s->ac_pred = 0;
3222
        if (s->h263_pred || s->h263_aic) {
3223
            s->ac_pred = get_bits1(&s->gb);
3224
            if (s->ac_pred && s->h263_aic)
3225
                s->h263_aic_dir = get_bits1(&s->gb);
3226
        }
3227
        PRINT_MB_TYPE(s->ac_pred ? "A" : "I");
3228
        
3229
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3230
        if(cbpy<0) return -1;
3231
        cbp = (cbpc & 3) | (cbpy << 2);
3232
        if (dquant) {
3233
            change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3234
        }
3235
        
3236
        if(!s->progressive_sequence)
3237
            s->interlaced_dct= get_bits1(&s->gb);
3238

    
3239
        /* decode each block */
3240
        if (s->h263_pred) {
3241
            for (i = 0; i < 6; i++) {
3242
                if (mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0)
3243
                    return -1;
3244
                cbp+=cbp;
3245
            }
3246
        } else {
3247
            for (i = 0; i < 6; i++) {
3248
                if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3249
                    return -1;
3250
                cbp+=cbp;
3251
            }
3252
        }
3253
        goto end;
3254
    }
3255

    
3256
    /* decode each block */
3257
    if (s->h263_pred) {
3258
        for (i = 0; i < 6; i++) {
3259
            if (mpeg4_decode_block(s, block[i], i, cbp&32, 0) < 0)
3260
                return -1;
3261
            cbp+=cbp;
3262
        }
3263
    } else {
3264
        for (i = 0; i < 6; i++) {
3265
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3266
                return -1;
3267
            cbp+=cbp;
3268
        }
3269
    }
3270
end:
3271

    
3272
        /* per-MB end of slice check */
3273
    if(s->codec_id==CODEC_ID_MPEG4){
3274
        if(mpeg4_is_resync(s)){
3275
            if(s->pict_type==B_TYPE && s->mbskip_table[s->mb_y * s->mb_width + s->mb_x+1])
3276
                return SLICE_OK;
3277
            return SLICE_END;
3278
        }
3279
    }else{
3280
        if(get_bits_count(&s->gb) + 7 >= s->gb.size*8){
3281
            int v= show_bits(&s->gb, 8) >> (((get_bits_count(&s->gb)-1)&7)+1);
3282
            if(v==0)
3283
                return SLICE_END;
3284
        }else{
3285
            if(show_bits(&s->gb, 16)==0)
3286
                return SLICE_END; 
3287
        }
3288
    }
3289

    
3290
    return SLICE_OK;     
3291
}
3292

    
3293
static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
3294
{
3295
    int code, val, sign, shift, l;
3296
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
3297
    if (code < 0)
3298
        return 0xffff;
3299

    
3300
    if (code == 0)
3301
        return pred;
3302

    
3303
    sign = get_bits1(&s->gb);
3304
    shift = f_code - 1;
3305
    val = (code - 1) << shift;
3306
    if (shift > 0)
3307
        val |= get_bits(&s->gb, shift);
3308
    val++;
3309
    if (sign)
3310
        val = -val;
3311
    val += pred;
3312

    
3313
    /* modulo decoding */
3314
    if (!s->h263_long_vectors) {
3315
        l = 1 << (f_code + 4);
3316
        if (val < -l) {
3317
            val += l<<1;
3318
        } else if (val >= l) {
3319
            val -= l<<1;
3320
        }
3321
    } else {
3322
        /* horrible h263 long vector mode */
3323
        if (pred < -31 && val < -63)
3324
            val += 64;
3325
        if (pred > 32 && val > 63)
3326
            val -= 64;
3327
        
3328
    }
3329
    return val;
3330
}
3331

    
3332
/* Decodes RVLC of H.263+ UMV */
3333
static int h263p_decode_umotion(MpegEncContext * s, int pred)
3334
{
3335
   int code = 0, sign;
3336
   
3337
   if (get_bits1(&s->gb)) /* Motion difference = 0 */
3338
      return pred;
3339
   
3340
   code = 2 + get_bits1(&s->gb);
3341
   
3342
   while (get_bits1(&s->gb))
3343
   {
3344
      code <<= 1;
3345
      code += get_bits1(&s->gb);
3346
   }
3347
   sign = code & 1;
3348
   code >>= 1;
3349
   
3350
   code = (sign) ? (pred - code) : (pred + code);
3351
#ifdef DEBUG
3352
   fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
3353
#endif
3354
   return code;   
3355

    
3356
}
3357

    
3358
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
3359
                             int n, int coded)
3360
{
3361
    int code, level, i, j, last, run;
3362
    RLTable *rl = &rl_inter;
3363
    const UINT8 *scan_table;
3364

    
3365
    scan_table = s->intra_scantable.permutated;
3366
    if (s->h263_aic && s->mb_intra) {
3367
        rl = &rl_intra_aic;
3368
        i = 0;
3369
        if (s->ac_pred) {
3370
            if (s->h263_aic_dir) 
3371
                scan_table = s->intra_v_scantable.permutated; /* left */
3372
            else
3373
                scan_table = s->intra_h_scantable.permutated; /* top */
3374
        }
3375
    } else if (s->mb_intra) {
3376
        /* DC coef */
3377
        if (s->h263_rv10 && s->rv10_version == 3 && s->pict_type == I_TYPE) {
3378
            int component, diff;
3379
            component = (n <= 3 ? 0 : n - 4 + 1);
3380
            level = s->last_dc[component];
3381
            if (s->rv10_first_dc_coded[component]) {
3382
                diff = rv_decode_dc(s, n);
3383
                if (diff == 0xffff)
3384
                    return -1;
3385
                level += diff;
3386
                level = level & 0xff; /* handle wrap round */
3387
                s->last_dc[component] = level;
3388
            } else {
3389
                s->rv10_first_dc_coded[component] = 1;
3390
            }
3391
        } else {
3392
            level = get_bits(&s->gb, 8);
3393
            if (level == 255)
3394
                level = 128;
3395
        }
3396
        block[0] = level;
3397
        i = 1;
3398
    } else {
3399
        i = 0;
3400
    }
3401
    if (!coded) {
3402
        if (s->mb_intra && s->h263_aic)
3403
            goto not_coded;
3404
        s->block_last_index[n] = i - 1;
3405
        return 0;
3406
    }
3407

    
3408
    for(;;) {
3409
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
3410
        if (code < 0){
3411
            fprintf(stderr, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
3412
            return -1;
3413
        }
3414
        if (code == rl->n) {
3415
            /* escape */
3416
            last = get_bits1(&s->gb);
3417
            run = get_bits(&s->gb, 6);
3418
            level = (INT8)get_bits(&s->gb, 8);
3419
            if (s->h263_rv10 && level == -128) {
3420
                /* XXX: should patch encoder too */
3421
                level = get_bits(&s->gb, 12);
3422
                level= (level + ((-1)<<11)) ^ ((-1)<<11); //sign extension
3423
            }
3424
        } else {
3425
            run = rl->table_run[code];
3426
            level = rl->table_level[code];
3427
            last = code >= rl->last;
3428
            if (get_bits1(&s->gb))
3429
                level = -level;
3430
        }
3431
        i += run;
3432
        if (i >= 64){
3433
            fprintf(stderr, "run overflow at %dx%d\n", s->mb_x, s->mb_y);
3434
            return -1;
3435
        }
3436
        j = scan_table[i];
3437
        block[j] = level;
3438
        if (last)
3439
            break;
3440
        i++;
3441
    }
3442
not_coded:    
3443
    if (s->mb_intra && s->h263_aic) {
3444
        h263_pred_acdc(s, block, n);
3445
        i = 63;
3446
    }
3447
    s->block_last_index[n] = i;
3448
    return 0;
3449
}
3450

    
3451
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
3452
{
3453
    int level, pred, code;
3454
    UINT16 *dc_val;
3455

    
3456
    if (n < 4) 
3457
        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
3458
    else 
3459
        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
3460
    if (code < 0 || code > 9 /* && s->nbit<9 */){
3461
        fprintf(stderr, "illegal dc vlc\n");
3462
        return -1;
3463
    }
3464
    if (code == 0) {
3465
        level = 0;
3466
    } else {
3467
        level = get_bits(&s->gb, code);
3468
        if ((level >> (code - 1)) == 0) /* if MSB not set it is negative*/
3469
            level = - (level ^ ((1 << code) - 1));
3470
        if (code > 8){
3471
            if(get_bits1(&s->gb)==0){ /* marker */
3472
                if(s->error_resilience>=2){
3473
                    fprintf(stderr, "dc marker bit missing\n");
3474
                    return -1;
3475
                }
3476
            }
3477
        }
3478
    }
3479
    pred = ff_mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
3480
    level += pred;
3481
    if (level < 0){
3482
        if(s->error_resilience>=3){
3483
            fprintf(stderr, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
3484
            return -1;
3485
        }
3486
        level = 0;
3487
    }
3488
    if (n < 4) {
3489
        *dc_val = level * s->y_dc_scale;
3490
    } else {
3491
        *dc_val = level * s->c_dc_scale;
3492
    }
3493
    if(s->error_resilience>=3){
3494
        if(*dc_val > 2048 + s->y_dc_scale + s->c_dc_scale){
3495
            fprintf(stderr, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
3496
            return -1;
3497
        }
3498
    }
3499
    return level;
3500
}
3501

    
3502
/**
3503
 * decodes a block.
3504
 * @return <0 if an error occured
3505
 */
3506
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
3507
                              int n, int coded, int intra)
3508
{
3509
    int level, i, last, run;
3510
    int dc_pred_dir;
3511
    RLTable * rl;
3512
    RL_VLC_ELEM * rl_vlc;
3513
    const UINT8 * scan_table;
3514
    int qmul, qadd;
3515

    
3516
    if(intra) {
3517
        /* DC coef */
3518
        if(s->partitioned_frame){
3519
            level = s->dc_val[0][ s->block_index[n] ];
3520
            if(n<4) level= (level + (s->y_dc_scale>>1))/s->y_dc_scale; //FIXME optimizs
3521
            else    level= (level + (s->c_dc_scale>>1))/s->c_dc_scale;
3522
            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_width]<<n)&32;
3523
        }else{
3524
            level = mpeg4_decode_dc(s, n, &dc_pred_dir);
3525
            if (level < 0)
3526
                return -1;
3527
        }
3528
        block[0] = level;
3529
        i = 0;
3530
        if (!coded) 
3531
            goto not_coded;
3532
        rl = &rl_intra;
3533
        rl_vlc = rl_intra.rl_vlc[0];
3534
        if (s->ac_pred) {
3535
            if (dc_pred_dir == 0) 
3536
                scan_table = s->intra_v_scantable.permutated; /* left */
3537
            else
3538
                scan_table = s->intra_h_scantable.permutated; /* top */
3539
        } else {
3540
            scan_table = s->intra_scantable.permutated;
3541
        }
3542
        qmul=1;
3543
        qadd=0;
3544
    } else {
3545
        i = -1;
3546
        if (!coded) {
3547
            s->block_last_index[n] = i;
3548
            return 0;
3549
        }
3550
        rl = &rl_inter;
3551
   
3552
        scan_table = s->intra_scantable.permutated;
3553

    
3554
        if(s->mpeg_quant){
3555
            qmul=1;
3556
            qadd=0;
3557
            rl_vlc = rl_inter.rl_vlc[0];        
3558
        }else{
3559
            qmul = s->qscale << 1;
3560
            qadd = (s->qscale - 1) | 1;
3561
            rl_vlc = rl_inter.rl_vlc[s->qscale];
3562
        }
3563
    }
3564
  {
3565
    OPEN_READER(re, &s->gb);
3566
    for(;;) {
3567
        UPDATE_CACHE(re, &s->gb);
3568
        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3569
        if (level==0) {
3570
            int cache;
3571
            cache= GET_CACHE(re, &s->gb);
3572
            /* escape */
3573
            if (cache&0x80000000) {
3574
                if (cache&0x40000000) {
3575
                    /* third escape */
3576
                    SKIP_CACHE(re, &s->gb, 2);
3577
                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
3578
                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
3579
                    SKIP_COUNTER(re, &s->gb, 2+1+6);
3580
                    UPDATE_CACHE(re, &s->gb);
3581

    
3582
                    if(SHOW_UBITS(re, &s->gb, 1)==0){
3583
                        fprintf(stderr, "1. marker bit missing in 3. esc\n");
3584
                        return -1;
3585
                    }; SKIP_CACHE(re, &s->gb, 1);
3586
                    
3587
                    level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
3588
 
3589
                    if(SHOW_UBITS(re, &s->gb, 1)==0){
3590
                        fprintf(stderr, "2. marker bit missing in 3. esc\n");
3591
                        return -1;
3592
                    }; LAST_SKIP_CACHE(re, &s->gb, 1);
3593
                    
3594
                    SKIP_COUNTER(re, &s->gb, 1+12+1);
3595
                    
3596
                    if(level*s->qscale>1024 || level*s->qscale<-1024){
3597
                        fprintf(stderr, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
3598
                        return -1;
3599
                    }
3600
#if 1 
3601
                    {
3602
                        const int abs_level= ABS(level);
3603
                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN && ((s->workaround_bugs&FF_BUG_AC_VLC)==0)){
3604
                            const int run1= run - rl->max_run[last][abs_level] - 1;
3605
                            if(abs_level <= rl->max_level[last][run]){
3606
                                fprintf(stderr, "illegal 3. esc, vlc encoding possible\n");
3607
                                return -1;
3608
                            }
3609
                            if(abs_level <= rl->max_level[last][run]*2){
3610
                                fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");
3611
                                return -1;
3612
                            }
3613
                            if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
3614
                                fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");
3615
                                return -1;
3616
                            }
3617
                        }
3618
                    }
3619
#endif
3620
                    if (level>0) level= level * qmul + qadd;
3621
                    else         level= level * qmul - qadd;
3622

    
3623
                    i+= run + 1;
3624
                    if(last) i+=192;
3625
                } else {
3626
                    /* second escape */
3627
#if MIN_CACHE_BITS < 20
3628
                    LAST_SKIP_BITS(re, &s->gb, 2);
3629
                    UPDATE_CACHE(re, &s->gb);
3630
#else
3631
                    SKIP_BITS(re, &s->gb, 2);
3632
#endif
3633
                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3634
                    i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
3635
                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3636
                    LAST_SKIP_BITS(re, &s->gb, 1);
3637
                }
3638
            } else {
3639
                /* first escape */
3640
#if MIN_CACHE_BITS < 19
3641
                LAST_SKIP_BITS(re, &s->gb, 1);
3642
                UPDATE_CACHE(re, &s->gb);
3643
#else
3644
                SKIP_BITS(re, &s->gb, 1);
3645
#endif
3646
                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3647
                i+= run;
3648
                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
3649
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3650
                LAST_SKIP_BITS(re, &s->gb, 1);
3651
            }
3652
        } else {
3653
            i+= run;
3654
            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3655
            LAST_SKIP_BITS(re, &s->gb, 1);
3656
        }
3657
        if (i > 62){
3658
            i-= 192;
3659
            if(i&(~63)){
3660
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
3661
                return -1;
3662
            }
3663

    
3664
            block[scan_table[i]] = level;
3665
            break;
3666
        }
3667

    
3668
        block[scan_table[i]] = level;
3669
    }
3670
    CLOSE_READER(re, &s->gb);
3671
  }
3672
 not_coded:
3673
    if (s->mb_intra) {
3674
        mpeg4_pred_ac(s, block, n, dc_pred_dir);
3675
        if (s->ac_pred) {
3676
            i = 63; /* XXX: not optimal */
3677
        }
3678
    }
3679
    s->block_last_index[n] = i;
3680
    return 0;
3681
}
3682

    
3683
/* most is hardcoded. should extend to handle all h263 streams */
3684
int h263_decode_picture_header(MpegEncContext *s)
3685
{
3686
    int format, width, height;
3687

    
3688
    /* picture start code */
3689
    if (get_bits(&s->gb, 22) != 0x20) {
3690
        fprintf(stderr, "Bad picture start code\n");
3691
        return -1;
3692
    }
3693
    /* temporal reference */
3694
    s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
3695

    
3696
    /* PTYPE starts here */    
3697
    if (get_bits1(&s->gb) != 1) {
3698
        /* marker */
3699
        fprintf(stderr, "Bad marker\n");
3700
        return -1;
3701
    }
3702
    if (get_bits1(&s->gb) != 0) {
3703
        fprintf(stderr, "Bad H263 id\n");
3704
        return -1;        /* h263 id */
3705
    }
3706
    skip_bits1(&s->gb);        /* split screen off */
3707
    skip_bits1(&s->gb);        /* camera  off */
3708
    skip_bits1(&s->gb);        /* freeze picture release off */
3709

    
3710
    /* Reset GOB number */
3711
    s->gob_number = 0;
3712
        
3713
    format = get_bits(&s->gb, 3);
3714
    /*
3715
        0    forbidden
3716
        1    sub-QCIF
3717
        10   QCIF
3718
        7        extended PTYPE (PLUSPTYPE)
3719
    */
3720

    
3721
    if (format != 7 && format != 6) {
3722
        s->h263_plus = 0;
3723
        /* H.263v1 */
3724
        width = h263_format[format][0];
3725
        height = h263_format[format][1];
3726
        if (!width)
3727
            return -1;
3728
        
3729
        s->width = width;
3730
        s->height = height;
3731
        s->pict_type = I_TYPE + get_bits1(&s->gb);
3732

    
3733
        s->unrestricted_mv = get_bits1(&s->gb); 
3734
        s->h263_long_vectors = s->unrestricted_mv;
3735

    
3736
        if (get_bits1(&s->gb) != 0) {
3737
            fprintf(stderr, "H263 SAC not supported\n");
3738
            return -1;        /* SAC: off */
3739
        }
3740
        if (get_bits1(&s->gb) != 0) {
3741
            s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3742
        }   
3743
        
3744
        if (get_bits1(&s->gb) != 0) {
3745
            fprintf(stderr, "H263 PB frame not supported\n");
3746
            return -1;        /* not PB frame */
3747
        }
3748
        s->qscale = get_bits(&s->gb, 5);
3749
        skip_bits1(&s->gb);        /* Continuous Presence Multipoint mode: off */
3750
    } else {
3751
        int ufep;
3752
        
3753
        /* H.263v2 */
3754
        s->h263_plus = 1;
3755
        ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
3756

    
3757
        /* ufep other than 0 and 1 are reserved */        
3758
        if (ufep == 1) {
3759
            /* OPPTYPE */       
3760
            format = get_bits(&s->gb, 3);
3761
            dprintf("ufep=1, format: %d\n", format);
3762
            skip_bits(&s->gb,1); /* Custom PCF */
3763
            s->umvplus_dec = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */
3764
            skip_bits1(&s->gb); /* Syntax-based Arithmetic Coding (SAC) */
3765
            if (get_bits1(&s->gb) != 0) {
3766
                s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3767
            }
3768
            if (get_bits1(&s->gb) != 0) { /* Advanced Intra Coding (AIC) */
3769
                s->h263_aic = 1;
3770
            }
3771
            
3772
            skip_bits(&s->gb, 7);
3773
            /* these are the 7 bits: (in order of appearence  */
3774
            /* Deblocking Filter */
3775
            /* Slice Structured */
3776
            /* Reference Picture Selection */
3777
            /* Independent Segment Decoding */
3778
            /* Alternative Inter VLC */
3779
            /* Modified Quantization */
3780
            /* Prevent start code emulation */
3781

    
3782
            skip_bits(&s->gb, 3); /* Reserved */
3783
        } else if (ufep != 0) {
3784
            fprintf(stderr, "Bad UFEP type (%d)\n", ufep);
3785
            return -1;
3786
        }
3787
            
3788
        /* MPPTYPE */
3789
        s->pict_type = get_bits(&s->gb, 3) + I_TYPE;
3790
        dprintf("pict_type: %d\n", s->pict_type);
3791
        if (s->pict_type != I_TYPE &&
3792
            s->pict_type != P_TYPE)
3793
            return -1;
3794
        skip_bits(&s->gb, 2);
3795
        s->no_rounding = get_bits1(&s->gb);
3796
        dprintf("RTYPE: %d\n", s->no_rounding);
3797
        skip_bits(&s->gb, 4);
3798
        
3799
        /* Get the picture dimensions */
3800
        if (ufep) {
3801
            if (format == 6) {
3802
                /* Custom Picture Format (CPFMT) */
3803
                s->aspect_ratio_info = get_bits(&s->gb, 4);
3804
                dprintf("aspect: %d\n", s->aspect_ratio_info);
3805
                /* aspect ratios:
3806
                0 - forbidden
3807
                1 - 1:1
3808
                2 - 12:11 (CIF 4:3)
3809
                3 - 10:11 (525-type 4:3)
3810
                4 - 16:11 (CIF 16:9)
3811
                5 - 40:33 (525-type 16:9)
3812
                6-14 - reserved
3813
                */
3814
                width = (get_bits(&s->gb, 9) + 1) * 4;
3815
                skip_bits1(&s->gb);
3816
                height = get_bits(&s->gb, 9) * 4;
3817
                dprintf("\nH.263+ Custom picture: %dx%d\n",width,height);
3818
                if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
3819
                    /* aspected dimensions */
3820
                    s->aspected_width = get_bits(&s->gb, 8);
3821
                    s->aspected_height = get_bits(&s->gb, 8);
3822
                }
3823
            } else {
3824
                width = h263_format[format][0];
3825
                height = h263_format[format][1];
3826
            }
3827
            if ((width == 0) || (height == 0))
3828
                return -1;
3829
            s->width = width;
3830
            s->height = height;
3831
            if (s->umvplus_dec) {
3832
                skip_bits1(&s->gb); /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
3833
            }
3834
        }
3835
            
3836
        s->qscale = get_bits(&s->gb, 5);
3837
    }
3838
    /* PEI */
3839
    while (get_bits1(&s->gb) != 0) {
3840
        skip_bits(&s->gb, 8);
3841
    }
3842
    s->f_code = 1;
3843
    
3844
    if(s->h263_aic){
3845
         s->y_dc_scale_table= 
3846
         s->c_dc_scale_table= h263_aic_dc_scale_table;
3847
    }else{
3848
        s->y_dc_scale_table=
3849
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
3850
    }
3851

    
3852
    return 0;
3853
}
3854

    
3855
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
3856
{
3857
    int i;
3858
    int a= 2<<s->sprite_warping_accuracy;
3859
    int rho= 3-s->sprite_warping_accuracy;
3860
    int r=16/a;
3861
    const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
3862
    int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
3863
    int sprite_ref[4][2];
3864
    int virtual_ref[2][2];
3865
    int w2, h2;
3866
    int alpha=0, beta=0;
3867
    int w= s->width;
3868
    int h= s->height;
3869
//printf("SP %d\n", s->sprite_warping_accuracy);
3870
    for(i=0; i<s->num_sprite_warping_points; i++){
3871
        int length;
3872
        int x=0, y=0;
3873

    
3874
        length= get_vlc(&s->gb, &sprite_trajectory);
3875
        if(length){
3876
            x= get_bits(&s->gb, length);
3877
//printf("lx %d %d\n", length, x);
3878
            if ((x >> (length - 1)) == 0) /* if MSB not set it is negative*/
3879
                x = - (x ^ ((1 << length) - 1));
3880
        }
3881
        if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
3882
        
3883
        length= get_vlc(&s->gb, &sprite_trajectory);
3884
        if(length){
3885
            y=get_bits(&s->gb, length);
3886
//printf("ly %d %d\n", length, y);
3887
            if ((y >> (length - 1)) == 0) /* if MSB not set it is negative*/
3888
                y = - (y ^ ((1 << length) - 1));
3889
        }
3890
        skip_bits1(&s->gb); /* marker bit */
3891
//printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
3892
//if(i>0 && (x!=0 || y!=0)) printf("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n");
3893
//x=y=0;
3894
        d[i][0]= x;
3895
        d[i][1]= y;
3896
    }
3897

    
3898
    while((1<<alpha)<w) alpha++;
3899
    while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
3900
    w2= 1<<alpha;
3901
    h2= 1<<beta;
3902

    
3903
// Note, the 4th point isnt used for GMC
3904
    if(s->divx_version==500 && s->divx_build==413){
3905
        sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
3906
        sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
3907
        sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
3908
        sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
3909
        sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
3910
        sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
3911
    } else {
3912
        sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
3913
        sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
3914
        sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
3915
        sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
3916
        sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
3917
        sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
3918
    }
3919
/*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
3920
    sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
3921
    
3922
// this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
3923
// perhaps it should be reordered to be more readable ...
3924
// the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
3925
// so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
3926
    virtual_ref[0][0]= 16*(vop_ref[0][0] + w2) 
3927
        + 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);
3928
    virtual_ref[0][1]= 16*vop_ref[0][1] 
3929
        + 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);
3930
    virtual_ref[1][0]= 16*vop_ref[0][0] 
3931
        + 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);
3932
    virtual_ref[1][1]= 16*(vop_ref[0][1] + h2) 
3933
        + 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);
3934

    
3935
    switch(s->num_sprite_warping_points)
3936
    {
3937
        case 0:
3938
            s->sprite_offset[0][0]= 0;
3939
            s->sprite_offset[0][1]= 0;
3940
            s->sprite_offset[1][0]= 0;
3941
            s->sprite_offset[1][1]= 0;
3942
            s->sprite_delta[0][0][0]= a;
3943
            s->sprite_delta[0][0][1]= 0;
3944
            s->sprite_delta[0][1][0]= 0;
3945
            s->sprite_delta[0][1][1]= a;
3946
            s->sprite_delta[1][0][0]= a;
3947
            s->sprite_delta[1][0][1]= 0;
3948
            s->sprite_delta[1][1][0]= 0;
3949
            s->sprite_delta[1][1][1]= a;
3950
            s->sprite_shift[0][0]= 0;
3951
            s->sprite_shift[0][1]= 0;
3952
            s->sprite_shift[1][0]= 0;
3953
            s->sprite_shift[1][1]= 0;
3954
            break;
3955
        case 1: //GMC only
3956
            s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
3957
            s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
3958
            s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
3959
            s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
3960
            s->sprite_delta[0][0][0]= a;
3961
            s->sprite_delta[0][0][1]= 0;
3962
            s->sprite_delta[0][1][0]= 0;
3963
            s->sprite_delta[0][1][1]= a;
3964
            s->sprite_delta[1][0][0]= a;
3965
            s->sprite_delta[1][0][1]= 0;
3966
            s->sprite_delta[1][1][0]= 0;
3967
            s->sprite_delta[1][1][1]= a;
3968
            s->sprite_shift[0][0]= 0;
3969
            s->sprite_shift[0][1]= 0;
3970
            s->sprite_shift[1][0]= 0;
3971
            s->sprite_shift[1][1]= 0;
3972
            break;
3973
        case 2:
3974
        case 3: //FIXME
3975
            s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
3976
                                                  + ((-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
3977
                                                    +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1]));
3978
            s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
3979
                                                  + ((-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
3980
                                                    +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1]));
3981
            s->sprite_offset[1][0]= ((-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)
3982
                                 +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)
3983
                                 +2*w2*r*sprite_ref[0][0] - 16*w2);
3984
            s->sprite_offset[1][1]= ((-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1) 
3985
                                 +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)
3986
                                 +2*w2*r*sprite_ref[0][1] - 16*w2);
3987
            s->sprite_delta[0][0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
3988
            s->sprite_delta[0][0][1]=   ( r*sprite_ref[0][1] - virtual_ref[0][1]);
3989
            s->sprite_delta[0][1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);
3990
            s->sprite_delta[0][1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
3991
            s->sprite_delta[1][0][0]= 4*(-r*sprite_ref[0][0] + virtual_ref[0][0]);
3992
            s->sprite_delta[1][0][1]= 4*( r*sprite_ref[0][1] - virtual_ref[0][1]);
3993
            s->sprite_delta[1][1][0]= 4*(-r*sprite_ref[0][1] + virtual_ref[0][1]);
3994
            s->sprite_delta[1][1][1]= 4*(-r*sprite_ref[0][0] + virtual_ref[0][0]);
3995
            s->sprite_shift[0][0]= alpha+rho;
3996
            s->sprite_shift[0][1]= alpha+rho;
3997
            s->sprite_shift[1][0]= alpha+rho+2;
3998
            s->sprite_shift[1][1]= alpha+rho+2;
3999
            break;
4000
//        case 3:
4001
            break;
4002
    }
4003
/*printf("%d %d\n", s->sprite_delta[0][0][0], a<<s->sprite_shift[0][0]);
4004
printf("%d %d\n", s->sprite_delta[0][0][1], 0);
4005
printf("%d %d\n", s->sprite_delta[0][1][0], 0);
4006
printf("%d %d\n", s->sprite_delta[0][1][1], a<<s->sprite_shift[0][1]);
4007
printf("%d %d\n", s->sprite_delta[1][0][0], a<<s->sprite_shift[1][0]);
4008
printf("%d %d\n", s->sprite_delta[1][0][1], 0);
4009
printf("%d %d\n", s->sprite_delta[1][1][0], 0);
4010
printf("%d %d\n", s->sprite_delta[1][1][1], a<<s->sprite_shift[1][1]);*/
4011
    /* try to simplify the situation */ 
4012
    if(   s->sprite_delta[0][0][0] == a<<s->sprite_shift[0][0]
4013
       && s->sprite_delta[0][0][1] == 0
4014
       && s->sprite_delta[0][1][0] == 0
4015
       && s->sprite_delta[0][1][1] == a<<s->sprite_shift[0][1]
4016
       && s->sprite_delta[1][0][0] == a<<s->sprite_shift[1][0]
4017
       && s->sprite_delta[1][0][1] == 0
4018
       && s->sprite_delta[1][1][0] == 0
4019
       && s->sprite_delta[1][1][1] == a<<s->sprite_shift[1][1])
4020
    {
4021
        s->sprite_offset[0][0]>>=s->sprite_shift[0][0];
4022
        s->sprite_offset[0][1]>>=s->sprite_shift[0][1];
4023
        s->sprite_offset[1][0]>>=s->sprite_shift[1][0];
4024
        s->sprite_offset[1][1]>>=s->sprite_shift[1][1];
4025
        s->sprite_delta[0][0][0]= a;
4026
        s->sprite_delta[0][0][1]= 0;
4027
        s->sprite_delta[0][1][0]= 0;
4028
        s->sprite_delta[0][1][1]= a;
4029
        s->sprite_delta[1][0][0]= a;
4030
        s->sprite_delta[1][0][1]= 0;
4031
        s->sprite_delta[1][1][0]= 0;
4032
        s->sprite_delta[1][1][1]= a;
4033
        s->sprite_shift[0][0]= 0;
4034
        s->sprite_shift[0][1]= 0;
4035
        s->sprite_shift[1][0]= 0;
4036
        s->sprite_shift[1][1]= 0;
4037
        s->real_sprite_warping_points=1;
4038
    }
4039
    else
4040
        s->real_sprite_warping_points= s->num_sprite_warping_points;
4041

    
4042
//printf("%d %d %d %d\n", d[0][0], d[0][1], s->sprite_offset[0][0], s->sprite_offset[0][1]);
4043
}
4044

    
4045
static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){
4046
    int width, height, vo_ver_id;
4047

    
4048
    /* vol header */
4049
    skip_bits(gb, 1); /* random access */
4050
    s->vo_type= get_bits(gb, 8);
4051
    if (get_bits1(gb) != 0) { /* is_ol_id */
4052
        vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
4053
        skip_bits(gb, 3); /* vo_priority */
4054
    } else {
4055
        vo_ver_id = 1;
4056
    }
4057
//printf("vo type:%d\n",s->vo_type);
4058
    s->aspect_ratio_info= get_bits(gb, 4);
4059
    if(s->aspect_ratio_info == FF_ASPECT_EXTENDED){            
4060
        s->aspected_width = get_bits(gb, 8); // par_width
4061
        s->aspected_height = get_bits(gb, 8); // par_height
4062
    }
4063

    
4064
    if ((s->vol_control_parameters=get_bits1(gb))) { /* vol control parameter */
4065
        int chroma_format= get_bits(gb, 2);
4066
        if(chroma_format!=1){
4067
            printf("illegal chroma format\n");
4068
        }
4069
        s->low_delay= get_bits1(gb);
4070
        if(get_bits1(gb)){ /* vbv parameters */
4071
            get_bits(gb, 15);        /* first_half_bitrate */
4072
            skip_bits1(gb);        /* marker */
4073
            get_bits(gb, 15);        /* latter_half_bitrate */
4074
            skip_bits1(gb);        /* marker */
4075
            get_bits(gb, 15);        /* first_half_vbv_buffer_size */
4076
            skip_bits1(gb);        /* marker */
4077
            get_bits(gb, 3);        /* latter_half_vbv_buffer_size */
4078
            get_bits(gb, 11);        /* first_half_vbv_occupancy */
4079
            skip_bits1(gb);        /* marker */
4080
            get_bits(gb, 15);        /* latter_half_vbv_occupancy */
4081
            skip_bits1(gb);        /* marker */               
4082
        }
4083
    }else{
4084
        // set low delay flag only once so the smart? low delay detection wont be overriden
4085
        if(s->picture_number==0)
4086
            s->low_delay=0;
4087
    }
4088

    
4089
    s->shape = get_bits(gb, 2); /* vol shape */
4090
    if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");
4091
    if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
4092
        printf("Gray shape not supported\n");
4093
        skip_bits(gb, 4);  //video_object_layer_shape_extension
4094
    }
4095

    
4096
    skip_bits1(gb);   /* marker */
4097
    
4098
    s->time_increment_resolution = get_bits(gb, 16);
4099
    
4100
    s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
4101
    if (s->time_increment_bits < 1)
4102
        s->time_increment_bits = 1;
4103
    skip_bits1(gb);   /* marker */
4104

    
4105
    if (get_bits1(gb) != 0) {   /* fixed_vop_rate  */
4106
        skip_bits(gb, s->time_increment_bits);
4107
    }
4108

    
4109
    if (s->shape != BIN_ONLY_SHAPE) {
4110
        if (s->shape == RECT_SHAPE) {
4111
            skip_bits1(gb);   /* marker */
4112
            width = get_bits(gb, 13);
4113
            skip_bits1(gb);   /* marker */
4114
            height = get_bits(gb, 13);
4115
            skip_bits1(gb);   /* marker */
4116
            if(width && height){ /* they should be non zero but who knows ... */
4117
                s->width = width;
4118
                s->height = height;
4119
//                printf("width/height: %d %d\n", width, height);
4120
            }
4121
        }
4122
        
4123
        s->progressive_sequence= get_bits1(gb)^1;
4124
        if(!get_bits1(gb)) printf("OBMC not supported (very likely buggy encoder)\n");   /* OBMC Disable */
4125
        if (vo_ver_id == 1) {
4126
            s->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
4127
        } else {
4128
            s->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
4129
        }
4130
        if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");
4131
        if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
4132
            if(s->vol_sprite_usage==STATIC_SPRITE){
4133
                s->sprite_width = get_bits(gb, 13);
4134
                skip_bits1(gb); /* marker */
4135
                s->sprite_height= get_bits(gb, 13);
4136
                skip_bits1(gb); /* marker */
4137
                s->sprite_left  = get_bits(gb, 13);
4138
                skip_bits1(gb); /* marker */
4139
                s->sprite_top   = get_bits(gb, 13);
4140
                skip_bits1(gb); /* marker */
4141
            }
4142
            s->num_sprite_warping_points= get_bits(gb, 6);
4143
            s->sprite_warping_accuracy = get_bits(gb, 2);
4144
            s->sprite_brightness_change= get_bits1(gb);
4145
            if(s->vol_sprite_usage==STATIC_SPRITE)
4146
                s->low_latency_sprite= get_bits1(gb);            
4147
        }
4148
        // FIXME sadct disable bit if verid!=1 && shape not rect
4149
        
4150
        if (get_bits1(gb) == 1) {   /* not_8_bit */
4151
            s->quant_precision = get_bits(gb, 4); /* quant_precision */
4152
            if(get_bits(gb, 4)!=8) printf("N-bit not supported\n"); /* bits_per_pixel */
4153
            if(s->quant_precision!=5) printf("quant precission %d\n", s->quant_precision);
4154
        } else {
4155
            s->quant_precision = 5;
4156
        }
4157
        
4158
        // FIXME a bunch of grayscale shape things
4159

    
4160
        if((s->mpeg_quant=get_bits1(gb))){ /* vol_quant_type */
4161
            int i, j, v;
4162
            
4163
            /* load default matrixes */
4164
            for(i=0; i<64; i++){
4165
                int j= s->idct_permutation[i];
4166
                v= ff_mpeg4_default_intra_matrix[i];
4167
                s->intra_matrix[j]= v;
4168
                s->chroma_intra_matrix[j]= v;
4169
                
4170
                v= ff_mpeg4_default_non_intra_matrix[i];
4171
                s->inter_matrix[j]= v;
4172
                s->chroma_inter_matrix[j]= v;
4173
            }
4174

    
4175
            /* load custom intra matrix */
4176
            if(get_bits1(gb)){
4177
                int last=0;
4178
                for(i=0; i<64; i++){
4179
                    v= get_bits(gb, 8);
4180
                    if(v==0) break;
4181
                    
4182
                    last= v;
4183
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4184
                    s->intra_matrix[j]= v;
4185
                    s->chroma_intra_matrix[j]= v;
4186
                }
4187

    
4188
                /* replicate last value */
4189
                for(; i<64; i++){
4190
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4191
                    s->intra_matrix[j]= v;
4192
                    s->chroma_intra_matrix[j]= v;
4193
                }
4194
            }
4195

    
4196
            /* load custom non intra matrix */
4197
            if(get_bits1(gb)){
4198
                int last=0;
4199
                for(i=0; i<64; i++){
4200
                    v= get_bits(gb, 8);
4201
                    if(v==0) break;
4202

    
4203
                    last= v;
4204
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4205
                    s->inter_matrix[j]= v;
4206
                    s->chroma_inter_matrix[j]= v;
4207
                }
4208

    
4209
                /* replicate last value */
4210
                for(; i<64; i++){
4211
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4212
                    s->inter_matrix[j]= last;
4213
                    s->chroma_inter_matrix[j]= last;
4214
                }
4215
            }
4216

    
4217
            // FIXME a bunch of grayscale shape things
4218
        }
4219

    
4220
        if(vo_ver_id != 1)
4221
             s->quarter_sample= get_bits1(gb);
4222
        else s->quarter_sample=0;
4223

    
4224
        if(!get_bits1(gb)) printf("Complexity estimation not supported\n");
4225

    
4226
        s->resync_marker= !get_bits1(gb); /* resync_marker_disabled */
4227

    
4228
        s->data_partitioning= get_bits1(gb);
4229
        if(s->data_partitioning){
4230
            s->rvlc= get_bits1(gb);
4231
            if(s->rvlc){
4232
                printf("reversible vlc not supported\n");
4233
            }
4234
        }
4235
        
4236
        if(vo_ver_id != 1) {
4237
            s->new_pred= get_bits1(gb);
4238
            if(s->new_pred){
4239
                printf("new pred not supported\n");
4240
                skip_bits(gb, 2); /* requested upstream message type */
4241
                skip_bits1(gb); /* newpred segment type */
4242
            }
4243
            s->reduced_res_vop= get_bits1(gb);
4244
            if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");
4245
        }
4246
        else{
4247
            s->new_pred=0;
4248
            s->reduced_res_vop= 0;
4249
        }
4250

    
4251
        s->scalability= get_bits1(gb);
4252

    
4253
        if (s->scalability) {
4254
            GetBitContext bak= *gb;
4255
            int ref_layer_id;
4256
            int ref_layer_sampling_dir;
4257
            int h_sampling_factor_n;
4258
            int h_sampling_factor_m;
4259
            int v_sampling_factor_n;
4260
            int v_sampling_factor_m;
4261
            
4262
            s->hierachy_type= get_bits1(gb);
4263
            ref_layer_id= get_bits(gb, 4);
4264
            ref_layer_sampling_dir= get_bits1(gb);
4265
            h_sampling_factor_n= get_bits(gb, 5);
4266
            h_sampling_factor_m= get_bits(gb, 5);
4267
            v_sampling_factor_n= get_bits(gb, 5);
4268
            v_sampling_factor_m= get_bits(gb, 5);
4269
            s->enhancement_type= get_bits1(gb);
4270
            
4271
            if(   h_sampling_factor_n==0 || h_sampling_factor_m==0 
4272
               || v_sampling_factor_n==0 || v_sampling_factor_m==0){
4273
               
4274
//                fprintf(stderr, "illegal scalability header (VERY broken encoder), trying to workaround\n");
4275
                s->scalability=0;
4276
               
4277
                *gb= bak;
4278
            }else
4279
                printf("scalability not supported\n");
4280
            
4281
            // bin shape stuff FIXME
4282
        }
4283
    }
4284
    return 0;
4285
}
4286

    
4287
static int decode_user_data(MpegEncContext *s, GetBitContext *gb){
4288
    char buf[256];
4289
    int i;
4290
    int e;
4291
    int ver, build, ver2, ver3;
4292

    
4293
    buf[0]= show_bits(gb, 8);
4294
    for(i=1; i<256; i++){
4295
        buf[i]= show_bits(gb, 16)&0xFF;
4296
        if(buf[i]==0) break;
4297
        skip_bits(gb, 8);
4298
    }
4299
    buf[255]=0;
4300
    e=sscanf(buf, "DivX%dBuild%d", &ver, &build);
4301
    if(e!=2)
4302
        e=sscanf(buf, "DivX%db%d", &ver, &build);
4303
    if(e==2){
4304
        s->divx_version= ver;
4305
        s->divx_build= build;
4306
        if(s->picture_number==0){
4307
            printf("This file was encoded with DivX%d Build%d\n", ver, build);
4308
            if(ver==500 && build==413){
4309
                printf("WARNING: this version of DivX is not MPEG4 compatible, trying to workaround these bugs...\n");
4310
            }
4311
        }
4312
    }
4313
    e=sscanf(buf, "FFmpeg%d.%d.%db%d", &ver, &ver2, &ver3, &build);
4314
    if(e!=4)
4315
        e=sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); 
4316
    if(e!=4){
4317
        if(strcmp(buf, "ffmpeg")==0){
4318
            s->ffmpeg_version= 0x000406;
4319
            s->lavc_build= 4600;
4320
        }
4321
    }
4322
    if(e==4){
4323
        s->ffmpeg_version= ver*256*256 + ver2*256 + ver3;
4324
        s->lavc_build= build;
4325
        if(s->picture_number==0)
4326
            printf("This file was encoded with libavcodec build %d\n", build);
4327
    }
4328
//printf("User Data: %s\n", buf);
4329
    return 0;
4330
}
4331

    
4332
static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){
4333
    int time_incr, time_increment;
4334

    
4335
    s->pict_type = get_bits(gb, 2) + I_TYPE;        /* pict type: I = 0 , P = 1 */
4336
    if(s->pict_type==B_TYPE && s->low_delay && s->vol_control_parameters==0){
4337
        printf("low_delay flag set, but shouldnt, clearing it\n");
4338
        s->low_delay=0;
4339
    }
4340
// printf("pic: %d, qpel:%d part:%d resync:%d\n", s->pict_type, s->quarter_sample, s->data_partitioning, s->resync_marker); 
4341
    
4342
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
4343
    if(s->partitioned_frame)
4344
        s->decode_mb= mpeg4_decode_partitioned_mb;
4345
    else
4346
        s->decode_mb= ff_h263_decode_mb;
4347

    
4348
    if(s->time_increment_resolution==0){
4349
        s->time_increment_resolution=1;
4350
//        fprintf(stderr, "time_increment_resolution is illegal\n");
4351
    }
4352
    time_incr=0;
4353
    while (get_bits1(gb) != 0) 
4354
        time_incr++;
4355

    
4356
    check_marker(gb, "before time_increment");
4357
    time_increment= get_bits(gb, s->time_increment_bits);
4358
//printf(" type:%d modulo_time_base:%d increment:%d\n", s->pict_type, time_incr, time_increment);
4359
    if(s->pict_type!=B_TYPE){
4360
        s->last_time_base= s->time_base;
4361
        s->time_base+= time_incr;
4362
        s->time= s->time_base*s->time_increment_resolution + time_increment;
4363
        if(s->workaround_bugs&FF_BUG_UMP4){
4364
            if(s->time < s->last_non_b_time){
4365
//                fprintf(stderr, "header is not mpeg4 compatible, broken encoder, trying to workaround\n");
4366
                s->time_base++;
4367
                s->time+= s->time_increment_resolution;
4368
            }
4369
        }
4370
        s->pp_time= s->time - s->last_non_b_time;
4371
        s->last_non_b_time= s->time;
4372
    }else{
4373
        s->time= (s->last_time_base + time_incr)*s->time_increment_resolution + time_increment;
4374
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
4375
        if(s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0){
4376
//            printf("messed up order, seeking?, skiping current b frame\n");
4377
            return FRAME_SKIPED;
4378
        }
4379
        
4380
        if(s->t_frame==0) s->t_frame= s->time - s->last_time_base;
4381
        if(s->t_frame==0) s->t_frame=1; // 1/0 protection
4382
//printf("%Ld %Ld %d %d\n", s->last_non_b_time, s->time, s->pp_time, s->t_frame); fflush(stdout);
4383
        s->pp_field_time= (  ROUNDED_DIV(s->last_non_b_time, s->t_frame) 
4384
                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
4385
        s->pb_field_time= (  ROUNDED_DIV(s->time, s->t_frame) 
4386
                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
4387
    }
4388
    
4389
    s->avctx->pts= s->time*1000LL*1000LL / s->time_increment_resolution;
4390
    
4391
    if(check_marker(gb, "before vop_coded")==0 && s->picture_number==0){
4392
        printf("hmm, seems the headers arnt complete, trying to guess time_increment_bits\n");
4393
        for(s->time_increment_bits++ ;s->time_increment_bits<16; s->time_increment_bits++){
4394
            if(get_bits1(gb)) break;
4395
        }
4396
        printf("my guess is %d bits ;)\n",s->time_increment_bits);
4397
    }
4398
    /* vop coded */
4399
    if (get_bits1(gb) != 1){
4400
        printf("vop not coded\n");
4401
        return FRAME_SKIPED;
4402
    }
4403
//printf("time %d %d %d || %Ld %Ld %Ld\n", s->time_increment_bits, s->time_increment_resolution, s->time_base,
4404
//s->time, s->last_non_b_time, s->last_non_b_time - s->pp_time);  
4405
    if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == P_TYPE
4406
                          || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {
4407
        /* rounding type for motion estimation */
4408
        s->no_rounding = get_bits1(gb);
4409
    } else {
4410
        s->no_rounding = 0;
4411
    }
4412
//FIXME reduced res stuff
4413

    
4414
     if (s->shape != RECT_SHAPE) {
4415
         if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {
4416
             int width, height, hor_spat_ref, ver_spat_ref;
4417
 
4418
             width = get_bits(gb, 13);
4419
             skip_bits1(gb);   /* marker */
4420
             height = get_bits(gb, 13);
4421
             skip_bits1(gb);   /* marker */
4422
             hor_spat_ref = get_bits(gb, 13); /* hor_spat_ref */
4423
             skip_bits1(gb);   /* marker */
4424
             ver_spat_ref = get_bits(gb, 13); /* ver_spat_ref */
4425
         }
4426
         skip_bits1(gb); /* change_CR_disable */
4427
 
4428
         if (get_bits1(gb) != 0) {
4429
             skip_bits(gb, 8); /* constant_alpha_value */
4430
         }
4431
     }
4432
//FIXME complexity estimation stuff
4433
     
4434
     if (s->shape != BIN_ONLY_SHAPE) {
4435
         int t;
4436
         t=get_bits(gb, 3); /* intra dc VLC threshold */
4437
//printf("threshold %d\n", t);
4438
         if(!s->progressive_sequence){
4439
             s->top_field_first= get_bits1(gb);
4440
             s->alternate_scan= get_bits1(gb);
4441
         }else
4442
             s->alternate_scan= 0;
4443
     }
4444

    
4445
     if(s->alternate_scan){
4446
         ff_init_scantable(s, &s->inter_scantable  , ff_alternate_vertical_scan);
4447
         ff_init_scantable(s, &s->intra_scantable  , ff_alternate_vertical_scan);
4448
         ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_vertical_scan);
4449
         ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
4450
     } else{
4451
         ff_init_scantable(s, &s->inter_scantable  , ff_zigzag_direct);
4452
         ff_init_scantable(s, &s->intra_scantable  , ff_zigzag_direct);
4453
         ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_horizontal_scan);
4454
         ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
4455
     }
4456
 
4457
     if(s->pict_type == S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){
4458
         if(s->num_sprite_warping_points){
4459
             mpeg4_decode_sprite_trajectory(s);
4460
         }
4461
         if(s->sprite_brightness_change) printf("sprite_brightness_change not supported\n");
4462
         if(s->vol_sprite_usage==STATIC_SPRITE) printf("static sprite not supported\n");
4463
     }
4464

    
4465
     if (s->shape != BIN_ONLY_SHAPE) {
4466
         s->qscale = get_bits(gb, s->quant_precision);
4467
         if(s->qscale==0){
4468
             printf("Error, header damaged or not MPEG4 header (qscale=0)\n");
4469
             return -1; // makes no sense to continue, as there is nothing left from the image then
4470
         }
4471
  
4472
         if (s->pict_type != I_TYPE) {
4473
             s->f_code = get_bits(gb, 3);        /* fcode_for */
4474
             if(s->f_code==0){
4475
                 printf("Error, header damaged or not MPEG4 header (f_code=0)\n");
4476
                 return -1; // makes no sense to continue, as the MV decoding will break very quickly
4477
             }
4478
         }else
4479
             s->f_code=1;
4480
     
4481
         if (s->pict_type == B_TYPE) {
4482
             s->b_code = get_bits(gb, 3);
4483
         }else
4484
             s->b_code=1;
4485
#if 0
4486
printf("qp:%d fc:%d bc:%d type:%s size:%d pro:%d alt:%d top:%d qpel:%d part:%d resync:%d\n", 
4487
    s->qscale, s->f_code, s->b_code, 
4488
    s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")), 
4489
    gb->size,s->progressive_sequence, s->alternate_scan, s->top_field_first, 
4490
    s->quarter_sample, s->data_partitioning, s->resync_marker); 
4491
#endif
4492
         if(!s->scalability){
4493
             if (s->shape!=RECT_SHAPE && s->pict_type!=I_TYPE) {
4494
                 skip_bits1(gb); // vop shape coding type
4495
             }
4496
         }else{
4497
             if(s->enhancement_type){
4498
                 int load_backward_shape= get_bits1(gb);
4499
                 if(load_backward_shape){
4500
                     printf("load backward shape isnt supported\n");
4501
                 }
4502
             }
4503
             skip_bits(gb, 2); //ref_select_code
4504
         }
4505
     }
4506
     /* detect buggy encoders which dont set the low_delay flag (divx4/xvid/opendivx)*/
4507
     // note we cannot detect divx5 without b-frames easyly (allthough its buggy too)
4508
     if(s->vo_type==0 && s->vol_control_parameters==0 && s->divx_version==0 && s->picture_number==0){
4509
         printf("looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
4510
         s->low_delay=1;
4511
     }
4512

    
4513
     s->picture_number++; // better than pic number==0 allways ;)
4514

    
4515
     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support 
4516
     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
4517

    
4518
     if(s->divx_version==0 || s->divx_version < 500){
4519
         s->h_edge_pos= s->width;
4520
         s->v_edge_pos= s->height;
4521
     }
4522
     return 0;
4523
}
4524

    
4525
/**
4526
 * decode mpeg4 headers
4527
 * @return <0 if no VOP found (or a damaged one)
4528
 *         FRAME_SKIPPED if a not coded VOP is found
4529
 *         0 if a VOP is found
4530
 */
4531
int ff_mpeg4_decode_picture_header(MpegEncContext * s, GetBitContext *gb)
4532
{
4533
    int startcode, v;
4534

    
4535
    /* search next start code */
4536
    align_get_bits(gb);
4537
    startcode = 0xff;
4538
    for(;;) {
4539
        v = get_bits(gb, 8);
4540
        startcode = ((startcode << 8) | v) & 0xffffffff;
4541
        
4542
        if(get_bits_count(gb) >= gb->size*8){
4543
            if(gb->size==1 && s->divx_version){
4544
                printf("frame skip %d\n", gb->size);
4545
                return FRAME_SKIPED; //divx bug
4546
            }else
4547
                return -1; //end of stream
4548
        }
4549

    
4550
        if((startcode&0xFFFFFF00) != 0x100)
4551
            continue; //no startcode
4552
        
4553
        switch(startcode){
4554
        case 0x120:
4555
            decode_vol_header(s, gb);
4556
            break;
4557
        case 0x1b2:
4558
            decode_user_data(s, gb);
4559
            break;
4560
        case 0x1b6:
4561
            return decode_vop_header(s, gb);
4562
        default:
4563
//            printf("startcode %X found\n", startcode);
4564
            break;
4565
        }
4566

    
4567
        align_get_bits(gb);
4568
        startcode = 0xff;
4569
    }
4570
}
4571

    
4572
/* don't understand why they choose a different header ! */
4573
int intel_h263_decode_picture_header(MpegEncContext *s)
4574
{
4575
    int format;
4576

    
4577
    /* picture header */
4578
    if (get_bits(&s->gb, 22) != 0x20) {
4579
        fprintf(stderr, "Bad picture start code\n");
4580
        return -1;
4581
    }
4582
    s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
4583

    
4584
    if (get_bits1(&s->gb) != 1) {
4585
        fprintf(stderr, "Bad marker\n");
4586
        return -1;        /* marker */
4587
    }
4588
    if (get_bits1(&s->gb) != 0) {
4589
        fprintf(stderr, "Bad H263 id\n");
4590
        return -1;        /* h263 id */
4591
    }
4592
    skip_bits1(&s->gb);        /* split screen off */
4593
    skip_bits1(&s->gb);        /* camera  off */
4594
    skip_bits1(&s->gb);        /* freeze picture release off */
4595

    
4596
    format = get_bits(&s->gb, 3);
4597
    if (format != 7) {
4598
        fprintf(stderr, "Intel H263 free format not supported\n");
4599
        return -1;
4600
    }
4601
    s->h263_plus = 0;
4602

    
4603
    s->pict_type = I_TYPE + get_bits1(&s->gb);
4604
    
4605
    s->unrestricted_mv = get_bits1(&s->gb); 
4606
    s->h263_long_vectors = s->unrestricted_mv;
4607

    
4608
    if (get_bits1(&s->gb) != 0) {
4609
        fprintf(stderr, "SAC not supported\n");
4610
        return -1;        /* SAC: off */
4611
    }
4612
    if (get_bits1(&s->gb) != 0) {
4613
        fprintf(stderr, "Advanced Prediction Mode not supported\n");
4614
        return -1;        /* advanced prediction mode: off */
4615
    }
4616
    if (get_bits1(&s->gb) != 0) {
4617
        fprintf(stderr, "PB frame mode no supported\n");
4618
        return -1;        /* PB frame mode */
4619
    }
4620

    
4621
    /* skip unknown header garbage */
4622
    skip_bits(&s->gb, 41);
4623

    
4624
    s->qscale = get_bits(&s->gb, 5);
4625
    skip_bits1(&s->gb);        /* Continuous Presence Multipoint mode: off */
4626

    
4627
    /* PEI */
4628
    while (get_bits1(&s->gb) != 0) {
4629
        skip_bits(&s->gb, 8);
4630
    }
4631
    s->f_code = 1;
4632
    return 0;
4633
}
4634