Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h263.c @ 41773b73

History | View | Annotate | Download (161 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
#if 1
38
#define PRINT_MB_TYPE(a) {}
39
#else
40
#define PRINT_MB_TYPE(a) printf(a)
41
#endif
42

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

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

    
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
extern UINT32 inverse[256];
76

    
77
static UINT16 uni_DCtab_lum  [512][2];
78
static UINT16 uni_DCtab_chrom[512][2];
79

    
80
#ifdef CONFIG_ENCODERS
81
static UINT16 (*mv_penalty)[MAX_MV*2+1]= NULL;
82
static UINT8 fcode_tab[MAX_MV*2+1];
83
static UINT8 umv_fcode_tab[MAX_MV*2+1];
84

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

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

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

    
103

    
104
int h263_get_picture_format(int width, int height)
105
{
106
    int format;
107

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

    
123
static void float_aspect_to_info(MpegEncContext * s, float aspect){
124
    int i;
125

    
126
    aspect*= s->height/(double)s->width;
127
//printf("%f\n", aspect);
128
    
129
    if(aspect==0) aspect= 1.0;
130

    
131
    ff_float2fraction(&s->aspected_width, &s->aspected_height, aspect, 255);
132

    
133
//printf("%d %d\n", s->aspected_width, s->aspected_height);
134
    for(i=1; i<6; i++){
135
        if(s->aspected_width == pixel_aspect[i][0] && s->aspected_height== pixel_aspect[i][1]){
136
            s->aspect_ratio_info=i;
137
            return;
138
        }
139
    }
140
    
141
    s->aspect_ratio_info= FF_ASPECT_EXTENDED;
142
}
143

    
144
void h263_encode_picture_header(MpegEncContext * s, int picture_number)
145
{
146
    int format;
147

    
148
    align_put_bits(&s->pb);
149

    
150
    /* Update the pointer to last GOB */
151
    s->ptr_lastgob = pbBufPtr(&s->pb);
152
    s->gob_number = 0;
153

    
154
    put_bits(&s->pb, 22, 0x20); /* PSC */
155
    put_bits(&s->pb, 8, (((INT64)s->picture_number * 30 * FRAME_RATE_BASE) / 
156
                         s->frame_rate) & 0xff);
157

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

    
218
            put_bits(&s->pb,4,s->aspect_ratio_info);
219
            put_bits(&s->pb,9,(s->width >> 2) - 1);
220
            put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
221
            put_bits(&s->pb,9,(s->height >> 2));
222
            if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
223
            {
224
                put_bits(&s->pb, 8, s->aspected_width);
225
                put_bits(&s->pb, 8, s->aspected_height);
226
            }
227
        }
228
        
229
        /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
230
        if (s->umvplus)
231
            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
232
        put_bits(&s->pb, 5, s->qscale);
233
    }
234

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

    
237
    if(s->h263_aic){
238
         s->y_dc_scale_table= 
239
         s->c_dc_scale_table= h263_aic_dc_scale_table;
240
    }else{
241
        s->y_dc_scale_table=
242
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
243
    }
244
}
245

    
246
/**
247
 * Encodes a group of blocks header.
248
 */
249
int h263_encode_gob_header(MpegEncContext * s, int mb_line)
250
{
251
           align_put_bits(&s->pb);
252
           flush_put_bits(&s->pb);
253
           /* Call the RTP callback to send the last GOB */
254
           if (s->rtp_callback) {
255
               int pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
256
               s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
257
           }
258
           put_bits(&s->pb, 17, 1); /* GBSC */
259
           s->gob_number = mb_line / s->gob_index;
260
           put_bits(&s->pb, 5, s->gob_number); /* GN */
261
           put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
262
           put_bits(&s->pb, 5, s->qscale); /* GQUANT */
263
           //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
264
    return 0;
265
}
266

    
267
static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6])
268
{
269
    int score0=0, score1=0;
270
    int i, n;
271
    int8_t * const qscale_table= s->current_picture.qscale_table;
272

    
273
    for(n=0; n<6; n++){
274
        INT16 *ac_val, *ac_val1;
275

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

    
327
    return score0 > score1 ? 1 : 0;    
328
}
329

    
330
/**
331
 * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
332
 */
333
void ff_clean_h263_qscales(MpegEncContext *s){
334
    int i;
335
    int8_t * const qscale_table= s->current_picture.qscale_table;
336
    
337
    for(i=1; i<s->mb_num; i++){
338
        if(qscale_table[i] - qscale_table[i-1] >2)
339
            qscale_table[i]= qscale_table[i-1]+2;
340
    }
341
    for(i=s->mb_num-2; i>=0; i--){
342
        if(qscale_table[i] - qscale_table[i+1] >2)
343
            qscale_table[i]= qscale_table[i+1]+2;
344
    }
345
}
346

    
347
/**
348
 * modify mb_type & qscale so that encoding is acually possible in mpeg4
349
 */
350
void ff_clean_mpeg4_qscales(MpegEncContext *s){
351
    int i;
352
    int8_t * const qscale_table= s->current_picture.qscale_table;
353

    
354
    ff_clean_h263_qscales(s);
355
    
356
    for(i=1; i<s->mb_num; i++){
357
        if(qscale_table[i] != qscale_table[i-1] && (s->mb_type[i]&MB_TYPE_INTER4V)){
358
            s->mb_type[i]&= ~MB_TYPE_INTER4V;
359
            s->mb_type[i]|= MB_TYPE_INTER;
360
        }
361
    }
362

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

    
391
void ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
392
    const int mb_index= s->mb_x + s->mb_y*s->mb_width;
393
    int xy= s->block_index[0];
394
    uint16_t time_pp= s->pp_time;
395
    uint16_t time_pb= s->pb_time;
396
    int i;
397
        
398
    //FIXME avoid divides
399
    switch(s->co_located_type_table[mb_index]){
400
    case 0:
401
        s->mv_type= MV_TYPE_16X16;
402
        s->mv[0][0][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
403
        s->mv[0][0][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
404
        s->mv[1][0][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
405
                            : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
406
        s->mv[1][0][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1] 
407
                            : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
408
        break;
409
    case CO_LOCATED_TYPE_4MV:
410
        s->mv_type = MV_TYPE_8X8;
411
        for(i=0; i<4; i++){
412
            xy= s->block_index[i];
413
            s->mv[0][i][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
414
            s->mv[0][i][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
415
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->motion_val[xy][0]
416
                                : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
417
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->motion_val[xy][1] 
418
                                : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
419
        }
420
        break;
421
    case CO_LOCATED_TYPE_FIELDMV:
422
        s->mv_type = MV_TYPE_FIELD;
423
        for(i=0; i<2; i++){
424
            if(s->top_field_first){
425
                time_pp= s->pp_field_time - s->field_select_table[mb_index][i] + i;
426
                time_pb= s->pb_field_time - s->field_select_table[mb_index][i] + i;
427
            }else{
428
                time_pp= s->pp_field_time + s->field_select_table[mb_index][i] - i;
429
                time_pb= s->pb_field_time + s->field_select_table[mb_index][i] - i;
430
            }
431
            s->mv[0][i][0] = s->field_mv_table[mb_index][i][0]*time_pb/time_pp + mx;
432
            s->mv[0][i][1] = s->field_mv_table[mb_index][i][1]*time_pb/time_pp + my;
433
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->field_mv_table[mb_index][i][0]
434
                                : s->field_mv_table[mb_index][i][0]*(time_pb - time_pp)/time_pp;
435
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->field_mv_table[mb_index][i][1] 
436
                                : s->field_mv_table[mb_index][i][1]*(time_pb - time_pp)/time_pp;
437
        }
438
        break;
439
    }
440
}
441

    
442
#ifdef CONFIG_ENCODERS
443
void mpeg4_encode_mb(MpegEncContext * s,
444
                    DCTELEM block[6][64],
445
                    int motion_x, int motion_y)
446
{
447
    int cbpc, cbpy, i, pred_x, pred_y;
448
    int bits;
449
    PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
450
    PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=B_TYPE ? &s->tex_pb : &s->pb;
451
    PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=I_TYPE ? &s->pb2    : &s->pb;
452
    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
453
    const int dquant_code[5]= {1,0,9,2,3};
454
    
455
    //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
456
    if (!s->mb_intra) {
457
        /* compute cbp */
458
        int cbp = 0;
459
        for (i = 0; i < 6; i++) {
460
            if (s->block_last_index[i] >= 0)
461
                cbp |= 1 << (5 - i);
462
        }
463

    
464
        if(s->pict_type==B_TYPE){
465
            static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
466
            int mb_type=  mb_type_table[s->mv_dir];
467
            
468
            if(s->mb_x==0){
469
                s->last_mv[0][0][0]= 
470
                s->last_mv[0][0][1]= 
471
                s->last_mv[1][0][0]= 
472
                s->last_mv[1][0][1]= 0;
473
            }
474
            
475
            assert(s->dquant>=-2 && s->dquant<=2);
476
            assert((s->dquant&1)==0);
477
            assert(mb_type>=0);
478

    
479
            /* nothing to do if this MB was skiped in the next P Frame */
480
            if(s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x]){ //FIXME avoid DCT & ...
481
                s->skip_count++;
482
                s->mv[0][0][0]= 
483
                s->mv[0][0][1]= 
484
                s->mv[1][0][0]= 
485
                s->mv[1][0][1]= 0;
486
                s->mv_dir= MV_DIR_FORWARD; //doesnt matter
487
                s->qscale -= s->dquant;
488
//                s->mb_skiped=1;
489

    
490
                return;
491
            }
492
            
493
            if ((cbp | motion_x | motion_y | mb_type) ==0) {
494
                /* direct MB with MV={0,0} */
495
                assert(s->dquant==0);
496
                
497
                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
498

    
499
                if(interleaved_stats){
500
                    s->misc_bits++;
501
                    s->last_bits++;
502
                }
503
                s->skip_count++;
504
                return;
505
            }
506
            
507
            put_bits(&s->pb, 1, 0);        /* mb coded modb1=0 */
508
            put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
509
            put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we dont need it :)
510
            if(cbp) put_bits(&s->pb, 6, cbp);
511
            
512
            if(cbp && mb_type){
513
                if(s->dquant)
514
                    put_bits(&s->pb, 2, (s->dquant>>2)+3);
515
                else
516
                    put_bits(&s->pb, 1, 0);
517
            }else
518
                s->qscale -= s->dquant;
519
            
520
            if(!s->progressive_sequence){
521
                if(cbp)
522
                    put_bits(&s->pb, 1, s->interlaced_dct);
523
                if(mb_type) // not diect mode
524
                    put_bits(&s->pb, 1, 0); // no interlaced ME yet
525
            }
526

    
527
            if(interleaved_stats){
528
                bits= get_bit_count(&s->pb);
529
                s->misc_bits+= bits - s->last_bits;
530
                s->last_bits=bits;
531
            }
532

    
533
            switch(mb_type)
534
            {
535
            case 0: /* direct */
536
                h263_encode_motion(s, motion_x, 1);
537
                h263_encode_motion(s, motion_y, 1);                
538
                s->b_count++;
539
                s->f_count++;
540
                break;
541
            case 1: /* bidir */
542
                h263_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
543
                h263_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
544
                h263_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
545
                h263_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
546
                s->last_mv[0][0][0]= s->mv[0][0][0];
547
                s->last_mv[0][0][1]= s->mv[0][0][1];
548
                s->last_mv[1][0][0]= s->mv[1][0][0];
549
                s->last_mv[1][0][1]= s->mv[1][0][1];
550
                s->b_count++;
551
                s->f_count++;
552
                break;
553
            case 2: /* backward */
554
                h263_encode_motion(s, motion_x - s->last_mv[1][0][0], s->b_code);
555
                h263_encode_motion(s, motion_y - s->last_mv[1][0][1], s->b_code);
556
                s->last_mv[1][0][0]= motion_x;
557
                s->last_mv[1][0][1]= motion_y;
558
                s->b_count++;
559
                break;
560
            case 3: /* forward */
561
                h263_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);
562
                h263_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);
563
                s->last_mv[0][0][0]= motion_x;
564
                s->last_mv[0][0][1]= motion_y;
565
                s->f_count++;
566
                break;
567
            default:
568
                printf("unknown mb type\n");
569
                return;
570
            }
571

    
572
            if(interleaved_stats){
573
                bits= get_bit_count(&s->pb);
574
                s->mv_bits+= bits - s->last_bits;
575
                s->last_bits=bits;
576
            }
577

    
578
            /* encode each block */
579
            for (i = 0; i < 6; i++) {
580
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, &s->pb);
581
            }
582

    
583
            if(interleaved_stats){
584
                bits= get_bit_count(&s->pb);
585
                s->p_tex_bits+= bits - s->last_bits;
586
                s->last_bits=bits;
587
            }
588
        }else{ /* s->pict_type==B_TYPE */
589
            if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
590
                /* check if the B frames can skip it too, as we must skip it if we skip here 
591
                   why didnt they just compress the skip-mb bits instead of reusing them ?! */
592
                if(s->max_b_frames>0){
593
                    int i;
594
                    int x,y, offset;
595
                    uint8_t *p_pic;
596

    
597
                    x= s->mb_x*16;
598
                    y= s->mb_y*16;
599
                    if(x+16 > s->width)  x= s->width-16;
600
                    if(y+16 > s->height) y= s->height-16;
601

    
602
                    offset= x + y*s->linesize;
603
                    p_pic= s->new_picture.data[0] + offset;
604
                    
605
                    s->mb_skiped=1;
606
                    for(i=0; i<s->max_b_frames; i++){
607
                        uint8_t *b_pic;
608
                        int diff;
609
                        Picture *pic= s->reordered_input_picture[i+1];
610

    
611
                        if(pic==NULL || pic->pict_type!=B_TYPE) break;
612

    
613
                        b_pic= pic->data[0] + offset + 16; //FIXME +16
614
                        diff= s->dsp.pix_abs16x16(p_pic, b_pic, s->linesize);
615
                        if(diff>s->qscale*70){ //FIXME check that 70 is optimal
616
                            s->mb_skiped=0;
617
                            break;
618
                        }
619
                    }
620
                }else
621
                    s->mb_skiped=1; 
622

    
623
                if(s->mb_skiped==1){
624
                    /* skip macroblock */
625
                    put_bits(&s->pb, 1, 1);
626

    
627
                    if(interleaved_stats){
628
                        s->misc_bits++;
629
                        s->last_bits++;
630
                    }
631
                    s->skip_count++;
632
                    return;
633
                }
634
            }
635

    
636
            put_bits(&s->pb, 1, 0);        /* mb coded */
637
            if(s->mv_type==MV_TYPE_16X16){
638
                cbpc = cbp & 3;
639
                if(s->dquant) cbpc+= 8;
640
                put_bits(&s->pb,
641
                        inter_MCBPC_bits[cbpc],
642
                        inter_MCBPC_code[cbpc]);
643

    
644
                cbpy = cbp >> 2;
645
                cbpy ^= 0xf;
646
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
647
                if(s->dquant)
648
                    put_bits(pb2, 2, dquant_code[s->dquant+2]);
649

    
650
                if(!s->progressive_sequence){
651
                    if(cbp)
652
                        put_bits(pb2, 1, s->interlaced_dct);
653
                    put_bits(pb2, 1, 0); // no interlaced ME yet
654
                }
655
                    
656
                if(interleaved_stats){
657
                    bits= get_bit_count(&s->pb);
658
                    s->misc_bits+= bits - s->last_bits;
659
                    s->last_bits=bits;
660
                }
661

    
662
                /* motion vectors: 16x16 mode */
663
                h263_pred_motion(s, 0, &pred_x, &pred_y);
664
            
665
                h263_encode_motion(s, motion_x - pred_x, s->f_code);
666
                h263_encode_motion(s, motion_y - pred_y, s->f_code);
667
            }else{
668
                cbpc = (cbp & 3)+16;
669
                put_bits(&s->pb,
670
                        inter_MCBPC_bits[cbpc],
671
                        inter_MCBPC_code[cbpc]);
672
                cbpy = cbp >> 2;
673
                cbpy ^= 0xf;
674
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
675

    
676
                if(!s->progressive_sequence){
677
                    if(cbp)
678
                        put_bits(pb2, 1, s->interlaced_dct);
679
                }
680
    
681
                if(interleaved_stats){
682
                    bits= get_bit_count(&s->pb);
683
                    s->misc_bits+= bits - s->last_bits;
684
                    s->last_bits=bits;
685
                }
686

    
687
                for(i=0; i<4; i++){
688
                    /* motion vectors: 8x8 mode*/
689
                    h263_pred_motion(s, i, &pred_x, &pred_y);
690

    
691
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x, s->f_code);
692
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y, s->f_code);
693
                }
694
            }
695

    
696
            if(interleaved_stats){ 
697
                bits= get_bit_count(&s->pb);
698
                s->mv_bits+= bits - s->last_bits;
699
                s->last_bits=bits;
700
            }
701

    
702
            /* encode each block */
703
            for (i = 0; i < 6; i++) {
704
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, tex_pb);
705
            }
