Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h263.c @ c40c3482

History | View | Annotate | Download (162 KB)

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

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

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

    
43
#if 1
44
#define PRINT_MB_TYPE(a) {}
45
#else
46
#define PRINT_MB_TYPE(a) printf(a)
47
#endif
48

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

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

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

    
81
extern UINT32 inverse[256];
82

    
83
static UINT8 uni_DCtab_lum_len[512];
84
static UINT8 uni_DCtab_chrom_len[512];
85
static UINT16 uni_DCtab_lum_bits[512];
86
static UINT16 uni_DCtab_chrom_bits[512];
87

    
88
#ifdef CONFIG_ENCODERS
89
static UINT16 (*mv_penalty)[MAX_MV*2+1]= NULL;
90
static UINT8 fcode_tab[MAX_MV*2+1];
91
static UINT8 umv_fcode_tab[MAX_MV*2+1];
92

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

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

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

    
112

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

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

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

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

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

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

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

    
157
    align_put_bits(&s->pb);
158

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

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

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

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

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

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

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

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

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

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

    
336
    return score0 > score1 ? 1 : 0;    
337
}
338

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

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

    
363
    ff_clean_h263_qscales(s);
364
    
365
    for(i=1; i<s->mb_num; i++){
366
        if(qscale_table[i] != qscale_table[i-1] && (s->mb_type[i]&MB_TYPE_INTER4V)){
367
            s->mb_type[i]&= ~MB_TYPE_INTER4V;
368
            s->mb_type[i]|= MB_TYPE_INTER;
369
        }
370
    }
371

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

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

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

    
476
        if(s->pict_type==B_TYPE){
477
            static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
478
            int mb_type=  mb_type_table[s->mv_dir];
479
            
480
            if(s->mb_x==0){
481
                s->last_mv[0][0][0]= 
482
                s->last_mv[0][0][1]= 
483
                s->last_mv[1][0][0]= 
484
                s->last_mv[1][0][1]= 0;
485
            }
486
            
487
            assert(s->dquant>=-2 && s->dquant<=2);
488
            assert((s->dquant&1)==0);
489
            assert(mb_type>=0);
490

    
491
            /* nothing to do if this MB was skiped in the next P Frame */
492
            if(s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x]){ //FIXME avoid DCT & ...
493
                s->skip_count++;
494
                s->mv[0][0][0]= 
495
                s->mv[0][0][1]= 
496
                s->mv[1][0][0]= 
497
                s->mv[1][0][1]= 0;
498
                s->mv_dir= MV_DIR_FORWARD; //doesnt matter
499
                s->qscale -= s->dquant;
500
//                s->mb_skiped=1;
501

    
502
                return;
503
            }
504
            
505
            if ((cbp | motion_x | motion_y | mb_type) ==0) {
506
                /* direct MB with MV={0,0} */
507
                assert(s->dquant==0);
508
                
509
                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
510

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

    
539
            if(interleaved_stats){
540
                bits= get_bit_count(&s->pb);
541
                s->misc_bits+= bits - s->last_bits;
542
                s->last_bits=bits;
543
            }
544

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

    
584
            if(interleaved_stats){
585
                bits= get_bit_count(&s->pb);
586
                s->mv_bits+= bits - s->last_bits;
587
                s->last_bits=bits;
588
            }
589

    
590
            /* encode each block */
591
            for (i = 0; i < 6; i++) {
592
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, &s->pb);
593
            }
594

    
595
            if(interleaved_stats){
596
                bits= get_bit_count(&s->pb);
597
                s->p_tex_bits+= bits - s->last_bits;
598
                s->last_bits=bits;
599
            }
600
        }else{ /* s->pict_type==B_TYPE */
601
            if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
602
                /* check if the B frames can skip it too, as we must skip it if we skip here 
603
                   why didnt they just compress the skip-mb bits instead of reusing them ?! */
604
                if(s->max_b_frames>0){
605
                    int i;
606
                    int x,y, offset;
607
                    uint8_t *p_pic;
608

    
609
                    x= s->mb_x*16;
610
                    y= s->mb_y*16;
611
                    if(x+16 > s->width)  x= s->width-16;
612
                    if(y+16 > s->height) y= s->height-16;
613

    
614
                    offset= x + y*s->linesize;
615
                    p_pic= s->new_picture.data[0] + offset;
616
                    
617
                    s->mb_skiped=1;
618
                    for(i=0; i<s->max_b_frames; i++){
619
                        uint8_t *b_pic;
620
                        int diff;
621
                        Picture *pic= s->reordered_input_picture[i+1];
622

    
623
                        if(pic==NULL || pic->pict_type!=B_TYPE) break;
624

    
625
                        b_pic= pic->data[0] + offset + 16; //FIXME +16
626
                        diff= s->dsp.pix_abs16x16(p_pic, b_pic, s->linesize);
627
                        if(diff>s->qscale*70){ //FIXME check that 70 is optimal
628
                            s->mb_skiped=0;
629
                            break;
630
                        }
631
                    }
632
                }else
633
                    s->mb_skiped=1; 
634

    
635
                if(s->mb_skiped==1){
636
                    /* skip macroblock */
637
                    put_bits(&s->pb, 1, 1);
638

    
639
                    if(interleaved_stats){
640
                        s->misc_bits++;
641
                        s->last_bits++;
642
                    }
643
                    s->skip_count++;
644
                    return;
645
                }
646
            }
647

    
648
            put_bits(&s->pb, 1, 0);        /* mb coded */
