Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h263.c @ 4ccde216

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

    
27
/**
28
 * @file h263.c
29
 * h263/mpeg4 codec.
30
 */
31
 
32
//#define DEBUG
33
#include <limits.h>
34

    
35
#include "common.h"
36
#include "dsputil.h"
37
#include "avcodec.h"
38
#include "mpegvideo.h"
39
#include "h263data.h"
40
#include "mpeg4data.h"
41

    
42
//#undef NDEBUG
43
//#include <assert.h>
44

    
45
#define INTRA_MCBPC_VLC_BITS 6
46
#define INTER_MCBPC_VLC_BITS 7
47
#define CBPY_VLC_BITS 6
48
#define MV_VLC_BITS 9
49
#define DC_VLC_BITS 9
50
#define SPRITE_TRAJ_VLC_BITS 6
51
#define MB_TYPE_B_VLC_BITS 4
52
#define TEX_VLC_BITS 9
53
#define H263_MBTYPE_B_VLC_BITS 6
54
#define CBPC_B_VLC_BITS 3
55

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

    
66
static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
67
static int h263p_decode_umotion(MpegEncContext * s, int pred);
68
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
69
                             int n, int coded);
70
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr);
71
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
72
                              int n, int coded, int intra, int rvlc);
73
static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr);
74
#ifdef CONFIG_ENCODERS
75
static void mpeg4_encode_visual_object_header(MpegEncContext * s);
76
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number);
77
#endif //CONFIG_ENCODERS
78
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s, GetBitContext *gb);
79
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, int level, int *dir_ptr, int encoding);
80

    
81
#ifdef CONFIG_ENCODERS
82
static uint8_t uni_DCtab_lum_len[512];
83
static uint8_t uni_DCtab_chrom_len[512];
84
static uint16_t uni_DCtab_lum_bits[512];
85
static uint16_t uni_DCtab_chrom_bits[512];
86

    
87
static uint8_t (*mv_penalty)[MAX_MV*2+1]= NULL;
88
static uint8_t fcode_tab[MAX_MV*2+1];
89
static uint8_t umv_fcode_tab[MAX_MV*2+1];
90

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

    
99
/* mpeg4
100
inter
101
max level: 24/6
102
max run: 53/63
103

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

    
110
#if 0 //3IV1 is quite rare and tis slows things down a tiny bit
111
#define IS_3IV1 s->avctx->codec_tag == ff_get_fourcc("3IV1")
112
#else 
113
#define IS_3IV1 0
114
#endif
115

    
116
int h263_get_picture_format(int width, int height)
117
{
118
    int format;
119

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

    
135
#ifdef CONFIG_ENCODERS
136

    
137
static void aspect_to_info(MpegEncContext * s, AVRational aspect){
138
    int i;
139

    
140
    if(aspect.num==0) aspect= (AVRational){1,1};
141

    
142
    for(i=1; i<6; i++){
143
        if(av_cmp_q(pixel_aspect[i], aspect) == 0){
144
            s->aspect_ratio_info=i;
145
            return;
146
        }
147
    }
148
    
149
    s->aspect_ratio_info= FF_ASPECT_EXTENDED;
150
}
151

    
152
void ff_flv_encode_picture_header(MpegEncContext * s, int picture_number)
153
{
154
      int format;
155

    
156
      align_put_bits(&s->pb);
157

    
158
      put_bits(&s->pb, 17, 1);
159
      put_bits(&s->pb, 5, (s->h263_flv-1)); /* 0: h263 escape codes 1: 11-bit escape codes */
160
      put_bits(&s->pb, 8, (((int64_t)s->picture_number * 30 * s->avctx->frame_rate_base) / 
161
                           s->avctx->frame_rate) & 0xff); /* TemporalReference */
162
      if (s->width == 352 && s->height == 288)
163
        format = 2;
164
      else if (s->width == 176 && s->height == 144)
165
        format = 3;
166
      else if (s->width == 128 && s->height == 96)
167
        format = 4;
168
      else if (s->width == 320 && s->height == 240)
169
        format = 5;
170
      else if (s->width == 160 && s->height == 120)
171
        format = 6;
172
      else if (s->width <= 255 && s->height <= 255)
173
        format = 0; /* use 1 byte width & height */
174
      else
175
        format = 1; /* use 2 bytes width & height */
176
      put_bits(&s->pb, 3, format); /* PictureSize */
177
      if (format == 0) {
178
        put_bits(&s->pb, 8, s->width);
179
        put_bits(&s->pb, 8, s->height);
180
      } else if (format == 1) {
181
        put_bits(&s->pb, 16, s->width);
182
        put_bits(&s->pb, 16, s->height);
183
      }
184
      put_bits(&s->pb, 2, s->pict_type == P_TYPE); /* PictureType */
185
      put_bits(&s->pb, 1, 1); /* DeblockingFlag: on */
186
      put_bits(&s->pb, 5, s->qscale); /* Quantizer */
187
      put_bits(&s->pb, 1, 0); /* ExtraInformation */
188

    
189
      if(s->h263_aic){
190
        s->y_dc_scale_table= 
191
          s->c_dc_scale_table= ff_aic_dc_scale_table;
192
      }else{
193
        s->y_dc_scale_table=
194
          s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
195
      }
196
}
197

    
198
void h263_encode_picture_header(MpegEncContext * s, int picture_number)
199
{
200
    int format, coded_frame_rate, coded_frame_rate_base, i, temp_ref;
201
    int best_clock_code=1;
202
    int best_divisor=60;
203
    int best_error= INT_MAX;
204
   
205
    if(s->h263_plus){
206
        for(i=0; i<2; i++){
207
            int div, error;
208
            div= (s->avctx->frame_rate_base*1800000LL + 500LL*s->avctx->frame_rate) / ((1000LL+i)*s->avctx->frame_rate);
209
            div= clip(1, div, 127);
210
            error= ABS(s->avctx->frame_rate_base*1800000LL - (1000LL+i)*s->avctx->frame_rate*div);
211
            if(error < best_error){
212
                best_error= error;
213
                best_divisor= div;
214
                best_clock_code= i;
215
            }
216
        }
217
    }
218
    s->custom_pcf= best_clock_code!=1 || best_divisor!=60;
219
    coded_frame_rate= 1800000;
220
    coded_frame_rate_base= (1000+best_clock_code)*best_divisor;
221

    
222
    align_put_bits(&s->pb);
223

    
224
    /* Update the pointer to last GOB */
225
    s->ptr_lastgob = pbBufPtr(&s->pb);
226
    put_bits(&s->pb, 22, 0x20); /* PSC */
227
    temp_ref= s->picture_number * (int64_t)coded_frame_rate * s->avctx->frame_rate_base / 
228
                         (coded_frame_rate_base * (int64_t)s->avctx->frame_rate);
229
    put_bits(&s->pb, 8, temp_ref & 0xff); /* TemporalReference */
230

    
231
    put_bits(&s->pb, 1, 1);        /* marker */
232
    put_bits(&s->pb, 1, 0);        /* h263 id */
233
    put_bits(&s->pb, 1, 0);        /* split screen off */
234
    put_bits(&s->pb, 1, 0);        /* camera  off */
235
    put_bits(&s->pb, 1, 0);        /* freeze picture release off */
236
    
237
    format = h263_get_picture_format(s->width, s->height);
238
    if (!s->h263_plus) {
239
        /* H.263v1 */
240
        put_bits(&s->pb, 3, format);
241
        put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
242
        /* By now UMV IS DISABLED ON H.263v1, since the restrictions
243
        of H.263v1 UMV implies to check the predicted MV after
244
        calculation of the current MB to see if we're on the limits */
245
        put_bits(&s->pb, 1, 0);        /* unrestricted motion vector: off */
246
        put_bits(&s->pb, 1, 0);        /* SAC: off */
247
        put_bits(&s->pb, 1, s->obmc);        /* advanced prediction mode */
248
        put_bits(&s->pb, 1, 0);        /* not PB frame */
249
        put_bits(&s->pb, 5, s->qscale);
250
        put_bits(&s->pb, 1, 0);        /* Continuous Presence Multipoint mode: off */
251
    } else {
252
        int ufep=1;
253
        /* H.263v2 */
254
        /* H.263 Plus PTYPE */
255
        
256
        put_bits(&s->pb, 3, 7);
257
        put_bits(&s->pb,3,ufep); /* Update Full Extended PTYPE */
258
        if (format == 7)
259
            put_bits(&s->pb,3,6); /* Custom Source Format */
260
        else
261
            put_bits(&s->pb, 3, format);
262
            
263
        put_bits(&s->pb,1, s->custom_pcf);
264
        put_bits(&s->pb,1, s->umvplus); /* Unrestricted Motion Vector */
265
        put_bits(&s->pb,1,0); /* SAC: off */
266
        put_bits(&s->pb,1,s->obmc); /* Advanced Prediction Mode */
267
        put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
268
        put_bits(&s->pb,1,s->loop_filter); /* Deblocking Filter */
269
        put_bits(&s->pb,1,s->h263_slice_structured); /* Slice Structured */
270
        put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
271
        put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
272
        put_bits(&s->pb,1,s->alt_inter_vlc); /* Alternative Inter VLC */
273
        put_bits(&s->pb,1,s->modified_quant); /* Modified Quantization: */
274
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
275
        put_bits(&s->pb,3,0); /* Reserved */
276
                
277
        put_bits(&s->pb, 3, s->pict_type == P_TYPE);
278
                
279
        put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
280
        put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
281
        put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
282
        put_bits(&s->pb,2,0); /* Reserved */
283
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
284
                
285
        /* This should be here if PLUSPTYPE */
286
        put_bits(&s->pb, 1, 0);        /* Continuous Presence Multipoint mode: off */
287
                
288
                if (format == 7) {
289
            /* Custom Picture Format (CPFMT) */
290
            aspect_to_info(s, s->avctx->sample_aspect_ratio);
291

    
292
            put_bits(&s->pb,4,s->aspect_ratio_info);
293
            put_bits(&s->pb,9,(s->width >> 2) - 1);
294
            put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
295
            put_bits(&s->pb,9,(s->height >> 2));
296
            if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
297
                put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
298
                put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
299
            }
300
        }
301
        if(s->custom_pcf){
302
            if(ufep){
303
                put_bits(&s->pb, 1, best_clock_code);
304
                put_bits(&s->pb, 7, best_divisor);
305
            }
306
            put_bits(&s->pb, 2, (temp_ref>>8)&3);
307
        }
308
        
309
        /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
310
        if (s->umvplus)
311
//            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
312
//FIXME check actual requested range
313
            put_bits(&s->pb,2,1); /* unlimited */
314
        if(s->h263_slice_structured)
315
            put_bits(&s->pb,2,0); /* no weird submodes */
316

    
317
        put_bits(&s->pb, 5, s->qscale);
318
    }
319

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

    
322
    if(s->h263_slice_structured){
323
        put_bits(&s->pb, 1, 1);
324
        
325
        assert(s->mb_x == 0 && s->mb_y == 0);
326
        ff_h263_encode_mba(s);
327

    
328
        put_bits(&s->pb, 1, 1);
329
    }
330

    
331
    if(s->h263_aic){
332
         s->y_dc_scale_table= 
333
         s->c_dc_scale_table= ff_aic_dc_scale_table;
334
    }else{
335
        s->y_dc_scale_table=
336
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
337
    }
338
}
339

    
340
/**
341
 * Encodes a group of blocks header.
342
 */
343
void h263_encode_gob_header(MpegEncContext * s, int mb_line)
344
{
345
    put_bits(&s->pb, 17, 1); /* GBSC */
346

    
347
    if(s->h263_slice_structured){
348
        put_bits(&s->pb, 1, 1);
349

    
350
        ff_h263_encode_mba(s);
351

    
352
        if(s->mb_num > 1583)
353
            put_bits(&s->pb, 1, 1);
354
        put_bits(&s->pb, 5, s->qscale); /* GQUANT */
355
        put_bits(&s->pb, 1, 1);
356
        put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
357
    }else{
358
        int gob_number= mb_line / s->gob_index;
359

    
360
        put_bits(&s->pb, 5, gob_number); /* GN */
361
        put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
362
        put_bits(&s->pb, 5, s->qscale); /* GQUANT */
363
    }
364
}
365

    
366
static inline int get_block_rate(MpegEncContext * s, DCTELEM block[64], int block_last_index, uint8_t scantable[64]){
367
    int last=0;
368
    int j;
369
    int rate=0;
370

    
371
    for(j=1; j<=block_last_index; j++){
372
        const int index= scantable[j];
373
        int level= block[index];
374
        if(level){
375
            level+= 64;
376
            if((level&(~127)) == 0){
377
                if(j<block_last_index) rate+= s->intra_ac_vlc_length     [UNI_AC_ENC_INDEX(j-last-1, level)];
378
                else                   rate+= s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j-last-1, level)];
379
            }else
380
                rate += s->ac_esc_length;
381
            level-= 64;
382

    
383
            last= j;
384
        }
385
    }
386
    
387
    return rate;
388
}
389

    
390
static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
391
{
392
    int score= 0;
393
    int i, n;
394
    int8_t * const qscale_table= s->current_picture.qscale_table;
395

    
396
    memcpy(zigzag_last_index, s->block_last_index, sizeof(int)*6);
397
    
398
    for(n=0; n<6; n++){
399
        int16_t *ac_val, *ac_val1;
400
        
401
        score -= get_block_rate(s, block[n], s->block_last_index[n], s->intra_scantable.permutated);
402

    
403
        ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
404
        ac_val1= ac_val;
405
        if(dir[n]){
406
            const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
407
            /* top prediction */
408
            ac_val-= s->block_wrap[n]*16;
409
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
410
                /* same qscale */
411
                for(i=1; i<8; i++){
412
                    const int level= block[n][s->dsp.idct_permutation[i   ]];
413
                    block[n][s->dsp.idct_permutation[i   ]] = level - ac_val[i+8];
414
                    ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
415
                    ac_val1[i+8]= level;
416
                }
417
            }else{
418
                /* different qscale, we must rescale */
419
                for(i=1; i<8; i++){
420
                    const int level= block[n][s->dsp.idct_permutation[i   ]];
421
                    block[n][s->dsp.idct_permutation[i   ]] = level - ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
422
                    ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
423
                    ac_val1[i+8]= level;
424
                }
425
            }
426
            st[n]= s->intra_h_scantable.permutated;
427
        }else{
428
            const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
429
            /* left prediction */
430
            ac_val-= 16;
431
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
432
                /* same qscale */
433
                for(i=1; i<8; i++){
434
                    const int level= block[n][s->dsp.idct_permutation[i<<3]];
435
                    block[n][s->dsp.idct_permutation[i<<3]]= level - ac_val[i];
436
                    ac_val1[i  ]= level;
437
                    ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
438
                }
439
            }else{
440
                /* different qscale, we must rescale */
441
                for(i=1; i<8; i++){
442
                    const int level= block[n][s->dsp.idct_permutation[i<<3]];
443
                    block[n][s->dsp.idct_permutation[i<<3]]= level - ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
444
                    ac_val1[i  ]= level;
445
                    ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
446
                }
447
            }
448
            st[n]= s->intra_v_scantable.permutated;
449
        }
450

    
451
        for(i=63; i>0; i--) //FIXME optimize
452
            if(block[n][ st[n][i] ]) break;
453
        s->block_last_index[n]= i;
454

    
455
        score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
456
    }
457

    
458
    return score < 0;
459
}
460

    
461
static inline void restore_ac_coeffs(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
462
{
463
    int i, n;
464
    memcpy(s->block_last_index, zigzag_last_index, sizeof(int)*6);
465

    
466
    for(n=0; n<6; n++){
467
        int16_t *ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
468

    
469
        st[n]= s->intra_scantable.permutated;
470
        if(dir[n]){
471
            /* top prediction */
472
            for(i=1; i<8; i++){
473
                block[n][s->dsp.idct_permutation[i   ]] = ac_val[i+8];
474
            }
475
        }else{
476
            /* left prediction */
477
            for(i=1; i<8; i++){
478
                block[n][s->dsp.idct_permutation[i<<3]]= ac_val[i  ];
479
            }
480
        }
481
    }
482
}
483

    
484
/**
485
 * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
486
 */
487
void ff_clean_h263_qscales(MpegEncContext *s){
488
    int i;
489
    int8_t * const qscale_table= s->current_picture.qscale_table;
490
    
491
    for(i=1; i<s->mb_num; i++){
492
        if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i-1] ] >2)
493
            qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i-1] ]+2;
494
    }
495
    for(i=s->mb_num-2; i>=0; i--){
496
        if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i+1] ] >2)
497
            qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i+1] ]+2;
498
    }
499

    
500
    if(s->codec_id != CODEC_ID_H263P){
501
        for(i=1; i<s->mb_num; i++){
502
            int mb_xy= s->mb_index2xy[i];
503
        
504
            if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTER4V)){
505
                s->mb_type[mb_xy]&= ~CANDIDATE_MB_TYPE_INTER4V;
506
                s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_INTER;
507
            }
508
        }
509
    }
510
}
511

    
512
/**
513
 * modify mb_type & qscale so that encoding is acually possible in mpeg4
514
 */
515
void ff_clean_mpeg4_qscales(MpegEncContext *s){
516
    int i;
517
    int8_t * const qscale_table= s->current_picture.qscale_table;
518

    
519
    ff_clean_h263_qscales(s);
520
    
521
    if(s->pict_type== B_TYPE){
522
        int odd=0;
523
        /* ok, come on, this isnt funny anymore, theres more code for handling this mpeg4 mess than
524
           for the actual adaptive quantization */
525
        
526
        for(i=0; i<s->mb_num; i++){
527
            int mb_xy= s->mb_index2xy[i];
528
            odd += qscale_table[mb_xy]&1;
529
        }
530
        
531
        if(2*odd > s->mb_num) odd=1;
532
        else                  odd=0;
533
        
534
        for(i=0; i<s->mb_num; i++){
535
            int mb_xy= s->mb_index2xy[i];
536
            if((qscale_table[mb_xy]&1) != odd)
537
                qscale_table[mb_xy]++;
538
            if(qscale_table[mb_xy] > 31)
539
                qscale_table[mb_xy]= 31;
540
        }            
541
    
542
        for(i=1; i<s->mb_num; i++){
543
            int mb_xy= s->mb_index2xy[i];
544
            if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_DIRECT)){
545
                s->mb_type[mb_xy]&= ~CANDIDATE_MB_TYPE_DIRECT;
546
                s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_BIDIR;
547
            }
548
        }
549
    }
550
}
551

    
552
#endif //CONFIG_ENCODERS
553
/**
554
 *
555
 * @return the mb_type
556
 */
557
int ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
558
    const int mb_index= s->mb_x + s->mb_y*s->mb_stride;
559
    const int colocated_mb_type= s->next_picture.mb_type[mb_index];
560
    int xy= s->block_index[0];
561
    uint16_t time_pp= s->pp_time;
562
    uint16_t time_pb= s->pb_time;
563
    int i;
564
    
565
    //FIXME avoid divides
566
    
567
    if(IS_8X8(colocated_mb_type)){
568
        s->mv_type = MV_TYPE_8X8;
569
        for(i=0; i<4; i++){
570
            xy= s->block_index[i];
571
            s->mv[0][i][0] = s->next_picture.motion_val[0][xy][0]*time_pb/time_pp + mx;
572
            s->mv[0][i][1] = s->next_picture.motion_val[0][xy][1]*time_pb/time_pp + my;
573
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->next_picture.motion_val[0][xy][0]
574
                                : s->next_picture.motion_val[0][xy][0]*(time_pb - time_pp)/time_pp;
575
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->next_picture.motion_val[0][xy][1] 
576
                                : s->next_picture.motion_val[0][xy][1]*(time_pb - time_pp)/time_pp;
577
        }
578
        return MB_TYPE_DIRECT2 | MB_TYPE_8x8 | MB_TYPE_L0L1;
579
    } else if(IS_INTERLACED(colocated_mb_type)){
580
        s->mv_type = MV_TYPE_FIELD;
581
        for(i=0; i<2; i++){
582
            int field_select= s->next_picture.ref_index[0][s->block_index[2*i]];
583
            if(s->top_field_first){
584
                time_pp= s->pp_field_time - field_select + i;
585
                time_pb= s->pb_field_time - field_select + i;
586
            }else{
587
                time_pp= s->pp_field_time + field_select - i;
588
                time_pb= s->pb_field_time + field_select - i;
589
            }
590
            s->mv[0][i][0] = s->p_field_mv_table[i][0][mb_index][0]*time_pb/time_pp + mx;
591
            s->mv[0][i][1] = s->p_field_mv_table[i][0][mb_index][1]*time_pb/time_pp + my;
592
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->p_field_mv_table[i][0][mb_index][0]
593
                                : s->p_field_mv_table[i][0][mb_index][0]*(time_pb - time_pp)/time_pp;
594
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->p_field_mv_table[i][0][mb_index][1] 
595
                                : s->p_field_mv_table[i][0][mb_index][1]*(time_pb - time_pp)/time_pp;
596
        }
597
        return MB_TYPE_DIRECT2 | MB_TYPE_16x8 | MB_TYPE_L0L1 | MB_TYPE_INTERLACED;
598
    }else{
599
        s->mv[0][0][0] = s->mv[0][1][0] = s->mv[0][2][0] = s->mv[0][3][0] = s->next_picture.motion_val[0][xy][0]*time_pb/time_pp + mx;
600
        s->mv[0][0][1] = s->mv[0][1][1] = s->mv[0][2][1] = s->mv[0][3][1] = s->next_picture.motion_val[0][xy][1]*time_pb/time_pp + my;
601
        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->next_picture.motion_val[0][xy][0]
602
                            : s->next_picture.motion_val[0][xy][0]*(time_pb - time_pp)/time_pp;
603
        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->next_picture.motion_val[0][xy][1] 
604
                            : s->next_picture.motion_val[0][xy][1]*(time_pb - time_pp)/time_pp;
605
        if((s->avctx->workaround_bugs & FF_BUG_DIRECT_BLOCKSIZE) || !s->quarter_sample)
606
            s->mv_type= MV_TYPE_16X16;
607
        else
608
            s->mv_type= MV_TYPE_8X8;
609
        return MB_TYPE_DIRECT2 | MB_TYPE_16x16 | MB_TYPE_L0L1; //Note see prev line
610
    }