706

    
707
            if(interleaved_stats){
708
                bits= get_bit_count(&s->pb);
709
                s->p_tex_bits+= bits - s->last_bits;
710
                s->last_bits=bits;
711
            }
712
            s->f_count++;
713
        }
714
    } else {
715
        int cbp;
716
        int dc_diff[6];   //dc values with the dc prediction subtracted 
717
        int dir[6];  //prediction direction
718
        int zigzag_last_index[6];
719
        UINT8 *scan_table[6];
720

    
721
        for(i=0; i<6; i++){
722
            const int level= block[i][0];
723
            UINT16 *dc_ptr;
724

    
725
            dc_diff[i]= level - ff_mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
726
            if (i < 4) {
727
                *dc_ptr = level * s->y_dc_scale;
728
            } else {
729
                *dc_ptr = level * s->c_dc_scale;
730
            }
731
        }
732

    
733
        s->ac_pred= decide_ac_pred(s, block, dir);
734

    
735
        if(s->ac_pred){
736
            for(i=0; i<6; i++){
737
                UINT8 *st;
738
                int last_index;
739

    
740
                mpeg4_inv_pred_ac(s, block[i], i, dir[i]);
741
                if (dir[i]==0) st = s->intra_v_scantable.permutated; /* left */
742
                else           st = s->intra_h_scantable.permutated; /* top */
743

    
744
                for(last_index=63; last_index>=0; last_index--) //FIXME optimize
745
                    if(block[i][st[last_index]]) break;
746
                zigzag_last_index[i]= s->block_last_index[i];
747
                s->block_last_index[i]= last_index;
748
                scan_table[i]= st;
749
            }
750
        }else{
751
            for(i=0; i<6; i++)
752
                scan_table[i]= s->intra_scantable.permutated;
753
        }
754

    
755
        /* compute cbp */
756
        cbp = 0;
757
        for (i = 0; i < 6; i++) {
758
            if (s->block_last_index[i] >= 1)
759
                cbp |= 1 << (5 - i);
760
        }
761

    
762
        cbpc = cbp & 3;
763
        if (s->pict_type == I_TYPE) {
764
            if(s->dquant) cbpc+=4;
765
            put_bits(&s->pb,
766
                intra_MCBPC_bits[cbpc],
767
                intra_MCBPC_code[cbpc]);
768
        } else {
769
            if(s->dquant) cbpc+=8;
770
            put_bits(&s->pb, 1, 0);        /* mb coded */
771
            put_bits(&s->pb,
772
                inter_MCBPC_bits[cbpc + 4],
773
                inter_MCBPC_code[cbpc + 4]);
774
        }
775
        put_bits(pb2, 1, s->ac_pred);
776
        cbpy = cbp >> 2;
777
        put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
778
        if(s->dquant)
779
            put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
780

    
781
        if(!s->progressive_sequence){
782
            put_bits(dc_pb, 1, s->interlaced_dct);
783
        }
784

    
785
        if(interleaved_stats){
786
            bits= get_bit_count(&s->pb);
787
            s->misc_bits+= bits - s->last_bits;
788
            s->last_bits=bits;
789
        }
790

    
791
        /* encode each block */
792
        for (i = 0; i < 6; i++) {
793
            mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
794
        }
795

    
796
        if(interleaved_stats){
797
            bits= get_bit_count(&s->pb);
798
            s->i_tex_bits+= bits - s->last_bits;
799
            s->last_bits=bits;
800
        }
801
        s->i_count++;
802

    
803
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
804
        if(s->ac_pred){
805
            for(i=0; i<6; i++){
806
                int j;    
807
                INT16 *ac_val;
808

    
809
                ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
810

    
811
                if(dir[i]){
812
                    for(j=1; j<8; j++) 
813
                        block[i][s->idct_permutation[j   ]]= ac_val[j+8];
814
                }else{
815
                    for(j=1; j<8; j++) 
816
                        block[i][s->idct_permutation[j<<3]]= ac_val[j  ];
817
                }
818
                s->block_last_index[i]= zigzag_last_index[i];
819
            }
820
        }
821
    }
822
}
823

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

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

    
919
        cbpc = cbp & 3;
920
        if (s->pict_type == I_TYPE) {
921
            if(s->dquant) cbpc+=4;
922
            put_bits(&s->pb,
923
                intra_MCBPC_bits[cbpc],
924
                intra_MCBPC_code[cbpc]);
925
        } else {
926
            if(s->dquant) cbpc+=8;
927
            put_bits(&s->pb, 1, 0);        /* mb coded */
928
            put_bits(&s->pb,
929
                inter_MCBPC_bits[cbpc + 4],
930
                inter_MCBPC_code[cbpc + 4]);
931
        }
932
        if (s->h263_aic) {
933
            /* XXX: currently, we do not try to use ac prediction */
934
            put_bits(&s->pb, 1, 0);        /* no AC prediction */
935
        }
936
        cbpy = cbp >> 2;
937
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
938
        if(s->dquant)
939
            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
940
    }
941

    
942
    for(i=0; i<6; i++) {
943
        /* encode each block */
944
        h263_encode_block(s, block[i], i);
945
    
946
        /* Update INTRADC for decoding */
947
        if (s->h263_aic && s->mb_intra) {
948
            block[i][0] = rec_intradc[i];
949
            
950
        }
951
    }
952
}
953
#endif
954

    
955
static int h263_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr)
956
{
957
    int x, y, wrap, a, c, pred_dc, scale;
958
    INT16 *dc_val, *ac_val;
959

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

    
1000

    
1001
void h263_pred_acdc(MpegEncContext * s, INT16 *block, int n)
1002
{
1003
    int x, y, wrap, a, c, pred_dc, scale, i;
1004
    INT16 *dc_val, *ac_val, *ac_val1;
1005

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

    
1085
INT16 *h263_pred_motion(MpegEncContext * s, int block, 
1086
                        int *px, int *py)
1087
{
1088
    int xy, wrap;
1089
    INT16 *A, *B, *C, *mot_val;
1090
    static const int off[4]= {2, 1, 1, -1};
1091

    
1092
    wrap = s->block_wrap[0];
1093
    xy = s->block_index[block];
1094

    
1095
    mot_val = s->motion_val[xy];
1096

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

    
1145
#ifdef CONFIG_ENCODERS
1146
static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
1147
{
1148
    int range, l, bit_size, sign, code, bits;
1149

    
1150
    if (val == 0) {
1151
        /* zero vector */
1152
        code = 0;
1153
        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1154
    } else {
1155
        bit_size = f_code - 1;
1156
        range = 1 << bit_size;
1157
        /* modulo encoding */
1158
        l = range * 32;
1159
#if 1
1160
        val+= l;
1161
        val&= 2*l-1;
1162
        val-= l;
1163
        sign = val>>31;
1164
        val= (val^sign)-sign;
1165
        sign&=1;
1166
#else
1167
        if (val < -l) {
1168
            val += 2*l;
1169
        } else if (val >= l) {
1170
            val -= 2*l;
1171
        }
1172

    
1173
        assert(val>=-l && val<l);
1174

    
1175
        if (val >= 0) {
1176
            sign = 0;
1177
        } else {
1178
            val = -val;
1179
            sign = 1;
1180
        }
1181
#endif
1182
        val--;
1183
        code = (val >> bit_size) + 1;
1184
        bits = val & (range - 1);
1185

    
1186
        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
1187
        if (bit_size > 0) {
1188
            put_bits(&s->pb, bit_size, bits);
1189
        }
1190
    }
1191

    
1192
}
1193

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

    
1233
static void init_mv_penalty_and_fcode(MpegEncContext *s)
1234
{
1235
    int f_code;
1236
    int mv;
1237
    
1238
    if(mv_penalty==NULL)
1239
        mv_penalty= av_mallocz( sizeof(UINT16)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1240
    
1241
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
1242
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1243
            int len;
1244

    
1245
            if(mv==0) len= mvtab[0][1];
1246
            else{
1247
                int val, bit_size, range, code;
1248

    
1249
                bit_size = s->f_code - 1;
1250
                range = 1 << bit_size;
1251

    
1252
                val=mv;
1253
                if (val < 0) 
1254
                    val = -val;
1255
                val--;
1256
                code = (val >> bit_size) + 1;
1257
                if(code<33){
1258
                    len= mvtab[code][1] + 1 + bit_size;
1259
                }else{
1260
                    len= mvtab[32][1] + 2 + bit_size;
1261
                }
1262
            }
1263

    
1264
            mv_penalty[f_code][mv+MAX_MV]= len;
1265
        }
1266
    }
1267

    
1268
    for(f_code=MAX_FCODE; f_code>0; f_code--){
1269
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1270
            fcode_tab[mv+MAX_MV]= f_code;
1271
        }
1272
    }
1273

    
1274
    for(mv=0; mv<MAX_MV*2+1; mv++){
1275
        umv_fcode_tab[mv]= 1;
1276
    }
1277
}
1278
#endif
1279

    
1280
static void init_uni_dc_tab(void)
1281
{
1282
    int level, uni_code, uni_len;
1283

    
1284
    for(level=-256; level<256; level++){
1285
        int size, v, l;
1286
        /* find number of bits */
1287
        size = 0;
1288
        v = abs(level);
1289
        while (v) {
1290
            v >>= 1;
1291
            size++;
1292
        }
1293

    
1294
        if (level < 0)
1295
            l= (-level) ^ ((1 << size) - 1);
1296
        else
1297
            l= level;
1298

    
1299
        /* luminance */
1300
        uni_code= DCtab_lum[size][0];
1301
        uni_len = DCtab_lum[size][1];
1302

    
1303
        if (size > 0) {
1304
            uni_code<<=size; uni_code|=l;
1305
            uni_len+=size;
1306
            if (size > 8){
1307
                uni_code<<=1; uni_code|=1;
1308
                uni_len++;
1309
            }
1310
        }
1311
        uni_DCtab_lum[level+256][0]= uni_code;
1312
        uni_DCtab_lum[level+256][1]= uni_len;
1313

    
1314
        /* chrominance */
1315
        uni_code= DCtab_chrom[size][0];
1316
        uni_len = DCtab_chrom[size][1];
1317
        
1318
        if (size > 0) {
1319
            uni_code<<=size; uni_code|=l;
1320
            uni_len+=size;
1321
            if (size > 8){
1322
                uni_code<<=1; uni_code|=1;
1323
                uni_len++;
1324
            }
1325
        }
1326
        uni_DCtab_chrom[level+256][0]= uni_code;
1327
        uni_DCtab_chrom[level+256][1]= uni_len;
1328

    
1329
    }
1330
}
1331

    
1332
#ifdef CONFIG_ENCODERS
1333
static void init_uni_mpeg4_rl_tab(RLTable *rl, UINT32 *bits_tab, UINT8 *len_tab){
1334
    int slevel, run, last;
1335
    
1336
    assert(MAX_LEVEL >= 64);
1337
    assert(MAX_RUN   >= 63);
1338

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

    
1418
void h263_encode_init(MpegEncContext *s)
1419
{
1420
    static int done = 0;
1421

    
1422
    if (!done) {
1423
        done = 1;
1424

    
1425
        init_uni_dc_tab();
1426

    
1427
        init_rl(&rl_inter);
1428
        init_rl(&rl_intra);
1429
        init_rl(&rl_intra_aic);
1430
        
1431
        init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1432
        init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1433

    
1434
        init_mv_penalty_and_fcode(s);
1435
    }
1436
    s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
1437
    
1438
    // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
1439
    switch(s->codec_id){
1440
    case CODEC_ID_MPEG4:
1441
        s->fcode_tab= fcode_tab;
1442
        s->min_qcoeff= -2048;
1443
        s->max_qcoeff=  2047;
1444
        break;
1445
    case CODEC_ID_H263P:
1446
        s->fcode_tab= umv_fcode_tab;
1447
        s->min_qcoeff= -128;
1448
        s->max_qcoeff=  127;
1449
        break;
1450
        //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later 
1451
    default: //nothing needed default table allready set in mpegvideo.c
1452
        s->min_qcoeff= -128;
1453
        s->max_qcoeff=  127;
1454
        s->y_dc_scale_table=
1455
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1456
    }
1457

    
1458
    if(s->mpeg_quant){
1459
        s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
1460
        s->inter_quant_bias= 0;
1461
    }else{
1462
        s->intra_quant_bias=0;
1463
        s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
1464
    }
1465
}
1466

    
1467
static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
1468
{
1469
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
1470
    RLTable *rl;
1471

    
1472
    rl = &rl_inter;
1473
    if (s->mb_intra && !s->h263_aic) {
1474
        /* DC coef */
1475
            level = block[0];
1476
        /* 255 cannot be represented, so we clamp */
1477
        if (level > 254) {
1478
            level = 254;
1479
            block[0] = 254;
1480
        }
1481
        /* 0 cannot be represented also */
1482
        else if (!level) {
1483
            level = 1;
1484
            block[0] = 1;
1485
        }
1486
            if (level == 128)
1487
                put_bits(&s->pb, 8, 0xff);
1488
            else
1489
                put_bits(&s->pb, 8, level & 0xff);
1490
            i = 1;
1491
    } else {
1492
            i = 0;
1493
            if (s->h263_aic && s->mb_intra)
1494
                rl = &rl_intra_aic;
1495
    }
1496
   
1497
    /* AC coefs */
1498
    last_index = s->block_last_index[n];
1499
    last_non_zero = i - 1;
1500
    for (; i <= last_index; i++) {
1501
        j = s->intra_scantable.permutated[i];
1502
        level = block[j];
1503
        if (level) {
1504
            run = i - last_non_zero - 1;
1505
            last = (i == last_index);
1506
            sign = 0;
1507
            slevel = level;
1508
            if (level < 0) {
1509
                sign = 1;
1510
                level = -level;
1511
            }
1512
            code = get_rl_index(rl, last, run, level);
1513
            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1514
            if (code == rl->n) {
1515
                put_bits(&s->pb, 1, last);
1516
                put_bits(&s->pb, 6, run);
1517
                put_bits(&s->pb, 8, slevel & 0xff);
1518
            } else {
1519
                put_bits(&s->pb, 1, sign);
1520
            }
1521
                last_non_zero = i;
1522
            }
1523
    }
1524
}
1525
#endif
1526

    
1527
/***************************************************/
1528
/**
1529
 * add mpeg4 stuffing bits (01...1)
1530
 */
1531
void ff_mpeg4_stuffing(PutBitContext * pbc)
1532
{
1533
    int length;
1534
    put_bits(pbc, 1, 0);
1535
    length= (-get_bit_count(pbc))&7;
1536
    if(length) put_bits(pbc, length, (1<<length)-1);
1537
}
1538

    
1539
/* must be called before writing the header */
1540
void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
1541
    int time_div, time_mod;
1542

    
1543
    if(s->pict_type==I_TYPE){ //we will encode a vol header
1544
        s->time_increment_resolution= s->frame_rate/ff_gcd(s->frame_rate, FRAME_RATE_BASE);
1545
        if(s->time_increment_resolution>=256*256) s->time_increment_resolution= 256*128;
1546

    
1547
        s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
1548
    }
1549
    
1550
    if(s->current_picture.pts)
1551
        s->time= (s->current_picture.pts*s->time_increment_resolution + 500*1000)/(1000*1000);
1552
    else
1553
        s->time= picture_number*(INT64)FRAME_RATE_BASE*s->time_increment_resolution/s->frame_rate;
1554
    time_div= s->time/s->time_increment_resolution;
1555
    time_mod= s->time%s->time_increment_resolution;
1556

    
1557
    if(s->pict_type==B_TYPE){
1558
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
1559
    }else{
1560
        s->last_time_base= s->time_base;
1561
        s->time_base= time_div;
1562
        s->pp_time= s->time - s->last_non_b_time;
1563
        s->last_non_b_time= s->time;
1564
    }
1565
}
1566

    
1567
static void mpeg4_encode_gop_header(MpegEncContext * s){
1568
    int hours, minutes, seconds;
1569
    
1570
    put_bits(&s->pb, 16, 0);
1571
    put_bits(&s->pb, 16, GOP_STARTCODE);
1572
    
1573
    seconds= s->time/s->time_increment_resolution;
1574
    minutes= seconds/60; seconds %= 60;
1575
    hours= minutes/60; minutes %= 60;
1576
    hours%=24;
1577

    
1578
    put_bits(&s->pb, 5, hours);
1579
    put_bits(&s->pb, 6, minutes);
1580
    put_bits(&s->pb, 1, 1);
1581
    put_bits(&s->pb, 6, seconds);
1582
    
1583
    put_bits(&s->pb, 1, 0); //closed gov == NO
1584
    put_bits(&s->pb, 1, 0); //broken link == NO
1585

    
1586
    ff_mpeg4_stuffing(&s->pb);
1587
}
1588

    
1589
static void mpeg4_encode_visual_object_header(MpegEncContext * s){
1590
    int profile_and_level_indication;
1591
    int vo_ver_id;
1592
    
1593
    if(s->max_b_frames || s->quarter_sample){
1594
        profile_and_level_indication= 0xF1; // adv simple level 1
1595
        vo_ver_id= 5;
1596
    }else{
1597
        profile_and_level_indication= 0x01; // simple level 1
1598
        vo_ver_id= 1;
1599
    }
1600
    //FIXME levels
1601

    
1602
    put_bits(&s->pb, 16, 0);
1603
    put_bits(&s->pb, 16, VOS_STARTCODE);
1604
    
1605
    put_bits(&s->pb, 8, profile_and_level_indication);
1606
    
1607
    put_bits(&s->pb, 16, 0);
1608
    put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
1609
    
1610
    put_bits(&s->pb, 1, 1);
1611
        put_bits(&s->pb, 4, vo_ver_id);
1612
        put_bits(&s->pb, 3, 1); //priority
1613
 
1614
    put_bits(&s->pb, 4, 1); //visual obj type== video obj
1615
    
1616
    put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
1617

    
1618
    ff_mpeg4_stuffing(&s->pb);
1619
}
1620

    
1621
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
1622
{
1623
    int vo_ver_id;
1624
    char buf[255];
1625

    
1626
    if(s->max_b_frames || s->quarter_sample){
1627
        vo_ver_id= 5;
1628
        s->vo_type= ADV_SIMPLE_VO_TYPE;
1629
    }else{
1630
        vo_ver_id= 1;
1631
        s->vo_type= SIMPLE_VO_TYPE;
1632
    }
1633

    
1634
    put_bits(&s->pb, 16, 0);
1635
    put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
1636
    put_bits(&s->pb, 16, 0);
1637
    put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
1638

    
1639
    put_bits(&s->pb, 1, 0);                /* random access vol */
1640
    put_bits(&s->pb, 8, s->vo_type);        /* video obj type indication */
1641
    put_bits(&s->pb, 1, 1);                /* is obj layer id= yes */
1642
      put_bits(&s->pb, 4, vo_ver_id);        /* is obj layer ver id */
1643
      put_bits(&s->pb, 3, 1);                /* is obj layer priority */
1644
    
1645
    float_aspect_to_info(s, s->avctx->aspect_ratio);
1646

    
1647
    put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
1648
    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
1649
    {
1650
        put_bits(&s->pb, 8, s->aspected_width);
1651
        put_bits(&s->pb, 8, s->aspected_height);
1652
    }
1653

    
1654
    if(s->low_delay){
1655
        put_bits(&s->pb, 1, 1);                /* vol control parameters= yes */
1656
        put_bits(&s->pb, 2, 1);                /* chroma format YUV 420/YV12 */
1657
        put_bits(&s->pb, 1, s->low_delay);
1658
        put_bits(&s->pb, 1, 0);                /* vbv parameters= no */
1659
    }else{
1660
        put_bits(&s->pb, 1, 0);                /* vol control parameters= no */
1661
    }
1662

    
1663
    put_bits(&s->pb, 2, RECT_SHAPE);        /* vol shape= rectangle */
1664
    put_bits(&s->pb, 1, 1);                /* marker bit */
1665
    
1666
    put_bits(&s->pb, 16, s->time_increment_resolution);
1667
    if (s->time_increment_bits < 1)
1668
        s->time_increment_bits = 1;
1669
    put_bits(&s->pb, 1, 1);                /* marker bit */
1670
    put_bits(&s->pb, 1, 0);                /* fixed vop rate=no */
1671
    put_bits(&s->pb, 1, 1);                /* marker bit */
1672
    put_bits(&s->pb, 13, s->width);        /* vol width */
1673
    put_bits(&s->pb, 1, 1);                /* marker bit */
1674
    put_bits(&s->pb, 13, s->height);        /* vol height */
1675
    put_bits(&s->pb, 1, 1);                /* marker bit */
1676
    put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1677
    put_bits(&s->pb, 1, 1);                /* obmc disable */
1678
    if (vo_ver_id == 1) {
1679
        put_bits(&s->pb, 1, s->vol_sprite_usage=0);                /* sprite enable */
1680
    }else{
1681
        put_bits(&s->pb, 2, s->vol_sprite_usage=0);                /* sprite enable */
1682
    }
1683
    
1684
    s->quant_precision=5;
1685
    put_bits(&s->pb, 1, 0);                /* not 8 bit == false */
1686
    put_bits(&s->pb, 1, s->mpeg_quant);        /* quant type= (0=h263 style)*/
1687
    if(s->mpeg_quant) put_bits(&s->pb, 2, 0); /* no custom matrixes */
1688

    
1689
    if (vo_ver_id != 1)
1690
        put_bits(&s->pb, 1, s->quarter_sample);
1691
    put_bits(&s->pb, 1, 1);                /* complexity estimation disable */
1692
    s->resync_marker= s->rtp_mode;
1693
    put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
1694
    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1695
    if(s->data_partitioning){
1696
        put_bits(&s->pb, 1, 0);                /* no rvlc */
1697
    }
1698

    
1699
    if (vo_ver_id != 1){
1700
        put_bits(&s->pb, 1, 0);                /* newpred */
1701
        put_bits(&s->pb, 1, 0);                /* reduced res vop */
1702
    }
1703
    put_bits(&s->pb, 1, 0);                /* scalability */
1704
    
1705
    ff_mpeg4_stuffing(&s->pb);
1706

    
1707
    /* user data */
1708
    if(!ff_bit_exact){
1709
        put_bits(&s->pb, 16, 0);
1710
        put_bits(&s->pb, 16, 0x1B2);        /* user_data */
1711
        sprintf(buf, "FFmpeg%sb%s", FFMPEG_VERSION, LIBAVCODEC_BUILD_STR);
1712
        put_string(&s->pb, buf);
1713
        ff_mpeg4_stuffing(&s->pb);
1714
    }
1715
}
1716

    
1717
/* write mpeg4 VOP header */
1718
void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
1719
{
1720
    int time_incr;
1721
    int time_div, time_mod;
1722
    
1723
    if(s->pict_type==I_TYPE){
1724
        if(picture_number - s->last_vo_picture_number >= 300 || picture_number==0){
1725
            mpeg4_encode_visual_object_header(s);
1726
            mpeg4_encode_vol_header(s, 0, 0);
1727

    
1728
            s->last_vo_picture_number= picture_number;
1729
        }
1730
        mpeg4_encode_gop_header(s);
1731
    }
1732
    
1733
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
1734

    
1735
//printf("num:%d rate:%d base:%d\n", s->picture_number, s->frame_rate, FRAME_RATE_BASE);
1736
    
1737
    put_bits(&s->pb, 16, 0);                /* vop header */
1738
    put_bits(&s->pb, 16, VOP_STARTCODE);        /* vop header */
1739
    put_bits(&s->pb, 2, s->pict_type - 1);        /* pict type: I = 0 , P = 1 */
1740

    
1741
    time_div= s->time/s->time_increment_resolution;
1742
    time_mod= s->time%s->time_increment_resolution;
1743
    time_incr= time_div - s->last_time_base;
1744
    while(time_incr--)
1745
        put_bits(&s->pb, 1, 1);
1746
        
1747
    put_bits(&s->pb, 1, 0);
1748

    
1749
    put_bits(&s->pb, 1, 1);        /* marker */
1750
    put_bits(&s->pb, s->time_increment_bits, time_mod);        /* time increment */
1751
    put_bits(&s->pb, 1, 1);        /* marker */
1752
    put_bits(&s->pb, 1, 1);        /* vop coded */
1753
    if (    s->pict_type == P_TYPE 
1754
        || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
1755
        put_bits(&s->pb, 1, s->no_rounding);        /* rounding type */
1756
    }
1757
    put_bits(&s->pb, 3, 0);        /* intra dc VLC threshold */
1758
    if(!s->progressive_sequence){
1759
         put_bits(&s->pb, 1, s->top_field_first);
1760
         put_bits(&s->pb, 1, s->alternate_scan);
1761
    }
1762
    //FIXME sprite stuff
1763

    
1764
    put_bits(&s->pb, 5, s->qscale);
1765

    
1766
    if (s->pict_type != I_TYPE)
1767
        put_bits(&s->pb, 3, s->f_code);        /* fcode_for */
1768
    if (s->pict_type == B_TYPE)
1769
        put_bits(&s->pb, 3, s->b_code);        /* fcode_back */
1770
    //    printf("****frame %d\n", picture_number);
1771

    
1772
     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support 
1773
     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
1774
     s->h_edge_pos= s->width;
1775
     s->v_edge_pos= s->height;
1776
}
1777

    
1778
/**
1779
 * change qscale by given dquant and update qscale dependant variables.
1780
 */
1781
static void change_qscale(MpegEncContext * s, int dquant)
1782
{
1783
    s->qscale += dquant;
1784

    
1785
    if (s->qscale < 1)
1786
        s->qscale = 1;
1787
    else if (s->qscale > 31)
1788
        s->qscale = 31;
1789

    
1790
    s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
1791
    s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
1792
}
1793

    
1794
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr, int *dir_ptr)
1795
{
1796
    int a, b, c, wrap, pred, scale;
1797
    UINT16 *dc_val;
1798
    int dummy;
1799

    
1800
    /* find prediction */
1801
    if (n < 4) {
1802
        scale = s->y_dc_scale;
1803
    } else {
1804
        scale = s->c_dc_scale;
1805
    }
1806
    wrap= s->block_wrap[n];
1807
    dc_val = s->dc_val[0] + s->block_index[n];
1808

    
1809
    /* B C
1810
     * A X 
1811
     */
1812
    a = dc_val[ - 1];
1813
    b = dc_val[ - 1 - wrap];
1814
    c = dc_val[ - wrap];
1815

    
1816
    /* outside slice handling (we cant do that by memset as we need the dc for error resilience) */
1817
    if(s->first_slice_line && n!=3){
1818
        if(n!=2) b=c= 1024;
1819
        if(n!=1 && s->mb_x == s->resync_mb_x) b=a= 1024;
1820
    }
1821
    if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1){
1822
        if(n==0 || n==4 || n==5)
1823
            b=1024;
1824
    }