649
            if(s->mv_type==MV_TYPE_16X16){
650
                cbpc = cbp & 3;
651
                if(s->dquant) cbpc+= 8;
652
                put_bits(&s->pb,
653
                        inter_MCBPC_bits[cbpc],
654
                        inter_MCBPC_code[cbpc]);
655

    
656
                cbpy = cbp >> 2;
657
                cbpy ^= 0xf;
658
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
659
                if(s->dquant)
660
                    put_bits(pb2, 2, dquant_code[s->dquant+2]);
661

    
662
                if(!s->progressive_sequence){
663
                    if(cbp)
664
                        put_bits(pb2, 1, s->interlaced_dct);
665
                    put_bits(pb2, 1, 0); // no interlaced ME yet
666
                }
667
                    
668
                if(interleaved_stats){
669
                    bits= get_bit_count(&s->pb);
670
                    s->misc_bits+= bits - s->last_bits;
671
                    s->last_bits=bits;
672
                }
673

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

    
688
                if(!s->progressive_sequence){
689
                    if(cbp)
690
                        put_bits(pb2, 1, s->interlaced_dct);
691
                }
692
    
693
                if(interleaved_stats){
694
                    bits= get_bit_count(&s->pb);
695
                    s->misc_bits+= bits - s->last_bits;
696
                    s->last_bits=bits;
697
                }
698

    
699
                for(i=0; i<4; i++){
700
                    /* motion vectors: 8x8 mode*/
701
                    h263_pred_motion(s, i, &pred_x, &pred_y);
702

    
703
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x, s->f_code);
704
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y, s->f_code);
705
                }
706
            }
707

    
708
            if(interleaved_stats){ 
709
                bits= get_bit_count(&s->pb);
710
                s->mv_bits+= bits - s->last_bits;
711
                s->last_bits=bits;
712
            }
713

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

    
719
            if(interleaved_stats){
720
                bits= get_bit_count(&s->pb);
721
                s->p_tex_bits+= bits - s->last_bits;
722
                s->last_bits=bits;
723
            }
724
            s->f_count++;
725
        }
726
    } else {
727
        int cbp;
728
        int dc_diff[6];   //dc values with the dc prediction subtracted 
729
        int dir[6];  //prediction direction
730
        int zigzag_last_index[6];
731
        UINT8 *scan_table[6];
732

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

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

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

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

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

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

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

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

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

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

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

    
808
        if(interleaved_stats){
809
            bits= get_bit_count(&s->pb);
810
            s->i_tex_bits+= bits - s->last_bits;
811
            s->last_bits=bits;
812
        }
813
        s->i_count++;
814

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

    
821
                ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
822

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

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

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

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

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

    
967
static int h263_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr)
968
{
969
    int x, y, wrap, a, c, pred_dc, scale;
970
    INT16 *dc_val, *ac_val;
971

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

    
1012

    
1013
void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1014
{
1015
    int x, y, wrap, a, c, pred_dc, scale, i;
1016
    INT16 *dc_val, *ac_val, *ac_val1;
1017

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

    
1097
INT16 *h263_pred_motion(MpegEncContext * s, int block, 
1098
                        int *px, int *py)
1099
{
1100
    int xy, wrap;
1101
    INT16 *A, *B, *C, *mot_val;
1102
    static const int off[4]= {2, 1, 1, -1};
1103

    
1104
    wrap = s->block_wrap[0];
1105
    xy = s->block_index[block];
1106

    
1107
    mot_val = s->motion_val[xy];
1108

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

    
1157
#ifdef CONFIG_ENCODERS
1158
static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
1159
{
1160
    int range, l, bit_size, sign, code, bits;
1161

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

    
1185
        assert(val>=-l && val<l);
1186

    
1187
        if (val >= 0) {
1188
            sign = 0;
1189
        } else {
1190
            val = -val;
1191
            sign = 1;
1192
        }
1193
#endif
1194
        val--;
1195
        code = (val >> bit_size) + 1;
1196
        bits = val & (range - 1);
1197

    
1198
        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
1199
        if (bit_size > 0) {
1200
            put_bits(&s->pb, bit_size, bits);
1201
        }
1202
    }
1203

    
1204
}
1205

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

    
1245
static void init_mv_penalty_and_fcode(MpegEncContext *s)
1246
{
1247
    int f_code;
1248
    int mv;
1249
    
1250
    if(mv_penalty==NULL)
1251
        mv_penalty= av_mallocz( sizeof(UINT16)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1252
    
1253
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
1254
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1255
            int len;
1256

    
1257
            if(mv==0) len= mvtab[0][1];
1258
            else{
1259
                int val, bit_size, range, code;
1260

    
1261
                bit_size = s->f_code - 1;
1262
                range = 1 << bit_size;
1263

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

    
1276
            mv_penalty[f_code][mv+MAX_MV]= len;
1277
        }
1278
    }
1279

    
1280
    for(f_code=MAX_FCODE; f_code>0; f_code--){
1281
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1282
            fcode_tab[mv+MAX_MV]= f_code;
1283
        }
1284
    }
1285

    
1286
    for(mv=0; mv<MAX_MV*2+1; mv++){
1287
        umv_fcode_tab[mv]= 1;
1288
    }
1289
}
1290
#endif
1291

    
1292
static void init_uni_dc_tab(void)
1293
{
1294
    int level, uni_code, uni_len;
1295

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

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

    
1311
        /* luminance */
1312
        uni_code= DCtab_lum[size][0];
1313
        uni_len = DCtab_lum[size][1];
1314

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

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

    
1341
    }
1342
}
1343

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

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

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

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

    
1437
        init_uni_dc_tab();
1438

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

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

    
1477
    if(s->mpeg_quant){
1478
        s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
1479
        s->inter_quant_bias= 0;
1480
    }else{
1481
        s->intra_quant_bias=0;
1482
        s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
1483
    }
1484
}
1485

    
1486
/**
1487
 * encodes a 8x8 block.
1488
 * @param block the 8x8 block
1489
 * @param n block index (0-3 are luma, 4-5 are chroma)
1490
 */