611
}
612

    
613
void ff_h263_update_motion_val(MpegEncContext * s){
614
    const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
615
               //FIXME a lot of thet is only needed for !low_delay
616
    const int wrap = s->b8_stride;
617
    const int xy = s->block_index[0];
618
    
619
    s->current_picture.mbskip_table[mb_xy]= s->mb_skiped; 
620

    
621
    if(s->mv_type != MV_TYPE_8X8){
622
        int motion_x, motion_y;
623
        if (s->mb_intra) {
624
            motion_x = 0;
625
            motion_y = 0;
626
        } else if (s->mv_type == MV_TYPE_16X16) {
627
            motion_x = s->mv[0][0][0];
628
            motion_y = s->mv[0][0][1];
629
        } else /*if (s->mv_type == MV_TYPE_FIELD)*/ {
630
            int i;
631
            motion_x = s->mv[0][0][0] + s->mv[0][1][0];
632
            motion_y = s->mv[0][0][1] + s->mv[0][1][1];
633
            motion_x = (motion_x>>1) | (motion_x&1);
634
            for(i=0; i<2; i++){
635
                s->p_field_mv_table[i][0][mb_xy][0]= s->mv[0][i][0];
636
                s->p_field_mv_table[i][0][mb_xy][1]= s->mv[0][i][1];
637
            }
638
            s->current_picture.ref_index[0][xy           ]=
639
            s->current_picture.ref_index[0][xy        + 1]= s->field_select[0][0];
640
            s->current_picture.ref_index[0][xy + wrap    ]=
641
            s->current_picture.ref_index[0][xy + wrap + 1]= s->field_select[0][1];
642
        }
643

    
644
        /* no update if 8X8 because it has been done during parsing */
645
        s->current_picture.motion_val[0][xy][0] = motion_x;
646
        s->current_picture.motion_val[0][xy][1] = motion_y;
647
        s->current_picture.motion_val[0][xy + 1][0] = motion_x;
648
        s->current_picture.motion_val[0][xy + 1][1] = motion_y;
649
        s->current_picture.motion_val[0][xy + wrap][0] = motion_x;
650
        s->current_picture.motion_val[0][xy + wrap][1] = motion_y;
651
        s->current_picture.motion_val[0][xy + 1 + wrap][0] = motion_x;
652
        s->current_picture.motion_val[0][xy + 1 + wrap][1] = motion_y;
653
    }
654

    
655
    if(s->encoding){ //FIXME encoding MUST be cleaned up
656
        if (s->mv_type == MV_TYPE_8X8) 
657
            s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_8x8;
658
        else if(s->mb_intra)
659
            s->current_picture.mb_type[mb_xy]= MB_TYPE_INTRA;
660
        else
661
            s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_16x16;
662
    }
663
}
664

    
665
#ifdef CONFIG_ENCODERS
666

    
667
static inline int get_p_cbp(MpegEncContext * s,
668
                      DCTELEM block[6][64],
669
                      int motion_x, int motion_y){
670
    int cbp, i;
671

    
672
    if(s->flags & CODEC_FLAG_CBP_RD){
673
        int best_cbpy_score= INT_MAX;
674
        int best_cbpc_score= INT_MAX;
675
        int cbpc = (-1), cbpy= (-1);
676
        const int offset= (s->mv_type==MV_TYPE_16X16 ? 0 : 16) + (s->dquant ? 8 : 0);
677
        const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
678

    
679
        for(i=0; i<4; i++){
680
            int score= inter_MCBPC_bits[i + offset] * lambda;
681
            if(i&1) score += s->coded_score[5];
682
            if(i&2) score += s->coded_score[4];
683

    
684
            if(score < best_cbpc_score){
685
                best_cbpc_score= score;
686
                cbpc= i;
687
            }
688
        }
689

    
690
        for(i=0; i<16; i++){
691
            int score= cbpy_tab[i ^ 0xF][1] * lambda;
692
            if(i&1) score += s->coded_score[3];
693
            if(i&2) score += s->coded_score[2];
694
            if(i&4) score += s->coded_score[1];
695
            if(i&8) score += s->coded_score[0];
696

    
697
            if(score < best_cbpy_score){
698
                best_cbpy_score= score;
699
                cbpy= i;
700
            }
701
        }
702
        cbp= cbpc + 4*cbpy;
703
        if ((motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16){
704
            if(best_cbpy_score + best_cbpc_score + 2*lambda >= 0)
705
                cbp= 0;
706
        }
707

    
708
        for (i = 0; i < 6; i++) {
709
            if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
710
                s->block_last_index[i]= -1;
711
                memset(s->block[i], 0, sizeof(DCTELEM)*64);
712
            }
713
        }
714
    }else{
715
        cbp= 0;
716
        for (i = 0; i < 6; i++) {
717
            if (s->block_last_index[i] >= 0)
718
                cbp |= 1 << (5 - i);
719
        }
720
    }
721
    return cbp;
722
}
723

    
724
static inline int get_b_cbp(MpegEncContext * s, DCTELEM block[6][64],
725
                            int motion_x, int motion_y, int mb_type){
726
    int cbp=0, i;
727

    
728
    if(s->flags & CODEC_FLAG_CBP_RD){
729
        int score=0;
730
        const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
731
        
732
        for(i=0; i<6; i++){
733
            if(s->coded_score[i] < 0){
734
                score += s->coded_score[i];
735
                cbp |= 1 << (5 - i);
736
            }
737
        }
738
        
739
        if(cbp){
740
            int zero_score= -6;
741
            if ((motion_x | motion_y | s->dquant | mb_type) == 0){
742
                zero_score-= 4; //2*MV + mb_type + cbp bit
743
            }
744

    
745
            zero_score*= lambda;
746
            if(zero_score <= score){
747
                cbp=0;
748
            }
749
        }
750

    
751
        for (i = 0; i < 6; i++) {
752
            if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
753
                s->block_last_index[i]= -1;
754
                memset(s->block[i], 0, sizeof(DCTELEM)*64);
755
            }
756
        }
757
    }else{
758
        for (i = 0; i < 6; i++) {
759
            if (s->block_last_index[i] >= 0)
760
                cbp |= 1 << (5 - i);
761
        }
762
    }
763
    return cbp;
764
}
765

    
766
void mpeg4_encode_mb(MpegEncContext * s,
767
                    DCTELEM block[6][64],
768
                    int motion_x, int motion_y)
769
{
770
    int cbpc, cbpy, pred_x, pred_y;
771
    PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
772
    PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=B_TYPE ? &s->tex_pb : &s->pb;
773
    PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=I_TYPE ? &s->pb2    : &s->pb;
774
    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
775
    const int dquant_code[5]= {1,0,9,2,3};
776
    
777
    //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
778
    if (!s->mb_intra) {
779
        int i, cbp;
780
        
781
        if(s->pict_type==B_TYPE){
782
            static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
783
            int mb_type=  mb_type_table[s->mv_dir];
784

    
785
            if(s->mb_x==0){
786
                for(i=0; i<2; i++){
787
                    s->last_mv[i][0][0]= 
788
                    s->last_mv[i][0][1]= 
789
                    s->last_mv[i][1][0]= 
790
                    s->last_mv[i][1][1]= 0;
791
                }
792
            }
793
            
794
            assert(s->dquant>=-2 && s->dquant<=2);
795
            assert((s->dquant&1)==0);
796
            assert(mb_type>=0);
797

    
798
            /* nothing to do if this MB was skiped in the next P Frame */
799
            if(s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]){ //FIXME avoid DCT & ...
800
                s->skip_count++;
801
                s->mv[0][0][0]= 
802
                s->mv[0][0][1]= 
803
                s->mv[1][0][0]= 
804
                s->mv[1][0][1]= 0;
805
                s->mv_dir= MV_DIR_FORWARD; //doesnt matter
806
                s->qscale -= s->dquant;
807
//                s->mb_skiped=1;
808

    
809
                return;
810
            }
811
            
812
            cbp= get_b_cbp(s, block, motion_x, motion_y, mb_type);
813
            
814
            if ((cbp | motion_x | motion_y | mb_type) ==0) {
815
                /* direct MB with MV={0,0} */
816
                assert(s->dquant==0);
817
                
818
                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
819

    
820
                if(interleaved_stats){
821
                    s->misc_bits++;
822
                    s->last_bits++;
823
                }
824
                s->skip_count++;
825
                return;
826
            }
827
            
828
            put_bits(&s->pb, 1, 0);        /* mb coded modb1=0 */
829
            put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
830
            put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we dont need it :)
831
            if(cbp) put_bits(&s->pb, 6, cbp);
832
            
833
            if(cbp && mb_type){
834
                if(s->dquant)
835
                    put_bits(&s->pb, 2, (s->dquant>>2)+3);
836
                else
837
                    put_bits(&s->pb, 1, 0);
838
            }else
839
                s->qscale -= s->dquant;
840
            
841
            if(!s->progressive_sequence){
842
                if(cbp)
843
                    put_bits(&s->pb, 1, s->interlaced_dct);
844
                if(mb_type) // not diect mode
845
                    put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
846
            }
847

    
848
            if(interleaved_stats){
849
                s->misc_bits+= get_bits_diff(s);
850
            }
851

    
852
            if(mb_type == 0){
853
                assert(s->mv_dir & MV_DIRECT);
854
                h263_encode_motion(s, motion_x, 1);
855
                h263_encode_motion(s, motion_y, 1);                
856
                s->b_count++;
857
                s->f_count++;
858
            }else{
859
                assert(mb_type > 0 && mb_type < 4);
860
                if(s->mv_type != MV_TYPE_FIELD){
861
                    if(s->mv_dir & MV_DIR_FORWARD){
862
                        h263_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
863
                        h263_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
864
                        s->last_mv[0][0][0]= s->last_mv[0][1][0]= s->mv[0][0][0];
865
                        s->last_mv[0][0][1]= s->last_mv[0][1][1]= s->mv[0][0][1];
866
                        s->f_count++;
867
                    }
868
                    if(s->mv_dir & MV_DIR_BACKWARD){
869
                        h263_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
870
                        h263_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
871
                        s->last_mv[1][0][0]= s->last_mv[1][1][0]= s->mv[1][0][0];
872
                        s->last_mv[1][0][1]= s->last_mv[1][1][1]= s->mv[1][0][1];
873
                        s->b_count++;
874
                    }
875
                }else{
876
                    if(s->mv_dir & MV_DIR_FORWARD){
877
                        put_bits(&s->pb, 1, s->field_select[0][0]);
878
                        put_bits(&s->pb, 1, s->field_select[0][1]);
879
                    }
880
                    if(s->mv_dir & MV_DIR_BACKWARD){
881
                        put_bits(&s->pb, 1, s->field_select[1][0]);
882
                        put_bits(&s->pb, 1, s->field_select[1][1]);
883
                    }
884
                    if(s->mv_dir & MV_DIR_FORWARD){
885
                        for(i=0; i<2; i++){
886
                            h263_encode_motion(s, s->mv[0][i][0] - s->last_mv[0][i][0]  , s->f_code);
887
                            h263_encode_motion(s, s->mv[0][i][1] - s->last_mv[0][i][1]/2, s->f_code);
888
                            s->last_mv[0][i][0]= s->mv[0][i][0];
889
                            s->last_mv[0][i][1]= s->mv[0][i][1]*2;
890
                        }
891
                        s->f_count++;
892
                    }
893
                    if(s->mv_dir & MV_DIR_BACKWARD){
894
                        for(i=0; i<2; i++){
895
                            h263_encode_motion(s, s->mv[1][i][0] - s->last_mv[1][i][0]  , s->b_code);
896
                            h263_encode_motion(s, s->mv[1][i][1] - s->last_mv[1][i][1]/2, s->b_code);
897
                            s->last_mv[1][i][0]= s->mv[1][i][0];
898
                            s->last_mv[1][i][1]= s->mv[1][i][1]*2;
899
                        }
900
                        s->b_count++;
901
                    }
902
                }
903
            }
904

    
905
            if(interleaved_stats){
906
                s->mv_bits+= get_bits_diff(s);
907
            }
908

    
909
            /* encode each block */
910
            for (i = 0; i < 6; i++) {
911
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, &s->pb);
912
            }
913

    
914
            if(interleaved_stats){
915
                s->p_tex_bits+= get_bits_diff(s);
916
            }
917

    
918
        }else{ /* s->pict_type==B_TYPE */
919
            cbp= get_p_cbp(s, block, motion_x, motion_y);
920
        
921
            if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
922
                /* check if the B frames can skip it too, as we must skip it if we skip here 
923
                   why didnt they just compress the skip-mb bits instead of reusing them ?! */
924
                if(s->max_b_frames>0){
925
                    int i;
926
                    int x,y, offset;
927
                    uint8_t *p_pic;
928

    
929
                    x= s->mb_x*16;
930
                    y= s->mb_y*16;
931
                    if(x+16 > s->width)  x= s->width-16;
932
                    if(y+16 > s->height) y= s->height-16;
933

    
934
                    offset= x + y*s->linesize;
935
                    p_pic= s->new_picture.data[0] + offset;
936
                    
937
                    s->mb_skiped=1;
938
                    for(i=0; i<s->max_b_frames; i++){
939
                        uint8_t *b_pic;
940
                        int diff;
941
                        Picture *pic= s->reordered_input_picture[i+1];
942

    
943
                        if(pic==NULL || pic->pict_type!=B_TYPE) break;
944

    
945
                        b_pic= pic->data[0] + offset + 16; //FIXME +16
946
                        diff= s->dsp.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
947
                        if(diff>s->qscale*70){ //FIXME check that 70 is optimal
948
                            s->mb_skiped=0;
949
                            break;
950
                        }
951
                    }
952
                }else
953
                    s->mb_skiped=1; 
954

    
955
                if(s->mb_skiped==1){
956
                    /* skip macroblock */
957
                    put_bits(&s->pb, 1, 1);
958

    
959
                    if(interleaved_stats){
960
                        s->misc_bits++;
961
                        s->last_bits++;
962
                    }
963
                    s->skip_count++;
964
                    
965
                    return;
966
                }
967
            }
968

    
969
            put_bits(&s->pb, 1, 0);        /* mb coded */
970
            cbpc = cbp & 3;
971
            cbpy = cbp >> 2;
972
            cbpy ^= 0xf;
973
            if(s->mv_type==MV_TYPE_16X16){
974
                if(s->dquant) cbpc+= 8;
975
                put_bits(&s->pb,
976
                        inter_MCBPC_bits[cbpc],
977
                        inter_MCBPC_code[cbpc]);
978

    
979
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
980
                if(s->dquant)
981
                    put_bits(pb2, 2, dquant_code[s->dquant+2]);
982

    
983
                if(!s->progressive_sequence){
984
                    if(cbp)
985
                        put_bits(pb2, 1, s->interlaced_dct);
986
                    put_bits(pb2, 1, 0);
987
                }
988
                    
989
                if(interleaved_stats){
990
                    s->misc_bits+= get_bits_diff(s);
991
                }
992

    
993
                /* motion vectors: 16x16 mode */
994
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
995
            
996
                h263_encode_motion(s, motion_x - pred_x, s->f_code);
997
                h263_encode_motion(s, motion_y - pred_y, s->f_code);
998
            }else if(s->mv_type==MV_TYPE_FIELD){
999
                if(s->dquant) cbpc+= 8;
1000
                put_bits(&s->pb,
1001
                        inter_MCBPC_bits[cbpc],
1002
                        inter_MCBPC_code[cbpc]);
1003

    
1004
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1005
                if(s->dquant)
1006
                    put_bits(pb2, 2, dquant_code[s->dquant+2]);
1007

    
1008
                assert(!s->progressive_sequence);
1009
                if(cbp)
1010
                    put_bits(pb2, 1, s->interlaced_dct);
1011
                put_bits(pb2, 1, 1);
1012
                    
1013
                if(interleaved_stats){
1014
                    s->misc_bits+= get_bits_diff(s);
1015
                }
1016

    
1017
                /* motion vectors: 16x8 interlaced mode */
1018
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1019
                pred_y /=2;
1020
                
1021
                put_bits(&s->pb, 1, s->field_select[0][0]);
1022
                put_bits(&s->pb, 1, s->field_select[0][1]);
1023
            
1024
                h263_encode_motion(s, s->mv[0][0][0] - pred_x, s->f_code);
1025
                h263_encode_motion(s, s->mv[0][0][1] - pred_y, s->f_code);
1026
                h263_encode_motion(s, s->mv[0][1][0] - pred_x, s->f_code);
1027
                h263_encode_motion(s, s->mv[0][1][1] - pred_y, s->f_code);
1028
            }else{
1029
                assert(s->mv_type==MV_TYPE_8X8);
1030
                put_bits(&s->pb,
1031
                        inter_MCBPC_bits[cbpc+16],
1032
                        inter_MCBPC_code[cbpc+16]);
1033
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1034

    
1035
                if(!s->progressive_sequence){
1036
                    if(cbp)
1037
                        put_bits(pb2, 1, s->interlaced_dct);
1038
                }
1039
    
1040
                if(interleaved_stats){
1041
                    s->misc_bits+= get_bits_diff(s);
1042
                }
1043

    
1044
                for(i=0; i<4; i++){
1045
                    /* motion vectors: 8x8 mode*/
1046
                    h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1047

    
1048
                    h263_encode_motion(s, s->current_picture.motion_val[0][ s->block_index[i] ][0] - pred_x, s->f_code);
1049
                    h263_encode_motion(s, s->current_picture.motion_val[0][ s->block_index[i] ][1] - pred_y, s->f_code);
1050
                }
1051
            }
1052

    
1053
            if(interleaved_stats){ 
1054
                s->mv_bits+= get_bits_diff(s);
1055
            }
1056

    
1057
            /* encode each block */
1058
            for (i = 0; i < 6; i++) {
1059
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, tex_pb);
1060
            }
1061

    
1062
            if(interleaved_stats){
1063
                s->p_tex_bits+= get_bits_diff(s);
1064
            }
1065
            s->f_count++;
1066
        }
1067
    } else {
1068
        int cbp;
1069
        int dc_diff[6];   //dc values with the dc prediction subtracted 
1070
        int dir[6];  //prediction direction
1071
        int zigzag_last_index[6];
1072
        uint8_t *scan_table[6];
1073
        int i;
1074

    
1075
        for(i=0; i<6; i++){
1076
            dc_diff[i]= ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
1077
        }
1078

    
1079
        if(s->flags & CODEC_FLAG_AC_PRED){
1080
            s->ac_pred= decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
1081
            if(!s->ac_pred)
1082
                restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1083
        }else{
1084
            for(i=0; i<6; i++)
1085
                scan_table[i]= s->intra_scantable.permutated;
1086
        }
1087

    
1088
        /* compute cbp */
1089
        cbp = 0;
1090
        for (i = 0; i < 6; i++) {
1091
            if (s->block_last_index[i] >= 1)
1092
                cbp |= 1 << (5 - i);
1093
        }
1094

    
1095
        cbpc = cbp & 3;
1096
        if (s->pict_type == I_TYPE) {
1097
            if(s->dquant) cbpc+=4;
1098
            put_bits(&s->pb,
1099
                intra_MCBPC_bits[cbpc],
1100
                intra_MCBPC_code[cbpc]);
1101
        } else {
1102
            if(s->dquant) cbpc+=8;
1103
            put_bits(&s->pb, 1, 0);        /* mb coded */
1104
            put_bits(&s->pb,
1105
                inter_MCBPC_bits[cbpc + 4],
1106
                inter_MCBPC_code[cbpc + 4]);
1107
        }
1108
        put_bits(pb2, 1, s->ac_pred);
1109
        cbpy = cbp >> 2;
1110
        put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1111
        if(s->dquant)
1112
            put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
1113

    
1114
        if(!s->progressive_sequence){
1115
            put_bits(dc_pb, 1, s->interlaced_dct);
1116
        }
1117

    
1118
        if(interleaved_stats){
1119
            s->misc_bits+= get_bits_diff(s);
1120
        }
1121

    
1122
        /* encode each block */
1123
        for (i = 0; i < 6; i++) {
1124
            mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
1125
        }
1126

    
1127
        if(interleaved_stats){
1128
            s->i_tex_bits+= get_bits_diff(s);
1129
        }
1130
        s->i_count++;
1131

    
1132
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
1133
        if(s->ac_pred)
1134
            restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1135
    }
1136
}
1137

    
1138
void h263_encode_mb(MpegEncContext * s,
1139
                    DCTELEM block[6][64],
1140
                    int motion_x, int motion_y)
1141
{
1142
    int cbpc, cbpy, i, cbp, pred_x, pred_y;
1143
    int16_t pred_dc;
1144
    int16_t rec_intradc[6];
1145
    uint16_t *dc_ptr[6];
1146
    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1);