1825

    
1826
    if (abs(a - b) < abs(b - c)) {
1827
        pred = c;
1828
        *dir_ptr = 1; /* top */
1829
    } else {
1830
        pred = a;
1831
        *dir_ptr = 0; /* left */
1832
    }
1833
    /* we assume pred is positive */
1834
#ifdef ARCH_X86
1835
        asm volatile (
1836
                "xorl %%edx, %%edx        \n\t"
1837
                "mul %%ecx                \n\t"
1838
                : "=d" (pred), "=a"(dummy)
1839
                : "a" (pred + (scale >> 1)), "c" (inverse[scale])
1840
        );
1841
#else
1842
    pred = (pred + (scale >> 1)) / scale;
1843
#endif
1844

    
1845
    /* prepare address for prediction update */
1846
    *dc_val_ptr = &dc_val[0];
1847

    
1848
    return pred;
1849
}
1850

    
1851
void mpeg4_pred_ac(MpegEncContext * s, INT16 *block, int n,
1852
                   int dir)
1853
{
1854
    int i;
1855
    INT16 *ac_val, *ac_val1;
1856
    int8_t * const qscale_table= s->current_picture.qscale_table;
1857

    
1858
    /* find prediction */
1859
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1860
    ac_val1 = ac_val;
1861
    if (s->ac_pred) {
1862
        if (dir == 0) {
1863
            const int xy= s->mb_x-1 + s->mb_y*s->mb_width;
1864
            /* left prediction */
1865
            ac_val -= 16;
1866
            
1867
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
1868
                /* same qscale */
1869
                for(i=1;i<8;i++) {
1870
                    block[s->idct_permutation[i<<3]] += ac_val[i];
1871
                }
1872
            }else{
1873
                /* different qscale, we must rescale */
1874
                for(i=1;i<8;i++) {
1875
                    block[s->idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
1876
                }
1877
            }
1878
        } else {
1879
            const int xy= s->mb_x + s->mb_y*s->mb_width - s->mb_width;
1880
            /* top prediction */
1881
            ac_val -= 16 * s->block_wrap[n];
1882

    
1883
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
1884
                /* same qscale */
1885
                for(i=1;i<8;i++) {
1886
                    block[s->idct_permutation[i]] += ac_val[i + 8];
1887
                }
1888
            }else{
1889
                /* different qscale, we must rescale */
1890
                for(i=1;i<8;i++) {
1891
                    block[s->idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
1892
                }
1893
            }
1894
        }
1895
    }
1896
    /* left copy */
1897
    for(i=1;i<8;i++)
1898
        ac_val1[i    ] = block[s->idct_permutation[i<<3]];
1899

    
1900
    /* top copy */
1901
    for(i=1;i<8;i++)
1902
        ac_val1[8 + i] = block[s->idct_permutation[i   ]];
1903

    
1904
}
1905

    
1906
static void mpeg4_inv_pred_ac(MpegEncContext * s, INT16 *block, int n,
1907
                              int dir)
1908
{
1909
    int i;
1910
    INT16 *ac_val;
1911
    int8_t * const qscale_table= s->current_picture.qscale_table;
1912

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

    
1949
static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
1950
{
1951
#if 1
1952
//    if(level<-255 || level>255) printf("dc overflow\n");
1953
    level+=256;
1954
    if (n < 4) {
1955
        /* luminance */
1956
        put_bits(s, uni_DCtab_lum[level][1], uni_DCtab_lum[level][0]);
1957
    } else {
1958
        /* chrominance */
1959
        put_bits(s, uni_DCtab_chrom[level][1], uni_DCtab_chrom[level][0]);
1960
    }
1961
#else
1962
    int size, v;
1963
    /* find number of bits */
1964
    size = 0;
1965
    v = abs(level);
1966
    while (v) {
1967
        v >>= 1;
1968
        size++;
1969
    }
1970

    
1971
    if (n < 4) {
1972
        /* luminance */
1973
        put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
1974
    } else {
1975
        /* chrominance */
1976
        put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
1977
    }
1978

    
1979
    /* encode remaining bits */
1980
    if (size > 0) {
1981
        if (level < 0)
1982
            level = (-level) ^ ((1 << size) - 1);
1983
        put_bits(&s->pb, size, level);
1984
        if (size > 8)
1985
            put_bits(&s->pb, 1, 1);
1986
    }
1987
#endif
1988
}
1989
#ifdef CONFIG_ENCODERS
1990
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
1991
                               UINT8 *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
1992
{
1993
    int i, last_non_zero;
1994
#if 0 //variables for the outcommented version
1995
    int code, sign, last;
1996
#endif
1997
    const RLTable *rl;
1998
    UINT32 *bits_tab;
1999
    UINT8 *len_tab;
2000
    const int last_index = s->block_last_index[n];
2001

    
2002
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2003
        /* mpeg4 based DC predictor */
2004
        mpeg4_encode_dc(dc_pb, intra_dc, n);
2005
        if(last_index<1) return;
2006
        i = 1;
2007
        rl = &rl_intra;
2008
        bits_tab= uni_mpeg4_intra_rl_bits;
2009
        len_tab = uni_mpeg4_intra_rl_len;
2010
    } else {
2011
        if(last_index<0) return;
2012
        i = 0;
2013
        rl = &rl_inter;
2014
        bits_tab= uni_mpeg4_inter_rl_bits;
2015
        len_tab = uni_mpeg4_inter_rl_len;
2016
    }
2017

    
2018
    /* AC coefs */
2019
    last_non_zero = i - 1;
2020
#if 1
2021
    for (; i < last_index; i++) {
2022
        int level = block[ scan_table[i] ];
2023
        if (level) {
2024
            int run = i - last_non_zero - 1;
2025
            level+=64;
2026
            if((level&(~127)) == 0){
2027
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2028
                put_bits(ac_pb, len_tab[index], bits_tab[index]);
2029
            }else{ //ESC3
2030
                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);
2031
            }
2032
            last_non_zero = i;
2033
        }
2034
    }
2035
    /*if(i<=last_index)*/{
2036
        int level = block[ scan_table[i] ];
2037
        int run = i - last_non_zero - 1;
2038
        level+=64;
2039
        if((level&(~127)) == 0){
2040
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2041
            put_bits(ac_pb, len_tab[index], bits_tab[index]);
2042
        }else{ //ESC3
2043
            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);
2044
        }
2045
    }