1491
static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
1492
{
1493
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
1494
    RLTable *rl;
1495

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

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

    
1563
/* must be called before writing the header */
1564
void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
1565
    int time_div, time_mod;
1566

    
1567
    if(s->pict_type==I_TYPE){ //we will encode a vol header
1568
        s->time_increment_resolution= s->frame_rate/ff_gcd(s->frame_rate, FRAME_RATE_BASE);
1569
        if(s->time_increment_resolution>=256*256) s->time_increment_resolution= 256*128;
1570

    
1571
        s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
1572
    }
1573
    
1574
    if(s->current_picture.pts)
1575
        s->time= (s->current_picture.pts*s->time_increment_resolution + 500*1000)/(1000*1000);
1576
    else
1577
        s->time= picture_number*(INT64)FRAME_RATE_BASE*s->time_increment_resolution/s->frame_rate;
1578
    time_div= s->time/s->time_increment_resolution;
1579
    time_mod= s->time%s->time_increment_resolution;
1580

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

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

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

    
1610
    ff_mpeg4_stuffing(&s->pb);
1611
}
1612

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

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

    
1642
    ff_mpeg4_stuffing(&s->pb);
1643
}
1644

    
1645
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
1646
{
1647
    int vo_ver_id;
1648
    char buf[255];
1649

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

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

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

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

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

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

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

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

    
1731
    /* user data */
1732
    if(!ff_bit_exact){
1733
        put_bits(&s->pb, 16, 0);
1734
        put_bits(&s->pb, 16, 0x1B2);        /* user_data */
1735
        sprintf(buf, "FFmpeg%sb%s", FFMPEG_VERSION, LIBAVCODEC_BUILD_STR);
1736
        put_string(&s->pb, buf);
1737
        ff_mpeg4_stuffing(&s->pb);
1738
    }
1739
}
1740

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

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

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

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

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

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

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

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

    
1807
    if (s->qscale < 1)
1808
        s->qscale = 1;
1809
    else if (s->qscale > 31)
1810
        s->qscale = 31;
1811

    
1812
    s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
1813
    s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
1814
}
1815

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

    
1829
    /* find prediction */
1830
    if (n < 4) {
1831
        scale = s->y_dc_scale;
1832
    } else {
1833
        scale = s->c_dc_scale;
1834
    }
1835
    wrap= s->block_wrap[n];
1836
    dc_val = s->dc_val[0] + s->block_index[n];
1837

    
1838
    /* B C
1839
     * A X 
1840
     */
1841
    a = dc_val[ - 1];
1842
    b = dc_val[ - 1 - wrap];
1843
    c = dc_val[ - wrap];
1844

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

    
1855
    if (abs(a - b) < abs(b - c)) {
1856
        pred = c;
1857
        *dir_ptr = 1; /* top */
1858
    } else {
1859
        pred = a;
1860
        *dir_ptr = 0; /* left */
1861
    }
1862
    /* we assume pred is positive */
1863
#ifdef ARCH_X86
1864
        asm volatile (
1865
                "xorl %%edx, %%edx        \n\t"
1866
                "mul %%ecx                \n\t"
1867
                : "=d" (pred), "=a"(dummy)
1868
                : "a" (pred + (scale >> 1)), "c" (inverse[scale])
1869
        );
1870
#else
1871
    pred = (pred + (scale >> 1)) / scale;
1872
#endif
1873

    
1874
    /* prepare address for prediction update */
1875
    *dc_val_ptr = &dc_val[0];
1876

    
1877
    return pred;
1878
}
1879

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

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

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

    
1934
    /* top copy */
1935
    for(i=1;i<8;i++)
1936
        ac_val1[8 + i] = block[s->idct_permutation[i   ]];
1937

    
1938
}
1939

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

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

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

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

    
2017
    /* encode remaining bits */
2018
    if (size > 0) {
2019
        if (level < 0)
2020
            level = (-level) ^ ((1 << size) - 1);
2021
        put_bits(&s->pb, size, level);
2022
        if (size > 8)
2023
            put_bits(&s->pb, 1, 1);
2024
    }
2025
#endif
2026
}
2027
#ifdef CONFIG_ENCODERS
2028
/**
2029
 * encodes a 8x8 block
2030
 * @param n block index (0-3 are luma, 4-5 are chroma)
2031
 */
2032
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2033
                               UINT8 *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
2034
{
2035
    int i, last_non_zero;
2036
#if 0 //variables for the outcommented version
2037
    int code, sign, last;
2038
#endif
2039
    const RLTable *rl;
2040
    UINT32 *bits_tab;
2041
    UINT8 *len_tab;
2042
    const int last_index = s->block_last_index[n];
2043

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

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

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

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

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

    
2202
#endif
2203

    
2204

    
2205
/***********************************************/
2206
/* decoding */
2207

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

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

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

    
2263
/* init vlcs */
2264

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

    
2270
    if (!done) {
2271
        done = 1;
2272

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

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

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

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

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

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

    
2365
void ff_mpeg4_init_partitions(MpegEncContext *s)
2366
{
2367
    init_put_bits(&s->tex_pb, s->tex_pb_buffer, PB_BUFFER_SIZE, NULL, NULL);
2368
    init_put_bits(&s->pb2   , s->pb2_buffer   , PB_BUFFER_SIZE, NULL, NULL);
2369
}
2370

    
2371
void ff_mpeg4_merge_partitions(MpegEncContext *s)
2372
{
2373
    const int pb2_len   = get_bit_count(&s->pb2   );
2374
    const int tex_pb_len= get_bit_count(&s->tex_pb);
2375
    const int bits= get_bit_count(&s->pb);
2376

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

    
2388
    flush_put_bits(&s->pb2);
2389
    flush_put_bits(&s->tex_pb);
2390

    
2391
    ff_copy_bits(&s->pb, s->pb2_buffer   , pb2_len);
2392
    ff_copy_bits(&s->pb, s->tex_pb_buffer, tex_pb_len);
2393
    s->last_bits= get_bit_count(&s->pb);
2394
}
2395

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

    
2410
void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
2411
{
2412
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2413

    
2414
    ff_mpeg4_stuffing(&s->pb);
2415
    put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
2416
    put_bits(&s->pb, 1, 1);
2417
    
2418
    put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
2419
    put_bits(&s->pb, s->quant_precision, s->qscale);
2420
    put_bits(&s->pb, 1, 0); /* no HEC */
2421
}
2422

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

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

    
2452
            s->gb= gb;
2453

    
2454
            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
2455
                return 1;
2456
        }
2457
    }