1147
    const int dquant_code[5]= {1,0,9,2,3};
1148
           
1149
    //printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
1150
    if (!s->mb_intra) {
1151
        /* compute cbp */
1152
        cbp= get_p_cbp(s, block, motion_x, motion_y);
1153

    
1154
        if ((cbp | motion_x | motion_y | s->dquant | (s->mv_type - MV_TYPE_16X16)) == 0) {
1155
            /* skip macroblock */
1156
            put_bits(&s->pb, 1, 1);
1157
            if(interleaved_stats){
1158
                s->misc_bits++;
1159
                s->last_bits++;
1160
            }
1161
            s->skip_count++;
1162

    
1163
            return;
1164
        }
1165
        put_bits(&s->pb, 1, 0);        /* mb coded */
1166
        
1167
        cbpc = cbp & 3;
1168
        cbpy = cbp >> 2;
1169
        if(s->alt_inter_vlc==0 || cbpc!=3)
1170
            cbpy ^= 0xF;
1171
        if(s->dquant) cbpc+= 8;
1172
        if(s->mv_type==MV_TYPE_16X16){
1173
            put_bits(&s->pb,
1174
                    inter_MCBPC_bits[cbpc],
1175
                    inter_MCBPC_code[cbpc]);
1176

    
1177
            put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1178
            if(s->dquant)
1179
                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1180
                
1181
            if(interleaved_stats){
1182
                s->misc_bits+= get_bits_diff(s);
1183
            }
1184

    
1185
            /* motion vectors: 16x16 mode */
1186
            h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1187
            
1188
            if (!s->umvplus) {  
1189
                h263_encode_motion(s, motion_x - pred_x, 1);
1190
                h263_encode_motion(s, motion_y - pred_y, 1);
1191
            }
1192
            else {
1193
                h263p_encode_umotion(s, motion_x - pred_x);
1194
                h263p_encode_umotion(s, motion_y - pred_y);
1195
                if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1196
                    /* To prevent Start Code emulation */
1197
                    put_bits(&s->pb,1,1);
1198
            }
1199
        }else{
1200
            put_bits(&s->pb,
1201
                    inter_MCBPC_bits[cbpc+16],
1202
                    inter_MCBPC_code[cbpc+16]);
1203
            put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1204
            if(s->dquant)
1205
                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1206

    
1207
            if(interleaved_stats){
1208
                s->misc_bits+= get_bits_diff(s);
1209
            }
1210

    
1211
            for(i=0; i<4; i++){
1212
                /* motion vectors: 8x8 mode*/
1213
                h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1214

    
1215
                motion_x= s->current_picture.motion_val[0][ s->block_index[i] ][0];
1216
                motion_y= s->current_picture.motion_val[0][ s->block_index[i] ][1];
1217
                if (!s->umvplus) {  
1218
                    h263_encode_motion(s, motion_x - pred_x, 1);
1219
                    h263_encode_motion(s, motion_y - pred_y, 1);
1220
                }
1221
                else {
1222
                    h263p_encode_umotion(s, motion_x - pred_x);
1223
                    h263p_encode_umotion(s, motion_y - pred_y);
1224
                    if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1225
                        /* To prevent Start Code emulation */
1226
                        put_bits(&s->pb,1,1);
1227
                }
1228
            }
1229
        }
1230

    
1231
        if(interleaved_stats){
1232
            s->mv_bits+= get_bits_diff(s);
1233
        }
1234
    } else {
1235
        assert(s->mb_intra);
1236
        
1237
        cbp = 0;
1238
        if (s->h263_aic) {
1239
            /* Predict DC */
1240
            for(i=0; i<6; i++) {
1241
                int16_t level = block[i][0];
1242
                int scale;
1243
                
1244
                if(i<4) scale= s->y_dc_scale;
1245
                else    scale= s->c_dc_scale;
1246

    
1247
                pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
1248
                level -= pred_dc;
1249
                /* Quant */
1250
                if (level >= 0)
1251
                    level = (level + (scale>>1))/scale;
1252
                else
1253
                    level = (level - (scale>>1))/scale;
1254
                    
1255
                /* AIC can change CBP */
1256
                if (level == 0 && s->block_last_index[i] == 0)
1257
                    s->block_last_index[i] = -1;
1258

    
1259
                if(!s->modified_quant){
1260
                    if (level < -127)
1261
                        level = -127;
1262
                    else if (level > 127)
1263
                        level = 127;
1264
                }
1265

    
1266
                block[i][0] = level;
1267
                /* Reconstruction */ 
1268
                rec_intradc[i] = scale*level + pred_dc;
1269
                /* Oddify */
1270
                rec_intradc[i] |= 1;
1271
                //if ((rec_intradc[i] % 2) == 0)
1272
                //    rec_intradc[i]++;
1273
                /* Clipping */
1274
                if (rec_intradc[i] < 0)
1275
                    rec_intradc[i] = 0;
1276
                else if (rec_intradc[i] > 2047)
1277
                    rec_intradc[i] = 2047;
1278
                                
1279
                /* Update AC/DC tables */
1280
                *dc_ptr[i] = rec_intradc[i];
1281
                if (s->block_last_index[i] >= 0)
1282
                    cbp |= 1 << (5 - i);
1283
            }
1284
        }else{
1285
            for(i=0; i<6; i++) {
1286
                /* compute cbp */
1287
                if (s->block_last_index[i] >= 1)
1288
                    cbp |= 1 << (5 - i);
1289
            }
1290
        }
1291

    
1292
        cbpc = cbp & 3;
1293
        if (s->pict_type == I_TYPE) {
1294
            if(s->dquant) cbpc+=4;
1295
            put_bits(&s->pb,
1296
                intra_MCBPC_bits[cbpc],
1297
                intra_MCBPC_code[cbpc]);
1298
        } else {
1299
            if(s->dquant) cbpc+=8;
1300
            put_bits(&s->pb, 1, 0);        /* mb coded */
1301
            put_bits(&s->pb,
1302
                inter_MCBPC_bits[cbpc + 4],
1303
                inter_MCBPC_code[cbpc + 4]);
1304
        }
1305
        if (s->h263_aic) {
1306
            /* XXX: currently, we do not try to use ac prediction */
1307
            put_bits(&s->pb, 1, 0);        /* no AC prediction */
1308
        }
1309
        cbpy = cbp >> 2;
1310
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1311
        if(s->dquant)
1312
            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1313

    
1314
        if(interleaved_stats){
1315
            s->misc_bits+= get_bits_diff(s);
1316
        }
1317
    }
1318

    
1319
    for(i=0; i<6; i++) {
1320
        /* encode each block */
1321
        h263_encode_block(s, block[i], i);
1322
    
1323
        /* Update INTRADC for decoding */
1324
        if (s->h263_aic && s->mb_intra) {
1325
            block[i][0] = rec_intradc[i];
1326
            
1327
        }
1328
    }
1329

    
1330
    if(interleaved_stats){
1331
        if (!s->mb_intra) {
1332
            s->p_tex_bits+= get_bits_diff(s);
1333
            s->f_count++;
1334
        }else{
1335
            s->i_tex_bits+= get_bits_diff(s);
1336
            s->i_count++;
1337
        }
1338
    }
1339
}
1340
#endif
1341

    
1342
void ff_h263_loop_filter(MpegEncContext * s){
1343
    int qp_c;
1344
    const int linesize  = s->linesize;
1345
    const int uvlinesize= s->uvlinesize;
1346
    const int xy = s->mb_y * s->mb_stride + s->mb_x;
1347
    uint8_t *dest_y = s->dest[0];
1348
    uint8_t *dest_cb= s->dest[1];
1349
    uint8_t *dest_cr= s->dest[2];
1350
    
1351
//    if(s->pict_type==B_TYPE && !s->readable) return;
1352

    
1353
    /*
1354
       Diag Top
1355
       Left Center
1356
    */
1357
    if(!IS_SKIP(s->current_picture.mb_type[xy])){
1358
        qp_c= s->qscale;
1359
        s->dsp.h263_v_loop_filter(dest_y+8*linesize  , linesize, qp_c);
1360
        s->dsp.h263_v_loop_filter(dest_y+8*linesize+8, linesize, qp_c);
1361
    }else
1362
        qp_c= 0;
1363

    
1364
    if(s->mb_y){
1365
        int qp_dt, qp_t, qp_tc;
1366

    
1367
        if(IS_SKIP(s->current_picture.mb_type[xy-s->mb_stride]))
1368
            qp_t=0;
1369
        else 
1370
            qp_t= s->current_picture.qscale_table[xy-s->mb_stride];
1371

    
1372
        if(qp_c) 
1373
            qp_tc= qp_c;
1374
        else
1375
            qp_tc= qp_t;
1376
            
1377
        if(qp_tc){
1378
            const int chroma_qp= s->chroma_qscale_table[qp_tc];
1379
            s->dsp.h263_v_loop_filter(dest_y  ,   linesize, qp_tc);
1380
            s->dsp.h263_v_loop_filter(dest_y+8,   linesize, qp_tc);
1381
        
1382
            s->dsp.h263_v_loop_filter(dest_cb , uvlinesize, chroma_qp);
1383
            s->dsp.h263_v_loop_filter(dest_cr , uvlinesize, chroma_qp);
1384
        }
1385
        
1386
        if(qp_t)
1387
            s->dsp.h263_h_loop_filter(dest_y-8*linesize+8  ,   linesize, qp_t);
1388
        
1389
        if(s->mb_x){
1390
            if(qp_t || IS_SKIP(s->current_picture.mb_type[xy-1-s->mb_stride]))
1391
                qp_dt= qp_t;
1392
            else
1393
                qp_dt= s->current_picture.qscale_table[xy-1-s->mb_stride];
1394
            
1395
            if(qp_dt){
1396
                const int chroma_qp= s->chroma_qscale_table[qp_dt];
1397
                s->dsp.h263_h_loop_filter(dest_y -8*linesize  ,   linesize, qp_dt);
1398
                s->dsp.h263_h_loop_filter(dest_cb-8*uvlinesize, uvlinesize, chroma_qp);
1399
                s->dsp.h263_h_loop_filter(dest_cb-8*uvlinesize, uvlinesize, chroma_qp);
1400
            }
1401
        }
1402
    }
1403

    
1404
    if(qp_c){
1405
        s->dsp.h263_h_loop_filter(dest_y +8,   linesize, qp_c);
1406
        if(s->mb_y + 1 == s->mb_height)
1407
            s->dsp.h263_h_loop_filter(dest_y+8*linesize+8,   linesize, qp_c);
1408
    }
1409
    
1410
    if(s->mb_x){
1411
        int qp_lc;
1412
        if(qp_c || IS_SKIP(s->current_picture.mb_type[xy-1]))
1413
            qp_lc= qp_c;
1414
        else
1415
            qp_lc= s->current_picture.qscale_table[xy-1];
1416
        
1417
        if(qp_lc){
1418
            s->dsp.h263_h_loop_filter(dest_y,   linesize, qp_lc);
1419
            if(s->mb_y + 1 == s->mb_height){
1420
                const int chroma_qp= s->chroma_qscale_table[qp_lc];
1421
                s->dsp.h263_h_loop_filter(dest_y +8*  linesize,   linesize, qp_lc);
1422
                s->dsp.h263_h_loop_filter(dest_cb             , uvlinesize, chroma_qp);
1423
                s->dsp.h263_h_loop_filter(dest_cr             , uvlinesize, chroma_qp);
1424
            }
1425
        }
1426
    }
1427
}
1428

    
1429
static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr)
1430
{
1431
    int x, y, wrap, a, c, pred_dc, scale;
1432
    int16_t *dc_val, *ac_val;
1433

    
1434
    /* find prediction */
1435
    if (n < 4) {
1436
        x = 2 * s->mb_x + (n & 1);
1437
        y = 2 * s->mb_y + ((n & 2) >> 1);
1438
        wrap = s->b8_stride;
1439
        dc_val = s->dc_val[0];
1440
        ac_val = s->ac_val[0][0];
1441
        scale = s->y_dc_scale;
1442
    } else {
1443
        x = s->mb_x;
1444
        y = s->mb_y;
1445
        wrap = s->mb_stride;
1446
        dc_val = s->dc_val[n - 4 + 1];
1447
        ac_val = s->ac_val[n - 4 + 1][0];
1448
        scale = s->c_dc_scale;
1449
    }
1450
    /* B C
1451
     * A X 
1452
     */
1453
    a = dc_val[(x - 1) + (y) * wrap];
1454
    c = dc_val[(x) + (y - 1) * wrap];
1455
    
1456
    /* No prediction outside GOB boundary */
1457
    if(s->first_slice_line && n!=3){
1458
        if(n!=2) c= 1024;
1459
        if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
1460
    }
1461
    pred_dc = 1024;
1462
    /* just DC prediction */
1463
    if (a != 1024 && c != 1024)
1464
        pred_dc = (a + c) >> 1;
1465
    else if (a != 1024)
1466
        pred_dc = a;
1467
    else
1468
        pred_dc = c;
1469
    
1470
    /* we assume pred is positive */
1471
    //pred_dc = (pred_dc + (scale >> 1)) / scale;
1472
    *dc_val_ptr = &dc_val[x + y * wrap];
1473
    return pred_dc;
1474
}
1475

    
1476
static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1477
{
1478
    int x, y, wrap, a, c, pred_dc, scale, i;
1479
    int16_t *dc_val, *ac_val, *ac_val1;
1480

    
1481
    /* find prediction */
1482
    if (n < 4) {
1483
        x = 2 * s->mb_x + (n & 1);
1484
        y = 2 * s->mb_y + (n>> 1);
1485
        wrap = s->b8_stride;
1486
        dc_val = s->dc_val[0];
1487
        ac_val = s->ac_val[0][0];
1488
        scale = s->y_dc_scale;
1489
    } else {
1490
        x = s->mb_x;
1491
        y = s->mb_y;
1492
        wrap = s->mb_stride;
1493
        dc_val = s->dc_val[n - 4 + 1];
1494
        ac_val = s->ac_val[n - 4 + 1][0];
1495
        scale = s->c_dc_scale;
1496
    }
1497
    
1498
    ac_val += ((y) * wrap + (x)) * 16;
1499
    ac_val1 = ac_val;
1500
    
1501
    /* B C
1502
     * A X 
1503
     */
1504
    a = dc_val[(x - 1) + (y) * wrap];
1505
    c = dc_val[(x) + (y - 1) * wrap];
1506
    
1507
    /* No prediction outside GOB boundary */
1508
    if(s->first_slice_line && n!=3){
1509
        if(n!=2) c= 1024;
1510
        if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
1511
    }
1512
    
1513
    if (s->ac_pred) {
1514
        pred_dc = 1024;
1515
        if (s->h263_aic_dir) {
1516
            /* left prediction */
1517
            if (a != 1024) {
1518
                ac_val -= 16;
1519
                for(i=1;i<8;i++) {
1520
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1521
                }
1522
                pred_dc = a;
1523
            }
1524
        } else {
1525
            /* top prediction */
1526
            if (c != 1024) {
1527
                ac_val -= 16 * wrap;
1528
                for(i=1;i<8;i++) {
1529
                    block[s->dsp.idct_permutation[i   ]] += ac_val[i + 8];
1530
                }
1531
                pred_dc = c;
1532
            }
1533
        }
1534
    } else {
1535
        /* just DC prediction */
1536
        if (a != 1024 && c != 1024)
1537
            pred_dc = (a + c) >> 1;
1538
        else if (a != 1024)
1539
            pred_dc = a;
1540
        else
1541
            pred_dc = c;
1542
    }
1543
    
1544
    /* we assume pred is positive */
1545
    block[0]=block[0]*scale + pred_dc;
1546
    
1547
    if (block[0] < 0)
1548
        block[0] = 0;
1549
    else 
1550
        block[0] |= 1;
1551
    
1552
    /* Update AC/DC tables */
1553
    dc_val[(x) + (y) * wrap] = block[0];
1554
    
1555
    /* left copy */
1556
    for(i=1;i<8;i++)
1557
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1558
    /* top copy */
1559
    for(i=1;i<8;i++)
1560
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1561
}
1562

    
1563
int16_t *h263_pred_motion(MpegEncContext * s, int block, int dir,
1564
                        int *px, int *py)
1565
{
1566
    int wrap;
1567
    int16_t *A, *B, *C, (*mot_val)[2];
1568
    static const int off[4]= {2, 1, 1, -1};
1569

    
1570
    wrap = s->b8_stride;
1571
    mot_val = s->current_picture.motion_val[dir] + s->block_index[block];
1572

    
1573
    A = mot_val[ - 1];
1574
    /* special case for first (slice) line */
1575
    if (s->first_slice_line && block<3) {
1576
        // we cant just change some MVs to simulate that as we need them for the B frames (and ME)
1577
        // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1578
        if(block==0){ //most common case
1579
            if(s->mb_x  == s->resync_mb_x){ //rare
1580
                *px= *py = 0;
1581
            }else if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1582
                C = mot_val[off[block] - wrap];
1583
                if(s->mb_x==0){
1584
                    *px = C[0];
1585
                    *py = C[1];
1586
                }else{
1587
                    *px = mid_pred(A[0], 0, C[0]);
1588
                    *py = mid_pred(A[1], 0, C[1]);
1589
                }
1590
            }else{
1591
                *px = A[0];
1592
                *py = A[1];
1593
            }
1594
        }else if(block==1){
1595
            if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1596
                C = mot_val[off[block] - wrap];
1597
                *px = mid_pred(A[0], 0, C[0]);
1598
                *py = mid_pred(A[1], 0, C[1]);
1599
            }else{
1600
                *px = A[0];
1601
                *py = A[1];
1602
            }
1603
        }else{ /* block==2*/
1604
            B = mot_val[ - wrap];
1605
            C = mot_val[off[block] - wrap];
1606
            if(s->mb_x == s->resync_mb_x) //rare
1607
                A[0]=A[1]=0;
1608
    
1609
            *px = mid_pred(A[0], B[0], C[0]);
1610
            *py = mid_pred(A[1], B[1], C[1]);
1611
        }
1612
    } else {
1613
        B = mot_val[ - wrap];
1614
        C = mot_val[off[block] - wrap];
1615
        *px = mid_pred(A[0], B[0], C[0]);
1616
        *py = mid_pred(A[1], B[1], C[1]);
1617
    }
1618
    return *mot_val;
1619
}
1620

    
1621
#ifdef CONFIG_ENCODERS
1622
static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
1623
{
1624
    int range, l, bit_size, sign, code, bits;
1625

    
1626
    if (val == 0) {
1627
        /* zero vector */
1628
        code = 0;
1629
        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1630
    } else {
1631
        bit_size = f_code - 1;
1632
        range = 1 << bit_size;
1633
        /* modulo encoding */
1634
        l = range * 32;
1635
#if 1
1636
        val+= l;
1637
        val&= 2*l-1;
1638
        val-= l;
1639
        sign = val>>31;
1640
        val= (val^sign)-sign;
1641
        sign&=1;
1642
#else
1643
        if (val < -l) {
1644
            val += 2*l;
1645
        } else if (val >= l) {
1646
            val -= 2*l;
1647
        }
1648

    
1649
        assert(val>=-l && val<l);
1650

    
1651
        if (val >= 0) {
1652
            sign = 0;
1653
        } else {
1654
            val = -val;
1655
            sign = 1;
1656
        }
1657
#endif
1658
        val--;
1659
        code = (val >> bit_size) + 1;
1660
        bits = val & (range - 1);
1661

    
1662
        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
1663
        if (bit_size > 0) {
1664
            put_bits(&s->pb, bit_size, bits);
1665
        }
1666
    }
1667

    
1668
}
1669

    
1670
/* Encode MV differences on H.263+ with Unrestricted MV mode */
1671
static void h263p_encode_umotion(MpegEncContext * s, int val)
1672
{
1673
    short sval = 0; 
1674
    short i = 0;
1675
    short n_bits = 0;
1676
    short temp_val;
1677
    int code = 0;
1678
    int tcode;
1679
    
1680
    if ( val == 0)
1681
        put_bits(&s->pb, 1, 1);
1682
    else if (val == 1)
1683
        put_bits(&s->pb, 3, 0);
1684
    else if (val == -1)
1685
        put_bits(&s->pb, 3, 2);
1686
    else {
1687
        
1688
        sval = ((val < 0) ? (short)(-val):(short)val);
1689
        temp_val = sval;
1690
        
1691
        while (temp_val != 0) {
1692
            temp_val = temp_val >> 1;
1693
            n_bits++;
1694
        }
1695
        
1696
        i = n_bits - 1;
1697
        while (i > 0) {
1698
            tcode = (sval & (1 << (i-1))) >> (i-1);
1699
            tcode = (tcode << 1) | 1;
1700
            code = (code << 2) | tcode;
1701
            i--;
1702
        }
1703
        code = ((code << 1) | (val < 0)) << 1;
1704
        put_bits(&s->pb, (2*n_bits)+1, code);
1705
        //printf("\nVal = %d\tCode = %d", sval, code);
1706
    }
1707
}
1708

    
1709
static void init_mv_penalty_and_fcode(MpegEncContext *s)
1710
{
1711
    int f_code;
1712
    int mv;
1713
    
1714
    if(mv_penalty==NULL)
1715
        mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1716
    
1717
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
1718
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1719
            int len;
1720

    
1721
            if(mv==0) len= mvtab[0][1];
1722
            else{
1723
                int val, bit_size, range, code;
1724

    
1725
                bit_size = f_code - 1;
1726
                range = 1 << bit_size;
1727

    
1728
                val=mv;
1729
                if (val < 0) 
1730
                    val = -val;
1731
                val--;
1732
                code = (val >> bit_size) + 1;
1733
                if(code<33){
1734
                    len= mvtab[code][1] + 1 + bit_size;
1735
                }else{
1736
                    len= mvtab[32][1] + 2 + bit_size;
1737
                }
1738
            }
1739

    
1740
            mv_penalty[f_code][mv+MAX_MV]= len;
1741
        }