2046
#else
2047
    for (; i <= last_index; i++) {
2048
        const int slevel = block[ scan_table[i] ];
2049
        if (slevel) {
2050
            int level;
2051
            int run = i - last_non_zero - 1;
2052
            last = (i == last_index);
2053
            sign = 0;
2054
            level = slevel;
2055
            if (level < 0) {
2056
                sign = 1;
2057
                level = -level;
2058
            }
2059
            code = get_rl_index(rl, last, run, level);
2060
            put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2061
            if (code == rl->n) {
2062
                int level1, run1;
2063
                level1 = level - rl->max_level[last][run];
2064
                if (level1 < 1) 
2065
                    goto esc2;
2066
                code = get_rl_index(rl, last, run, level1);
2067
                if (code == rl->n) {
2068
                esc2:
2069
                    put_bits(ac_pb, 1, 1);
2070
                    if (level > MAX_LEVEL)
2071
                        goto esc3;
2072
                    run1 = run - rl->max_run[last][level] - 1;
2073
                    if (run1 < 0)
2074
                        goto esc3;
2075
                    code = get_rl_index(rl, last, run1, level);
2076
                    if (code == rl->n) {
2077
                    esc3:
2078
                        /* third escape */
2079
                        put_bits(ac_pb, 1, 1);
2080
                        put_bits(ac_pb, 1, last);
2081
                        put_bits(ac_pb, 6, run);
2082
                        put_bits(ac_pb, 1, 1);
2083
                        put_bits(ac_pb, 12, slevel & 0xfff);
2084
                        put_bits(ac_pb, 1, 1);
2085
                    } else {
2086
                        /* second escape */
2087
                        put_bits(ac_pb, 1, 0);
2088
                        put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2089
                        put_bits(ac_pb, 1, sign);
2090
                    }
2091
                } else {
2092
                    /* first escape */
2093
                    put_bits(ac_pb, 1, 0);
2094
                    put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2095
                    put_bits(ac_pb, 1, sign);
2096
                }
2097
            } else {
2098
                put_bits(ac_pb, 1, sign);
2099
            }
2100
            last_non_zero = i;
2101
        }
2102
    }
2103
#endif
2104
}
2105

    
2106
static inline int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2107
                               UINT8 *scan_table)
2108
{
2109
    int i, last_non_zero;
2110
    const RLTable *rl;
2111
    UINT8 *len_tab;
2112
    const int last_index = s->block_last_index[n];
2113
    int len=0;
2114

    
2115
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2116
        /* mpeg4 based DC predictor */
2117
        //mpeg4_encode_dc(dc_pb, intra_dc, n); //FIXME
2118
        if(last_index<1) return len;
2119
        i = 1;
2120
        rl = &rl_intra;
2121
        len_tab = uni_mpeg4_intra_rl_len;
2122
    } else {
2123
        if(last_index<0) return 0;
2124
        i = 0;
2125
        rl = &rl_inter;
2126
        len_tab = uni_mpeg4_inter_rl_len;
2127
    }
2128

    
2129
    /* AC coefs */
2130
    last_non_zero = i - 1;
2131
    for (; i < last_index; i++) {
2132
        int level = block[ scan_table[i] ];
2133
        if (level) {
2134
            int run = i - last_non_zero - 1;
2135
            level+=64;
2136
            if((level&(~127)) == 0){
2137
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2138
                len += len_tab[index];
2139
            }else{ //ESC3
2140
                len += 7+2+1+6+1+12+1;
2141
            }
2142
            last_non_zero = i;
2143
        }
2144
    }
2145
    /*if(i<=last_index)*/{
2146
        int level = block[ scan_table[i] ];
2147
        int run = i - last_non_zero - 1;
2148
        level+=64;
2149
        if((level&(~127)) == 0){
2150
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2151
            len += len_tab[index];
2152
        }else{ //ESC3
2153
            len += 7+2+1+6+1+12+1;
2154
        }
2155
    }
2156
    
2157
    return len;
2158
}
2159

    
2160
#endif
2161

    
2162

    
2163
/***********************************************/
2164
/* decoding */
2165

    
2166
static VLC intra_MCBPC_vlc;
2167
static VLC inter_MCBPC_vlc;
2168
static VLC cbpy_vlc;
2169
static VLC mv_vlc;
2170
static VLC dc_lum, dc_chrom;
2171
static VLC sprite_trajectory;
2172
static VLC mb_type_b_vlc;
2173

    
2174
void init_rl(RLTable *rl)
2175
{
2176
    INT8 max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
2177
    UINT8 index_run[MAX_RUN+1];
2178
    int last, run, level, start, end, i;
2179

    
2180
    /* compute max_level[], max_run[] and index_run[] */
2181
    for(last=0;last<2;last++) {
2182
        if (last == 0) {
2183
            start = 0;
2184
            end = rl->last;
2185
        } else {
2186
            start = rl->last;
2187
            end = rl->n;
2188
        }
2189

    
2190
        memset(max_level, 0, MAX_RUN + 1);
2191
        memset(max_run, 0, MAX_LEVEL + 1);
2192
        memset(index_run, rl->n, MAX_RUN + 1);
2193
        for(i=start;i<end;i++) {
2194
            run = rl->table_run[i];
2195
            level = rl->table_level[i];
2196
            if (index_run[run] == rl->n)
2197
                index_run[run] = i;
2198
            if (level > max_level[run])
2199
                max_level[run] = level;
2200
            if (run > max_run[level])
2201
                max_run[level] = run;
2202
        }
2203
        rl->max_level[last] = av_malloc(MAX_RUN + 1);
2204
        memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
2205
        rl->max_run[last] = av_malloc(MAX_LEVEL + 1);
2206
        memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
2207
        rl->index_run[last] = av_malloc(MAX_RUN + 1);
2208
        memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
2209
    }
2210
}
2211

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

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

    
2259
/* init vlcs */
2260

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

    
2266
    if (!done) {
2267
        done = 1;
2268

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

    
2302
/**
2303
 * Get the GOB height based on picture height.
2304
 */
2305
int ff_h263_get_gob_height(MpegEncContext *s){
2306
    if (s->height <= 400)
2307
        return 1;
2308
    else if (s->height <= 800)
2309
        return  2;
2310
    else
2311
        return 4;
2312
}
2313

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

    
2328
        /* We have a GBSC probably with GSTUFF */
2329
    skip_bits(&s->gb, 16); /* Drop the zeros */
2330
    left= s->gb.size*8 - get_bits_count(&s->gb);
2331
    //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2332
    for(;left>13; left--){
2333
        if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2334
    }
2335
    if(left<=13) 
2336
        return -1;
2337

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

    
2354
static inline void memsetw(short *tab, int val, int n)
2355
{
2356
    int i;
2357
    for(i=0;i<n;i++)
2358
        tab[i] = val;
2359
}
2360

    
2361
void ff_mpeg4_init_partitions(MpegEncContext *s)
2362
{
2363
    init_put_bits(&s->tex_pb, s->tex_pb_buffer, PB_BUFFER_SIZE, NULL, NULL);
2364
    init_put_bits(&s->pb2   , s->pb2_buffer   , PB_BUFFER_SIZE, NULL, NULL);
2365
}
2366

    
2367
void ff_mpeg4_merge_partitions(MpegEncContext *s)
2368
{
2369
    const int pb2_len   = get_bit_count(&s->pb2   );
2370
    const int tex_pb_len= get_bit_count(&s->tex_pb);
2371
    const int bits= get_bit_count(&s->pb);
2372

    
2373
    if(s->pict_type==I_TYPE){
2374
        put_bits(&s->pb, 19, DC_MARKER);
2375
        s->misc_bits+=19 + pb2_len + bits - s->last_bits;
2376
        s->i_tex_bits+= tex_pb_len;
2377
    }else{
2378
        put_bits(&s->pb, 17, MOTION_MARKER);
2379
        s->misc_bits+=17 + pb2_len;
2380
        s->mv_bits+= bits - s->last_bits;
2381
        s->p_tex_bits+= tex_pb_len;
2382
    }
2383

    
2384
    flush_put_bits(&s->pb2);
2385
    flush_put_bits(&s->tex_pb);
2386

    
2387
    ff_copy_bits(&s->pb, s->pb2_buffer   , pb2_len);
2388
    ff_copy_bits(&s->pb, s->tex_pb_buffer, tex_pb_len);
2389
    s->last_bits= get_bit_count(&s->pb);
2390
}
2391

    
2392
int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
2393
    switch(s->pict_type){
2394
        case I_TYPE:
2395
            return 16;
2396
        case P_TYPE:
2397
        case S_TYPE:
2398
            return s->f_code+15;
2399
        case B_TYPE:
2400
            return FFMAX(FFMAX(s->f_code, s->b_code)+15, 17);
2401
        default:
2402
            return -1;
2403
    }
2404
}
2405

    
2406
void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
2407
{
2408
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2409

    
2410
    ff_mpeg4_stuffing(&s->pb);
2411
    put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
2412
    put_bits(&s->pb, 1, 1);
2413
    
2414
    put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
2415
    put_bits(&s->pb, s->quant_precision, s->qscale);
2416
    put_bits(&s->pb, 1, 0); /* no HEC */
2417
}
2418

    
2419
/**
2420
 * check if the next stuff is a resync marker or the end.
2421
 * @return 0 if not
2422
 */
2423
static inline int mpeg4_is_resync(MpegEncContext *s){
2424
    const int bits_count= get_bits_count(&s->gb);
2425
    
2426
    if(s->workaround_bugs&FF_BUG_NO_PADDING){
2427
        return 0;
2428
    }
2429

    
2430
    if(bits_count + 8 >= s->gb.size*8){
2431
        int v= show_bits(&s->gb, 8);
2432
        v|= 0x7F >> (7-(bits_count&7));
2433
                
2434
        if(v==0x7F)
2435
            return 1;
2436
    }else{
2437
        if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){
2438
            int len;
2439
            GetBitContext gb= s->gb;
2440
        
2441
            skip_bits(&s->gb, 1);
2442
            align_get_bits(&s->gb);
2443
        
2444
            for(len=0; len<32; len++){
2445
                if(get_bits1(&s->gb)) break;
2446
            }
2447

    
2448
            s->gb= gb;
2449

    
2450
            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
2451
                return 1;
2452
        }
2453
    }
2454
    return 0;
2455
}
2456

    
2457
/**
2458
 * decodes the next video packet.
2459
 * @return <0 if something went wrong
2460
 */
2461
static int mpeg4_decode_video_packet_header(MpegEncContext *s)
2462
{
2463
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2464
    int header_extension=0, mb_num, len;
2465
    
2466
    /* is there enough space left for a video packet + header */
2467
    if( get_bits_count(&s->gb) > s->gb.size*8-20) return -1;
2468

    
2469
    for(len=0; len<32; len++){
2470
        if(get_bits1(&s->gb)) break;
2471
    }
2472

    
2473
    if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
2474
        printf("marker does not match f_code\n");
2475
        return -1;
2476
    }
2477
    
2478
    if(s->shape != RECT_SHAPE){
2479
        header_extension= get_bits1(&s->gb);
2480
        //FIXME more stuff here
2481
    }
2482

    
2483
    mb_num= get_bits(&s->gb, mb_num_bits);
2484
    if(mb_num>=s->mb_num){
2485
        fprintf(stderr, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
2486
        return -1;
2487
    }
2488
    s->mb_x= mb_num % s->mb_width;
2489
    s->mb_y= mb_num / s->mb_width;
2490

    
2491
    if(s->shape != BIN_ONLY_SHAPE){
2492
        int qscale= get_bits(&s->gb, s->quant_precision); 
2493
        if(qscale)
2494
            s->qscale= qscale;
2495
    }
2496

    
2497
    if(s->shape == RECT_SHAPE){
2498
        header_extension= get_bits1(&s->gb);
2499
    }
2500
    if(header_extension){
2501
        int time_increment;
2502
        int time_incr=0;
2503

    
2504
        while (get_bits1(&s->gb) != 0) 
2505
            time_incr++;
2506

    
2507
        check_marker(&s->gb, "before time_increment in video packed header");
2508
        time_increment= get_bits(&s->gb, s->time_increment_bits);
2509
        check_marker(&s->gb, "before vop_coding_type in video packed header");
2510
        
2511
        skip_bits(&s->gb, 2); /* vop coding type */
2512
        //FIXME not rect stuff here
2513

    
2514
        if(s->shape != BIN_ONLY_SHAPE){
2515
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
2516
//FIXME dont just ignore everything
2517
            if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2518
                mpeg4_decode_sprite_trajectory(s);
2519
                fprintf(stderr, "untested\n");
2520
            }
2521

    
2522
            //FIXME reduced res stuff here
2523
            
2524
            if (s->pict_type != I_TYPE) {
2525
                int f_code = get_bits(&s->gb, 3);        /* fcode_for */
2526
                if(f_code==0){
2527
                    printf("Error, video packet header damaged (f_code=0)\n");
2528
                }
2529
            }
2530
            if (s->pict_type == B_TYPE) {
2531
                int b_code = get_bits(&s->gb, 3);
2532
                if(b_code==0){
2533
                    printf("Error, video packet header damaged (b_code=0)\n");
2534
                }
2535
            }       
2536
        }
2537
    }
2538
    //FIXME new-pred stuff
2539
    
2540
//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));
2541

    
2542
    return 0;
2543
}
2544

    
2545
void ff_mpeg4_clean_buffers(MpegEncContext *s)
2546
{
2547
    int c_wrap, c_xy, l_wrap, l_xy;
2548

    
2549
    l_wrap= s->block_wrap[0];
2550
    l_xy= s->mb_y*l_wrap*2 + s->mb_x*2;
2551
    c_wrap= s->block_wrap[4];
2552
    c_xy= s->mb_y*c_wrap + s->mb_x;
2553

    
2554
#if 0
2555
    /* clean DC */
2556
    memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
2557
    memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
2558
    memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
2559
#endif
2560

    
2561
    /* clean AC */
2562
    memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(INT16));
2563
    memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(INT16));
2564
    memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(INT16));
2565

    
2566
    /* clean MV */
2567
    // we cant clear the MVs as they might be needed by a b frame
2568
//    memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(INT16));
2569
//    memset(s->motion_val, 0, 2*sizeof(INT16)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
2570
    s->last_mv[0][0][0]=
2571
    s->last_mv[0][0][1]=
2572
    s->last_mv[1][0][0]=
2573
    s->last_mv[1][0][1]= 0;
2574
}
2575

    
2576
/**
2577
 * decodes the group of blocks / video packet header.
2578
 * @return <0 if no resync found
2579
 */
2580
int ff_h263_resync(MpegEncContext *s){
2581
    int left, ret;
2582
    
2583
    if(s->codec_id==CODEC_ID_MPEG4)
2584
        skip_bits1(&s->gb);
2585
    
2586
    align_get_bits(&s->gb);
2587

    
2588
    if(show_bits(&s->gb, 16)==0){
2589
        if(s->codec_id==CODEC_ID_MPEG4)
2590
            ret= mpeg4_decode_video_packet_header(s);
2591
        else
2592
            ret= h263_decode_gob_header(s);
2593
        if(ret>=0)
2594
            return 0;
2595
    }
2596
    //ok, its not where its supposed to be ...
2597
    s->gb= s->last_resync_gb;
2598
    align_get_bits(&s->gb);
2599
    left= s->gb.size*8 - get_bits_count(&s->gb);
2600
    
2601
    for(;left>16+1+5+5; left-=8){ 
2602
        if(show_bits(&s->gb, 16)==0){
2603
            GetBitContext bak= s->gb;
2604

    
2605
            if(s->codec_id==CODEC_ID_MPEG4)
2606
                ret= mpeg4_decode_video_packet_header(s);
2607
            else
2608
                ret= h263_decode_gob_header(s);
2609
            if(ret>=0)
2610
                return 0;
2611

    
2612
            s->gb= bak;
2613
        }
2614
        skip_bits(&s->gb, 8);
2615
    }
2616
    
2617
    return -1;
2618
}
2619

    
2620
/**
2621
 * @param n either 0 for the x component or 1 for y
2622
 * @returns the average MV for a GMC MB
2623
 */
2624
static inline int get_amv(MpegEncContext *s, int n){
2625
    int x, y, mb_v, sum, dx, dy, shift;
2626
    int len = 1 << (s->f_code + 4);
2627
    const int a= s->sprite_warping_accuracy;
2628

    
2629
    if(s->real_sprite_warping_points==1){
2630
        if(s->divx_version==500 && s->divx_build==413)
2631
            sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
2632
        else
2633
            sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
2634
    }else{
2635
        dx= s->sprite_delta[n][0];
2636
        dy= s->sprite_delta[n][1];
2637
        shift= s->sprite_shift[0];
2638
        if(n) dy -= 1<<(shift + a + 1);
2639
        else  dx -= 1<<(shift + a + 1);
2640
        mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
2641

    
2642
        sum=0;
2643
        for(y=0; y<16; y++){
2644
            int v;
2645
        
2646
            v= mb_v + dy*y;
2647
            //XXX FIXME optimize
2648
            for(x=0; x<16; x++){
2649
                sum+= v>>shift;
2650
                v+= dx;
2651
            }
2652
        }
2653
        sum /= 256;
2654
        sum= RSHIFT(sum<<s->quarter_sample, a);
2655
    }
2656

    
2657
    if      (sum < -len) sum= -len;
2658
    else if (sum >= len) sum= len-1;
2659

    
2660
    return sum;
2661
}
2662

    
2663
/**
2664
 * decodes first partition.
2665
 * @return number of MBs decoded or <0 if an error occured
2666
 */