2458
    return 0;
2459
}
2460

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

    
2473
    for(len=0; len<32; len++){
2474
        if(get_bits1(&s->gb)) break;
2475
    }
2476

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

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

    
2495
    if(s->shape != BIN_ONLY_SHAPE){
2496
        int qscale= get_bits(&s->gb, s->quant_precision); 
2497
        if(qscale)
2498
            s->qscale= qscale;
2499
    }
2500

    
2501
    if(s->shape == RECT_SHAPE){
2502
        header_extension= get_bits1(&s->gb);
2503
    }
2504
    if(header_extension){
2505
        int time_increment;
2506
        int time_incr=0;
2507

    
2508
        while (get_bits1(&s->gb) != 0) 
2509
            time_incr++;
2510

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

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

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

    
2546
    return 0;
2547
}
2548

    
2549
void ff_mpeg4_clean_buffers(MpegEncContext *s)
2550
{
2551
    int c_wrap, c_xy, l_wrap, l_xy;
2552

    
2553
    l_wrap= s->block_wrap[0];
2554
    l_xy= s->mb_y*l_wrap*2 + s->mb_x*2;
2555
    c_wrap= s->block_wrap[4];
2556
    c_xy= s->mb_y*c_wrap + s->mb_x;
2557

    
2558
#if 0
2559
    /* clean DC */
2560
    memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
2561
    memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
2562
    memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
2563
#endif
2564

    
2565
    /* clean AC */
2566
    memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(INT16));
2567
    memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(INT16));
2568
    memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(INT16));
2569

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

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

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

    
2609
            if(s->codec_id==CODEC_ID_MPEG4)
2610
                ret= mpeg4_decode_video_packet_header(s);
2611
            else
2612
                ret= h263_decode_gob_header(s);
2613
            if(ret>=0)
2614
                return 0;
2615

    
2616
            s->gb= bak;
2617
        }
2618
        skip_bits(&s->gb, 8);
2619
    }
2620
    
2621
    return -1;
2622
}
2623

    
2624
/**
2625
 * gets the average motion vector for a GMC MB.
2626
 * @param n either 0 for the x component or 1 for y
2627
 * @returns the average MV for a GMC MB
2628
 */
2629
static inline int get_amv(MpegEncContext *s, int n){
2630
    int x, y, mb_v, sum, dx, dy, shift;
2631
    int len = 1 << (s->f_code + 4);
2632
    const int a= s->sprite_warping_accuracy;
2633

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

    
2647
        sum=0;
2648
        for(y=0; y<16; y++){
2649
            int v;
2650
        
2651
            v= mb_v + dy*y;
2652
            //XXX FIXME optimize
2653
            for(x=0; x<16; x++){
2654
                sum+= v>>shift;
2655
                v+= dx;
2656
            }
2657
        }
2658
        sum= RSHIFT(sum, a+8-s->quarter_sample);
2659
    }
2660

    
2661
    if      (sum < -len) sum= -len;
2662
    else if (sum >= len) sum= len-1;
2663

    
2664
    return sum;
2665
}
2666

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

    
2692
            if(s->pict_type==I_TYPE){
2693
                int i;
2694

    
2695
                if(show_bits(&s->gb, 19)==DC_MARKER){
2696
                    return mb_num-1;
2697
                }
2698

    
2699
                PRINT_MB_TYPE("I");
2700
                cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
2701
                if (cbpc < 0){
2702

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

    
2710
                if(cbpc & 4) {
2711
                    change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2712
                }
2713
                s->current_picture.qscale_table[xy]= s->qscale;
2714

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

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

    
2755
                    if(s->mbintra_table[xy])
2756
                        ff_clean_intra_table_entries(s);
2757

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

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

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

    
2802
                            my = h263_decode_motion(s, pred_y, s->f_code);
2803
                            if (my >= 0xffff)
2804
                                return -1;
2805
                        } else {
2806
                            mx = get_amv(s, 0);
2807
                            my = get_amv(s, 1);
2808
                        }
2809

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

    
2838
    return mb_num;
2839
}
2840

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

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

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

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

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

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

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

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

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

    
2967
    return 0;        
2968
}
2969

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

    
2979
    mb_type= s->mb_type[xy];
2980
    cbp = s->cbp_table[xy];
2981

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

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

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

    
3053
    s->error_status_table[xy]&= ~AC_ERROR;
3054

    
3055
    /* per-MB end of slice check */
3056

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

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

    
3078
    s->error_status_table[s->mb_x + s->mb_y*s->mb_width]= 0;
3079

    
3080
    if(s->mb_x==0) PRINT_MB_TYPE("\n");
3081

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

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

    
3145
                s->field_select[0][0]= get_bits1(&s->gb);
3146
                s->field_select[0][1]= get_bits1(&s->gb);
3147

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

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

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

    
3220
        s->mb_intra = 0; //B-frames never contain intra blocks
3221
        s->mcsel=0;      //     ...               true gmc blocks
3222

    
3223
        if(s->mb_x==0){
3224
            for(i=0; i<2; i++){
3225
                s->last_mv[i][0][0]= 
3226
                s->last_mv[i][0][1]= 
3227
                s->last_mv[i][1][0]= 
3228
                s->last_mv[i][1][1]= 0;
3229
            }
3230
        }
3231

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

    
3235
        if(s->mb_skiped){
3236
                /* skip mb */
3237
            for(i=0;i<6;i++)
3238
                s->block_last_index[i] = -1;
3239

    
3240
            s->mv_dir = MV_DIR_FORWARD;
3241
            s->mv_type = MV_TYPE_16X16;
3242
            s->mv[0][0][0] = 0;
3243
            s->mv[0][0][1] = 0;
3244
            s->mv[1][0][0] = 0;
3245
            s->mv[1][0][1] = 0;
3246
            PRINT_MB_TYPE("s");
3247
            goto end;
3248
        }