1742
    }
1743

    
1744
    for(f_code=MAX_FCODE; f_code>0; f_code--){
1745
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1746
            fcode_tab[mv+MAX_MV]= f_code;
1747
        }
1748
    }
1749

    
1750
    for(mv=0; mv<MAX_MV*2+1; mv++){
1751
        umv_fcode_tab[mv]= 1;
1752
    }
1753
}
1754
#endif
1755

    
1756
#ifdef CONFIG_ENCODERS
1757

    
1758
static void init_uni_dc_tab(void)
1759
{
1760
    int level, uni_code, uni_len;
1761

    
1762
    for(level=-256; level<256; level++){
1763
        int size, v, l;
1764
        /* find number of bits */
1765
        size = 0;
1766
        v = abs(level);
1767
        while (v) {
1768
            v >>= 1;
1769
            size++;
1770
        }
1771

    
1772
        if (level < 0)
1773
            l= (-level) ^ ((1 << size) - 1);
1774
        else
1775
            l= level;
1776

    
1777
        /* luminance */
1778
        uni_code= DCtab_lum[size][0];
1779
        uni_len = DCtab_lum[size][1];
1780

    
1781
        if (size > 0) {
1782
            uni_code<<=size; uni_code|=l;
1783
            uni_len+=size;
1784
            if (size > 8){
1785
                uni_code<<=1; uni_code|=1;
1786
                uni_len++;
1787
            }
1788
        }
1789
        uni_DCtab_lum_bits[level+256]= uni_code;
1790
        uni_DCtab_lum_len [level+256]= uni_len;
1791

    
1792
        /* chrominance */
1793
        uni_code= DCtab_chrom[size][0];
1794
        uni_len = DCtab_chrom[size][1];
1795
        
1796
        if (size > 0) {
1797
            uni_code<<=size; uni_code|=l;
1798
            uni_len+=size;
1799
            if (size > 8){
1800
                uni_code<<=1; uni_code|=1;
1801
                uni_len++;
1802
            }
1803
        }
1804
        uni_DCtab_chrom_bits[level+256]= uni_code;
1805
        uni_DCtab_chrom_len [level+256]= uni_len;
1806

    
1807
    }
1808
}
1809

    
1810
#endif //CONFIG_ENCODERS
1811

    
1812
#ifdef CONFIG_ENCODERS
1813
static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1814
    int slevel, run, last;
1815
    
1816
    assert(MAX_LEVEL >= 64);
1817
    assert(MAX_RUN   >= 63);
1818

    
1819
    for(slevel=-64; slevel<64; slevel++){
1820
        if(slevel==0) continue;
1821
        for(run=0; run<64; run++){
1822
            for(last=0; last<=1; last++){
1823
                const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1824
                int level= slevel < 0 ? -slevel : slevel;
1825
                int sign= slevel < 0 ? 1 : 0;
1826
                int bits, len, code;
1827
                int level1, run1;
1828
                
1829
                len_tab[index]= 100;
1830
                     
1831
                /* ESC0 */
1832
                code= get_rl_index(rl, last, run, level);
1833
                bits= rl->table_vlc[code][0];
1834
                len=  rl->table_vlc[code][1];
1835
                bits=bits*2+sign; len++;
1836
                
1837
                if(code!=rl->n && len < len_tab[index]){
1838
                    bits_tab[index]= bits;
1839
                    len_tab [index]= len;
1840
                }
1841
#if 1
1842
                /* ESC1 */
1843
                bits= rl->table_vlc[rl->n][0];
1844
                len=  rl->table_vlc[rl->n][1];
1845
                bits=bits*2;    len++; //esc1
1846
                level1= level - rl->max_level[last][run];
1847
                if(level1>0){
1848
                    code= get_rl_index(rl, last, run, level1);
1849
                    bits<<= rl->table_vlc[code][1];
1850
                    len  += rl->table_vlc[code][1];
1851
                    bits += rl->table_vlc[code][0];
1852
                    bits=bits*2+sign; len++;
1853
                
1854
                    if(code!=rl->n && len < len_tab[index]){
1855
                        bits_tab[index]= bits;
1856
                        len_tab [index]= len;
1857
                    }
1858
                }
1859
#endif 
1860
#if 1
1861
                /* ESC2 */
1862
                bits= rl->table_vlc[rl->n][0];
1863
                len=  rl->table_vlc[rl->n][1];
1864
                bits=bits*4+2;    len+=2; //esc2
1865
                run1 = run - rl->max_run[last][level] - 1;
1866
                if(run1>=0){
1867
                    code= get_rl_index(rl, last, run1, level);
1868
                    bits<<= rl->table_vlc[code][1];
1869
                    len  += rl->table_vlc[code][1];
1870
                    bits += rl->table_vlc[code][0];
1871
                    bits=bits*2+sign; len++;
1872
                
1873
                    if(code!=rl->n && len < len_tab[index]){
1874
                        bits_tab[index]= bits;
1875
                        len_tab [index]= len;
1876
                    }
1877
                }
1878
#endif           
1879
                /* ESC3 */        
1880
                bits= rl->table_vlc[rl->n][0];
1881
                len = rl->table_vlc[rl->n][1];
1882
                bits=bits*4+3;    len+=2; //esc3
1883
                bits=bits*2+last; len++;
1884
                bits=bits*64+run; len+=6;
1885
                bits=bits*2+1;    len++;  //marker
1886
                bits=bits*4096+(slevel&0xfff); len+=12;
1887
                bits=bits*2+1;    len++;  //marker
1888
                
1889
                if(len < len_tab[index]){
1890
                    bits_tab[index]= bits;
1891
                    len_tab [index]= len;
1892
                }
1893
            }
1894
        }
1895
    }
1896
}
1897

    
1898
void h263_encode_init(MpegEncContext *s)
1899
{
1900
    static int done = 0;
1901

    
1902
    if (!done) {
1903
        done = 1;
1904

    
1905
        init_uni_dc_tab();
1906

    
1907
        init_rl(&rl_inter);
1908
        init_rl(&rl_intra);
1909
        init_rl(&rl_intra_aic);
1910
        
1911
        init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1912
        init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1913

    
1914
        init_mv_penalty_and_fcode(s);
1915
    }
1916
    s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
1917
    
1918
    // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
1919
    switch(s->codec_id){
1920
    case CODEC_ID_MPEG4:
1921
        s->fcode_tab= fcode_tab;
1922
        s->min_qcoeff= -2048;
1923
        s->max_qcoeff=  2047;
1924
        s->intra_ac_vlc_length     = uni_mpeg4_intra_rl_len;
1925
        s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;
1926
        s->inter_ac_vlc_length     = uni_mpeg4_inter_rl_len;
1927
        s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;
1928
        s->luma_dc_vlc_length= uni_DCtab_lum_len;
1929
        s->chroma_dc_vlc_length= uni_DCtab_chrom_len;
1930
        s->ac_esc_length= 7+2+1+6+1+12+1;
1931
        s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table;
1932
        s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
1933

    
1934
        if(s->flags & CODEC_FLAG_GLOBAL_HEADER){
1935

    
1936
            s->avctx->extradata= av_malloc(1024);
1937
            init_put_bits(&s->pb, s->avctx->extradata, 1024);
1938
            
1939
            mpeg4_encode_visual_object_header(s);
1940
            mpeg4_encode_vol_header(s, 0, 0);
1941

    
1942
//            ff_mpeg4_stuffing(&s->pb); ?
1943
            flush_put_bits(&s->pb);
1944
            s->avctx->extradata_size= (put_bits_count(&s->pb)+7)>>3;
1945
        }
1946
        
1947
        break;
1948
    case CODEC_ID_H263P:
1949
        if(s->umvplus)
1950
            s->fcode_tab= umv_fcode_tab;
1951
        if(s->modified_quant){
1952
            s->min_qcoeff= -2047;
1953
            s->max_qcoeff=  2047;
1954
        }else{
1955
            s->min_qcoeff= -127;
1956
            s->max_qcoeff=  127;
1957
        }
1958
        break;
1959
        //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later 
1960
    case CODEC_ID_FLV1:
1961
        if (s->h263_flv > 1) {
1962
            s->min_qcoeff= -1023;
1963
            s->max_qcoeff=  1023;
1964
        } else {
1965
            s->min_qcoeff= -127;
1966
            s->max_qcoeff=  127;
1967
        }
1968
        s->y_dc_scale_table=
1969
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1970
        break;
1971
    default: //nothing needed default table allready set in mpegvideo.c
1972
        s->min_qcoeff= -127;
1973
        s->max_qcoeff=  127;
1974
        s->y_dc_scale_table=
1975
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1976
    }
1977
}
1978

    
1979
/**
1980
 * encodes a 8x8 block.
1981
 * @param block the 8x8 block
1982
 * @param n block index (0-3 are luma, 4-5 are chroma)
1983
 */
1984
static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
1985
{
1986
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
1987
    RLTable *rl;
1988

    
1989
    rl = &rl_inter;
1990
    if (s->mb_intra && !s->h263_aic) {
1991
        /* DC coef */
1992
        level = block[0];
1993
        /* 255 cannot be represented, so we clamp */
1994
        if (level > 254) {
1995
            level = 254;
1996
            block[0] = 254;
1997
        }
1998
        /* 0 cannot be represented also */
1999
        else if (level < 1) {
2000
            level = 1;
2001
            block[0] = 1;
2002
        }
2003
        if (level == 128) //FIXME check rv10
2004
            put_bits(&s->pb, 8, 0xff);
2005
        else
2006
            put_bits(&s->pb, 8, level);
2007
        i = 1;
2008
    } else {
2009
        i = 0;
2010
        if (s->h263_aic && s->mb_intra)
2011
            rl = &rl_intra_aic;
2012
            
2013
        if(s->alt_inter_vlc && !s->mb_intra){
2014
            int aic_vlc_bits=0;
2015
            int inter_vlc_bits=0;
2016
            int wrong_pos=-1;
2017
            int aic_code;
2018
            
2019
            last_index = s->block_last_index[n];
2020
            last_non_zero = i - 1;
2021
            for (; i <= last_index; i++) {
2022
                j = s->intra_scantable.permutated[i];
2023
                level = block[j];
2024
                if (level) {
2025
                    run = i - last_non_zero - 1;
2026
                    last = (i == last_index);
2027
                    
2028
                    if(level<0) level= -level;
2029
                
2030
                    code = get_rl_index(rl, last, run, level);
2031
                    aic_code = get_rl_index(&rl_intra_aic, last, run, level);
2032
                    inter_vlc_bits += rl->table_vlc[code][1]+1;
2033
                    aic_vlc_bits   += rl_intra_aic.table_vlc[aic_code][1]+1;
2034

    
2035
                    if (code == rl->n) {
2036
                        inter_vlc_bits += 1+6+8-1;
2037
                    }                
2038
                    if (aic_code == rl_intra_aic.n) {
2039
                        aic_vlc_bits += 1+6+8-1;
2040
                        wrong_pos += run + 1;
2041
                    }else
2042
                        wrong_pos += wrong_run[aic_code];
2043
                    last_non_zero = i;
2044
                }    
2045
            }
2046
            i = 0;
2047
            if(aic_vlc_bits < inter_vlc_bits && wrong_pos > 63)
2048
                rl = &rl_intra_aic;
2049
        }
2050
    }
2051
   
2052
    /* AC coefs */
2053
    last_index = s->block_last_index[n];
2054
    last_non_zero = i - 1;
2055
    for (; i <= last_index; i++) {
2056
        j = s->intra_scantable.permutated[i];
2057
        level = block[j];
2058
        if (level) {
2059
            run = i - last_non_zero - 1;
2060
            last = (i == last_index);
2061
            sign = 0;
2062
            slevel = level;
2063
            if (level < 0) {
2064
                sign = 1;
2065
                level = -level;
2066
            }
2067
            code = get_rl_index(rl, last, run, level);
2068
            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2069
            if (code == rl->n) {
2070
              if(s->h263_flv <= 1){
2071
                put_bits(&s->pb, 1, last);
2072
                put_bits(&s->pb, 6, run);
2073
                
2074
                assert(slevel != 0);
2075

    
2076
                if(level < 128) 
2077
                    put_bits(&s->pb, 8, slevel & 0xff);
2078
                else{
2079
                    put_bits(&s->pb, 8, 128);
2080
                    put_bits(&s->pb, 5, slevel & 0x1f);
2081
                    put_bits(&s->pb, 6, (slevel>>5)&0x3f);
2082
                }
2083
              }else{
2084
                if(level < 64) { // 7-bit level
2085
                        put_bits(&s->pb, 1, 0);
2086
                        put_bits(&s->pb, 1, last);
2087
                        put_bits(&s->pb, 6, run);
2088

    
2089
                        put_bits(&s->pb, 7, slevel & 0x7f);
2090
                    } else {
2091
                        /* 11-bit level */
2092
                        put_bits(&s->pb, 1, 1);
2093
                        put_bits(&s->pb, 1, last);
2094
                        put_bits(&s->pb, 6, run);
2095

    
2096
                        put_bits(&s->pb, 11, slevel & 0x7ff);
2097
                    }
2098
              }
2099
            } else {
2100
                put_bits(&s->pb, 1, sign);
2101
            }
2102
            last_non_zero = i;
2103
        }
2104
    }
2105
}
2106
#endif
2107

    
2108
#ifdef CONFIG_ENCODERS
2109

    
2110
/***************************************************/
2111
/**
2112
 * add mpeg4 stuffing bits (01...1)
2113
 */
2114
void ff_mpeg4_stuffing(PutBitContext * pbc)
2115
{
2116
    int length;
2117
    put_bits(pbc, 1, 0);
2118
    length= (-put_bits_count(pbc))&7;
2119
    if(length) put_bits(pbc, length, (1<<length)-1);
2120
}
2121

    
2122
/* must be called before writing the header */
2123
void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
2124
    int time_div, time_mod;
2125

    
2126
    assert(s->current_picture_ptr->pts != AV_NOPTS_VALUE);
2127
    s->time= (s->current_picture_ptr->pts*s->time_increment_resolution + AV_TIME_BASE/2)/AV_TIME_BASE;
2128

    
2129
    time_div= s->time/s->time_increment_resolution;
2130
    time_mod= s->time%s->time_increment_resolution;
2131

    
2132
    if(s->pict_type==B_TYPE){
2133
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
2134
    }else{
2135
        s->last_time_base= s->time_base;
2136
        s->time_base= time_div;
2137
        s->pp_time= s->time - s->last_non_b_time;
2138
        s->last_non_b_time= s->time;
2139
    }
2140
}
2141

    
2142
static void mpeg4_encode_gop_header(MpegEncContext * s){
2143
    int hours, minutes, seconds;
2144
    int64_t time;
2145
    
2146
    put_bits(&s->pb, 16, 0);
2147
    put_bits(&s->pb, 16, GOP_STARTCODE);
2148
    
2149
    time= s->current_picture_ptr->pts;
2150
    if(s->reordered_input_picture[1])
2151
        time= FFMIN(time, s->reordered_input_picture[1]->pts);
2152
    time= (time*s->time_increment_resolution + AV_TIME_BASE/2)/AV_TIME_BASE;
2153

    
2154
    seconds= time/s->time_increment_resolution;
2155
    minutes= seconds/60; seconds %= 60;
2156
    hours= minutes/60; minutes %= 60;
2157
    hours%=24;
2158

    
2159
    put_bits(&s->pb, 5, hours);
2160
    put_bits(&s->pb, 6, minutes);
2161
    put_bits(&s->pb, 1, 1);
2162
    put_bits(&s->pb, 6, seconds);
2163
    
2164
    put_bits(&s->pb, 1, !!(s->flags&CODEC_FLAG_CLOSED_GOP)); 
2165
    put_bits(&s->pb, 1, 0); //broken link == NO
2166
    
2167
    s->last_time_base= time / s->time_increment_resolution; 
2168

    
2169
    ff_mpeg4_stuffing(&s->pb);
2170
}
2171

    
2172
static void mpeg4_encode_visual_object_header(MpegEncContext * s){
2173
    int profile_and_level_indication;
2174
    int vo_ver_id;
2175
    
2176
    if(s->max_b_frames || s->quarter_sample){
2177
        profile_and_level_indication= 0xF1; // adv simple level 1
2178
        vo_ver_id= 5;
2179
    }else{
2180
        profile_and_level_indication= 0x01; // simple level 1
2181
        vo_ver_id= 1;
2182
    }
2183
    //FIXME levels
2184

    
2185
    put_bits(&s->pb, 16, 0);
2186
    put_bits(&s->pb, 16, VOS_STARTCODE);
2187

    
2188
    put_bits(&s->pb, 8, profile_and_level_indication);
2189

    
2190
    put_bits(&s->pb, 16, 0);
2191
    put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
2192
    
2193
    put_bits(&s->pb, 1, 1);
2194
        put_bits(&s->pb, 4, vo_ver_id);
2195
        put_bits(&s->pb, 3, 1); //priority
2196
 
2197
    put_bits(&s->pb, 4, 1); //visual obj type== video obj
2198
    
2199
    put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
2200

    
2201
    ff_mpeg4_stuffing(&s->pb);
2202
}
2203

    
2204
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
2205
{
2206
    int vo_ver_id;
2207

    
2208
    if(s->max_b_frames || s->quarter_sample){
2209
        vo_ver_id= 5;
2210
        s->vo_type= ADV_SIMPLE_VO_TYPE;
2211
    }else{
2212
        vo_ver_id= 1;
2213
        s->vo_type= SIMPLE_VO_TYPE;
2214
    }
2215

    
2216
    put_bits(&s->pb, 16, 0);
2217
    put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
2218
    put_bits(&s->pb, 16, 0);
2219
    put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
2220

    
2221
    put_bits(&s->pb, 1, 0);                /* random access vol */
2222
    put_bits(&s->pb, 8, s->vo_type);        /* video obj type indication */
2223
    put_bits(&s->pb, 1, 1);                /* is obj layer id= yes */
2224
      put_bits(&s->pb, 4, vo_ver_id);        /* is obj layer ver id */
2225
      put_bits(&s->pb, 3, 1);                /* is obj layer priority */
2226
    
2227
    aspect_to_info(s, s->avctx->sample_aspect_ratio);
2228

    
2229
    put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
2230
    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
2231
        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
2232
        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
2233
    }
2234

    
2235
    if(s->low_delay){
2236
        put_bits(&s->pb, 1, 1);                /* vol control parameters= yes */
2237
        put_bits(&s->pb, 2, 1);                /* chroma format YUV 420/YV12 */
2238
        put_bits(&s->pb, 1, s->low_delay);
2239
        put_bits(&s->pb, 1, 0);                /* vbv parameters= no */
2240
    }else{
2241
        put_bits(&s->pb, 1, 0);                /* vol control parameters= no */
2242
    }
2243

    
2244
    put_bits(&s->pb, 2, RECT_SHAPE);        /* vol shape= rectangle */
2245
    put_bits(&s->pb, 1, 1);                /* marker bit */
2246
    
2247
    put_bits(&s->pb, 16, s->time_increment_resolution);
2248
    if (s->time_increment_bits < 1)
2249
        s->time_increment_bits = 1;
2250
    put_bits(&s->pb, 1, 1);                /* marker bit */
2251
    put_bits(&s->pb, 1, 0);                /* fixed vop rate=no */
2252
    put_bits(&s->pb, 1, 1);                /* marker bit */
2253
    put_bits(&s->pb, 13, s->width);        /* vol width */
2254
    put_bits(&s->pb, 1, 1);                /* marker bit */
2255
    put_bits(&s->pb, 13, s->height);        /* vol height */
2256
    put_bits(&s->pb, 1, 1);                /* marker bit */
2257
    put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
2258
    put_bits(&s->pb, 1, 1);                /* obmc disable */
2259
    if (vo_ver_id == 1) {
2260
        put_bits(&s->pb, 1, s->vol_sprite_usage);                /* sprite enable */
2261
    }else{
2262
        put_bits(&s->pb, 2, s->vol_sprite_usage);                /* sprite enable */
2263
    }
2264
    
2265
    put_bits(&s->pb, 1, 0);                /* not 8 bit == false */
2266
    put_bits(&s->pb, 1, s->mpeg_quant);        /* quant type= (0=h263 style)*/
2267

    
2268
    if(s->mpeg_quant){
2269
        ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
2270
        ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
2271
    }
2272

    
2273
    if (vo_ver_id != 1)
2274
        put_bits(&s->pb, 1, s->quarter_sample);
2275
    put_bits(&s->pb, 1, 1);                /* complexity estimation disable */
2276
    s->resync_marker= s->rtp_mode;
2277
    put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
2278
    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
2279
    if(s->data_partitioning){
2280
        put_bits(&s->pb, 1, 0);                /* no rvlc */
2281
    }
2282

    
2283
    if (vo_ver_id != 1){
2284
        put_bits(&s->pb, 1, 0);                /* newpred */
2285
        put_bits(&s->pb, 1, 0);                /* reduced res vop */
2286
    }
2287
    put_bits(&s->pb, 1, 0);                /* scalability */
2288
    
2289
    ff_mpeg4_stuffing(&s->pb);
2290

    
2291
    /* user data */