2667
static int mpeg4_decode_partition_a(MpegEncContext *s){
2668
    int mb_num;
2669
    static const INT8 quant_tab[4] = { -1, -2, 1, 2 };
2670
    
2671
    /* decode first partition */
2672
    mb_num=0;
2673
    s->first_slice_line=1;
2674
    for(; s->mb_y<s->mb_height; s->mb_y++){
2675
        ff_init_block_index(s);
2676
        for(; s->mb_x<s->mb_width; s->mb_x++){
2677
            const int xy= s->mb_x + s->mb_y*s->mb_width;
2678
            int cbpc;
2679
            int dir=0;
2680
            
2681
            mb_num++;
2682
            ff_update_block_index(s);
2683
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2684
                s->first_slice_line=0;
2685
            
2686
            if(s->mb_x==0) PRINT_MB_TYPE("\n");
2687

    
2688
            if(s->pict_type==I_TYPE){
2689
                int i;
2690

    
2691
                if(show_bits(&s->gb, 19)==DC_MARKER){
2692
                    return mb_num-1;
2693
                }
2694

    
2695
                PRINT_MB_TYPE("I");
2696
                cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
2697
                if (cbpc < 0){
2698

    
2699
                    fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2700
                    return -1;
2701
                }
2702
                s->cbp_table[xy]= cbpc & 3;
2703
                s->mb_type[xy]= MB_TYPE_INTRA;
2704
                s->mb_intra = 1;
2705

    
2706
                if(cbpc & 4) {
2707
                    change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2708
                }
2709
                s->current_picture.qscale_table[xy]= s->qscale;
2710

    
2711
                s->mbintra_table[xy]= 1;
2712
                for(i=0; i<6; i++){
2713
                    int dc_pred_dir;
2714
                    int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2715
                    if(dc < 0){
2716
                        fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2717
                        return -1;
2718
                    }
2719
                    dir<<=1;
2720
                    if(dc_pred_dir) dir|=1;
2721
                }
2722
                s->pred_dir_table[xy]= dir;
2723
                
2724
                s->error_status_table[xy]= AC_ERROR;
2725
            }else{ /* P/S_TYPE */
2726
                int mx, my, pred_x, pred_y, bits;
2727
                INT16 * const mot_val= s->motion_val[s->block_index[0]];
2728
                const int stride= s->block_wrap[0]*2;
2729

    
2730
                bits= show_bits(&s->gb, 17);
2731
                if(bits==MOTION_MARKER){
2732
                    return mb_num-1;
2733
                }
2734
                skip_bits1(&s->gb);
2735
                if(bits&0x10000){
2736
                    /* skip mb */
2737
                    s->mb_type[xy]= MB_TYPE_SKIPED;
2738
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2739
                        PRINT_MB_TYPE("G");
2740
                        mx= get_amv(s, 0);
2741
                        my= get_amv(s, 1);
2742
                    }else{
2743
                        PRINT_MB_TYPE("S");
2744
                        mx=my=0;
2745
                    }
2746
                    mot_val[0       ]= mot_val[2       ]=
2747
                    mot_val[0+stride]= mot_val[2+stride]= mx;
2748
                    mot_val[1       ]= mot_val[3       ]=
2749
                    mot_val[1+stride]= mot_val[3+stride]= my;
2750

    
2751
                    if(s->mbintra_table[xy])
2752
                        ff_clean_intra_table_entries(s);
2753

    
2754
                    s->error_status_table[xy]= AC_ERROR;
2755
                    continue;
2756
                }
2757
                cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
2758
                if (cbpc < 0){
2759
                    fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2760
                    return -1;
2761
                }
2762
                if (cbpc > 20)
2763
                    cbpc+=3;
2764
                else if (cbpc == 20)
2765
                    fprintf(stderr, "Stuffing !");
2766
                s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
2767
    
2768
                s->mb_intra = ((cbpc & 4) != 0);
2769
        
2770
                if(s->mb_intra){
2771
                    PRINT_MB_TYPE("I");
2772
                    s->mbintra_table[xy]= 1;
2773
                    s->mb_type[xy]= MB_TYPE_INTRA;
2774
                    mot_val[0       ]= mot_val[2       ]= 
2775
                    mot_val[0+stride]= mot_val[2+stride]= 0;
2776
                    mot_val[1       ]= mot_val[3       ]=
2777
                    mot_val[1+stride]= mot_val[3+stride]= 0;
2778
                    s->error_status_table[xy]= DC_ERROR|AC_ERROR;
2779
                }else{
2780
                    if(s->mbintra_table[xy])
2781
                        ff_clean_intra_table_entries(s);
2782

    
2783
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
2784
                        s->mcsel= get_bits1(&s->gb);
2785
                    else s->mcsel= 0;
2786
        
2787
                    if ((cbpc & 16) == 0) {
2788
                        PRINT_MB_TYPE("P");
2789
                        /* 16x16 motion prediction */
2790
                        s->mb_type[xy]= MB_TYPE_INTER;
2791

    
2792
                        h263_pred_motion(s, 0, &pred_x, &pred_y);
2793
                        if(!s->mcsel){
2794
                            mx = h263_decode_motion(s, pred_x, s->f_code);
2795
                            if (mx >= 0xffff)
2796
                                return -1;
2797

    
2798
                            my = h263_decode_motion(s, pred_y, s->f_code);
2799
                            if (my >= 0xffff)
2800
                                return -1;
2801
                        } else {
2802
                            mx = get_amv(s, 0);
2803
                            my = get_amv(s, 1);
2804
                        }
2805

    
2806
                        mot_val[0       ]= mot_val[2       ] =
2807
                        mot_val[0+stride]= mot_val[2+stride]= mx;
2808
                        mot_val[1       ]= mot_val[3       ]=
2809
                        mot_val[1+stride]= mot_val[3+stride]= my;
2810
                    } else {
2811
                        int i;
2812
                        PRINT_MB_TYPE("4");
2813
                        s->mb_type[xy]= MB_TYPE_INTER4V;
2814
                        for(i=0;i<4;i++) {
2815
                            INT16 *mot_val= h263_pred_motion(s, i, &pred_x, &pred_y);
2816
                            mx = h263_decode_motion(s, pred_x, s->f_code);
2817
                            if (mx >= 0xffff)
2818
                                return -1;
2819
                
2820
                            my = h263_decode_motion(s, pred_y, s->f_code);
2821
                            if (my >= 0xffff)
2822
                                return -1;
2823
                            mot_val[0] = mx;
2824
                            mot_val[1] = my;
2825
                        }
2826
                    }
2827
                    s->error_status_table[xy]= AC_ERROR;
2828
                }
2829
            }
2830
        }
2831
        s->mb_x= 0;
2832
    }
2833

    
2834
    return mb_num;
2835
}
2836

    
2837
/**
2838
 * decode second partition.
2839
 * @return <0 if an error occured
2840
 */
2841
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
2842
    int mb_num=0;
2843
    static const INT8 quant_tab[4] = { -1, -2, 1, 2 };
2844

    
2845
    s->mb_x= s->resync_mb_x;
2846
    s->first_slice_line=1;
2847
    for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
2848
        ff_init_block_index(s);
2849
        for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
2850
            const int xy= s->mb_x + s->mb_y*s->mb_width;
2851

    
2852
            mb_num++;
2853
            ff_update_block_index(s);
2854
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2855
                s->first_slice_line=0;
2856
            
2857
            if(s->pict_type==I_TYPE){
2858
                int ac_pred= get_bits1(&s->gb);
2859
                int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2860
                if(cbpy<0){
2861
                    fprintf(stderr, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2862
                    return -1;
2863
                }
2864
                
2865
                s->cbp_table[xy]|= cbpy<<2;
2866
                s->pred_dir_table[xy]|= ac_pred<<7;
2867
            }else{ /* P || S_TYPE */
2868
                if(s->mb_type[xy]&MB_TYPE_INTRA){          
2869
                    int dir=0,i;
2870
                    int ac_pred = get_bits1(&s->gb);
2871
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2872

    
2873
                    if(cbpy<0){
2874
                        fprintf(stderr, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2875
                        return -1;
2876
                    }
2877
                    
2878
                    if(s->cbp_table[xy] & 8) {
2879
                        change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2880
                    }
2881
                    s->current_picture.qscale_table[xy]= s->qscale;
2882

    
2883
                    for(i=0; i<6; i++){
2884
                        int dc_pred_dir;
2885
                        int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2886
                        if(dc < 0){
2887
                            fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2888
                            return -1;
2889
                        }
2890
                        dir<<=1;
2891
                        if(dc_pred_dir) dir|=1;
2892
                    }
2893
                    s->cbp_table[xy]&= 3; //remove dquant
2894
                    s->cbp_table[xy]|= cbpy<<2;
2895
                    s->pred_dir_table[xy]= dir | (ac_pred<<7);
2896
                    s->error_status_table[xy]&= ~DC_ERROR;
2897
                }else if(s->mb_type[xy]&MB_TYPE_SKIPED){
2898
                    s->current_picture.qscale_table[xy]= s->qscale;
2899
                    s->cbp_table[xy]= 0;
2900
                }else{
2901
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2902

    
2903
                    if(cbpy<0){
2904
                        fprintf(stderr, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2905
                        return -1;
2906
                    }
2907
                    
2908
                    if(s->cbp_table[xy] & 8) {
2909
                        change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2910
                    }
2911
                    s->current_picture.qscale_table[xy]= s->qscale;
2912

    
2913
                    s->cbp_table[xy]&= 3; //remove dquant
2914
                    s->cbp_table[xy]|= (cbpy^0xf)<<2;
2915
                }
2916
            }
2917
        }
2918
        if(mb_num >= mb_count) return 0;
2919
        s->mb_x= 0;
2920
    }
2921
    return 0;
2922
}
2923

    
2924
/**
2925
 * decodes the first & second partition
2926
 * @return <0 if error (and sets error type in the error_status_table)
2927
 */
2928
int ff_mpeg4_decode_partitions(MpegEncContext *s)
2929
{
2930
    int mb_num;
2931
    
2932
    mb_num= mpeg4_decode_partition_a(s);    
2933
    if(mb_num<0)
2934
        return -1;
2935
    
2936
    if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
2937
        fprintf(stderr, "slice below monitor ...\n");
2938
        return -1;
2939
    }
2940

    
2941
    s->mb_num_left= mb_num;
2942
        
2943
    if(s->pict_type==I_TYPE){
2944
        if(get_bits(&s->gb, 19)!=DC_MARKER){
2945
            fprintf(stderr, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
2946
            return -1;
2947
        }else
2948
            s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= MV_END|DC_END;
2949
    }else{
2950
        if(get_bits(&s->gb, 17)!=MOTION_MARKER){
2951
            fprintf(stderr, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
2952
            return -1;
2953
        }else
2954
            s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= MV_END;
2955
    }
2956
    
2957
    if( mpeg4_decode_partition_b(s, mb_num) < 0){
2958
        return -1;
2959
    }
2960
    
2961
    s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= DC_END;
2962

    
2963
    return 0;        
2964
}
2965

    
2966
/**
2967
 * decode partition C of one MB.
2968
 * @return <0 if an error occured
2969
 */
2970
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
2971
{
2972
    int cbp, mb_type;
2973
    const int xy= s->mb_x + s->mb_y*s->mb_width;
2974

    
2975
    mb_type= s->mb_type[xy];
2976
    cbp = s->cbp_table[xy];
2977

    
2978
    if(s->current_picture.qscale_table[xy] != s->qscale){
2979
        s->qscale= s->current_picture.qscale_table[xy];
2980
        s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
2981
        s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
2982
    }
2983
    
2984
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
2985
        int i;
2986
        for(i=0; i<4; i++){
2987
            s->mv[0][i][0] = s->motion_val[ s->block_index[i] ][0];
2988
            s->mv[0][i][1] = s->motion_val[ s->block_index[i] ][1];
2989
        }
2990
        s->mb_intra = mb_type&MB_TYPE_INTRA;
2991

    
2992
        if (mb_type&MB_TYPE_SKIPED) {
2993
            /* skip mb */
2994
            for(i=0;i<6;i++)
2995
                s->block_last_index[i] = -1;
2996
            s->mv_dir = MV_DIR_FORWARD;
2997
            s->mv_type = MV_TYPE_16X16;
2998
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2999
                s->mcsel=1;
3000
                s->mb_skiped = 0;
3001
            }else{
3002
                s->mcsel=0;
3003
                s->mb_skiped = 1;
3004
            }
3005
        }else if(s->mb_intra){
3006
            s->ac_pred = s->pred_dir_table[xy]>>7;
3007

    
3008
            /* decode each block */
3009
            for (i = 0; i < 6; i++) {
3010
                if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){
3011
                    fprintf(stderr, "texture corrupted at %d %d\n", s->mb_x, s->mb_y);
3012
                    return -1;
3013
                }
3014
                cbp+=cbp;
3015
            }
3016
        }else if(!s->mb_intra){
3017
//            s->mcsel= 0; //FIXME do we need to init that
3018
            
3019
            s->mv_dir = MV_DIR_FORWARD;
3020
            if (mb_type&MB_TYPE_INTER4V) {
3021
                s->mv_type = MV_TYPE_8X8;
3022
            } else {
3023
                s->mv_type = MV_TYPE_16X16;
3024
            }
3025
            /* decode each block */
3026
            for (i = 0; i < 6; i++) {
3027
                if(mpeg4_decode_block(s, block[i], i, cbp&32, 0) < 0){
3028
                    fprintf(stderr, "texture corrupted at %d %d (trying to continue with mc/dc only)\n", s->mb_x, s->mb_y);
3029
                    return -1;
3030
                }
3031
                cbp+=cbp;
3032
            }
3033
        }
3034
    } else { /* I-Frame */
3035
        int i;
3036
        s->mb_intra = 1;
3037
        s->ac_pred = s->pred_dir_table[xy]>>7;
3038
        
3039
        /* decode each block */
3040
        for (i = 0; i < 6; i++) {
3041
            if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){
3042
                fprintf(stderr, "texture corrupted at %d %d (trying to continue with dc only)\n", s->mb_x, s->mb_y);
3043
                return -1;
3044
            }
3045
            cbp+=cbp;
3046
        }
3047
    }
3048

    
3049
    s->error_status_table[xy]&= ~AC_ERROR;
3050

    
3051
    /* per-MB end of slice check */
3052

    
3053
    if(--s->mb_num_left <= 0){
3054
//printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size*8 - get_bits_count(&s->gb));
3055
        if(mpeg4_is_resync(s))
3056
            return SLICE_END;
3057
        else
3058
            return SLICE_NOEND;     
3059
    }else{
3060
        if(s->cbp_table[xy+1] && mpeg4_is_resync(s))
3061
            return SLICE_END;
3062
        else
3063
            return SLICE_OK;
3064
    }
3065
}
3066

    
3067
int ff_h263_decode_mb(MpegEncContext *s,
3068
                      DCTELEM block[6][64])