3249

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

    
3262
            if (mb_type!=MB_TYPE_B_DIRECT && cbp) {
3263
                if(get_bits1(&s->gb)){
3264
                    change_qscale(s, get_bits1(&s->gb)*4 - 2);
3265
                }
3266
            }
3267
            field_mv=0;
3268

    
3269
            if(!s->progressive_sequence){
3270
                if(cbp)
3271
                    s->interlaced_dct= get_bits1(&s->gb);
3272

    
3273
                if(mb_type!=MB_TYPE_B_DIRECT && get_bits1(&s->gb)){
3274
                    field_mv=1;
3275

    
3276
                    if(mb_type!=MB_TYPE_B_BACKW){
3277
                        s->field_select[0][0]= get_bits1(&s->gb);
3278
                        s->field_select[0][1]= get_bits1(&s->gb);
3279
                    }
3280
                    if(mb_type!=MB_TYPE_B_FORW){
3281
                        s->field_select[1][0]= get_bits1(&s->gb);
3282
                        s->field_select[1][1]= get_bits1(&s->gb);
3283
                    }
3284
                }
3285
            }
3286

    
3287
            s->mv_dir = 0;
3288
            if(mb_type!=MB_TYPE_B_DIRECT && !field_mv){
3289
                s->mv_type= MV_TYPE_16X16;
3290
                if(mb_type!=MB_TYPE_B_BACKW){
3291
                    s->mv_dir = MV_DIR_FORWARD;
3292

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

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

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

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

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

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

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

    
3426
        if(v==0)
3427
            return SLICE_END;
3428
    }
3429

    
3430
    return SLICE_OK;     
3431
}
3432

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

    
3440
    if (code == 0)
3441
        return pred;
3442

    
3443
    sign = get_bits1(&s->gb);
3444
    shift = f_code - 1;
3445
    val = (code - 1) << shift;
3446
    if (shift > 0)
3447
        val |= get_bits(&s->gb, shift);
3448
    val++;
3449
    if (sign)
3450
        val = -val;
3451
    val += pred;
3452

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

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

    
3496
}
3497

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

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

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

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

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

    
3648
/**
3649
 * decodes a block.
3650
 * @return <0 if an error occured
3651
 */
3652
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
3653
                              int n, int coded, int intra)
3654
{
3655
    int level, i, last, run;
3656
    int dc_pred_dir;
3657
    RLTable * rl;
3658
    RL_VLC_ELEM * rl_vlc;
3659
    const UINT8 * scan_table;
3660
    int qmul, qadd;
3661

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

    
3700
        if(s->mpeg_quant){
3701
            qmul=1;
3702
            qadd=0;
3703
            rl_vlc = rl_inter.rl_vlc[0];        
3704
        }else{
3705
            qmul = s->qscale << 1;
3706
            qadd = (s->qscale - 1) | 1;
3707
            rl_vlc = rl_inter.rl_vlc[s->qscale];
3708
        }
3709
    }