2292
    if(!(s->flags & CODEC_FLAG_BITEXACT)){
2293
        put_bits(&s->pb, 16, 0);
2294
        put_bits(&s->pb, 16, 0x1B2);        /* user_data */
2295
        put_string(&s->pb, LIBAVCODEC_IDENT, 0);
2296
    }
2297
}
2298

    
2299
/* write mpeg4 VOP header */
2300
void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
2301
{
2302
    int time_incr;
2303
    int time_div, time_mod;
2304
    
2305
    if(s->pict_type==I_TYPE){
2306
        if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
2307
            if(s->strict_std_compliance < 2) //HACK, the reference sw is buggy
2308
                mpeg4_encode_visual_object_header(s);
2309
            if(s->strict_std_compliance < 2 || picture_number==0) //HACK, the reference sw is buggy
2310
                mpeg4_encode_vol_header(s, 0, 0);
2311
        }
2312
        mpeg4_encode_gop_header(s);
2313
    }
2314
    
2315
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
2316

    
2317
//printf("num:%d rate:%d base:%d\n", s->picture_number, s->frame_rate, FRAME_RATE_BASE);
2318
    
2319
    put_bits(&s->pb, 16, 0);                /* vop header */
2320
    put_bits(&s->pb, 16, VOP_STARTCODE);        /* vop header */
2321
    put_bits(&s->pb, 2, s->pict_type - 1);        /* pict type: I = 0 , P = 1 */
2322

    
2323
    time_div= s->time/s->time_increment_resolution;
2324
    time_mod= s->time%s->time_increment_resolution;
2325
    time_incr= time_div - s->last_time_base;
2326
    assert(time_incr >= 0);
2327
    while(time_incr--)
2328
        put_bits(&s->pb, 1, 1);
2329
        
2330
    put_bits(&s->pb, 1, 0);
2331

    
2332
    put_bits(&s->pb, 1, 1);        /* marker */
2333
    put_bits(&s->pb, s->time_increment_bits, time_mod);        /* time increment */
2334
    put_bits(&s->pb, 1, 1);        /* marker */
2335
    put_bits(&s->pb, 1, 1);        /* vop coded */
2336
    if (    s->pict_type == P_TYPE 
2337
        || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
2338
        put_bits(&s->pb, 1, s->no_rounding);        /* rounding type */
2339
    }
2340
    put_bits(&s->pb, 3, 0);        /* intra dc VLC threshold */
2341
    if(!s->progressive_sequence){
2342
         put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
2343
         put_bits(&s->pb, 1, s->alternate_scan);
2344
    }
2345
    //FIXME sprite stuff
2346

    
2347
    put_bits(&s->pb, 5, s->qscale);
2348

    
2349
    if (s->pict_type != I_TYPE)
2350
        put_bits(&s->pb, 3, s->f_code);        /* fcode_for */
2351
    if (s->pict_type == B_TYPE)
2352
        put_bits(&s->pb, 3, s->b_code);        /* fcode_back */
2353
    //    printf("****frame %d\n", picture_number);
2354
}
2355

    
2356
#endif //CONFIG_ENCODERS
2357

    
2358
/**
2359
 * set qscale and update qscale dependant variables.
2360
 */
2361
void ff_set_qscale(MpegEncContext * s, int qscale)
2362
{
2363
    if (qscale < 1)
2364
        qscale = 1;
2365
    else if (qscale > 31)
2366
        qscale = 31;
2367
        
2368
    s->qscale = qscale;
2369
    s->chroma_qscale= s->chroma_qscale_table[qscale];
2370

    
2371
    s->y_dc_scale= s->y_dc_scale_table[ qscale ];
2372
    s->c_dc_scale= s->c_dc_scale_table[ s->chroma_qscale ];
2373
}
2374

    
2375
/**
2376
 * predicts the dc.
2377
 * encoding quantized level -> quantized diff
2378
 * decoding quantized diff -> quantized level  
2379
 * @param n block index (0-3 are luma, 4-5 are chroma)
2380
 * @param dir_ptr pointer to an integer where the prediction direction will be stored
2381
 */
2382
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, int level, int *dir_ptr, int encoding)
2383
{
2384
    int a, b, c, wrap, pred, scale, ret;
2385
    uint16_t *dc_val;
2386

    
2387
    /* find prediction */
2388
    if (n < 4) {
2389
        scale = s->y_dc_scale;
2390
    } else {
2391
        scale = s->c_dc_scale;
2392
    }
2393
    if(IS_3IV1)
2394
        scale= 8;
2395

    
2396
    wrap= s->block_wrap[n];
2397
    dc_val = s->dc_val[0] + s->block_index[n];
2398

    
2399
    /* B C
2400
     * A X 
2401
     */
2402
    a = dc_val[ - 1];
2403
    b = dc_val[ - 1 - wrap];
2404
    c = dc_val[ - wrap];
2405

    
2406
    /* outside slice handling (we cant do that by memset as we need the dc for error resilience) */
2407
    if(s->first_slice_line && n!=3){
2408
        if(n!=2) b=c= 1024;
2409
        if(n!=1 && s->mb_x == s->resync_mb_x) b=a= 1024;
2410
    }
2411
    if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1){
2412
        if(n==0 || n==4 || n==5)
2413
            b=1024;
2414
    }
2415

    
2416
    if (abs(a - b) < abs(b - c)) {
2417
        pred = c;
2418
        *dir_ptr = 1; /* top */
2419
    } else {
2420
        pred = a;
2421
        *dir_ptr = 0; /* left */
2422
    }
2423
    /* we assume pred is positive */
2424
    pred = FASTDIV((pred + (scale >> 1)), scale);
2425

    
2426
    if(encoding){
2427
        ret = level - pred;
2428
    }else{
2429
        level += pred;
2430
        ret= level;
2431
        if(s->error_resilience>=3){
2432
            if(level<0){
2433
                av_log(s->avctx, AV_LOG_ERROR, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
2434
                return -1;
2435
            }
2436
            if(level*scale > 2048 + scale){
2437
                av_log(s->avctx, AV_LOG_ERROR, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
2438
                return -1;
2439
            }
2440
        }
2441
    }
2442
    level *=scale;
2443
    if(level&(~2047)){
2444
        if(level<0) 
2445
            level=0;
2446
        else if(!(s->workaround_bugs&FF_BUG_DC_CLIP))
2447
            level=2047;
2448
    }
2449
    dc_val[0]= level;
2450

    
2451
    return ret;
2452
}
2453

    
2454
/**
2455
 * predicts the ac.
2456
 * @param n block index (0-3 are luma, 4-5 are chroma)
2457
 * @param dir the ac prediction direction
2458
 */
2459
void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
2460
                   int dir)
2461
{
2462
    int i;
2463
    int16_t *ac_val, *ac_val1;
2464
    int8_t * const qscale_table= s->current_picture.qscale_table;
2465

    
2466
    /* find prediction */
2467
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
2468
    ac_val1 = ac_val;
2469
    if (s->ac_pred) {
2470
        if (dir == 0) {
2471
            const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
2472
            /* left prediction */
2473
            ac_val -= 16;
2474
            
2475
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
2476
                /* same qscale */
2477
                for(i=1;i<8;i++) {
2478
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
2479
                }
2480
            }else{
2481
                /* different qscale, we must rescale */
2482
                for(i=1;i<8;i++) {
2483
                    block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
2484
                }
2485
            }
2486
        } else {
2487
            const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
2488
            /* top prediction */
2489
            ac_val -= 16 * s->block_wrap[n];
2490

    
2491
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
2492
                /* same qscale */
2493
                for(i=1;i<8;i++) {
2494
                    block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
2495
                }
2496
            }else{
2497
                /* different qscale, we must rescale */
2498
                for(i=1;i<8;i++) {
2499
                    block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
2500
                }
2501
            }
2502
        }
2503
    }
2504
    /* left copy */
2505
    for(i=1;i<8;i++)
2506
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
2507

    
2508
    /* top copy */
2509
    for(i=1;i<8;i++)
2510
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
2511

    
2512
}
2513

    
2514
#ifdef CONFIG_ENCODERS
2515

    
2516
/**
2517
 * encodes the dc value.
2518
 * @param n block index (0-3 are luma, 4-5 are chroma)
2519
 */
2520
static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
2521
{
2522
#if 1
2523
//    if(level<-255 || level>255) printf("dc overflow\n");
2524
    level+=256;
2525
    if (n < 4) {
2526
        /* luminance */
2527
        put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
2528
    } else {
2529
        /* chrominance */
2530
        put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
2531
    }
2532
#else
2533
    int size, v;
2534
    /* find number of bits */
2535
    size = 0;
2536
    v = abs(level);
2537
    while (v) {
2538
        v >>= 1;
2539
        size++;
2540
    }
2541

    
2542
    if (n < 4) {
2543
        /* luminance */
2544
        put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
2545
    } else {
2546
        /* chrominance */
2547
        put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
2548
    }
2549

    
2550
    /* encode remaining bits */
2551
    if (size > 0) {
2552
        if (level < 0)
2553
            level = (-level) ^ ((1 << size) - 1);
2554
        put_bits(&s->pb, size, level);
2555
        if (size > 8)
2556
            put_bits(&s->pb, 1, 1);
2557
    }
2558
#endif
2559
}
2560

    
2561
/**
2562
 * encodes a 8x8 block
2563
 * @param n block index (0-3 are luma, 4-5 are chroma)
2564
 */
2565
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2566
                               uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
2567
{
2568
    int i, last_non_zero;
2569
#if 0 //variables for the outcommented version
2570
    int code, sign, last;
2571
#endif
2572
    const RLTable *rl;
2573
    uint32_t *bits_tab;
2574
    uint8_t *len_tab;
2575
    const int last_index = s->block_last_index[n];
2576

    
2577
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2578
        /* mpeg4 based DC predictor */
2579
        mpeg4_encode_dc(dc_pb, intra_dc, n);
2580
        if(last_index<1) return;
2581
        i = 1;
2582
        rl = &rl_intra;
2583
        bits_tab= uni_mpeg4_intra_rl_bits;
2584
        len_tab = uni_mpeg4_intra_rl_len;
2585
    } else {
2586
        if(last_index<0) return;
2587
        i = 0;
2588
        rl = &rl_inter;
2589
        bits_tab= uni_mpeg4_inter_rl_bits;
2590
        len_tab = uni_mpeg4_inter_rl_len;
2591
    }
2592

    
2593
    /* AC coefs */
2594
    last_non_zero = i - 1;
2595
#if 1
2596
    for (; i < last_index; i++) {
2597
        int level = block[ scan_table[i] ];
2598
        if (level) {
2599
            int run = i - last_non_zero - 1;
2600
            level+=64;
2601
            if((level&(~127)) == 0){
2602
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2603
                put_bits(ac_pb, len_tab[index], bits_tab[index]);
2604
            }else{ //ESC3
2605
                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);
2606
            }
2607
            last_non_zero = i;
2608
        }
2609
    }
2610
    /*if(i<=last_index)*/{
2611
        int level = block[ scan_table[i] ];
2612
        int run = i - last_non_zero - 1;
2613
        level+=64;
2614
        if((level&(~127)) == 0){
2615
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2616
            put_bits(ac_pb, len_tab[index], bits_tab[index]);
2617
        }else{ //ESC3
2618
            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);
2619
        }
2620
    }
2621
#else
2622
    for (; i <= last_index; i++) {
2623
        const int slevel = block[ scan_table[i] ];
2624
        if (slevel) {
2625
            int level;
2626
            int run = i - last_non_zero - 1;
2627
            last = (i == last_index);
2628
            sign = 0;
2629
            level = slevel;
2630
            if (level < 0) {
2631
                sign = 1;
2632
                level = -level;
2633
            }
2634
            code = get_rl_index(rl, last, run, level);
2635
            put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2636
            if (code == rl->n) {
2637
                int level1, run1;
2638
                level1 = level - rl->max_level[last][run];
2639
                if (level1 < 1) 
2640
                    goto esc2;
2641
                code = get_rl_index(rl, last, run, level1);
2642
                if (code == rl->n) {
2643
                esc2:
2644
                    put_bits(ac_pb, 1, 1);
2645
                    if (level > MAX_LEVEL)
2646
                        goto esc3;
2647
                    run1 = run - rl->max_run[last][level] - 1;
2648
                    if (run1 < 0)
2649
                        goto esc3;
2650
                    code = get_rl_index(rl, last, run1, level);
2651
                    if (code == rl->n) {
2652
                    esc3:
2653
                        /* third escape */
2654
                        put_bits(ac_pb, 1, 1);
2655
                        put_bits(ac_pb, 1, last);
2656
                        put_bits(ac_pb, 6, run);
2657
                        put_bits(ac_pb, 1, 1);
2658
                        put_bits(ac_pb, 12, slevel & 0xfff);
2659
                        put_bits(ac_pb, 1, 1);
2660
                    } else {
2661
                        /* second escape */
2662
                        put_bits(ac_pb, 1, 0);
2663
                        put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2664
                        put_bits(ac_pb, 1, sign);
2665
                    }
2666
                } else {
2667
                    /* first escape */
2668
                    put_bits(ac_pb, 1, 0);
2669
                    put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2670
                    put_bits(ac_pb, 1, sign);
2671
                }
2672
            } else {
2673
                put_bits(ac_pb, 1, sign);
2674
            }
2675
            last_non_zero = i;
2676
        }
2677
    }
2678
#endif
2679
}
2680

    
2681
static inline int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2682
                               uint8_t *scan_table)
2683
{
2684
    int i, last_non_zero;
2685
    const RLTable *rl;
2686
    uint8_t *len_tab;
2687
    const int last_index = s->block_last_index[n];
2688
    int len=0;
2689

    
2690
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2691
        /* mpeg4 based DC predictor */
2692
        //mpeg4_encode_dc(dc_pb, intra_dc, n); //FIXME
2693
        if(last_index<1) return len;
2694
        i = 1;
2695
        rl = &rl_intra;
2696
        len_tab = uni_mpeg4_intra_rl_len;
2697
    } else {
2698
        if(last_index<0) return 0;
2699
        i = 0;
2700
        rl = &rl_inter;
2701
        len_tab = uni_mpeg4_inter_rl_len;
2702
    }
2703

    
2704
    /* AC coefs */
2705
    last_non_zero = i - 1;
2706
    for (; i < last_index; i++) {
2707
        int level = block[ scan_table[i] ];
2708
        if (level) {
2709
            int run = i - last_non_zero - 1;
2710
            level+=64;
2711
            if((level&(~127)) == 0){
2712
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2713
                len += len_tab[index];
2714
            }else{ //ESC3
2715
                len += 7+2+1+6+1+12+1;
2716
            }
2717
            last_non_zero = i;
2718
        }
2719
    }
2720
    /*if(i<=last_index)*/{
2721
        int level = block[ scan_table[i] ];
2722
        int run = i - last_non_zero - 1;
2723
        level+=64;
2724
        if((level&(~127)) == 0){
2725
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2726
            len += len_tab[index];
2727
        }else{ //ESC3
2728
            len += 7+2+1+6+1+12+1;
2729
        }
2730
    }
2731
    
2732
    return len;
2733
}
2734

    
2735
#endif
2736

    
2737

    
2738
/***********************************************/
2739
/* decoding */
2740

    
2741
static VLC intra_MCBPC_vlc;
2742
static VLC inter_MCBPC_vlc;
2743
static VLC cbpy_vlc;
2744
static VLC mv_vlc;
2745
static VLC dc_lum, dc_chrom;
2746
static VLC sprite_trajectory;
2747
static VLC mb_type_b_vlc;
2748
static VLC h263_mbtype_b_vlc;
2749
static VLC cbpc_b_vlc;
2750

    
2751
void init_vlc_rl(RLTable *rl)
2752
{
2753
    int i, q;
2754
    
2755
    init_vlc(&rl->vlc, 9, rl->n + 1, 
2756
             &rl->table_vlc[0][1], 4, 2,
2757
             &rl->table_vlc[0][0], 4, 2);
2758

    
2759
    
2760
    for(q=0; q<32; q++){
2761
        int qmul= q*2;
2762
        int qadd= (q-1)|1;
2763
        
2764
        if(q==0){
2765
            qmul=1;
2766
            qadd=0;
2767
        }
2768
        
2769
        rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2770
        for(i=0; i<rl->vlc.table_size; i++){
2771
            int code= rl->vlc.table[i][0];
2772
            int len = rl->vlc.table[i][1];
2773
            int level, run;
2774
        
2775
            if(len==0){ // illegal code
2776
                run= 66;
2777
                level= MAX_LEVEL;
2778
            }else if(len<0){ //more bits needed
2779
                run= 0;
2780
                level= code;
2781
            }else{
2782
                if(code==rl->n){ //esc
2783
                    run= 66;
2784
                    level= 0;
2785
                }else{
2786
                    run=   rl->table_run  [code] + 1;
2787
                    level= rl->table_level[code] * qmul + qadd;
2788
                    if(code >= rl->last) run+=192;
2789
                }
2790
            }
2791
            rl->rl_vlc[q][i].len= len;
2792
            rl->rl_vlc[q][i].level= level;
2793
            rl->rl_vlc[q][i].run= run;
2794
        }
2795
    }
2796
}
2797

    
2798
/* init vlcs */
2799

    
2800
/* XXX: find a better solution to handle static init */
2801
void h263_decode_init_vlc(MpegEncContext *s)
2802
{
2803
    static int done = 0;
2804

    
2805
    if (!done) {
2806
        done = 1;
2807

    
2808
        init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 9, 
2809
                 intra_MCBPC_bits, 1, 1,
2810
                 intra_MCBPC_code, 1, 1);
2811
        init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 28, 
2812
                 inter_MCBPC_bits, 1, 1,
2813
                 inter_MCBPC_code, 1, 1);
2814
        init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,
2815
                 &cbpy_tab[0][1], 2, 1,
2816
                 &cbpy_tab[0][0], 2, 1);
2817
        init_vlc(&mv_vlc, MV_VLC_BITS, 33,
2818
                 &mvtab[0][1], 2, 1,
2819
                 &mvtab[0][0], 2, 1);
2820
        init_rl(&rl_inter);
2821
        init_rl(&rl_intra);
2822
        init_rl(&rvlc_rl_inter);
2823
        init_rl(&rvlc_rl_intra);
2824
        init_rl(&rl_intra_aic);
2825
        init_vlc_rl(&rl_inter);
2826
        init_vlc_rl(&rl_intra);
2827
        init_vlc_rl(&rvlc_rl_inter);
2828
        init_vlc_rl(&rvlc_rl_intra);
2829
        init_vlc_rl(&rl_intra_aic);
2830
        init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2831
                 &DCtab_lum[0][1], 2, 1,
2832
                 &DCtab_lum[0][0], 2, 1);
2833
        init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2834
                 &DCtab_chrom[0][1], 2, 1,
2835
                 &DCtab_chrom[0][0], 2, 1);
2836
        init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2837
                 &sprite_trajectory_tab[0][1], 4, 2,
2838
                 &sprite_trajectory_tab[0][0], 4, 2);
2839
        init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2840
                 &mb_type_b_tab[0][1], 2, 1,
2841
                 &mb_type_b_tab[0][0], 2, 1);
2842
        init_vlc(&h263_mbtype_b_vlc, H263_MBTYPE_B_VLC_BITS, 15,
2843
                 &h263_mbtype_b_tab[0][1], 2, 1,
2844
                 &h263_mbtype_b_tab[0][0], 2, 1);
2845
        init_vlc(&cbpc_b_vlc, CBPC_B_VLC_BITS, 4,
2846
                 &cbpc_b_tab[0][1], 2, 1,
2847
                 &cbpc_b_tab[0][0], 2, 1);
2848
    }
2849
}
2850

    
2851
/**
2852
 * Get the GOB height based on picture height.
2853
 */
2854
int ff_h263_get_gob_height(MpegEncContext *s){
2855
    if (s->height <= 400)
2856
        return 1;
2857
    else if (s->height <= 800)
2858
        return  2;
2859
    else
2860
        return 4;
2861
}
2862

    
2863
int ff_h263_decode_mba(MpegEncContext *s)
2864
{
2865
    int i, mb_pos;
2866

    
2867
    for(i=0; i<6; i++){
2868
        if(s->mb_num-1 <= ff_mba_max[i]) break;
2869
    }
2870
    mb_pos= get_bits(&s->gb, ff_mba_length[i]);
2871
    s->mb_x= mb_pos % s->mb_width;
2872
    s->mb_y= mb_pos / s->mb_width;
2873

    
2874
    return mb_pos;
2875
}
2876

    
2877
void ff_h263_encode_mba(MpegEncContext *s)
2878
{
2879
    int i, mb_pos;
2880

    
2881
    for(i=0; i<6; i++){
2882
        if(s->mb_num-1 <= ff_mba_max[i]) break;
2883
    }
2884
    mb_pos= s->mb_x + s->mb_width*s->mb_y;
2885
    put_bits(&s->pb, ff_mba_length[i], mb_pos);
2886
}
2887

    
2888
/**
2889
 * decodes the group of blocks header or slice header.
2890
 * @return <0 if an error occured
2891
 */