3069
{
3070
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
3071
    INT16 *mot_val;
3072
    static INT8 quant_tab[4] = { -1, -2, 1, 2 };
3073

    
3074
    s->error_status_table[s->mb_x + s->mb_y*s->mb_width]= 0;
3075

    
3076
    if(s->mb_x==0) PRINT_MB_TYPE("\n");
3077

    
3078
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3079
        if (get_bits1(&s->gb)) {
3080
            /* skip mb */
3081
            s->mb_intra = 0;
3082
            for(i=0;i<6;i++)
3083
                s->block_last_index[i] = -1;
3084
            s->mv_dir = MV_DIR_FORWARD;
3085
            s->mv_type = MV_TYPE_16X16;
3086
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3087
                PRINT_MB_TYPE("G");
3088
                s->mcsel=1;
3089
                s->mv[0][0][0]= get_amv(s, 0);
3090
                s->mv[0][0][1]= get_amv(s, 1);
3091

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

    
3141
                s->field_select[0][0]= get_bits1(&s->gb);
3142
                s->field_select[0][1]= get_bits1(&s->gb);
3143

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

    
3155
                    s->mv[0][i][0] = mx;
3156
                    s->mv[0][i][1] = my;
3157
                }
3158
            }else{
3159
                PRINT_MB_TYPE("P");
3160
                /* 16x16 motion prediction */
3161
                s->mv_type = MV_TYPE_16X16;
3162
                h263_pred_motion(s, 0, &pred_x, &pred_y);
3163
                if (s->umvplus_dec)
3164
                   mx = h263p_decode_umotion(s, pred_x);
3165
                else
3166
                   mx = h263_decode_motion(s, pred_x, s->f_code);
3167
            
3168
                if (mx >= 0xffff)
3169
                    return -1;
3170
            
3171
                if (s->umvplus_dec)
3172
                   my = h263p_decode_umotion(s, pred_y);
3173
                else
3174
                   my = h263_decode_motion(s, pred_y, s->f_code);
3175
            
3176
                if (my >= 0xffff)
3177
                    return -1;
3178
                s->mv[0][0][0] = mx;
3179
                s->mv[0][0][1] = my;
3180

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

    
3216
        s->mb_intra = 0; //B-frames never contain intra blocks
3217
        s->mcsel=0;      //     ...               true gmc blocks
3218

    
3219
        if(s->mb_x==0){
3220
            for(i=0; i<2; i++){
3221
                s->last_mv[i][0][0]= 
3222
                s->last_mv[i][0][1]= 
3223
                s->last_mv[i][1][0]= 
3224
                s->last_mv[i][1][1]= 0;
3225
            }
3226
        }
3227

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

    
3231
        if(s->mb_skiped){
3232
                /* skip mb */
3233
            for(i=0;i<6;i++)
3234
                s->block_last_index[i] = -1;
3235

    
3236
            s->mv_dir = MV_DIR_FORWARD;
3237
            s->mv_type = MV_TYPE_16X16;
3238
            s->mv[0][0][0] = 0;
3239
            s->mv[0][0][1] = 0;
3240
            s->mv[1][0][0] = 0;
3241
            s->mv[1][0][1] = 0;
3242
            PRINT_MB_TYPE("s");
3243
            goto end;
3244
        }
3245

    
3246
        modb1= get_bits1(&s->gb); 
3247
        if(modb1){
3248
            mb_type=4; //like MB_TYPE_B_DIRECT but no vectors coded
3249
            cbp=0;
3250
        }else{
3251
            int field_mv;
3252
        
3253
            modb2= get_bits1(&s->gb);
3254
            mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
3255
            if(modb2) cbp= 0;
3256
            else      cbp= get_bits(&s->gb, 6);
3257

    
3258
            if (mb_type!=MB_TYPE_B_DIRECT && cbp) {
3259
                if(get_bits1(&s->gb)){
3260
                    change_qscale(s, get_bits1(&s->gb)*4 - 2);
3261
                }
3262
            }
3263
            field_mv=0;
3264

    
3265
            if(!s->progressive_sequence){
3266
                if(cbp)
3267
                    s->interlaced_dct= get_bits1(&s->gb);
3268

    
3269
                if(mb_type!=MB_TYPE_B_DIRECT && get_bits1(&s->gb)){
3270
                    field_mv=1;
3271

    
3272
                    if(mb_type!=MB_TYPE_B_BACKW){
3273
                        s->field_select[0][0]= get_bits1(&s->gb);
3274
                        s->field_select[0][1]= get_bits1(&s->gb);
3275
                    }
3276
                    if(mb_type!=MB_TYPE_B_FORW){
3277
                        s->field_select[1][0]= get_bits1(&s->gb);
3278
                        s->field_select[1][1]= get_bits1(&s->gb);
3279
                    }
3280
                }
3281
            }
3282

    
3283
            s->mv_dir = 0;
3284
            if(mb_type!=MB_TYPE_B_DIRECT && !field_mv){
3285
                s->mv_type= MV_TYPE_16X16;
3286
                if(mb_type!=MB_TYPE_B_BACKW){
3287
                    s->mv_dir = MV_DIR_FORWARD;
3288

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

    
3298
                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
3299
                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
3300
                    s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
3301
                    s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
3302
                }
3303
                if(mb_type!=MB_TYPE_B_DIRECT)
3304
                    PRINT_MB_TYPE(mb_type==MB_TYPE_B_FORW ? "F" : (mb_type==MB_TYPE_B_BACKW ? "B" : "T"));
3305
            }else if(mb_type!=MB_TYPE_B_DIRECT){
3306
                s->mv_type= MV_TYPE_FIELD;
3307

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

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

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

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

    
3408
        /* per-MB end of slice check */
3409
    if(s->codec_id==CODEC_ID_MPEG4){
3410
        if(mpeg4_is_resync(s)){
3411
            if(s->pict_type==B_TYPE && s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x+1])
3412
                return SLICE_OK;
3413
            return SLICE_END;
3414
        }
3415
    }else{
3416
        int v= show_bits(&s->gb, 16);
3417
    
3418
        if(get_bits_count(&s->gb) + 16 > s->gb.size*8){
3419
            v>>= get_bits_count(&s->gb) + 16 - s->gb.size*8;
3420
        }
3421

    
3422
        if(v==0)
3423
            return SLICE_END;
3424
    }
3425

    
3426
    return SLICE_OK;     
3427
}
3428

    
3429
static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
3430
{
3431
    int code, val, sign, shift, l;
3432
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
3433
    if (code < 0)
3434
        return 0xffff;
3435

    
3436
    if (code == 0)
3437
        return pred;
3438

    
3439
    sign = get_bits1(&s->gb);
3440
    shift = f_code - 1;
3441
    val = (code - 1) << shift;
3442
    if (shift > 0)
3443
        val |= get_bits(&s->gb, shift);
3444
    val++;
3445
    if (sign)
3446
        val = -val;
3447
    val += pred;
3448

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

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

    
3492
}
3493

    
3494
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
3495
                             int n, int coded)
3496
{
3497
    int code, level, i, j, last, run;
3498
    RLTable *rl = &rl_inter;
3499
    const UINT8 *scan_table;
3500

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

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

    
3587
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
3588
{
3589
    int level, pred, code;
3590
    UINT16 *dc_val;
3591

    
3592
    if (n < 4) 
3593
        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
3594
    else 
3595
        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
3596
    if (code < 0 || code > 9 /* && s->nbit<9 */){
3597
        fprintf(stderr, "illegal dc vlc\n");
3598
        return -1;
3599
    }
3600
    if (code == 0) {
3601
        level = 0;
3602
    } else {
3603
        level = get_bits(&s->gb, code);
3604
        if ((level >> (code - 1)) == 0) /* if MSB not set it is negative*/
3605
            level = - (level ^ ((1 << code) - 1));
3606
        if (code > 8){
3607
            if(get_bits1(&s->gb)==0){ /* marker */
3608
                if(s->error_resilience>=2){
3609
                    fprintf(stderr, "dc marker bit missing\n");
3610
                    return -1;
3611
                }
3612
            }
3613
        }
3614
    }
3615
    pred = ff_mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
3616
    level += pred;
3617
    if (level < 0){
3618
        if(s->error_resilience>=3){
3619
            fprintf(stderr, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
3620
            return -1;
3621
        }
3622
        level = 0;
3623
    }
3624
    if (n < 4) {
3625
        *dc_val = level * s->y_dc_scale;
3626
    } else {
3627
        *dc_val = level * s->c_dc_scale;
3628
    }
3629
    if(s->error_resilience>=3){
3630
        if(*dc_val > 2048 + s->y_dc_scale + s->c_dc_scale){
3631
            fprintf(stderr, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
3632
            return -1;
3633
        }
3634
    }
3635
    return level;
3636
}
3637

    
3638
/**
3639
 * decodes a block.
3640
 * @return <0 if an error occured
3641
 */
3642
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
3643
                              int n, int coded, int intra)
3644
{
3645
    int level, i, last, run;
3646
    int dc_pred_dir;
3647
    RLTable * rl;
3648
    RL_VLC_ELEM * rl_vlc;
3649
    const UINT8 * scan_table;
3650
    int qmul, qadd;
3651

    
3652
    if(intra) {
3653
        /* DC coef */
3654
        if(s->partitioned_frame){
3655
            level = s->dc_val[0][ s->block_index[n] ];
3656
            if(n<4) level= (level + (s->y_dc_scale>>1))/s->y_dc_scale; //FIXME optimizs
3657
            else    level= (level + (s->c_dc_scale>>1))/s->c_dc_scale;
3658
            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_width]<<n)&32;
3659
        }else{
3660
            level = mpeg4_decode_dc(s, n, &dc_pred_dir);
3661
            if (level < 0)
3662
                return -1;
3663
        }
3664
        block[0] = level;
3665
        i = 0;
3666
        if (!coded) 
3667
            goto not_coded;
3668
        rl = &rl_intra;
3669
        rl_vlc = rl_intra.rl_vlc[0];
3670
        if (s->ac_pred) {
3671
            if (dc_pred_dir == 0) 
3672
                scan_table = s->intra_v_scantable.permutated; /* left */
3673
            else
3674
                scan_table = s->intra_h_scantable.permutated; /* top */
3675
        } else {
3676
            scan_table = s->intra_scantable.permutated;
3677
        }
3678
        qmul=1;
3679
        qadd=0;
3680
    } else {
3681
        i = -1;
3682
        if (!coded) {
3683
            s->block_last_index[n] = i;
3684
            return 0;
3685
        }
3686
        rl = &rl_inter;
3687
   
3688
        scan_table = s->intra_scantable.permutated;
3689

    
3690
        if(s->mpeg_quant){
3691
            qmul=1;
3692
            qadd=0;
3693
            rl_vlc = rl_inter.rl_vlc[0];        
3694
        }else{
3695
            qmul = s->qscale << 1;
3696
            qadd = (s->qscale - 1) | 1;
3697
            rl_vlc = rl_inter.rl_vlc[s->qscale];
3698
        }
3699
    }
3700
  {
3701
    OPEN_READER(re, &s->gb);
3702
    for(;;) {
3703
        UPDATE_CACHE(re, &s->gb);
3704
        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3705
        if (level==0) {
3706
            int cache;
3707
            cache= GET_CACHE(re, &s->gb);
3708
            /* escape */
3709
            if (cache&0x80000000) {
3710
                if (cache&0x40000000) {
3711
                    /* third escape */
3712
                    SKIP_CACHE(re, &s->gb, 2);
3713
                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
3714
                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
3715
                    SKIP_COUNTER(re, &s->gb, 2+1+6);
3716
                    UPDATE_CACHE(re, &s->gb);
3717

    
3718
                    if(SHOW_UBITS(re, &s->gb, 1)==0){
3719
                        fprintf(stderr, "1. marker bit missing in 3. esc\n");
3720
                        return -1;
3721
                    }; SKIP_CACHE(re, &s->gb, 1);
3722
                    
3723
                    level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
3724
 
3725
                    if(SHOW_UBITS(re, &s->gb, 1)==0){
3726
                        fprintf(stderr, "2. marker bit missing in 3. esc\n");
3727
                        return -1;
3728
                    }; LAST_SKIP_CACHE(re, &s->gb, 1);
3729
                    
3730
                    SKIP_COUNTER(re, &s->gb, 1+12+1);
3731
                    
3732
                    if(level*s->qscale>1024 || level*s->qscale<-1024){
3733
                        fprintf(stderr, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
3734
                        return -1;
3735
                    }
3736
#if 1 
3737
                    {
3738
                        const int abs_level= ABS(level);
3739
                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN && !(s->workaround_bugs&FF_BUG_AC_VLC)){
3740
                            const int run1= run - rl->max_run[last][abs_level] - 1;
3741
                            if(abs_level <= rl->max_level[last][run]){
3742
                                fprintf(stderr, "illegal 3. esc, vlc encoding possible\n");
3743
                                return -1;
3744
                            }
3745
                            if(s->error_resilience > FF_ER_COMPLIANT){
3746
                                if(abs_level <= rl->max_level[last][run]*2){
3747
                                    fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");
3748
                                    return -1;
3749
                                }
3750
                                if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
3751
                                    fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");
3752
                                    return -1;
3753
                                }
3754
                            }
3755
                        }
3756
                    }
3757
#endif
3758
                    if (level>0) level= level * qmul + qadd;
3759
                    else         level= level * qmul - qadd;
3760

    
3761
                    i+= run + 1;
3762
                    if(last) i+=192;
3763
                } else {
3764
                    /* second escape */
3765
#if MIN_CACHE_BITS < 20
3766
                    LAST_SKIP_BITS(re, &s->gb, 2);
3767
                    UPDATE_CACHE(re, &s->gb);
3768
#else
3769
                    SKIP_BITS(re, &s->gb, 2);
3770
#endif
3771
                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3772
                    i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
3773
                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3774
                    LAST_SKIP_BITS(re, &s->gb, 1);
3775
                }
3776
            } else {
3777
                /* first escape */
3778
#if MIN_CACHE_BITS < 19
3779
                LAST_SKIP_BITS(re, &s->gb, 1);
3780
                UPDATE_CACHE(re, &s->gb);
3781
#else
3782
                SKIP_BITS(re, &s->gb, 1);
3783
#endif
3784
                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3785
                i+= run;
3786
                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
3787
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3788
                LAST_SKIP_BITS(re, &s->gb, 1);
3789
            }
3790
        } else {
3791
            i+= run;
3792
            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3793
            LAST_SKIP_BITS(re, &s->gb, 1);
3794
        }
3795
        if (i > 62){
3796
            i-= 192;
3797
            if(i&(~63)){
3798
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
3799
                return -1;
3800
            }
3801

    
3802
            block[scan_table[i]] = level;
3803
            break;
3804
        }
3805

    
3806
        block[scan_table[i]] = level;
3807
    }
3808
    CLOSE_READER(re, &s->gb);
3809
  }
3810
 not_coded:
3811
    if (s->mb_intra) {
3812
        mpeg4_pred_ac(s, block, n, dc_pred_dir);
3813
        if (s->ac_pred) {
3814
            i = 63; /* XXX: not optimal */
3815
        }
3816
    }
3817
    s->block_last_index[n] = i;
3818
    return 0;
3819
}
3820

    
3821
/* most is hardcoded. should extend to handle all h263 streams */
3822
int h263_decode_picture_header(MpegEncContext *s)
3823
{
3824
    int format, width, height;
3825

    
3826
    /* picture start code */
3827
    if (get_bits(&s->gb, 22) != 0x20) {
3828
        fprintf(stderr, "Bad picture start code\n");
3829
        return -1;
3830
    }
3831
    /* temporal reference */
3832
    s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
3833

    
3834
    /* PTYPE starts here */    
3835
    if (get_bits1(&s->gb) != 1) {
3836
        /* marker */
3837
        fprintf(stderr, "Bad marker\n");
3838
        return -1;
3839
    }
3840
    if (get_bits1(&s->gb) != 0) {
3841
        fprintf(stderr, "Bad H263 id\n");
3842
        return -1;        /* h263 id */
3843
    }
3844
    skip_bits1(&s->gb);        /* split screen off */
3845
    skip_bits1(&s->gb);        /* camera  off */
3846
    skip_bits1(&s->gb);        /* freeze picture release off */
3847

    
3848
    /* Reset GOB number */
3849
    s->gob_number = 0;
3850
        
3851
    format = get_bits(&s->gb, 3);
3852
    /*
3853
        0    forbidden
3854
        1    sub-QCIF
3855
        10   QCIF
3856
        7        extended PTYPE (PLUSPTYPE)
3857
    */
3858

    
3859
    if (format != 7 && format != 6) {
3860
        s->h263_plus = 0;
3861
        /* H.263v1 */
3862
        width = h263_format[format][0];
3863
        height = h263_format[format][1];
3864
        if (!width)
3865
            return -1;
3866
        
3867
        s->width = width;
3868
        s->height = height;
3869
        s->pict_type = I_TYPE + get_bits1(&s->gb);
3870

    
3871
        s->unrestricted_mv = get_bits1(&s->gb); 
3872
        s->h263_long_vectors = s->unrestricted_mv;
3873

    
3874
        if (get_bits1(&s->gb) != 0) {
3875
            fprintf(stderr, "H263 SAC not supported\n");
3876
            return -1;        /* SAC: off */
3877
        }
3878
        if (get_bits1(&s->gb) != 0) {
3879
            s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3880
        }   
3881
        
3882
        if (get_bits1(&s->gb) != 0) {
3883
            fprintf(stderr, "H263 PB frame not supported\n");
3884
            return -1;        /* not PB frame */
3885
        }
3886
        s->qscale = get_bits(&s->gb, 5);
3887
        skip_bits1(&s->gb);        /* Continuous Presence Multipoint mode: off */
3888
    } else {
3889
        int ufep;
3890
        
3891
        /* H.263v2 */
3892
        s->h263_plus = 1;
3893
        ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
3894

    
3895
        /* ufep other than 0 and 1 are reserved */        
3896
        if (ufep == 1) {
3897
            /* OPPTYPE */       
3898
            format = get_bits(&s->gb, 3);
3899
            dprintf("ufep=1, format: %d\n", format);
3900
            skip_bits(&s->gb,1); /* Custom PCF */
3901
            s->umvplus_dec = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */
3902
            skip_bits1(&s->gb); /* Syntax-based Arithmetic Coding (SAC) */
3903
            if (get_bits1(&s->gb) != 0) {
3904
                s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3905
            }
3906
            if (get_bits1(&s->gb) != 0) { /* Advanced Intra Coding (AIC) */
3907
                s->h263_aic = 1;
3908
            }
3909
            
3910
            skip_bits(&s->gb, 7);
3911
            /* these are the 7 bits: (in order of appearence  */
3912
            /* Deblocking Filter */
3913
            /* Slice Structured */
3914
            /* Reference Picture Selection */
3915
            /* Independent Segment Decoding */
3916
            /* Alternative Inter VLC */
3917
            /* Modified Quantization */
3918
            /* Prevent start code emulation */
3919

    
3920
            skip_bits(&s->gb, 3); /* Reserved */
3921
        } else if (ufep != 0) {
3922
            fprintf(stderr, "Bad UFEP type (%d)\n", ufep);
3923
            return -1;
3924
        }
3925
            
3926
        /* MPPTYPE */
3927
        s->pict_type = get_bits(&s->gb, 3) + I_TYPE;
3928
        dprintf("pict_type: %d\n", s->pict_type);
3929
        if (s->pict_type != I_TYPE &&
3930
            s->pict_type != P_TYPE)
3931
            return -1;
3932
        skip_bits(&s->gb, 2);
3933
        s->no_rounding = get_bits1(&s->gb);
3934
        dprintf("RTYPE: %d\n", s->no_rounding);
3935
        skip_bits(&s->gb, 4);
3936
        
3937
        /* Get the picture dimensions */
3938
        if (ufep) {
3939
            if (format == 6) {
3940
                /* Custom Picture Format (CPFMT) */
3941
                s->aspect_ratio_info = get_bits(&s->gb, 4);
3942
                dprintf("aspect: %d\n", s->aspect_ratio_info);
3943
                /* aspect ratios:
3944
                0 - forbidden
3945
                1 - 1:1
3946
                2 - 12:11 (CIF 4:3)
3947
                3 - 10:11 (525-type 4:3)
3948
                4 - 16:11 (CIF 16:9)
3949
                5 - 40:33 (525-type 16:9)
3950
                6-14 - reserved
3951
                */
3952
                width = (get_bits(&s->gb, 9) + 1) * 4;
3953
                skip_bits1(&s->gb);
3954
                height = get_bits(&s->gb, 9) * 4;
3955
                dprintf("\nH.263+ Custom picture: %dx%d\n",width,height);
3956
                if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
3957
                    /* aspected dimensions */
3958
                    s->aspected_width = get_bits(&s->gb, 8);
3959
                    s->aspected_height = get_bits(&s->gb, 8);
3960
                }else{
3961
                    s->aspected_width = pixel_aspect[s->aspect_ratio_info][0];
3962
                    s->aspected_height= pixel_aspect[s->aspect_ratio_info][1];
3963
                }
3964
            } else {
3965
                width = h263_format[format][0];
3966
                height = h263_format[format][1];
3967
            }
3968
            if ((width == 0) || (height == 0))
3969
                return -1;
3970
            s->width = width;
3971
            s->height = height;
3972
            if (s->umvplus_dec) {
3973
                skip_bits1(&s->gb); /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
3974
            }
3975
        }
3976
            
3977
        s->qscale = get_bits(&s->gb, 5);
3978
    }