3710
  {
3711
    OPEN_READER(re, &s->gb);
3712
    for(;;) {
3713
        UPDATE_CACHE(re, &s->gb);
3714
        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3715
        if (level==0) {
3716
            int cache;
3717
            cache= GET_CACHE(re, &s->gb);
3718
            /* escape */
3719
            if (cache&0x80000000) {
3720
                if (cache&0x40000000) {
3721
                    /* third escape */
3722
                    SKIP_CACHE(re, &s->gb, 2);
3723
                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
3724
                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
3725
                    SKIP_COUNTER(re, &s->gb, 2+1+6);
3726
                    UPDATE_CACHE(re, &s->gb);
3727

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

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

    
3812
            block[scan_table[i]] = level;
3813
            break;
3814
        }
3815

    
3816
        block[scan_table[i]] = level;
3817
    }
3818
    CLOSE_READER(re, &s->gb);
3819
  }
3820
 not_coded:
3821
    if (s->mb_intra) {
3822
        mpeg4_pred_ac(s, block, n, dc_pred_dir);
3823
        if (s->ac_pred) {
3824
            i = 63; /* XXX: not optimal */
3825
        }
3826
    }
3827
    s->block_last_index[n] = i;
3828
    return 0;
3829
}
3830

    
3831
/* most is hardcoded. should extend to handle all h263 streams */
3832
int h263_decode_picture_header(MpegEncContext *s)
3833
{
3834
    int format, width, height;
3835

    
3836
    /* picture start code */
3837
    if (get_bits(&s->gb, 22) != 0x20) {
3838
        fprintf(stderr, "Bad picture start code\n");
3839
        return -1;
3840
    }
3841
    /* temporal reference */
3842
    s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
3843

    
3844
    /* PTYPE starts here */    
3845
    if (get_bits1(&s->gb) != 1) {
3846
        /* marker */
3847
        fprintf(stderr, "Bad marker\n");
3848
        return -1;
3849
    }
3850
    if (get_bits1(&s->gb) != 0) {
3851
        fprintf(stderr, "Bad H263 id\n");
3852
        return -1;        /* h263 id */
3853
    }
3854
    skip_bits1(&s->gb);        /* split screen off */
3855
    skip_bits1(&s->gb);        /* camera  off */
3856
    skip_bits1(&s->gb);        /* freeze picture release off */
3857

    
3858
    /* Reset GOB number */
3859
    s->gob_number = 0;
3860
        
3861
    format = get_bits(&s->gb, 3);
3862
    /*
3863
        0    forbidden
3864
        1    sub-QCIF
3865
        10   QCIF
3866
        7        extended PTYPE (PLUSPTYPE)
3867
    */
3868

    
3869
    if (format != 7 && format != 6) {
3870
        s->h263_plus = 0;
3871
        /* H.263v1 */
3872
        width = h263_format[format][0];
3873
        height = h263_format[format][1];
3874
        if (!width)
3875
            return -1;
3876
        
3877
        s->width = width;
3878
        s->height = height;
3879
        s->pict_type = I_TYPE + get_bits1(&s->gb);
3880

    
3881
        s->unrestricted_mv = get_bits1(&s->gb); 
3882
        s->h263_long_vectors = s->unrestricted_mv;
3883

    
3884
        if (get_bits1(&s->gb) != 0) {
3885
            fprintf(stderr, "H263 SAC not supported\n");
3886
            return -1;        /* SAC: off */
3887
        }
3888
        if (get_bits1(&s->gb) != 0) {
3889
            s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3890
        }   
3891
        
3892
        if (get_bits1(&s->gb) != 0) {
3893
            fprintf(stderr, "H263 PB frame not supported\n");
3894
            return -1;        /* not PB frame */
3895
        }
3896
        s->qscale = get_bits(&s->gb, 5);
3897
        skip_bits1(&s->gb);        /* Continuous Presence Multipoint mode: off */
3898
    } else {
3899
        int ufep;
3900
        
3901
        /* H.263v2 */
3902
        s->h263_plus = 1;
3903
        ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
3904

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

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

    
4003
    return 0;
4004
}
4005

    
4006
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
4007
{
4008
    int i;
4009
    int a= 2<<s->sprite_warping_accuracy;
4010
    int rho= 3-s->sprite_warping_accuracy;
4011
    int r=16/a;
4012
    const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
4013
    int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
4014
    int sprite_ref[4][2];
4015
    int virtual_ref[2][2];
4016
    int w2, h2, w3, h3;
4017
    int alpha=0, beta=0;
4018
    int w= s->width;
4019
    int h= s->height;
4020
    int min_ab;
4021

    
4022
    for(i=0; i<s->num_sprite_warping_points; i++){
4023
        int length;
4024
        int x=0, y=0;
4025

    
4026
        length= get_vlc(&s->gb, &sprite_trajectory);
4027
        if(length){
4028
            x= get_bits(&s->gb, length);
4029

    
4030
            if ((x >> (length - 1)) == 0) /* if MSB not set it is negative*/
4031
                x = - (x ^ ((1 << length) - 1));
4032
        }
4033
        if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
4034
        
4035
        length= get_vlc(&s->gb, &sprite_trajectory);
4036
        if(length){
4037
            y=get_bits(&s->gb, length);
4038

    
4039
            if ((y >> (length - 1)) == 0) /* if MSB not set it is negative*/
4040
                y = - (y ^ ((1 << length) - 1));
4041
        }
4042
        skip_bits1(&s->gb); /* marker bit */
4043
//printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
4044
        d[i][0]= x;
4045
        d[i][1]= y;
4046
    }
4047

    
4048
    while((1<<alpha)<w) alpha++;
4049
    while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
4050
    w2= 1<<alpha;
4051
    h2= 1<<beta;
4052

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

    
4221
static int mpeg4_decode_gop_header(MpegEncContext * s, GetBitContext *gb){
4222
    int hours, minutes, seconds;
4223

    
4224
    hours= get_bits(gb, 5);
4225
    minutes= get_bits(gb, 6);
4226
    skip_bits1(gb);
4227
    seconds= get_bits(gb, 6);
4228

    
4229
    s->time_base= seconds + 60*(minutes + 60*hours);
4230

    
4231
    skip_bits1(gb);
4232
    skip_bits1(gb);
4233
    
4234
    return 0;
4235
}
4236

    
4237
static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){
4238
    int width, height, vo_ver_id;
4239

    
4240
    /* vol header */
4241
    skip_bits(gb, 1); /* random access */
4242
    s->vo_type= get_bits(gb, 8);
4243
    if (get_bits1(gb) != 0) { /* is_ol_id */
4244
        vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
4245
        skip_bits(gb, 3); /* vo_priority */
4246
    } else {
4247
        vo_ver_id = 1;
4248
    }
4249
//printf("vo type:%d\n",s->vo_type);
4250
    s->aspect_ratio_info= get_bits(gb, 4);
4251
    if(s->aspect_ratio_info == FF_ASPECT_EXTENDED){            
4252
        s->aspected_width = get_bits(gb, 8); // par_width
4253
        s->aspected_height = get_bits(gb, 8); // par_height
4254
    }else{
4255
        s->aspected_width = pixel_aspect[s->aspect_ratio_info][0];
4256
        s->aspected_height= pixel_aspect[s->aspect_ratio_info][1];
4257
    }
4258

    
4259
    if ((s->vol_control_parameters=get_bits1(gb))) { /* vol control parameter */
4260
        int chroma_format= get_bits(gb, 2);
4261
        if(chroma_format!=1){
4262
            printf("illegal chroma format\n");
4263
        }
4264
        s->low_delay= get_bits1(gb);
4265
        if(get_bits1(gb)){ /* vbv parameters */
4266
            get_bits(gb, 15);        /* first_half_bitrate */
4267
            skip_bits1(gb);        /* marker */
4268
            get_bits(gb, 15);        /* latter_half_bitrate */
4269
            skip_bits1(gb);        /* marker */
4270
            get_bits(gb, 15);        /* first_half_vbv_buffer_size */
4271
            skip_bits1(gb);        /* marker */
4272
            get_bits(gb, 3);        /* latter_half_vbv_buffer_size */
4273
            get_bits(gb, 11);        /* first_half_vbv_occupancy */
4274
            skip_bits1(gb);        /* marker */
4275
            get_bits(gb, 15);        /* latter_half_vbv_occupancy */
4276
            skip_bits1(gb);        /* marker */               
4277
        }
4278
    }else{
4279
        // set low delay flag only once so the smart? low delay detection wont be overriden
4280
        if(s->picture_number==0)
4281
            s->low_delay=0;
4282
    }
4283

    
4284
    s->shape = get_bits(gb, 2); /* vol shape */
4285
    if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");
4286
    if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
4287
        printf("Gray shape not supported\n");
4288
        skip_bits(gb, 4);  //video_object_layer_shape_extension
4289
    }
4290

    
4291
    skip_bits1(gb);   /* marker */
4292
    
4293
    s->time_increment_resolution = get_bits(gb, 16);
4294
    
4295
    s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
4296
    if (s->time_increment_bits < 1)
4297
        s->time_increment_bits = 1;
4298
    skip_bits1(gb);   /* marker */
4299

    
4300
    if (get_bits1(gb) != 0) {   /* fixed_vop_rate  */
4301
        skip_bits(gb, s->time_increment_bits);
4302
    }
4303

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

    
4355
        if((s->mpeg_quant=get_bits1(gb))){ /* vol_quant_type */
4356
            int i, j, v;
4357
            
4358
            /* load default matrixes */
4359
            for(i=0; i<64; i++){
4360
                int j= s->idct_permutation[i];
4361
                v= ff_mpeg4_default_intra_matrix[i];
4362
                s->intra_matrix[j]= v;
4363
                s->chroma_intra_matrix[j]= v;
4364
                
4365
                v= ff_mpeg4_default_non_intra_matrix[i];
4366
                s->inter_matrix[j]= v;
4367
                s->chroma_inter_matrix[j]= v;
4368
            }
4369

    
4370
            /* load custom intra matrix */
4371
            if(get_bits1(gb)){
4372
                int last=0;
4373
                for(i=0; i<64; i++){
4374
                    v= get_bits(gb, 8);
4375
                    if(v==0) break;
4376
                    
4377
                    last= v;
4378
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4379
                    s->intra_matrix[j]= v;
4380
                    s->chroma_intra_matrix[j]= v;
4381
                }
4382

    
4383
                /* replicate last value */
4384
                for(; i<64; i++){
4385
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4386
                    s->intra_matrix[j]= v;
4387
                    s->chroma_intra_matrix[j]= v;
4388
                }
4389
            }
4390

    
4391
            /* load custom non intra matrix */
4392
            if(get_bits1(gb)){
4393
                int last=0;
4394
                for(i=0; i<64; i++){
4395
                    v= get_bits(gb, 8);
4396
                    if(v==0) break;
4397

    
4398
                    last= v;
4399
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4400
                    s->inter_matrix[j]= v;
4401
                    s->chroma_inter_matrix[j]= v;
4402
                }
4403

    
4404
                /* replicate last value */
4405
                for(; i<64; i++){
4406
                    j= s->idct_permutation[ ff_zigzag_direct[i] ];
4407
                    s->inter_matrix[j]= last;
4408
                    s->chroma_inter_matrix[j]= last;
4409
                }
4410
            }
4411

    
4412
            // FIXME a bunch of grayscale shape things
4413
        }
4414

    
4415
        if(vo_ver_id != 1)
4416
             s->quarter_sample= get_bits1(gb);
4417
        else s->quarter_sample=0;
4418

    
4419
        if(!get_bits1(gb)) printf("Complexity estimation not supported\n");
4420

    
4421
        s->resync_marker= !get_bits1(gb); /* resync_marker_disabled */
4422

    
4423
        s->data_partitioning= get_bits1(gb);
4424
        if(s->data_partitioning){
4425
            s->rvlc= get_bits1(gb);
4426
            if(s->rvlc){
4427
                printf("reversible vlc not supported\n");
4428
            }
4429
        }
4430
        
4431
        if(vo_ver_id != 1) {
4432
            s->new_pred= get_bits1(gb);
4433
            if(s->new_pred){
4434
                printf("new pred not supported\n");
4435
                skip_bits(gb, 2); /* requested upstream message type */
4436
                skip_bits1(gb); /* newpred segment type */
4437
            }
4438
            s->reduced_res_vop= get_bits1(gb);
4439
            if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");
4440
        }
4441
        else{
4442
            s->new_pred=0;
4443
            s->reduced_res_vop= 0;
4444
        }
4445

    
4446
        s->scalability= get_bits1(gb);
4447

    
4448
        if (s->scalability) {
4449
            GetBitContext bak= *gb;
4450
            int ref_layer_id;
4451
            int ref_layer_sampling_dir;
4452
            int h_sampling_factor_n;
4453
            int h_sampling_factor_m;
4454
            int v_sampling_factor_n;
4455
            int v_sampling_factor_m;
4456
            
4457
            s->hierachy_type= get_bits1(gb);
4458
            ref_layer_id= get_bits(gb, 4);
4459
            ref_layer_sampling_dir= get_bits1(gb);
4460
            h_sampling_factor_n= get_bits(gb, 5);
4461
            h_sampling_factor_m= get_bits(gb, 5);
4462
            v_sampling_factor_n= get_bits(gb, 5);
4463
            v_sampling_factor_m= get_bits(gb, 5);
4464
            s->enhancement_type= get_bits1(gb);
4465
            
4466
            if(   h_sampling_factor_n==0 || h_sampling_factor_m==0 
4467
               || v_sampling_factor_n==0 || v_sampling_factor_m==0){
4468
               
4469
//                fprintf(stderr, "illegal scalability header (VERY broken encoder), trying to workaround\n");
4470
                s->scalability=0;
4471
               
4472
                *gb= bak;
4473
            }else
4474
                printf("scalability not supported\n");
4475
            
4476
            // bin shape stuff FIXME
4477
        }
4478
    }
4479
    return 0;
4480
}
4481

    
4482
/**
4483
 * decodes the user data stuff in the header.
4484
 * allso inits divx/xvid/lavc_version/build
4485
 */