2892
static int h263_decode_gob_header(MpegEncContext *s)
2893
{
2894
    unsigned int val, gfid, gob_number;
2895
    int left;
2896
    
2897
    /* Check for GOB Start Code */
2898
    val = show_bits(&s->gb, 16);
2899
    if(val)
2900
        return -1;
2901

    
2902
        /* We have a GBSC probably with GSTUFF */
2903
    skip_bits(&s->gb, 16); /* Drop the zeros */
2904
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
2905
    //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2906
    for(;left>13; left--){
2907
        if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2908
    }
2909
    if(left<=13) 
2910
        return -1;
2911

    
2912
    if(s->h263_slice_structured){
2913
        if(get_bits1(&s->gb)==0)
2914
            return -1;
2915

    
2916
        ff_h263_decode_mba(s);
2917

    
2918
        if(s->mb_num > 1583)
2919
            if(get_bits1(&s->gb)==0)
2920
                return -1;
2921
        
2922
        s->qscale = get_bits(&s->gb, 5); /* SQUANT */
2923
        if(get_bits1(&s->gb)==0)
2924
            return -1;
2925
        gfid = get_bits(&s->gb, 2); /* GFID */
2926
    }else{
2927
        gob_number = get_bits(&s->gb, 5); /* GN */
2928
        s->mb_x= 0;
2929
        s->mb_y= s->gob_index* gob_number;
2930
        gfid = get_bits(&s->gb, 2); /* GFID */
2931
        s->qscale = get_bits(&s->gb, 5); /* GQUANT */
2932
    }
2933
        
2934
    if(s->mb_y >= s->mb_height) 
2935
        return -1;
2936

    
2937
    if(s->qscale==0) 
2938
        return -1;
2939

    
2940
    return 0;
2941
}
2942

    
2943
static inline void memsetw(short *tab, int val, int n)
2944
{
2945
    int i;
2946
    for(i=0;i<n;i++)
2947
        tab[i] = val;
2948
}
2949

    
2950
#ifdef CONFIG_ENCODERS
2951

    
2952
void ff_mpeg4_init_partitions(MpegEncContext *s)
2953
{
2954
    uint8_t *start= pbBufPtr(&s->pb);
2955
    uint8_t *end= s->pb.buf_end;
2956
    int size= end - start;
2957
    int pb_size = (((int)start + size/3)&(~3)) - (int)start;
2958
    int tex_size= (size - 2*pb_size)&(~3);
2959
    
2960
    set_put_bits_buffer_size(&s->pb, pb_size);
2961
    init_put_bits(&s->tex_pb, start + pb_size           , tex_size);
2962
    init_put_bits(&s->pb2   , start + pb_size + tex_size, pb_size);
2963
}
2964

    
2965
void ff_mpeg4_merge_partitions(MpegEncContext *s)
2966
{
2967
    const int pb2_len   = put_bits_count(&s->pb2   );
2968
    const int tex_pb_len= put_bits_count(&s->tex_pb);
2969
    const int bits= put_bits_count(&s->pb);
2970

    
2971
    if(s->pict_type==I_TYPE){
2972
        put_bits(&s->pb, 19, DC_MARKER);
2973
        s->misc_bits+=19 + pb2_len + bits - s->last_bits;
2974
        s->i_tex_bits+= tex_pb_len;
2975
    }else{
2976
        put_bits(&s->pb, 17, MOTION_MARKER);
2977
        s->misc_bits+=17 + pb2_len;
2978
        s->mv_bits+= bits - s->last_bits;
2979
        s->p_tex_bits+= tex_pb_len;
2980
    }
2981

    
2982
    flush_put_bits(&s->pb2);
2983
    flush_put_bits(&s->tex_pb);
2984

    
2985
    set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
2986
    ff_copy_bits(&s->pb, s->pb2.buf   , pb2_len);
2987
    ff_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
2988
    s->last_bits= put_bits_count(&s->pb);
2989
}
2990

    
2991
#endif //CONFIG_ENCODERS
2992

    
2993
int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
2994
    switch(s->pict_type){
2995
        case I_TYPE:
2996
            return 16;
2997
        case P_TYPE:
2998
        case S_TYPE:
2999
            return s->f_code+15;
3000
        case B_TYPE:
3001
            return FFMAX(FFMAX(s->f_code, s->b_code)+15, 17);
3002
        default:
3003
            return -1;
3004
    }
3005
}
3006

    
3007
#ifdef CONFIG_ENCODERS
3008

    
3009
void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
3010
{
3011
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
3012

    
3013
    put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
3014
    put_bits(&s->pb, 1, 1);
3015
    
3016
    put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
3017
    put_bits(&s->pb, s->quant_precision, s->qscale);
3018
    put_bits(&s->pb, 1, 0); /* no HEC */
3019
}
3020

    
3021
#endif //CONFIG_ENCODERS
3022

    
3023
/**
3024
 * check if the next stuff is a resync marker or the end.
3025
 * @return 0 if not
3026
 */
3027
static inline int mpeg4_is_resync(MpegEncContext *s){
3028
    const int bits_count= get_bits_count(&s->gb);
3029
    
3030
    if(s->workaround_bugs&FF_BUG_NO_PADDING){
3031
        return 0;
3032
    }
3033

    
3034
    if(bits_count + 8 >= s->gb.size_in_bits){
3035
        int v= show_bits(&s->gb, 8);
3036
        v|= 0x7F >> (7-(bits_count&7));
3037
                
3038
        if(v==0x7F)
3039
            return 1;
3040
    }else{
3041
        if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){
3042
            int len;
3043
            GetBitContext gb= s->gb;
3044
        
3045
            skip_bits(&s->gb, 1);
3046
            align_get_bits(&s->gb);
3047
        
3048
            for(len=0; len<32; len++){
3049
                if(get_bits1(&s->gb)) break;
3050
            }
3051

    
3052
            s->gb= gb;
3053

    
3054
            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
3055
                return 1;
3056
        }
3057
    }
3058
    return 0;
3059
}
3060

    
3061
/**
3062
 * decodes the next video packet.
3063
 * @return <0 if something went wrong
3064
 */
3065
static int mpeg4_decode_video_packet_header(MpegEncContext *s)
3066
{
3067
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
3068
    int header_extension=0, mb_num, len;
3069
    
3070
    /* is there enough space left for a video packet + header */
3071
    if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
3072

    
3073
    for(len=0; len<32; len++){
3074
        if(get_bits1(&s->gb)) break;
3075
    }
3076

    
3077
    if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
3078
        av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
3079
        return -1;
3080
    }
3081
    
3082
    if(s->shape != RECT_SHAPE){
3083
        header_extension= get_bits1(&s->gb);
3084
        //FIXME more stuff here
3085
    }
3086

    
3087
    mb_num= get_bits(&s->gb, mb_num_bits);
3088
    if(mb_num>=s->mb_num){
3089
        av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
3090
        return -1;
3091
    }
3092
    if(s->pict_type == B_TYPE){
3093
        while(s->next_picture.mbskip_table[ s->mb_index2xy[ mb_num ] ]) mb_num++;
3094
        if(mb_num >= s->mb_num) return -1; // slice contains just skiped MBs which where allready decoded
3095
    }
3096
    
3097
    s->mb_x= mb_num % s->mb_width;
3098
    s->mb_y= mb_num / s->mb_width;
3099

    
3100
    if(s->shape != BIN_ONLY_SHAPE){
3101
        int qscale= get_bits(&s->gb, s->quant_precision); 
3102
        if(qscale)
3103
            s->chroma_qscale=s->qscale= qscale;
3104
    }
3105

    
3106
    if(s->shape == RECT_SHAPE){
3107
        header_extension= get_bits1(&s->gb);
3108
    }
3109
    if(header_extension){
3110
        int time_increment;
3111
        int time_incr=0;
3112

    
3113
        while (get_bits1(&s->gb) != 0) 
3114
            time_incr++;
3115

    
3116
        check_marker(&s->gb, "before time_increment in video packed header");
3117
        time_increment= get_bits(&s->gb, s->time_increment_bits);
3118
        check_marker(&s->gb, "before vop_coding_type in video packed header");
3119
        
3120
        skip_bits(&s->gb, 2); /* vop coding type */
3121
        //FIXME not rect stuff here
3122

    
3123
        if(s->shape != BIN_ONLY_SHAPE){
3124
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
3125
//FIXME dont just ignore everything
3126
            if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3127
                mpeg4_decode_sprite_trajectory(s, &s->gb);
3128
                av_log(s->avctx, AV_LOG_ERROR, "untested\n");
3129
            }
3130

    
3131
            //FIXME reduced res stuff here
3132
            
3133
            if (s->pict_type != I_TYPE) {
3134
                int f_code = get_bits(&s->gb, 3);        /* fcode_for */
3135
                if(f_code==0){
3136
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n");
3137
                }
3138
            }
3139
            if (s->pict_type == B_TYPE) {
3140
                int b_code = get_bits(&s->gb, 3);
3141
                if(b_code==0){
3142
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n");
3143
                }
3144
            }       
3145
        }
3146
    }
3147
    //FIXME new-pred stuff
3148
    
3149
//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));
3150

    
3151
    return 0;
3152
}
3153

    
3154
void ff_mpeg4_clean_buffers(MpegEncContext *s)
3155
{
3156
    int c_wrap, c_xy, l_wrap, l_xy;
3157

    
3158
    l_wrap= s->b8_stride;
3159
    l_xy= (2*s->mb_y-1)*l_wrap + s->mb_x*2 - 1;
3160
    c_wrap= s->mb_stride;
3161
    c_xy= (s->mb_y-1)*c_wrap + s->mb_x - 1;
3162

    
3163
#if 0
3164
    /* clean DC */
3165
    memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
3166
    memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
3167
    memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
3168
#endif
3169

    
3170
    /* clean AC */
3171
    memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(int16_t));
3172
    memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
3173
    memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
3174

    
3175
    /* clean MV */
3176
    // we cant clear the MVs as they might be needed by a b frame
3177
//    memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(int16_t));
3178
//    memset(s->motion_val, 0, 2*sizeof(int16_t)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
3179
    s->last_mv[0][0][0]=
3180
    s->last_mv[0][0][1]=
3181
    s->last_mv[1][0][0]=
3182
    s->last_mv[1][0][1]= 0;
3183
}
3184

    
3185
/**
3186
 * decodes the group of blocks / video packet header.
3187
 * @return <0 if no resync found
3188
 */
3189
int ff_h263_resync(MpegEncContext *s){
3190
    int left, ret;
3191
    
3192
    if(s->codec_id==CODEC_ID_MPEG4){
3193
        skip_bits1(&s->gb);
3194
        align_get_bits(&s->gb);
3195
    }
3196

    
3197
    if(show_bits(&s->gb, 16)==0){
3198
        if(s->codec_id==CODEC_ID_MPEG4)
3199
            ret= mpeg4_decode_video_packet_header(s);
3200
        else
3201
            ret= h263_decode_gob_header(s);
3202
        if(ret>=0)
3203
            return 0;
3204
    }
3205
    //ok, its not where its supposed to be ...
3206
    s->gb= s->last_resync_gb;
3207
    align_get_bits(&s->gb);
3208
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
3209
    
3210
    for(;left>16+1+5+5; left-=8){ 
3211
        if(show_bits(&s->gb, 16)==0){
3212
            GetBitContext bak= s->gb;
3213

    
3214
            if(s->codec_id==CODEC_ID_MPEG4)
3215
                ret= mpeg4_decode_video_packet_header(s);
3216
            else
3217
                ret= h263_decode_gob_header(s);
3218
            if(ret>=0)
3219
                return 0;
3220

    
3221
            s->gb= bak;
3222
        }
3223
        skip_bits(&s->gb, 8);
3224
    }
3225
    
3226
    return -1;
3227
}
3228

    
3229
/**
3230
 * gets the average motion vector for a GMC MB.
3231
 * @param n either 0 for the x component or 1 for y
3232
 * @returns the average MV for a GMC MB
3233
 */
3234
static inline int get_amv(MpegEncContext *s, int n){
3235
    int x, y, mb_v, sum, dx, dy, shift;
3236
    int len = 1 << (s->f_code + 4);
3237
    const int a= s->sprite_warping_accuracy;
3238
    
3239
    if(s->workaround_bugs & FF_BUG_AMV)
3240
        len >>= s->quarter_sample;
3241

    
3242
    if(s->real_sprite_warping_points==1){
3243
        if(s->divx_version==500 && s->divx_build==413)
3244
            sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
3245
        else
3246
            sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
3247
    }else{
3248
        dx= s->sprite_delta[n][0];
3249
        dy= s->sprite_delta[n][1];
3250
        shift= s->sprite_shift[0];
3251
        if(n) dy -= 1<<(shift + a + 1);
3252
        else  dx -= 1<<(shift + a + 1);
3253
        mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
3254

    
3255
        sum=0;
3256
        for(y=0; y<16; y++){
3257
            int v;
3258
        
3259
            v= mb_v + dy*y;
3260
            //XXX FIXME optimize
3261
            for(x=0; x<16; x++){
3262
                sum+= v>>shift;
3263
                v+= dx;
3264
            }
3265
        }
3266
        sum= RSHIFT(sum, a+8-s->quarter_sample);
3267
    }
3268

    
3269
    if      (sum < -len) sum= -len;
3270
    else if (sum >= len) sum= len-1;
3271

    
3272
    return sum;
3273
}
3274

    
3275
/**
3276
 * decodes first partition.
3277
 * @return number of MBs decoded or <0 if an error occured
3278
 */
3279
static int mpeg4_decode_partition_a(MpegEncContext *s){
3280
    int mb_num;
3281
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3282
    
3283
    /* decode first partition */
3284
    mb_num=0;
3285
    s->first_slice_line=1;
3286
    for(; s->mb_y<s->mb_height; s->mb_y++){
3287
        ff_init_block_index(s);
3288
        for(; s->mb_x<s->mb_width; s->mb_x++){
3289
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
3290
            int cbpc;
3291
            int dir=0;
3292
            
3293
            mb_num++;
3294
            ff_update_block_index(s);
3295
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3296
                s->first_slice_line=0;
3297
            
3298
            if(s->pict_type==I_TYPE){
3299
                int i;
3300

    
3301
                do{
3302
                    if(show_bits_long(&s->gb, 19)==DC_MARKER){
3303
                        return mb_num-1;
3304
                    }
3305

    
3306
                    cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
3307
                    if (cbpc < 0){
3308
                        av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
3309
                        return -1;
3310
                    }
3311
                }while(cbpc == 8);
3312
                
3313
                s->cbp_table[xy]= cbpc & 3;
3314
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3315
                s->mb_intra = 1;
3316

    
3317
                if(cbpc & 4) {
3318
                    ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3319
                }
3320
                s->current_picture.qscale_table[xy]= s->qscale;
3321

    
3322
                s->mbintra_table[xy]= 1;
3323
                for(i=0; i<6; i++){
3324
                    int dc_pred_dir;
3325
                    int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
3326
                    if(dc < 0){
3327
                        av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3328
                        return -1;
3329
                    }
3330
                    dir<<=1;
3331
                    if(dc_pred_dir) dir|=1;
3332
                }
3333
                s->pred_dir_table[xy]= dir;
3334
            }else{ /* P/S_TYPE */
3335
                int mx, my, pred_x, pred_y, bits;
3336
                int16_t * const mot_val= s->current_picture.motion_val[0][s->block_index[0]];
3337
                const int stride= s->b8_stride*2;
3338

    
3339
try_again:
3340
                bits= show_bits(&s->gb, 17);
3341
                if(bits==MOTION_MARKER){
3342
                    return mb_num-1;
3343
                }
3344
                skip_bits1(&s->gb);
3345
                if(bits&0x10000){
3346
                    /* skip mb */
3347
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3348
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
3349
                        mx= get_amv(s, 0);
3350
                        my= get_amv(s, 1);
3351
                    }else{
3352
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3353
                        mx=my=0;
3354
                    }
3355
                    mot_val[0       ]= mot_val[2       ]=
3356
                    mot_val[0+stride]= mot_val[2+stride]= mx;
3357
                    mot_val[1       ]= mot_val[3       ]=
3358
                    mot_val[1+stride]= mot_val[3+stride]= my;
3359

    
3360
                    if(s->mbintra_table[xy])
3361
                        ff_clean_intra_table_entries(s);
3362
                    continue;
3363
                }
3364

    
3365
                cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3366
                if (cbpc < 0){
3367
                    av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
3368
                    return -1;
3369
                }
3370
                if(cbpc == 20)
3371
                    goto try_again;
3372

    
3373
                s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
3374
    
3375
                s->mb_intra = ((cbpc & 4) != 0);
3376
        
3377
                if(s->mb_intra){
3378
                    s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3379
                    s->mbintra_table[xy]= 1;
3380
                    mot_val[0       ]= mot_val[2       ]= 
3381
                    mot_val[0+stride]= mot_val[2+stride]= 0;
3382
                    mot_val[1       ]= mot_val[3       ]=
3383
                    mot_val[1+stride]= mot_val[3+stride]= 0;
3384
                }else{
3385
                    if(s->mbintra_table[xy])
3386
                        ff_clean_intra_table_entries(s);
3387

    
3388
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
3389
                        s->mcsel= get_bits1(&s->gb);
3390
                    else s->mcsel= 0;
3391
        
3392
                    if ((cbpc & 16) == 0) {
3393
                        /* 16x16 motion prediction */
3394

    
3395
                        h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3396
                        if(!s->mcsel){
3397
                            mx = h263_decode_motion(s, pred_x, s->f_code);
3398
                            if (mx >= 0xffff)
3399
                                return -1;
3400

    
3401
                            my = h263_decode_motion(s, pred_y, s->f_code);
3402
                            if (my >= 0xffff)
3403
                                return -1;
3404
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
3405
                        } else {
3406
                            mx = get_amv(s, 0);
3407
                            my = get_amv(s, 1);
3408
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
3409
                        }
3410

    
3411
                        mot_val[0       ]= mot_val[2       ] =
3412
                        mot_val[0+stride]= mot_val[2+stride]= mx;
3413
                        mot_val[1       ]= mot_val[3       ]=
3414
                        mot_val[1+stride]= mot_val[3+stride]= my;
3415
                    } else {
3416
                        int i;
3417
                        s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
3418
                        for(i=0;i<4;i++) {
3419
                            int16_t *mot_val= h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3420
                            mx = h263_decode_motion(s, pred_x, s->f_code);
3421
                            if (mx >= 0xffff)
3422
                                return -1;
3423
                
3424
                            my = h263_decode_motion(s, pred_y, s->f_code);
3425
                            if (my >= 0xffff)
3426
                                return -1;
3427
                            mot_val[0] = mx;
3428
                            mot_val[1] = my;
3429
                        }
3430
                    }
3431
                }
3432
            }
3433
        }
3434
        s->mb_x= 0;
3435
    }
3436

    
3437
    return mb_num;
3438
}
3439

    
3440
/**
3441
 * decode second partition.
3442
 * @return <0 if an error occured
3443
 */
3444
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
3445
    int mb_num=0;
3446
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3447

    
3448
    s->mb_x= s->resync_mb_x;
3449
    s->first_slice_line=1;
3450
    for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
3451
        ff_init_block_index(s);
3452
        for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
3453
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
3454

    
3455
            mb_num++;
3456
            ff_update_block_index(s);
3457
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3458
                s->first_slice_line=0;
3459
            
3460
            if(s->pict_type==I_TYPE){
3461
                int ac_pred= get_bits1(&s->gb);
3462
                int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3463
                if(cbpy<0){
3464
                    av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3465
                    return -1;
3466
                }
3467
                
3468
                s->cbp_table[xy]|= cbpy<<2;
3469
                s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
3470
            }else{ /* P || S_TYPE */
3471
                if(IS_INTRA(s->current_picture.mb_type[xy])){          
3472
                    int dir=0,i;
3473
                    int ac_pred = get_bits1(&s->gb);
3474
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3475

    
3476
                    if(cbpy<0){
3477
                        av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3478
                        return -1;
3479
                    }
3480
                    
3481
                    if(s->cbp_table[xy] & 8) {
3482
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3483
                    }
3484
                    s->current_picture.qscale_table[xy]= s->qscale;
3485

    
3486
                    for(i=0; i<6; i++){
3487
                        int dc_pred_dir;
3488
                        int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
3489
                        if(dc < 0){
3490
                            av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3491
                            return -1;
3492
                        }
3493
                        dir<<=1;
3494
                        if(dc_pred_dir) dir|=1;
3495
                    }
3496
                    s->cbp_table[xy]&= 3; //remove dquant
3497
                    s->cbp_table[xy]|= cbpy<<2;
3498
                    s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
3499
                    s->pred_dir_table[xy]= dir;
3500
                }else if(IS_SKIP(s->current_picture.mb_type[xy])){
3501
                    s->current_picture.qscale_table[xy]= s->qscale;
3502
                    s->cbp_table[xy]= 0;
3503
                }else{
3504
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3505

    
3506
                    if(cbpy<0){
3507
                        av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3508
                        return -1;
3509
                    }
3510
                    
3511
                    if(s->cbp_table[xy] & 8) {
3512
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3513
                    }
3514
                    s->current_picture.qscale_table[xy]= s->qscale;
3515

    
3516
                    s->cbp_table[xy]&= 3; //remove dquant
3517
                    s->cbp_table[xy]|= (cbpy^0xf)<<2;
3518
                }
3519
            }
3520
        }
3521
        if(mb_num >= mb_count) return 0;
3522
        s->mb_x= 0;
3523
    }
3524
    return 0;
3525
}
3526

    
3527
/**
3528
 * decodes the first & second partition
3529
 * @return <0 if error (and sets error type in the error_status_table)
3530
 */