3979
    /* PEI */
3980
    while (get_bits1(&s->gb) != 0) {
3981
        skip_bits(&s->gb, 8);
3982
    }
3983
    s->f_code = 1;
3984
    
3985
    if(s->h263_aic){
3986
         s->y_dc_scale_table= 
3987
         s->c_dc_scale_table= h263_aic_dc_scale_table;
3988
    }else{
3989
        s->y_dc_scale_table=
3990
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
3991
    }
3992

    
3993
    return 0;
3994
}
3995

    
3996
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
3997
{
3998
    int i;
3999
    int a= 2<<s->sprite_warping_accuracy;
4000
    int rho= 3-s->sprite_warping_accuracy;
4001
    int r=16/a;
4002
    const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
4003
    int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
4004
    int sprite_ref[4][2];
4005
    int virtual_ref[2][2];
4006
    int w2, h2, w3, h3;
4007
    int alpha=0, beta=0;
4008
    int w= s->width;
4009
    int h= s->height;
4010
    int min_ab;
4011

    
4012
    for(i=0; i<s->num_sprite_warping_points; i++){
4013
        int length;
4014
        int x=0, y=0;
4015

    
4016
        length= get_vlc(&s->gb, &sprite_trajectory);
4017
        if(length){
4018
            x= get_bits(&s->gb, length);
4019

    
4020
            if ((x >> (length - 1)) == 0) /* if MSB not set it is negative*/
4021
                x = - (x ^ ((1 << length) - 1));
4022
        }
4023
        if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
4024
        
4025
        length= get_vlc(&s->gb, &sprite_trajectory);
4026
        if(length){
4027
            y=get_bits(&s->gb, length);
4028

    
4029
            if ((y >> (length - 1)) == 0) /* if MSB not set it is negative*/
4030
                y = - (y ^ ((1 << length) - 1));
4031
        }
4032
        skip_bits1(&s->gb); /* marker bit */
4033
//printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
4034
        d[i][0]= x;
4035
        d[i][1]= y;
4036
    }
4037

    
4038
    while((1<<alpha)<w) alpha++;
4039
    while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
4040
    w2= 1<<alpha;
4041
    h2= 1<<beta;
4042

    
4043
// Note, the 4th point isnt used for GMC
4044
    if(s->divx_version==500 && s->divx_build==413){
4045
        sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
4046
        sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
4047
        sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
4048
        sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
4049
        sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
4050
        sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
4051
    } else {
4052
        sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
4053
        sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
4054
        sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
4055
        sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
4056
        sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
4057
        sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
4058
    }
4059
/*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
4060
    sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
4061
    
4062
// this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
4063
// perhaps it should be reordered to be more readable ...
4064
// the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
4065
// so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
4066
    virtual_ref[0][0]= 16*(vop_ref[0][0] + w2) 
4067
        + 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);
4068
    virtual_ref[0][1]= 16*vop_ref[0][1] 
4069
        + 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);
4070
    virtual_ref[1][0]= 16*vop_ref[0][0] 
4071
        + 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);
4072
    virtual_ref[1][1]= 16*(vop_ref[0][1] + h2) 
4073
        + 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);
4074
        
4075
    switch(s->num_sprite_warping_points)
4076
    {
4077
        case 0:
4078
            s->sprite_offset[0][0]= 0;
4079
            s->sprite_offset[0][1]= 0;
4080
            s->sprite_offset[1][0]= 0;
4081
            s->sprite_offset[1][1]= 0;
4082
            s->sprite_delta[0][0]= a;
4083
            s->sprite_delta[0][1]= 0;
4084
            s->sprite_delta[1][0]= 0;
4085
            s->sprite_delta[1][1]= a;
4086
            s->sprite_shift[0]= 0;
4087
            s->sprite_shift[1]= 0;
4088
            break;
4089
        case 1: //GMC only
4090
            s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
4091
            s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
4092
            s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
4093
            s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
4094
            s->sprite_delta[0][0]= a;
4095
            s->sprite_delta[0][1]= 0;
4096
            s->sprite_delta[1][0]= 0;
4097
            s->sprite_delta[1][1]= a;
4098
            s->sprite_shift[0]= 0;
4099
            s->sprite_shift[1]= 0;
4100
            break;
4101
        case 2:
4102
            s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
4103
                                                  + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
4104
                                                  + ( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1])
4105
                                                  + (1<<(alpha+rho-1));
4106
            s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
4107
                                                  + (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
4108
                                                  + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1])
4109
                                                  + (1<<(alpha+rho-1));
4110
            s->sprite_offset[1][0]= ( (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)
4111
                                     +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)
4112
                                     +2*w2*r*sprite_ref[0][0] 
4113
                                     - 16*w2 
4114
                                     + (1<<(alpha+rho+1)));
4115
            s->sprite_offset[1][1]= ( (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1) 
4116
                                     +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)
4117
                                     +2*w2*r*sprite_ref[0][1] 
4118
                                     - 16*w2
4119
                                     + (1<<(alpha+rho+1)));
4120
            s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
4121
            s->sprite_delta[0][1]=   (+r*sprite_ref[0][1] - virtual_ref[0][1]);
4122
            s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);
4123
            s->sprite_delta[1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
4124
            
4125
            s->sprite_shift[0]= alpha+rho;
4126
            s->sprite_shift[1]= alpha+rho+2;
4127
            break;
4128
        case 3:
4129
            min_ab= FFMIN(alpha, beta);
4130
            w3= w2>>min_ab;
4131
            h3= h2>>min_ab;
4132
            s->sprite_offset[0][0]=  (sprite_ref[0][0]<<(alpha+beta+rho-min_ab))
4133
                                   + (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-vop_ref[0][0])
4134
                                   + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-vop_ref[0][1])
4135
                                   + (1<<(alpha+beta+rho-min_ab-1));
4136
            s->sprite_offset[0][1]=  (sprite_ref[0][1]<<(alpha+beta+rho-min_ab))
4137
                                   + (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-vop_ref[0][0])
4138
                                   + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-vop_ref[0][1])
4139
                                   + (1<<(alpha+beta+rho-min_ab-1));
4140
            s->sprite_offset[1][0]=  (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-2*vop_ref[0][0] + 1)
4141
                                   + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-2*vop_ref[0][1] + 1)
4142
                                   + 2*w2*h3*r*sprite_ref[0][0]
4143
                                   - 16*w2*h3
4144
                                   + (1<<(alpha+beta+rho-min_ab+1));
4145
            s->sprite_offset[1][1]=  (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-2*vop_ref[0][0] + 1)
4146
                                   + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-2*vop_ref[0][1] + 1)
4147
                                   + 2*w2*h3*r*sprite_ref[0][1]
4148
                                   - 16*w2*h3
4149
                                   + (1<<(alpha+beta+rho-min_ab+1));
4150
            s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3;
4151
            s->sprite_delta[0][1]=   (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3;
4152
            s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3;
4153
            s->sprite_delta[1][1]=   (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3;
4154
                                   
4155
            s->sprite_shift[0]= alpha + beta + rho - min_ab;
4156
            s->sprite_shift[1]= alpha + beta + rho - min_ab + 2;
4157
            break;
4158
    }
4159
    /* try to simplify the situation */ 
4160
    if(   s->sprite_delta[0][0] == a<<s->sprite_shift[0]
4161
       && s->sprite_delta[0][1] == 0
4162
       && s->sprite_delta[1][0] == 0
4163
       && s->sprite_delta[1][1] == a<<s->sprite_shift[0])
4164
    {
4165
        s->sprite_offset[0][0]>>=s->sprite_shift[0];
4166
        s->sprite_offset[0][1]>>=s->sprite_shift[0];
4167
        s->sprite_offset[1][0]>>=s->sprite_shift[1];
4168
        s->sprite_offset[1][1]>>=s->sprite_shift[1];
4169
        s->sprite_delta[0][0]= a;
4170
        s->sprite_delta[0][1]= 0;
4171
        s->sprite_delta[1][0]= 0;
4172
        s->sprite_delta[1][1]= a;
4173
        s->sprite_shift[0]= 0;
4174
        s->sprite_shift[1]= 0;
4175
        s->real_sprite_warping_points=1;
4176
    }
4177
    else{
4178
        int shift_y= 16 - s->sprite_shift[0];
4179
        int shift_c= 16 - s->sprite_shift[1];
4180
//printf("shifts %d %d\n", shift_y, shift_c);
4181
        for(i=0; i<2; i++){
4182
            s->sprite_offset[0][i]<<= shift_y;
4183
            s->sprite_offset[1][i]<<= shift_c;
4184
            s->sprite_delta[0][i]<<= shift_y;
4185
            s->sprite_delta[1][i]<<= shift_y;
4186
            s->sprite_shift[i]= 16;
4187
        }
4188
        s->real_sprite_warping_points= s->num_sprite_warping_points;
4189
    }
4190
#if 0
4191
printf("vop:%d:%d %d:%d %d:%d, sprite:%d:%d %d:%d %d:%d, virtual: %d:%d %d:%d\n",
4192
    vop_ref[0][0], vop_ref[0][1],
4193
    vop_ref[1][0], vop_ref[1][1],
4194
    vop_ref[2][0], vop_ref[2][1],
4195
    sprite_ref[0][0], sprite_ref[0][1], 
4196
    sprite_ref[1][0], sprite_ref[1][1], 
4197
    sprite_ref[2][0], sprite_ref[2][1], 
4198
    virtual_ref[0][0], virtual_ref[0][1], 
4199
    virtual_ref[1][0], virtual_ref[1][1]
4200
    );
4201
    
4202
printf("offset: %d:%d , delta: %d %d %d %d, shift %d\n",
4203
    s->sprite_offset[0][0], s->sprite_offset[0][1],
4204
    s->sprite_delta[0][0], s->sprite_delta[0][1],
4205
    s->sprite_delta[1][0], s->sprite_delta[1][1],
4206
    s->sprite_shift[0]
4207
    );
4208
#endif
4209
}
4210

    
4211
static int mpeg4_decode_gop_header(MpegEncContext * s, GetBitContext *gb){
4212
    int hours, minutes, seconds;
4213

    
4214
    hours= get_bits(gb, 5);
4215
    minutes= get_bits(gb, 6);
4216
    skip_bits1(gb);
4217
    seconds= get_bits(gb, 6);
4218

    
4219
    s->time_base= seconds + 60*(minutes + 60*hours);
4220

    
4221
    skip_bits1(gb);
4222
    skip_bits1(gb);
4223
    
4224
    return 0;
4225
}
4226

    
4227
static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){
4228
    int width, height, vo_ver_id;
4229

    
4230
    /* vol header */
4231
    skip_bits(gb, 1); /* random access */
4232
    s->vo_type= get_bits(gb, 8);
4233
    if (get_bits1(gb) != 0) { /* is_ol_id */
4234
        vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
4235
        skip_bits(gb, 3); /* vo_priority */
4236
    } else {
4237
        vo_ver_id = 1;
4238
    }
4239
//printf("vo type:%d\n",s->vo_type);
4240
    s->aspect_ratio_info= get_bits(gb, 4);
4241
    if(s->aspect_ratio_info == FF_ASPECT_EXTENDED){            
4242
        s->aspected_width = get_bits(gb, 8); // par_width
4243
        s->aspected_height = get_bits(gb, 8); // par_height
4244
    }else{
4245
        s->aspected_width = pixel_aspect[s->aspect_ratio_info][0];
4246
        s->aspected_height= pixel_aspect[s->aspect_ratio_info][1];
4247
    }
4248

    
4249
    if ((s->vol_control_parameters=get_bits1(gb))) { /* vol control parameter */
4250
        int chroma_format= get_bits(gb, 2);
4251
        if(chroma_format!=1){
4252
            printf("illegal chroma format\n");
4253
        }
4254
        s->low_delay= get_bits1(gb);
4255
        if(get_bits1(gb)){ /* vbv parameters */
4256
            get_bits(gb, 15);        /* first_half_bitrate */
4257
            skip_bits1(gb);        /* marker */
4258
            get_bits(gb, 15);        /* latter_half_bitrate */
4259
            skip_bits1(gb);        /* marker */
4260
            get_bits(gb, 15);        /* first_half_vbv_buffer_size */
4261
            skip_bits1(gb);        /* marker */
4262
            get_bits(gb, 3);        /* latter_half_vbv_buffer_size */
4263
            get_bits(gb, 11);        /* first_half_vbv_occupancy */
4264
            skip_bits1(gb);        /* marker */
4265
            get_bits(gb, 15);        /* latter_half_vbv_occupancy */
4266
            skip_bits1(gb);        /* marker */               
4267
        }
4268
    }else{
4269
        // set low delay flag only once so the smart? low delay detection wont be overriden
4270
        if(s->picture_number==0)
4271
            s->low_delay=0;
4272
    }
4273

    
4274
    s->shape = get_bits(gb, 2); /* vol shape */
4275
    if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");
4276
    if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
4277
        printf("Gray shape not supported\n");
4278
        skip_bits(gb, 4);  //video_object_layer_shape_extension
4279
    }
4280

    
4281
    skip_bits1(gb);   /* marker */
4282
    
4283
    s->time_increment_resolution = get_bits(gb, 16);
4284
    
4285
    s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
4286
    if (s->time_increment_bits < 1)
4287
        s->time_increment_bits = 1;
4288
    skip_bits1(gb);   /* marker */
4289

    
4290
    if (get_bits1(gb) != 0) {   /* fixed_vop_rate  */
4291
        skip_bits(gb, s->time_increment_bits);
4292
    }