4486
static int decode_user_data(MpegEncContext *s, GetBitContext *gb){
4487
    char buf[256];
4488
    int i;
4489
    int e;
4490
    int ver, build, ver2, ver3;
4491

    
4492
    buf[0]= show_bits(gb, 8);
4493
    for(i=1; i<256; i++){
4494
        buf[i]= show_bits(gb, 16)&0xFF;
4495
        if(buf[i]==0) break;
4496
        skip_bits(gb, 8);
4497
    }
4498
    buf[255]=0;
4499
    
4500
    /* divx detection */
4501
    e=sscanf(buf, "DivX%dBuild%d", &ver, &build);
4502
    if(e!=2)
4503
        e=sscanf(buf, "DivX%db%d", &ver, &build);
4504
    if(e==2){
4505
        s->divx_version= ver;
4506
        s->divx_build= build;
4507
        if(s->picture_number==0){
4508
            printf("This file was encoded with DivX%d Build%d\n", ver, build);
4509
        }
4510
    }
4511
    
4512
    /* ffmpeg detection */
4513
    e=sscanf(buf, "FFmpeg%d.%d.%db%d", &ver, &ver2, &ver3, &build);
4514
    if(e!=4)
4515
        e=sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); 
4516
    if(e!=4){
4517
        if(strcmp(buf, "ffmpeg")==0){
4518
            s->ffmpeg_version= 0x000406;
4519
            s->lavc_build= 4600;
4520
        }
4521
    }