3531
int ff_mpeg4_decode_partitions(MpegEncContext *s)
3532
{
3533
    int mb_num;
3534
    const int part_a_error= s->pict_type==I_TYPE ? (DC_ERROR|MV_ERROR) : MV_ERROR;
3535
    const int part_a_end  = s->pict_type==I_TYPE ? (DC_END  |MV_END)   : MV_END;
3536
    
3537
    mb_num= mpeg4_decode_partition_a(s);    
3538
    if(mb_num<0){
3539
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3540
        return -1;
3541
    }
3542
    
3543
    if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
3544
        av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
3545
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3546
        return -1;
3547
    }
3548

    
3549
    s->mb_num_left= mb_num;
3550
        
3551
    if(s->pict_type==I_TYPE){
3552
        while(show_bits(&s->gb, 9) == 1)
3553
            skip_bits(&s->gb, 9);
3554
        if(get_bits_long(&s->gb, 19)!=DC_MARKER){
3555
            av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
3556
            return -1;
3557
        }
3558
    }else{
3559
        while(show_bits(&s->gb, 10) == 1)
3560
            skip_bits(&s->gb, 10);
3561
        if(get_bits(&s->gb, 17)!=MOTION_MARKER){
3562
            av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
3563
            return -1;
3564
        }
3565
    }
3566
    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, part_a_end);
3567
    
3568
    if( mpeg4_decode_partition_b(s, mb_num) < 0){
3569
        if(s->pict_type==P_TYPE)
3570
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, DC_ERROR);
3571
        return -1;
3572
    }else{
3573
        if(s->pict_type==P_TYPE)
3574
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, DC_END);
3575
    }
3576

    
3577
    return 0;        
3578
}
3579

    
3580
/**
3581
 * decode partition C of one MB.
3582
 * @return <0 if an error occured
3583
 */
3584
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
3585
{
3586
    int cbp, mb_type;
3587
    const int xy= s->mb_x + s->mb_y*s->mb_stride;
3588

    
3589
    mb_type= s->current_picture.mb_type[xy];
3590
    cbp = s->cbp_table[xy];
3591

    
3592
    if(s->current_picture.qscale_table[xy] != s->qscale){
3593
        ff_set_qscale(s, s->current_picture.qscale_table[xy] );
3594
    }
3595
    
3596
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3597
        int i;
3598
        for(i=0; i<4; i++){
3599
            s->mv[0][i][0] = s->current_picture.motion_val[0][ s->block_index[i] ][0];
3600
            s->mv[0][i][1] = s->current_picture.motion_val[0][ s->block_index[i] ][1];
3601
        }
3602
        s->mb_intra = IS_INTRA(mb_type);
3603

    
3604
        if (IS_SKIP(mb_type)) {
3605
            /* skip mb */
3606
            for(i=0;i<6;i++)
3607
                s->block_last_index[i] = -1;
3608
            s->mv_dir = MV_DIR_FORWARD;
3609
            s->mv_type = MV_TYPE_16X16;
3610
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3611
                s->mcsel=1;
3612
                s->mb_skiped = 0;
3613
            }else{
3614
                s->mcsel=0;
3615
                s->mb_skiped = 1;
3616
            }
3617
        }else if(s->mb_intra){
3618
            s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3619
        }else if(!s->mb_intra){
3620
//            s->mcsel= 0; //FIXME do we need to init that
3621
            
3622
            s->mv_dir = MV_DIR_FORWARD;
3623
            if (IS_8X8(mb_type)) {
3624
                s->mv_type = MV_TYPE_8X8;
3625
            } else {
3626
                s->mv_type = MV_TYPE_16X16;
3627
            }
3628
        }
3629
    } else { /* I-Frame */
3630
        s->mb_intra = 1;
3631
        s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3632
    }
3633

    
3634
    if (!IS_SKIP(mb_type)) {
3635
        int i;
3636
        /* decode each block */
3637
        for (i = 0; i < 6; i++) {
3638
            if(mpeg4_decode_block(s, block[i], i, cbp&32, s->mb_intra, s->rvlc) < 0){
3639
                av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra);
3640
                return -1;
3641
            }
3642
            cbp+=cbp;
3643
        }
3644
    }
3645

    
3646
    /* per-MB end of slice check */
3647

    
3648
    if(--s->mb_num_left <= 0){
3649
//printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size_in_bits - get_bits_count(&s->gb));
3650
        if(mpeg4_is_resync(s))
3651
            return SLICE_END;
3652
        else
3653
            return SLICE_NOEND;     
3654
    }else{
3655
        if(mpeg4_is_resync(s)){
3656
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
3657
            if(s->cbp_table[xy+delta])
3658
                return SLICE_END;
3659
        }
3660
        return SLICE_OK;
3661
    }
3662
}
3663

    
3664
/**
3665
 * read the next MVs for OBMC. yes this is a ugly hack, feel free to send a patch :)
3666
 */
3667
static void preview_obmc(MpegEncContext *s){
3668
    GetBitContext gb= s->gb;
3669
    
3670
    int cbpc, i, pred_x, pred_y, mx, my;
3671
    int16_t *mot_val;
3672
    const int xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
3673
    const int stride= s->b8_stride*2;
3674
    
3675
    for(i=0; i<4; i++)
3676
        s->block_index[i]+= 2;
3677
    for(i=4; i<6; i++)
3678
        s->block_index[i]+= 1;
3679
    s->mb_x++;
3680
    
3681
    assert(s->pict_type == P_TYPE);
3682

    
3683
    do{
3684
        if (get_bits1(&s->gb)) {
3685
            /* skip mb */
3686
            mot_val = s->current_picture.motion_val[0][ s->block_index[0] ];
3687
            mot_val[0       ]= mot_val[2       ]= 
3688
            mot_val[0+stride]= mot_val[2+stride]= 0;
3689
            mot_val[1       ]= mot_val[3       ]=
3690
            mot_val[1+stride]= mot_val[3+stride]= 0;
3691
            
3692
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3693
            goto end;
3694
        }
3695
        cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3696
    }while(cbpc == 20);
3697
    
3698
    if(cbpc & 4){
3699
        s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3700
    }else{
3701
        get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3702
        if (cbpc & 8) {
3703
            if(s->modified_quant){
3704
                if(get_bits1(&s->gb)) skip_bits(&s->gb, 1);
3705
                else                  skip_bits(&s->gb, 5);
3706
            }else
3707
                skip_bits(&s->gb, 2);
3708
        }
3709
        
3710
        if ((cbpc & 16) == 0) {
3711
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
3712
                /* 16x16 motion prediction */
3713
                mot_val= h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3714
                if (s->umvplus)
3715
                   mx = h263p_decode_umotion(s, pred_x);
3716
                else
3717
                   mx = h263_decode_motion(s, pred_x, 1);
3718
            
3719
                if (s->umvplus)
3720
                   my = h263p_decode_umotion(s, pred_y);
3721
                else
3722
                   my = h263_decode_motion(s, pred_y, 1);
3723
            
3724
                mot_val[0       ]= mot_val[2       ]= 
3725
                mot_val[0+stride]= mot_val[2+stride]= mx;
3726
                mot_val[1       ]= mot_val[3       ]=
3727
                mot_val[1+stride]= mot_val[3+stride]= my;
3728
        } else {
3729
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
3730
            for(i=0;i<4;i++) {
3731
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3732
                if (s->umvplus)
3733
                  mx = h263p_decode_umotion(s, pred_x);
3734
                else
3735
                  mx = h263_decode_motion(s, pred_x, 1);
3736
                
3737
                if (s->umvplus)
3738
                  my = h263p_decode_umotion(s, pred_y);
3739
                else    
3740
                  my = h263_decode_motion(s, pred_y, 1);
3741
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3742
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3743
                mot_val[0] = mx;
3744
                mot_val[1] = my;
3745
            }
3746
        }
3747
    }
3748
end:
3749
        
3750
    for(i=0; i<4; i++)
3751
        s->block_index[i]-= 2;
3752
    for(i=4; i<6; i++)
3753
        s->block_index[i]-= 1;
3754
    s->mb_x--;
3755

    
3756
    s->gb= gb;
3757
}
3758

    
3759
static void h263_decode_dquant(MpegEncContext *s){
3760
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3761

    
3762
    if(s->modified_quant){
3763
        if(get_bits1(&s->gb))
3764
            s->qscale= modified_quant_tab[get_bits1(&s->gb)][ s->qscale ];
3765
        else
3766
            s->qscale= get_bits(&s->gb, 5);
3767
    }else
3768
        s->qscale += quant_tab[get_bits(&s->gb, 2)];
3769
    ff_set_qscale(s, s->qscale);
3770
}
3771

    
3772
int ff_h263_decode_mb(MpegEncContext *s,
3773
                      DCTELEM block[6][64])
3774
{
3775
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
3776
    int16_t *mot_val;
3777
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
3778
    
3779
    assert(!s->h263_pred);
3780
    
3781
    if (s->pict_type == P_TYPE) {
3782
        do{
3783
            if (get_bits1(&s->gb)) {
3784
                /* skip mb */
3785
                s->mb_intra = 0;
3786
                for(i=0;i<6;i++)
3787
                    s->block_last_index[i] = -1;
3788
                s->mv_dir = MV_DIR_FORWARD;
3789
                s->mv_type = MV_TYPE_16X16;
3790
                s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3791
                s->mv[0][0][0] = 0;
3792
                s->mv[0][0][1] = 0;
3793
                s->mb_skiped = !(s->obmc | s->loop_filter);
3794
                goto end;
3795
            }
3796
            cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3797
            //fprintf(stderr, "\tCBPC: %d", cbpc);
3798
            if (cbpc < 0){
3799
                av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
3800
                return -1;
3801
            }
3802
        }while(cbpc == 20);
3803
        
3804
        dquant = cbpc & 8;
3805
        s->mb_intra = ((cbpc & 4) != 0);
3806
        if (s->mb_intra) goto intra;
3807
        
3808
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3809
        
3810
        if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
3811
            cbpy ^= 0xF;
3812
        
3813
        cbp = (cbpc & 3) | (cbpy << 2);
3814
        if (dquant) {
3815
            h263_decode_dquant(s);
3816
        }
3817
        
3818
        s->mv_dir = MV_DIR_FORWARD;
3819
        if ((cbpc & 16) == 0) {
3820
            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
3821
            /* 16x16 motion prediction */
3822
            s->mv_type = MV_TYPE_16X16;
3823
            h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3824
            if (s->umvplus)
3825
               mx = h263p_decode_umotion(s, pred_x);
3826
            else
3827
               mx = h263_decode_motion(s, pred_x, 1);
3828
            
3829
            if (mx >= 0xffff)
3830
                return -1;
3831
            
3832
            if (s->umvplus)
3833
               my = h263p_decode_umotion(s, pred_y);
3834
            else
3835
               my = h263_decode_motion(s, pred_y, 1);
3836
            
3837
            if (my >= 0xffff)
3838
                return -1;
3839
            s->mv[0][0][0] = mx;
3840
            s->mv[0][0][1] = my;
3841

    
3842
            if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3843
               skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */                   
3844
        } else {
3845
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
3846
            s->mv_type = MV_TYPE_8X8;
3847
            for(i=0;i<4;i++) {
3848
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3849
                if (s->umvplus)
3850
                  mx = h263p_decode_umotion(s, pred_x);
3851
                else
3852
                  mx = h263_decode_motion(s, pred_x, 1);
3853
                if (mx >= 0xffff)
3854
                    return -1;
3855
                
3856
                if (s->umvplus)
3857
                  my = h263p_decode_umotion(s, pred_y);
3858
                else    
3859
                  my = h263_decode_motion(s, pred_y, 1);
3860
                if (my >= 0xffff)
3861
                    return -1;
3862
                s->mv[0][i][0] = mx;
3863
                s->mv[0][i][1] = my;
3864
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3865
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3866
                mot_val[0] = mx;
3867
                mot_val[1] = my;
3868
            }
3869
        }
3870

    
3871
        /* decode each block */
3872
        for (i = 0; i < 6; i++) {
3873
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3874
                return -1;
3875
            cbp+=cbp;
3876
        }
3877

    
3878
        if(s->obmc){
3879
            if(s->pict_type == P_TYPE && s->mb_x+1<s->mb_width && s->mb_num_left != 1)
3880
                preview_obmc(s);
3881
        }
3882
    } else if(s->pict_type==B_TYPE) {
3883
        int mb_type;
3884
        const int stride= s->b8_stride;
3885
        int16_t *mot_val0 = s->current_picture.motion_val[0][ 2*(s->mb_x + s->mb_y*stride) ];
3886
        int16_t *mot_val1 = s->current_picture.motion_val[1][ 2*(s->mb_x + s->mb_y*stride) ];
3887
//        const int mv_xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
3888

    
3889
        //FIXME ugly 
3890
        mot_val0[0       ]= mot_val0[2       ]= mot_val0[0+2*stride]= mot_val0[2+2*stride]= 
3891
        mot_val0[1       ]= mot_val0[3       ]= mot_val0[1+2*stride]= mot_val0[3+2*stride]= 
3892
        mot_val1[0       ]= mot_val1[2       ]= mot_val1[0+2*stride]= mot_val1[2+2*stride]= 
3893
        mot_val1[1       ]= mot_val1[3       ]= mot_val1[1+2*stride]= mot_val1[3+2*stride]= 0;
3894

    
3895
        do{
3896
            mb_type= get_vlc2(&s->gb, h263_mbtype_b_vlc.table, H263_MBTYPE_B_VLC_BITS, 2);
3897
            if (mb_type < 0){
3898
                av_log(s->avctx, AV_LOG_ERROR, "b mb_type damaged at %d %d\n", s->mb_x, s->mb_y);
3899
                return -1;
3900
            }
3901

    
3902
            mb_type= h263_mb_type_b_map[ mb_type ];
3903
        }while(!mb_type);
3904

    
3905
        s->mb_intra = IS_INTRA(mb_type);
3906
        if(HAS_CBP(mb_type)){
3907
            cbpc = get_vlc2(&s->gb, cbpc_b_vlc.table, CBPC_B_VLC_BITS, 1);
3908
            if(s->mb_intra){
3909
                dquant = IS_QUANT(mb_type);
3910
                goto intra;
3911
            }
3912

    
3913
            cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3914

    
3915
            if (cbpy < 0){
3916
                av_log(s->avctx, AV_LOG_ERROR, "b cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
3917
                return -1;
3918
            }
3919
        
3920
            if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
3921
                cbpy ^= 0xF;
3922
        
3923
            cbp = (cbpc & 3) | (cbpy << 2);
3924
        }else
3925
            cbp=0;
3926
            
3927
        assert(!s->mb_intra);
3928

    
3929
        if(IS_QUANT(mb_type)){
3930
            h263_decode_dquant(s);
3931
        }
3932

    
3933
        if(IS_DIRECT(mb_type)){
3934
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3935
            mb_type |= ff_mpeg4_set_direct_mv(s, 0, 0);
3936
        }else{
3937
            s->mv_dir = 0;
3938
            s->mv_type= MV_TYPE_16X16;
3939
//FIXME UMV
3940

    
3941
            if(USES_LIST(mb_type, 0)){
3942
                int16_t *mot_val= h263_pred_motion(s, 0, 0, &mx, &my);
3943
                s->mv_dir = MV_DIR_FORWARD;
3944

    
3945
                mx = h263_decode_motion(s, mx, 1);
3946
                my = h263_decode_motion(s, my, 1);
3947
                
3948
                s->mv[0][0][0] = mx;
3949
                s->mv[0][0][1] = my;
3950
                mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
3951
                mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
3952
            }
3953
    
3954
            if(USES_LIST(mb_type, 1)){
3955
                int16_t *mot_val= h263_pred_motion(s, 0, 1, &mx, &my);
3956
                s->mv_dir |= MV_DIR_BACKWARD;
3957
                
3958
                mx = h263_decode_motion(s, mx, 1);
3959
                my = h263_decode_motion(s, my, 1);
3960

    
3961
                s->mv[1][0][0] = mx;
3962
                s->mv[1][0][1] = my;
3963
                mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
3964
                mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
3965
            }
3966
        }
3967
          
3968
        s->current_picture.mb_type[xy]= mb_type;
3969

    
3970
        /* decode each block */
3971
        for (i = 0; i < 6; i++) {
3972
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3973
                return -1;
3974
            cbp+=cbp;
3975
        }
3976
    } else { /* I-Frame */
3977
        do{
3978
            cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
3979
            if (cbpc < 0){
3980
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
3981
                return -1;
3982
            }
3983
        }while(cbpc == 8);
3984

    
3985
        dquant = cbpc & 4;
3986
        s->mb_intra = 1;
3987
intra:
3988
        s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3989
        if (s->h263_aic) {
3990
            s->ac_pred = get_bits1(&s->gb);
3991
            if(s->ac_pred){
3992
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
3993
            
3994
                s->h263_aic_dir = get_bits1(&s->gb);
3995
            }
3996
        }else
3997
            s->ac_pred = 0;
3998
        
3999
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
4000
        if(cbpy<0){
4001
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
4002
            return -1;
4003
        }
4004
        cbp = (cbpc & 3) | (cbpy << 2);
4005
        if (dquant) {
4006
            h263_decode_dquant(s);
4007
        }
4008

    
4009
        /* decode each block */
4010
        for (i = 0; i < 6; i++) {
4011
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
4012
                return -1;
4013
            cbp+=cbp;
4014
        }
4015
    }
4016
end:
4017

    
4018
        /* per-MB end of slice check */
4019
    {
4020
        int v= show_bits(&s->gb, 16);
4021
    
4022
        if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
4023
            v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
4024
        }
4025

    
4026
        if(v==0)
4027
            return SLICE_END;
4028
    }
4029

    
4030
    return SLICE_OK;     
4031
}
4032

    
4033
int ff_mpeg4_decode_mb(MpegEncContext *s,
4034
                      DCTELEM block[6][64])
4035
{
4036
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
4037
    int16_t *mot_val;
4038
    static int8_t quant_tab[4] = { -1, -2, 1, 2 };
4039
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
4040
    
4041
    assert(s->h263_pred);
4042
    
4043
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
4044
        do{
4045
            if (get_bits1(&s->gb)) {
4046
                /* skip mb */
4047
                s->mb_intra = 0;
4048
                for(i=0;i<6;i++)
4049
                    s->block_last_index[i] = -1;
4050
                s->mv_dir = MV_DIR_FORWARD;
4051
                s->mv_type = MV_TYPE_16X16;
4052
                if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
4053
                    s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
4054
                    s->mcsel=1;
4055
                    s->mv[0][0][0]= get_amv(s, 0);
4056
                    s->mv[0][0][1]= get_amv(s, 1);
4057

    
4058
                    s->mb_skiped = 0;
4059
                }else{
4060
                    s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
4061
                    s->mcsel=0;
4062
                    s->mv[0][0][0] = 0;
4063
                    s->mv[0][0][1] = 0;
4064
                    s->mb_skiped = 1;
4065
                }
4066
                goto end;
4067
            }
4068
            cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
4069
            //fprintf(stderr, "\tCBPC: %d", cbpc);
4070
            if (cbpc < 0){
4071
                av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
4072
                return -1;
4073
            }
4074
        }while(cbpc == 20);
4075
        
4076
        dquant = cbpc & 8;
4077
        s->mb_intra = ((cbpc & 4) != 0);
4078
        if (s->mb_intra) goto intra;
4079
        
4080
        if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
4081
            s->mcsel= get_bits1(&s->gb);
4082
        else s->mcsel= 0;
4083
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
4084
        
4085
        cbp = (cbpc & 3) | (cbpy << 2);
4086
        if (dquant) {
4087
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
4088
        }
4089
        if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
4090
            s->interlaced_dct= get_bits1(&s->gb);
4091
        
4092
        s->mv_dir = MV_DIR_FORWARD;
4093
        if ((cbpc & 16) == 0) {
4094
            if(s->mcsel){
4095
                s->current_picture.mb_type[xy]= MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
4096
                /* 16x16 global motion prediction */
4097
                s->mv_type = MV_TYPE_16X16;
4098
                mx= get_amv(s, 0);
4099
                my= get_amv(s, 1);
4100
                s->mv[0][0][0] = mx;
4101
                s->mv[0][0][1] = my;
4102
            }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
4103
                s->current_picture.mb_type[xy]= MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; 
4104
                /* 16x8 field motion prediction */
4105
                s->mv_type= MV_TYPE_FIELD;
4106

    
4107
                s->field_select[0][0]= get_bits1(&s->gb);
4108
                s->field_select[0][1]= get_bits1(&s->gb);
4109

    
4110
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
4111
                
4112
                for(i=0; i<2; i++){
4113
                    mx = h263_decode_motion(s, pred_x, s->f_code);
4114
                    if (mx >= 0xffff)
4115
                        return -1;
4116
            
4117
                    my = h263_decode_motion(s, pred_y/2, s->f_code);
4118
                    if (my >= 0xffff)
4119
                        return -1;
4120

    
4121
                    s->mv[0][i][0] = mx;
4122
                    s->mv[0][i][1] = my;
4123
                }
4124
            }else{
4125
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
4126
                /* 16x16 motion prediction */
4127
                s->mv_type = MV_TYPE_16X16;
4128
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
4129
                mx = h263_decode_motion(s, pred_x, s->f_code);
4130
            
4131
                if (mx >= 0xffff)
4132
                    return -1;
4133
            
4134
                my = h263_decode_motion(s, pred_y, s->f_code);
4135
            
4136
                if (my >= 0xffff)
4137
                    return -1;
4138
                s->mv[0][0][0] = mx;
4139
                s->mv[0][0][1] = my;
4140
            }