4293

    
4294
    if (s->shape != BIN_ONLY_SHAPE) {
4295
        if (s->shape == RECT_SHAPE) {
4296
            skip_bits1(gb);   /* marker */
4297
            width = get_bits(gb, 13);
4298
            skip_bits1(gb);   /* marker */
4299
            height = get_bits(gb, 13);
4300
            skip_bits1(gb);   /* marker */
4301
            if(width && height){ /* they should be non zero but who knows ... */
4302
                s->width = width;
4303
                s->height = height;
4304
//                printf("width/height: %d %d\n", width, height);
4305
            }
4306
        }
4307
        
4308
        s->progressive_sequence= get_bits1(gb)^1;
4309
        if(!get_bits1(gb)) printf("OBMC not supported (very likely buggy encoder)\n");   /* OBMC Disable */
4310
        if (vo_ver_id == 1) {
4311
            s->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
4312
        } else {
4313
            s->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
4314
        }
4315
        if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");
4316
        if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
4317
            if(s->vol_sprite_usage==STATIC_SPRITE){
4318
                s->sprite_width = get_bits(gb, 13);
4319
                skip_bits1(gb); /* marker */
4320
                s->sprite_height= get_bits(gb, 13);
4321
                skip_bits1(gb); /* marker */
4322
                s->sprite_left  = get_bits(gb, 13);
4323
                skip_bits1(gb); /* marker */
4324
                s->sprite_top   = get_bits(gb, 13);
4325
                skip_bits1(gb); /* marker */
4326
            }
4327
            s->num_sprite_warping_points= get_bits(gb, 6);
4328
            s->sprite_warping_accuracy = get_bits(gb, 2);
4329
            s->sprite_brightness_change= get_bits1(gb);
4330
            if(s->vol_sprite_usage==STATIC_SPRITE)
4331
                s->low_latency_sprite= get_bits1(gb);            
4332
        }
4333
        // FIXME sadct disable bit if verid!=1 && shape not rect
4334
        
4335
        if (get_bits1(gb) == 1) {   /* not_8_bit */
4336
            s->quant_precision = get_bits(gb, 4); /* quant_precision */
4337
            if(get_bits(gb, 4)!=8) printf("N-bit not supported\n"); /* bits_per_pixel */
4338
            if(s->quant_precision!=5) printf("quant precission %d\n", s->quant_precision);
4339
        } else {
4340
            s->quant_precision = 5;
4341
        }
4342
        
4343
        // FIXME a bunch of grayscale shape things
4344

    
4345
        if((s->mpeg_quant=get_bits1(gb))){ /* vol_quant_type */
4346
            int i, j, v;
4347
            
4348
            /* load default matrixes */
4349
            for(i=0; i<64; i++){
4350
                int j= s->idct_permutation[i];
4351
                v= ff_mpeg4_default_intra_matrix[i];
4352
                s->intra_matrix[j]= v;
4353
                s->chroma_intra_matrix[j]= v;
4354
                
4355
                v= ff_mpeg4_default_non_intra_matrix[i];
4356
                s->inter_matrix[j]= v;
4357
                s->chroma_inter_matrix[j]= v;
4358
            }
4359

    
4360
            /* load custom intra matrix */
4361
            if(get_bits1(gb)){
4362
                int last=0;
4363
                for(i=0; i<64; i++){
4364
                    v= get_bits(gb, 8);
4365
                    if(v==0) break;
4366
                    
4367
                    last= v;
4368
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4369
                    s->intra_matrix[j]= v;
4370
                    s->chroma_intra_matrix[j]= v;
4371
                }
4372

    
4373
                /* replicate last value */
4374
                for(; i<64; i++){
4375
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4376
                    s->intra_matrix[j]= v;
4377
                    s->chroma_intra_matrix[j]= v;
4378
                }
4379
            }
4380

    
4381
            /* load custom non intra matrix */
4382
            if(get_bits1(gb)){
4383
                int last=0;
4384
                for(i=0; i<64; i++){
4385
                    v= get_bits(gb, 8);
4386
                    if(v==0) break;
4387

    
4388
                    last= v;
4389
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4390
                    s->inter_matrix[j]= v;
4391
                    s->chroma_inter_matrix[j]= v;
4392
                }
4393

    
4394
                /* replicate last value */
4395
                for(; i<64; i++){
4396
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4397
                    s->inter_matrix[j]= last;
4398
                    s->chroma_inter_matrix[j]= last;
4399
                }
4400
            }
4401

    
4402
            // FIXME a bunch of grayscale shape things
4403
        }
4404

    
4405
        if(vo_ver_id != 1)
4406
             s->quarter_sample= get_bits1(gb);
4407
        else s->quarter_sample=0;
4408

    
4409
        if(!get_bits1(gb)) printf("Complexity estimation not supported\n");
4410

    
4411
        s->resync_marker= !get_bits1(gb); /* resync_marker_disabled */
4412

    
4413
        s->data_partitioning= get_bits1(gb);
4414
        if(s->data_partitioning){
4415
            s->rvlc= get_bits1(gb);
4416
            if(s->rvlc){
4417
                printf("reversible vlc not supported\n");
4418
            }
4419
        }
4420
        
4421
        if(vo_ver_id != 1) {
4422
            s->new_pred= get_bits1(gb);
4423
            if(s->new_pred){
4424
                printf("new pred not supported\n");
4425
                skip_bits(gb, 2); /* requested upstream message type */
4426
                skip_bits1(gb); /* newpred segment type */
4427
            }
4428
            s->reduced_res_vop= get_bits1(gb);
4429
            if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");
4430
        }
4431
        else{
4432
            s->new_pred=0;
4433
            s->reduced_res_vop= 0;
4434
        }
4435

    
4436
        s->scalability= get_bits1(gb);
4437

    
4438
        if (s->scalability) {
4439
            GetBitContext bak= *gb;
4440
            int ref_layer_id;
4441
            int ref_layer_sampling_dir;
4442
            int h_sampling_factor_n;
4443
            int h_sampling_factor_m;
4444
            int v_sampling_factor_n;
4445
            int v_sampling_factor_m;
4446
            
4447
            s->hierachy_type= get_bits1(gb);
4448
            ref_layer_id= get_bits(gb, 4);
4449
            ref_layer_sampling_dir= get_bits1(gb);
4450
            h_sampling_factor_n= get_bits(gb, 5);
4451
            h_sampling_factor_m= get_bits(gb, 5);
4452
            v_sampling_factor_n= get_bits(gb, 5);
4453
            v_sampling_factor_m= get_bits(gb, 5);
4454
            s->enhancement_type= get_bits1(gb);
4455
            
4456
            if(   h_sampling_factor_n==0 || h_sampling_factor_m==0 
4457
               || v_sampling_factor_n==0 || v_sampling_factor_m==0){
4458
               
4459
//                fprintf(stderr, "illegal scalability header (VERY broken encoder), trying to workaround\n");
4460
                s->scalability=0;
4461
               
4462
                *gb= bak;
4463
            }else
4464
                printf("scalability not supported\n");
4465
            
4466
            // bin shape stuff FIXME
4467
        }
4468
    }
4469
    return 0;
4470
}
4471

    
4472
static int decode_user_data(MpegEncContext *s, GetBitContext *gb){
4473
    char buf[256];
4474
    int i;
4475
    int e;
4476
    int ver, build, ver2, ver3;
4477

    
4478
    buf[0]= show_bits(gb, 8);
4479
    for(i=1; i<256; i++){
4480
        buf[i]= show_bits(gb, 16)&0xFF;
4481
        if(buf[i]==0) break;
4482
        skip_bits(gb, 8);
4483
    }
4484
    buf[255]=0;
4485
    
4486
    /* divx detection */
4487
    e=sscanf(buf, "DivX%dBuild%d", &ver, &build);
4488
    if(e!=2)
4489
        e=sscanf(buf, "DivX%db%d", &ver, &build);
4490
    if(e==2){
4491
        s->divx_version= ver;
4492
        s->divx_build= build;
4493
        if(s->picture_number==0){
4494
            printf("This file was encoded with DivX%d Build%d\n", ver, build);
4495
        }
4496
    }
4497
    
4498
    /* ffmpeg detection */
4499
    e=sscanf(buf, "FFmpeg%d.%d.%db%d", &ver, &ver2, &ver3, &build);
4500
    if(e!=4)
4501
        e=sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); 
4502
    if(e!=4){
4503
        if(strcmp(buf, "ffmpeg")==0){
4504
            s->ffmpeg_version= 0x000406;
4505
            s->lavc_build= 4600;
4506
        }
4507
    }
4508
    if(e==4){
4509
        s->ffmpeg_version= ver*256*256 + ver2*256 + ver3;
4510
        s->lavc_build= build;
4511
        if(s->picture_number==0)
4512
            printf("This file was encoded with libavcodec build %d\n", build);
4513
    }
4514
    
4515
    /* xvid detection */
4516
    e=sscanf(buf, "XviD%d", &build);
4517
    if(e==1){
4518
        s->xvid_build= build;
4519
        if(s->picture_number==0)
4520
            printf("This file was encoded with XviD build %d\n", build);
4521
    }
4522

    
4523
//printf("User Data: %s\n", buf);
4524
    return 0;
4525
}
4526

    
4527
static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){
4528
    int time_incr, time_increment;
4529

    
4530
    s->pict_type = get_bits(gb, 2) + I_TYPE;        /* pict type: I = 0 , P = 1 */
4531
    if(s->pict_type==B_TYPE && s->low_delay && s->vol_control_parameters==0){
4532
        printf("low_delay flag set, but shouldnt, clearing it\n");
4533
        s->low_delay=0;
4534
    }
4535
 
4536
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
4537
    if(s->partitioned_frame)
4538
        s->decode_mb= mpeg4_decode_partitioned_mb;
4539
    else
4540
        s->decode_mb= ff_h263_decode_mb;
4541

    
4542
    if(s->time_increment_resolution==0){
4543
        s->time_increment_resolution=1;
4544
//        fprintf(stderr, "time_increment_resolution is illegal\n");
4545
    }
4546
    time_incr=0;
4547
    while (get_bits1(gb) != 0) 
4548
        time_incr++;
4549

    
4550
    check_marker(gb, "before time_increment");
4551
    time_increment= get_bits(gb, s->time_increment_bits);
4552
//printf(" type:%d modulo_time_base:%d increment:%d\n", s->pict_type, time_incr, time_increment);
4553
    if(s->pict_type!=B_TYPE){
4554
        s->last_time_base= s->time_base;
4555
        s->time_base+= time_incr;
4556
        s->time= s->time_base*s->time_increment_resolution + time_increment;
4557
        if(s->workaround_bugs&FF_BUG_UMP4){
4558
            if(s->time < s->last_non_b_time){
4559
//                fprintf(stderr, "header is not mpeg4 compatible, broken encoder, trying to workaround\n");
4560
                s->time_base++;
4561
                s->time+= s->time_increment_resolution;
4562
            }
4563
        }
4564
        s->pp_time= s->time - s->last_non_b_time;
4565
        s->last_non_b_time= s->time;
4566
    }else{
4567
        s->time= (s->last_time_base + time_incr)*s->time_increment_resolution + time_increment;
4568
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
4569
        if(s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0){
4570
//            printf("messed up order, seeking?, skiping current b frame\n");
4571
            return FRAME_SKIPED;
4572
        }
4573
        
4574
        if(s->t_frame==0) s->t_frame= s->time - s->last_time_base;
4575
        if(s->t_frame==0) s->t_frame=1; // 1/0 protection
4576
//printf("%Ld %Ld %d %d\n", s->last_non_b_time, s->time, s->pp_time, s->t_frame); fflush(stdout);
4577
        s->pp_field_time= (  ROUNDED_DIV(s->last_non_b_time, s->t_frame) 
4578
                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
4579
        s->pb_field_time= (  ROUNDED_DIV(s->time, s->t_frame) 
4580
                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
4581
    }
4582
    
4583
    s->current_picture.pts= s->time*1000LL*1000LL / s->time_increment_resolution;
4584
    if(s->avctx->debug&FF_DEBUG_PTS)
4585
        printf("MPEG4 PTS: %f\n", s->current_picture.pts/(1000.0*1000.0));
4586
    
4587
    if(check_marker(gb, "before vop_coded")==0 && s->picture_number==0){
4588
        printf("hmm, seems the headers arnt complete, trying to guess time_increment_bits\n");
4589
        for(s->time_increment_bits++ ;s->time_increment_bits<16; s->time_increment_bits++){
4590
            if(get_bits1(gb)) break;
4591
        }
4592
        printf("my guess is %d bits ;)\n",s->time_increment_bits);
4593
    }
4594
    /* vop coded */
4595
    if (get_bits1(gb) != 1){
4596
        printf("vop not coded\n");
4597
        return FRAME_SKIPED;
4598
    }
4599
//printf("time %d %d %d || %Ld %Ld %Ld\n", s->time_increment_bits, s->time_increment_resolution, s->time_base,
4600
//s->time, s->last_non_b_time, s->last_non_b_time - s->pp_time);  
4601
    if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == P_TYPE
4602
                          || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {
4603
        /* rounding type for motion estimation */
4604
        s->no_rounding = get_bits1(gb);
4605
    } else {
4606
        s->no_rounding = 0;
4607
    }
4608
//FIXME reduced res stuff
4609

    
4610
     if (s->shape != RECT_SHAPE) {
4611
         if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {
4612
             int width, height, hor_spat_ref, ver_spat_ref;
4613
 
4614
             width = get_bits(gb, 13);
4615
             skip_bits1(gb);   /* marker */
4616
             height = get_bits(gb, 13);
4617
             skip_bits1(gb);   /* marker */
4618
             hor_spat_ref = get_bits(gb, 13); /* hor_spat_ref */
4619
             skip_bits1(gb);   /* marker */
4620
             ver_spat_ref = get_bits(gb, 13); /* ver_spat_ref */
4621
         }
4622
         skip_bits1(gb); /* change_CR_disable */
4623
 
4624
         if (get_bits1(gb) != 0) {
4625
             skip_bits(gb, 8); /* constant_alpha_value */
4626
         }
4627
     }
4628
//FIXME complexity estimation stuff
4629
     
4630
     if (s->shape != BIN_ONLY_SHAPE) {
4631
         int t;
4632
         t=get_bits(gb, 3); /* intra dc VLC threshold */
4633
//printf("threshold %d\n", t);
4634
         if(!s->progressive_sequence){
4635
             s->top_field_first= get_bits1(gb);
4636
             s->alternate_scan= get_bits1(gb);
4637
         }else
4638
             s->alternate_scan= 0;
4639
     }
4640

    
4641
     if(s->alternate_scan){
4642
         ff_init_scantable(s, &s->inter_scantable  , ff_alternate_vertical_scan);
4643
         ff_init_scantable(s, &s->intra_scantable  , ff_alternate_vertical_scan);
4644
         ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_vertical_scan);
4645
         ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
4646
     } else{
4647
         ff_init_scantable(s, &s->inter_scantable  , ff_zigzag_direct);
4648
         ff_init_scantable(s, &s->intra_scantable  , ff_zigzag_direct);
4649
         ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_horizontal_scan);
4650
         ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
4651
     }
4652
 
4653
     if(s->pict_type == S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){
4654
         mpeg4_decode_sprite_trajectory(s);
4655
         if(s->sprite_brightness_change) printf("sprite_brightness_change not supported\n");
4656
         if(s->vol_sprite_usage==STATIC_SPRITE) printf("static sprite not supported\n");
4657
     }
4658

    
4659
     if (s->shape != BIN_ONLY_SHAPE) {
4660
         s->qscale = get_bits(gb, s->quant_precision);
4661
         if(s->qscale==0){
4662
             printf("Error, header damaged or not MPEG4 header (qscale=0)\n");
4663
             return -1; // makes no sense to continue, as there is nothing left from the image then
4664
         }
4665
  
4666
         if (s->pict_type != I_TYPE) {
4667
             s->f_code = get_bits(gb, 3);        /* fcode_for */
4668
             if(s->f_code==0){
4669
                 printf("Error, header damaged or not MPEG4 header (f_code=0)\n");
4670
                 return -1; // makes no sense to continue, as the MV decoding will break very quickly
4671
             }
4672
         }else
4673
             s->f_code=1;
4674
     
4675
         if (s->pict_type == B_TYPE) {
4676
             s->b_code = get_bits(gb, 3);
4677
         }else
4678
             s->b_code=1;
4679

    
4680
         if(s->avctx->debug&FF_DEBUG_PICT_INFO){
4681
             printf("qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d\n", 
4682
                 s->qscale, s->f_code, s->b_code, 
4683
                 s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")), 
4684
                 gb->size,s->progressive_sequence, s->alternate_scan, s->top_field_first, 
4685
                 s->quarter_sample ? "q" : "h", s->data_partitioning, s->resync_marker, s->num_sprite_warping_points,
4686
                 s->sprite_warping_accuracy); 
4687
         }
4688

    
4689
         if(!s->scalability){
4690
             if (s->shape!=RECT_SHAPE && s->pict_type!=I_TYPE) {
4691
                 skip_bits1(gb); // vop shape coding type
4692
             }
4693
         }else{