4522
    if(e==4){
4523
        s->ffmpeg_version= ver*256*256 + ver2*256 + ver3;
4524
        s->lavc_build= build;
4525
        if(s->picture_number==0)
4526
            printf("This file was encoded with libavcodec build %d\n", build);
4527
    }
4528
    
4529
    /* xvid detection */
4530
    e=sscanf(buf, "XviD%d", &build);
4531
    if(e==1){
4532
        s->xvid_build= build;
4533
        if(s->picture_number==0)
4534
            printf("This file was encoded with XviD build %d\n", build);
4535
    }
4536

    
4537
//printf("User Data: %s\n", buf);
4538
    return 0;
4539
}
4540

    
4541
static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){
4542
    int time_incr, time_increment;
4543

    
4544
    s->pict_type = get_bits(gb, 2) + I_TYPE;        /* pict type: I = 0 , P = 1 */
4545
    if(s->pict_type==B_TYPE && s->low_delay && s->vol_control_parameters==0){
4546
        printf("low_delay flag set, but shouldnt, clearing it\n");
4547
        s->low_delay=0;
4548
    }
4549
 
4550
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
4551
    if(s->partitioned_frame)
4552
        s->decode_mb= mpeg4_decode_partitioned_mb;
4553
    else
4554
        s->decode_mb= ff_h263_decode_mb;
4555

    
4556
    if(s->time_increment_resolution==0){
4557
        s->time_increment_resolution=1;
4558
//        fprintf(stderr, "time_increment_resolution is illegal\n");
4559
    }
4560
    time_incr=0;
4561
    while (get_bits1(gb) != 0) 
4562
        time_incr++;
4563

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

    
4624
     if (s->shape != RECT_SHAPE) {
4625
         if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {
4626
             int width, height, hor_spat_ref, ver_spat_ref;
4627
 
4628
             width = get_bits(gb, 13);
4629
             skip_bits1(gb);   /* marker */
4630
             height = get_bits(gb, 13);
4631
             skip_bits1(gb);   /* marker */
4632
             hor_spat_ref = get_bits(gb, 13); /* hor_spat_ref */
4633
             skip_bits1(gb);   /* marker */
4634
             ver_spat_ref = get_bits(gb, 13); /* ver_spat_ref */
4635
         }
4636
         skip_bits1(gb); /* change_CR_disable */
4637
 
4638
         if (get_bits1(gb) != 0) {
4639
             skip_bits(gb, 8); /* constant_alpha_value */
4640
         }
4641
     }
4642
//FIXME complexity estimation stuff
4643
     
4644
     if (s->shape != BIN_ONLY_SHAPE) {
4645
         int t;
4646
         t=get_bits(gb, 3); /* intra dc VLC threshold */
4647
//printf("threshold %d\n", t);
4648
         if(!s->progressive_sequence){
4649
             s->top_field_first= get_bits1(gb);
4650
             s->alternate_scan= get_bits1(gb);
4651
         }else
4652
             s->alternate_scan= 0;
4653
     }
4654

    
4655
     if(s->alternate_scan){
4656
         ff_init_scantable(s, &s->inter_scantable  , ff_alternate_vertical_scan);
4657
         ff_init_scantable(s, &s->intra_scantable  , ff_alternate_vertical_scan);
4658
         ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_vertical_scan);
4659
         ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
4660
     } else{
4661
         ff_init_scantable(s, &s->inter_scantable  , ff_zigzag_direct);
4662
         ff_init_scantable(s, &s->intra_scantable  , ff_zigzag_direct);
4663
         ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_horizontal_scan);
4664
         ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
4665
     }
4666
 
4667
     if(s->pict_type == S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){
4668
         mpeg4_decode_sprite_trajectory(s);
4669
         if(s->sprite_brightness_change) printf("sprite_brightness_change not supported\n");
4670
         if(s->vol_sprite_usage==STATIC_SPRITE) printf("static sprite not supported\n");
4671
     }
4672

    
4673
     if (s->shape != BIN_ONLY_SHAPE) {
4674
         s->qscale = get_bits(gb, s->quant_precision);
4675
         if(s->qscale==0){
4676
             printf("Error, header damaged or not MPEG4 header (qscale=0)\n");
4677
             return -1; // makes no sense to continue, as there is nothing left from the image then
4678
         }
4679
  
4680
         if (s->pict_type != I_TYPE) {
4681
             s->f_code = get_bits(gb, 3);        /* fcode_for */
4682
             if(s->f_code==0){
4683
                 printf("Error, header damaged or not MPEG4 header (f_code=0)\n");
4684
                 return -1; // makes no sense to continue, as the MV decoding will break very quickly
4685
             }
4686
         }else
4687
             s->f_code=1;
4688
     
4689
         if (s->pict_type == B_TYPE) {
4690
             s->b_code = get_bits(gb, 3);
4691
         }else
4692