4141
        } else {
4142
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
4143
            s->mv_type = MV_TYPE_8X8;
4144
            for(i=0;i<4;i++) {
4145
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
4146
                mx = h263_decode_motion(s, pred_x, s->f_code);
4147
                if (mx >= 0xffff)
4148
                    return -1;
4149
                
4150
                my = h263_decode_motion(s, pred_y, s->f_code);
4151
                if (my >= 0xffff)
4152
                    return -1;
4153
                s->mv[0][i][0] = mx;
4154
                s->mv[0][i][1] = my;
4155
                mot_val[0] = mx;
4156
                mot_val[1] = my;
4157
            }
4158
        }
4159
    } else if(s->pict_type==B_TYPE) {
4160
        int modb1; // first bit of modb
4161
        int modb2; // second bit of modb
4162
        int mb_type;
4163

    
4164
        s->mb_intra = 0; //B-frames never contain intra blocks
4165
        s->mcsel=0;      //     ...               true gmc blocks
4166

    
4167
        if(s->mb_x==0){
4168
            for(i=0; i<2; i++){
4169
                s->last_mv[i][0][0]= 
4170
                s->last_mv[i][0][1]= 
4171
                s->last_mv[i][1][0]= 
4172
                s->last_mv[i][1][1]= 0;
4173
            }
4174
        }
4175

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

    
4179
        if(s->mb_skiped){
4180
                /* skip mb */
4181
            for(i=0;i<6;i++)
4182
                s->block_last_index[i] = -1;
4183

    
4184
            s->mv_dir = MV_DIR_FORWARD;
4185
            s->mv_type = MV_TYPE_16X16;
4186
            s->mv[0][0][0] = 0;
4187
            s->mv[0][0][1] = 0;
4188
            s->mv[1][0][0] = 0;
4189
            s->mv[1][0][1] = 0;
4190
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; 
4191
            goto end;
4192
        }
4193

    
4194
        modb1= get_bits1(&s->gb); 
4195
        if(modb1){
4196
            mb_type= MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; //like MB_TYPE_B_DIRECT but no vectors coded
4197
            cbp=0;
4198
        }else{
4199
            modb2= get_bits1(&s->gb);
4200
            mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
4201
            if(mb_type<0){
4202
                av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
4203
                return -1;
4204
            }
4205
            mb_type= mb_type_b_map[ mb_type ];
4206
            if(modb2) cbp= 0;
4207
            else      cbp= get_bits(&s->gb, 6);
4208

    
4209
            if ((!IS_DIRECT(mb_type)) && cbp) {
4210
                if(get_bits1(&s->gb)){
4211
                    ff_set_qscale(s, s->qscale + get_bits1(&s->gb)*4 - 2);
4212
                }
4213
            }
4214

    
4215
            if(!s->progressive_sequence){
4216
                if(cbp)
4217
                    s->interlaced_dct= get_bits1(&s->gb);
4218

    
4219
                if(!IS_DIRECT(mb_type) && get_bits1(&s->gb)){
4220
                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
4221
                    mb_type &= ~MB_TYPE_16x16;
4222

    
4223
                    if(USES_LIST(mb_type, 0)){
4224
                        s->field_select[0][0]= get_bits1(&s->gb);
4225
                        s->field_select[0][1]= get_bits1(&s->gb);
4226
                    }
4227
                    if(USES_LIST(mb_type, 1)){
4228
                        s->field_select[1][0]= get_bits1(&s->gb);
4229
                        s->field_select[1][1]= get_bits1(&s->gb);
4230
                    }
4231
                }
4232
            }
4233

    
4234
            s->mv_dir = 0;
4235
            if((mb_type & (MB_TYPE_DIRECT2|MB_TYPE_INTERLACED)) == 0){
4236
                s->mv_type= MV_TYPE_16X16;
4237

    
4238
                if(USES_LIST(mb_type, 0)){
4239
                    s->mv_dir = MV_DIR_FORWARD;
4240

    
4241
                    mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
4242
                    my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
4243
                    s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
4244
                    s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
4245
                }
4246
    
4247
                if(USES_LIST(mb_type, 1)){
4248
                    s->mv_dir |= MV_DIR_BACKWARD;
4249

    
4250
                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
4251
                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
4252
                    s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
4253
                    s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
4254
                }
4255
            }else if(!IS_DIRECT(mb_type)){
4256
                s->mv_type= MV_TYPE_FIELD;
4257

    
4258
                if(USES_LIST(mb_type, 0)){
4259
                    s->mv_dir = MV_DIR_FORWARD;
4260
                
4261
                    for(i=0; i<2; i++){
4262
                        mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
4263
                        my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
4264
                        s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
4265
                        s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
4266
                    }
4267
                }
4268
    
4269
                if(USES_LIST(mb_type, 1)){
4270
                    s->mv_dir |= MV_DIR_BACKWARD;
4271

    
4272
                    for(i=0; i<2; i++){
4273
                        mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
4274
                        my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
4275
                        s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
4276
                        s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
4277
                    }
4278
                }
4279
            }
4280
        }
4281
          
4282
        if(IS_DIRECT(mb_type)){
4283
            if(IS_SKIP(mb_type))
4284
                mx=my=0;
4285
            else{
4286
                mx = h263_decode_motion(s, 0, 1);
4287
                my = h263_decode_motion(s, 0, 1);
4288
            }
4289
 
4290
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
4291
            mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
4292
        }
4293
        s->current_picture.mb_type[xy]= mb_type;
4294
    } else { /* I-Frame */
4295
        do{
4296
            cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
4297
            if (cbpc < 0){
4298
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
4299
                return -1;
4300
            }
4301
        }while(cbpc == 8);
4302

    
4303
        dquant = cbpc & 4;
4304
        s->mb_intra = 1;
4305
intra:
4306
        s->ac_pred = get_bits1(&s->gb);
4307
        if(s->ac_pred)
4308
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
4309
        else
4310
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
4311
        
4312
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
4313
        if(cbpy<0){
4314
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
4315
            return -1;
4316
        }
4317
        cbp = (cbpc & 3) | (cbpy << 2);
4318
        if (dquant) {
4319
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
4320
        }
4321
        
4322
        if(!s->progressive_sequence)
4323
            s->interlaced_dct= get_bits1(&s->gb);
4324

    
4325
        /* decode each block */
4326
        for (i = 0; i < 6; i++) {
4327
            if (mpeg4_decode_block(s, block[i], i, cbp&32, 1, 0) < 0)
4328
                return -1;
4329
            cbp+=cbp;
4330
        }
4331
        goto end;
4332
    }
4333

    
4334
    /* decode each block */
4335
    for (i = 0; i < 6; i++) {
4336
        if (mpeg4_decode_block(s, block[i], i, cbp&32, 0, 0) < 0)
4337
            return -1;
4338
        cbp+=cbp;
4339
    }
4340
end:
4341

    
4342
        /* per-MB end of slice check */
4343
    if(s->codec_id==CODEC_ID_MPEG4){
4344
        if(mpeg4_is_resync(s)){
4345
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
4346
            if(s->pict_type==B_TYPE && s->next_picture.mbskip_table[xy + delta])
4347
                return SLICE_OK;
4348
            return SLICE_END;
4349
        }
4350
    }
4351

    
4352
    return SLICE_OK;     
4353
}
4354

    
4355
static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
4356
{
4357
    int code, val, sign, shift, l;
4358
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
4359

    
4360
    if (code == 0)
4361
        return pred;
4362
    if (code < 0)
4363
        return 0xffff;
4364

    
4365
    sign = get_bits1(&s->gb);
4366
    shift = f_code - 1;
4367
    val = code;
4368
    if (shift) {
4369
        val = (val - 1) << shift;
4370
        val |= get_bits(&s->gb, shift);
4371
        val++;
4372
    }
4373
    if (sign)
4374
        val = -val;
4375
    val += pred;
4376

    
4377
    /* modulo decoding */
4378
    if (!s->h263_long_vectors) {
4379
        l = 1 << (f_code + 4);
4380
        val = ((val + l)&(l*2-1)) - l;
4381
    } else {
4382
        /* horrible h263 long vector mode */
4383
        if (pred < -31 && val < -63)
4384
            val += 64;
4385
        if (pred > 32 && val > 63)
4386
            val -= 64;
4387
        
4388
    }
4389
    return val;
4390
}
4391

    
4392
/* Decodes RVLC of H.263+ UMV */
4393
static int h263p_decode_umotion(MpegEncContext * s, int pred)
4394
{
4395
   int code = 0, sign;
4396
   
4397
   if (get_bits1(&s->gb)) /* Motion difference = 0 */
4398
      return pred;
4399
   
4400
   code = 2 + get_bits1(&s->gb);
4401
   
4402
   while (get_bits1(&s->gb))
4403
   {
4404
      code <<= 1;
4405
      code += get_bits1(&s->gb);
4406
   }
4407
   sign = code & 1;
4408
   code >>= 1;
4409
   
4410
   code = (sign) ? (pred - code) : (pred + code);
4411
#ifdef DEBUG
4412
   fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
4413
#endif
4414
   return code;   
4415

    
4416
}
4417

    
4418
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
4419
                             int n, int coded)
4420
{
4421
    int code, level, i, j, last, run;
4422
    RLTable *rl = &rl_inter;
4423
    const uint8_t *scan_table;
4424
    GetBitContext gb= s->gb;
4425

    
4426
    scan_table = s->intra_scantable.permutated;
4427
    if (s->h263_aic && s->mb_intra) {
4428
        rl = &rl_intra_aic;
4429
        i = 0;
4430
        if (s->ac_pred) {
4431
            if (s->h263_aic_dir) 
4432
                scan_table = s->intra_v_scantable.permutated; /* left */
4433
            else
4434
                scan_table = s->intra_h_scantable.permutated; /* top */
4435
        }
4436
    } else if (s->mb_intra) {
4437
        /* DC coef */
4438
        if(s->codec_id == CODEC_ID_RV10){
4439
          if (s->rv10_version == 3 && s->pict_type == I_TYPE) {
4440
            int component, diff;
4441
            component = (n <= 3 ? 0 : n - 4 + 1);
4442
            level = s->last_dc[component];
4443
            if (s->rv10_first_dc_coded[component]) {
4444
                diff = rv_decode_dc(s, n);
4445
                if (diff == 0xffff)
4446
                    return -1;
4447
                level += diff;
4448
                level = level & 0xff; /* handle wrap round */
4449
                s->last_dc[component] = level;
4450
            } else {
4451
                s->rv10_first_dc_coded[component] = 1;
4452
            }
4453
          } else {
4454
                level = get_bits(&s->gb, 8);
4455
                if (level == 255)
4456
                    level = 128;
4457
          }
4458
        }else{
4459
            level = get_bits(&s->gb, 8);
4460
            if((level&0x7F) == 0){
4461
                av_log(s->avctx, AV_LOG_ERROR, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);
4462
                if(s->error_resilience >= FF_ER_COMPLIANT)
4463
                    return -1;
4464
            }
4465
            if (level == 255)
4466
                level = 128;
4467
        }
4468
        block[0] = level;
4469
        i = 1;
4470
    } else {
4471
        i = 0;
4472
    }
4473
    if (!coded) {
4474
        if (s->mb_intra && s->h263_aic)
4475
            goto not_coded;
4476
        s->block_last_index[n] = i - 1;
4477
        return 0;
4478
    }
4479
retry:
4480
    for(;;) {
4481
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
4482
        if (code < 0){
4483
            av_log(s->avctx, AV_LOG_ERROR, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
4484
            return -1;
4485
        }
4486
        if (code == rl->n) {
4487
            /* escape */
4488
            if (s->h263_flv > 1) {
4489
                int is11 = get_bits1(&s->gb);
4490
                last = get_bits1(&s->gb);
4491
                run = get_bits(&s->gb, 6);
4492
                if(is11){
4493
                    level = get_sbits(&s->gb, 11);
4494
                } else {
4495
                    level = get_sbits(&s->gb, 7);
4496
                }
4497
            } else {
4498
                last = get_bits1(&s->gb);
4499
                run = get_bits(&s->gb, 6);
4500
                level = (int8_t)get_bits(&s->gb, 8);
4501
                if(level == -128){
4502
                    if (s->codec_id == CODEC_ID_RV10) {
4503
                        /* XXX: should patch encoder too */
4504
                        level = get_sbits(&s->gb, 12);
4505
                    }else{
4506
                        level = get_bits(&s->gb, 5);
4507
                        level |= get_sbits(&s->gb, 6)<<5;
4508
                    }
4509
                }
4510
            }
4511
        } else {
4512
            run = rl->table_run[code];
4513
            level = rl->table_level[code];
4514
            last = code >= rl->last;
4515
            if (get_bits1(&s->gb))
4516
                level = -level;
4517
        }
4518
        i += run;
4519
        if (i >= 64){
4520
            if(s->alt_inter_vlc && rl == &rl_inter && !s->mb_intra){
4521
                //looks like a hack but no, its the way its supposed to work ...
4522
                rl = &rl_intra_aic;
4523
                i = 0;
4524
                s->gb= gb;
4525
                memset(block, 0, sizeof(DCTELEM)*64);
4526
                goto retry;
4527
            }
4528
            av_log(s->avctx, AV_LOG_ERROR, "run overflow at %dx%d\n", s->mb_x, s->mb_y);
4529
            return -1;
4530
        }
4531
        j = scan_table[i];
4532
        block[j] = level;
4533
        if (last)
4534
            break;
4535
        i++;
4536
    }
4537
not_coded:    
4538
    if (s->mb_intra && s->h263_aic) {
4539
        h263_pred_acdc(s, block, n);
4540
        i = 63;
4541
    }
4542
    s->block_last_index[n] = i;
4543
    return 0;
4544
}
4545

    
4546
/**
4547
 * decodes the dc value.
4548
 * @param n block index (0-3 are luma, 4-5 are chroma)
4549
 * @param dir_ptr the prediction direction will be stored here
4550
 * @return the quantized dc
4551
 */
4552
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
4553
{
4554
    int level, code;
4555

    
4556
    if (n < 4) 
4557
        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
4558
    else 
4559
        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
4560
    if (code < 0 || code > 9 /* && s->nbit<9 */){
4561
        av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
4562
        return -1;
4563
    }
4564
    if (code == 0) {
4565
        level = 0;
4566
    } else {
4567
        if(IS_3IV1){
4568
            if(code==1)
4569
                level= 2*get_bits1(&s->gb)-1;
4570
            else{
4571
                if(get_bits1(&s->gb))
4572
                    level = get_bits(&s->gb, code-1) + (1<<(code-1));
4573
                else
4574
                    level = -get_bits(&s->gb, code-1) - (1<<(code-1));
4575
            }
4576
        }else{
4577
            level = get_xbits(&s->gb, code);
4578
        }
4579

    
4580
        if (code > 8){
4581
            if(get_bits1(&s->gb)==0){ /* marker */
4582
                if(s->error_resilience>=2){
4583
                    av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
4584
                    return -1;
4585
                }
4586
            }
4587
        }
4588
    }
4589

    
4590
    return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
4591
}
4592

    
4593
/**
4594
 * decodes a block.
4595
 * @return <0 if an error occured
4596
 */
4597
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
4598
                              int n, int coded, int intra, int rvlc)
4599
{
4600
    int level, i, last, run;
4601
    int dc_pred_dir;
4602
    RLTable * rl;
4603
    RL_VLC_ELEM * rl_vlc;
4604
    const uint8_t * scan_table;
4605
    int qmul, qadd;
4606

    
4607
    //Note intra & rvlc should be optimized away if this is inlined
4608
    
4609
    if(intra) {
4610
      if(s->qscale < s->intra_dc_threshold){
4611
        /* DC coef */
4612
        if(s->partitioned_frame){
4613
            level = s->dc_val[0][ s->block_index[n] ];
4614
            if(n<4) level= FASTDIV((level + (s->y_dc_scale>>1)), s->y_dc_scale);
4615
            else    level= FASTDIV((level + (s->c_dc_scale>>1)), s->c_dc_scale);
4616
            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_stride]<<n)&32;
4617
        }else{
4618
            level = mpeg4_decode_dc(s, n, &dc_pred_dir);
4619
            if (level < 0)
4620
                return -1;
4621
        }
4622
        block[0] = level;
4623
        i = 0;
4624
      }else{
4625
            i = -1;
4626
      }  
4627
        if (!coded) 
4628
            goto not_coded;
4629
        
4630
        if(rvlc){        
4631
            rl = &rvlc_rl_intra;
4632
            rl_vlc = rvlc_rl_intra.rl_vlc[0];
4633
        }else{
4634
            rl = &rl_intra;
4635
            rl_vlc = rl_intra.rl_vlc[0];
4636
        }
4637
        if (s->ac_pred) {
4638
            if (dc_pred_dir == 0) 
4639
                scan_table = s->intra_v_scantable.permutated; /* left */
4640
            else
4641
                scan_table = s->intra_h_scantable.permutated; /* top */
4642
        } else {
4643
            scan_table = s->intra_scantable.permutated;
4644
        }
4645
        qmul=1;
4646
        qadd=0;
4647
    } else {
4648
        i = -1;
4649
        if (!coded) {
4650
            s->block_last_index[n] = i;
4651
            return 0;
4652
        }
4653
        if(rvlc) rl = &rvlc_rl_inter;
4654
        else     rl = &rl_inter;
4655
   
4656
        scan_table = s->intra_scantable.permutated;
4657

    
4658
        if(s->mpeg_quant){
4659
            qmul=1;
4660
            qadd=0;
4661
            if(rvlc){        
4662
                rl_vlc = rvlc_rl_inter.rl_vlc[0];        
4663
            }else{
4664
                rl_vlc = rl_inter.rl_vlc[0];        
4665
            }
4666
        }else{
4667
            qmul = s->qscale << 1;
4668
            qadd = (s->qscale - 1) | 1;
4669
            if(rvlc){        
4670
                rl_vlc = rvlc_rl_inter.rl_vlc[s->qscale];        
4671
            }else{
4672
                rl_vlc = rl_inter.rl_vlc[s->qscale];        
4673
            }
4674
        }
4675
    }
4676
  {
4677
    OPEN_READER(re, &s->gb);
4678
    for(;;) {
4679
        UPDATE_CACHE(re, &s->gb);
4680
        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
4681
        if (level==0) {
4682
          /* escape */                
4683
          if(rvlc){
4684
                if(SHOW_UBITS(re, &s->gb, 1)==0){
4685
                    av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n");
4686
                    return -1;
4687
                }; SKIP_CACHE(re, &s->gb, 1);
4688
 
4689
                last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
4690
                run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
4691
                SKIP_COUNTER(re, &s->gb, 1+1+6);
4692
                UPDATE_CACHE(re, &s->gb);
4693
              
4694
                if(SHOW_UBITS(re, &s->gb, 1)==0){
4695
                    av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n");
4696
                    return -1;
4697
                }; SKIP_CACHE(re, &s->gb, 1);
4698
 
4699
                level= SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11);
4700
 
4701
                if(SHOW_UBITS(re, &s->gb, 5)!=0x10){
4702
                    av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
4703
                    return -1;
4704
                }; SKIP_CACHE(re, &s->gb, 5);
4705

    
4706
                level=  level * qmul + qadd;
4707
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1);
4708
                SKIP_COUNTER(re, &s->gb, 1+11+5+1);
4709

    
4710
                i+= run + 1;
4711
                if(last) i+=192;
4712
          }else{
4713
            int cache;
4714
            cache= GET_CACHE(re, &s->gb);
4715

    
4716
            if(IS_3IV1) 
4717
                cache ^= 0xC0000000;
4718

    
4719
            if (cache&0x80000000) {
4720
                if (cache&0x40000000) {
4721
                    int ulevel;
4722

    
4723
                    /* third escape */
4724
                    SKIP_CACHE(re, &s->gb, 2);
4725
                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
4726
                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
4727
                    SKIP_COUNTER(re, &s->gb, 2+1+6);
4728
                    UPDATE_CACHE(re, &s->gb);
4729

    
4730
                    if(IS_3IV1){
4731
                        level= SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12);
4732
                    }else{
4733
                        if(SHOW_UBITS(re, &s->gb, 1)==0){
4734
                            av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n");
4735
                            return -1;
4736
                        }; SKIP_CACHE(re, &s->gb, 1);
4737

    
4738
                        level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
4739

    
4740
                        if(SHOW_UBITS(re, &s->gb, 1)==0){
4741
                            av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n");
4742
                            return -1;
4743
                        }; LAST_SKIP_CACHE(re, &s->gb, 1);
4744

    
4745
                        SKIP_COUNTER(re, &s->gb, 1+12+1);
4746
                    }
4747
 
4748
                    if(s->mpeg_quant){
4749
                        if(intra) ulevel= level*s->qscale*s->intra_matrix[scan_table[1]];
4750
                        else      ulevel= level*s->qscale*s->inter_matrix[scan_table[0]];
4751
                    }else
4752
                        ulevel= level*s->qscale*16;
4753
                    if(ulevel>1030*16 || ulevel<-1030*16){
4754
                        av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
4755
                        return -1;
4756
                    }
4757

    
4758
#if 0
4759
                    if(s->error_resilience >= FF_ER_COMPLIANT){
4760
                        const int abs_level= ABS(level);
4761
                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN){
4762
                            const int run1= run - rl->max_run[last][abs_level] - 1;
4763
                            if(abs_level <= rl->max_level[last][run]){
4764
                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
4765
                                return -1;
4766
                            }
4767
                            if(s->error_resilience > FF_ER_COMPLIANT){
4768
                                if(abs_level <= rl->max_level[last][run]*2){
4769
                                    fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");
4770
                                    return -1;
4771
                                }
4772
                                if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){