Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h263.c @ 49f3806d

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, uint16_t **dc_val_ptr, int *dir_ptr);
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

    
501
/**
502
 * modify mb_type & qscale so that encoding is acually possible in mpeg4
503
 */
504
void ff_clean_mpeg4_qscales(MpegEncContext *s){
505
    int i;
506
    int8_t * const qscale_table= s->current_picture.qscale_table;
507

    
508
    ff_clean_h263_qscales(s);
509
    
510
    for(i=1; i<s->mb_num; i++){
511
        int mb_xy= s->mb_index2xy[i];
512
    
513
        if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTER4V)){
514
            s->mb_type[mb_xy]&= ~CANDIDATE_MB_TYPE_INTER4V;
515
            s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_INTER;
516
        }
517
    }
518

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

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

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

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

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

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

    
663
#ifdef CONFIG_ENCODERS
664

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
941
                        if(pic==NULL || pic->pict_type!=B_TYPE) break;
942

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1073
        for(i=0; i<6; i++){
1074
            const int level= block[i][0];
1075
            uint16_t *dc_ptr;
1076

    
1077
            dc_diff[i]= level - ff_mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
1078
            if (i < 4) {
1079
                *dc_ptr = level * s->y_dc_scale;
1080
            } else {
1081
                *dc_ptr = level * s->c_dc_scale;
1082
            }
1083
        }
1084

    
1085
        if(s->flags & CODEC_FLAG_AC_PRED){
1086
            s->ac_pred= decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
1087
            if(!s->ac_pred)
1088
                restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1089
        }else{
1090
            for(i=0; i<6; i++)
1091
                scan_table[i]= s->intra_scantable.permutated;
1092
        }
1093

    
1094
        /* compute cbp */
1095
        cbp = 0;
1096
        for (i = 0; i < 6; i++) {
1097
            if (s->block_last_index[i] >= 1)
1098
                cbp |= 1 << (5 - i);
1099
        }
1100

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

    
1120
        if(!s->progressive_sequence){
1121
            put_bits(dc_pb, 1, s->interlaced_dct);
1122
        }
1123

    
1124
        if(interleaved_stats){
1125
            s->misc_bits+= get_bits_diff(s);
1126
        }
1127

    
1128
        /* encode each block */
1129
        for (i = 0; i < 6; i++) {
1130
            mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
1131
        }
1132

    
1133
        if(interleaved_stats){
1134
            s->i_tex_bits+= get_bits_diff(s);
1135
        }
1136
        s->i_count++;
1137

    
1138
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
1139
        if(s->ac_pred)
1140
            restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1141
    }
1142
}
1143

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

    
1160
        if ((cbp | motion_x | motion_y | s->dquant | (s->mv_type - MV_TYPE_16X16)) == 0) {
1161
            /* skip macroblock */
1162
            put_bits(&s->pb, 1, 1);
1163
            if(interleaved_stats){
1164
                s->misc_bits++;
1165
                s->last_bits++;
1166
            }
1167
            s->skip_count++;
1168

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

    
1183
            put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1184
            if(s->dquant)
1185
                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1186
                
1187
            if(interleaved_stats){
1188
                s->misc_bits+= get_bits_diff(s);
1189
            }
1190

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

    
1213
            if(interleaved_stats){
1214
                s->misc_bits+= get_bits_diff(s);
1215
            }
1216

    
1217
            for(i=0; i<4; i++){
1218
                /* motion vectors: 8x8 mode*/
1219
                h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1220

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

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

    
1253
                pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
1254
                level -= pred_dc;
1255
                /* Quant */
1256
                if (level >= 0)
1257
                    level = (level + (scale>>1))/scale;
1258
                else
1259
                    level = (level - (scale>>1))/scale;
1260
                    
1261
                /* AIC can change CBP */
1262
                if (level == 0 && s->block_last_index[i] == 0)
1263
                    s->block_last_index[i] = -1;
1264

    
1265
                if(!s->modified_quant){
1266
                    if (level < -127)
1267
                        level = -127;
1268
                    else if (level > 127)
1269
                        level = 127;
1270
                }
1271

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

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

    
1320
        if(interleaved_stats){
1321
            s->misc_bits+= get_bits_diff(s);
1322
        }
1323
    }
1324

    
1325
    for(i=0; i<6; i++) {
1326
        /* encode each block */
1327
        h263_encode_block(s, block[i], i);
1328
    
1329
        /* Update INTRADC for decoding */
1330
        if (s->h263_aic && s->mb_intra) {
1331
            block[i][0] = rec_intradc[i];
1332
            
1333
        }
1334
    }
1335

    
1336
    if(interleaved_stats){
1337
        if (!s->mb_intra) {
1338
            s->p_tex_bits+= get_bits_diff(s);
1339
            s->f_count++;
1340
        }else{
1341
            s->i_tex_bits+= get_bits_diff(s);
1342
            s->i_count++;
1343
        }
1344
    }
1345
}
1346
#endif
1347

    
1348
void ff_h263_loop_filter(MpegEncContext * s){
1349
    int qp_c;
1350
    const int linesize  = s->linesize;
1351
    const int uvlinesize= s->uvlinesize;
1352
    const int xy = s->mb_y * s->mb_stride + s->mb_x;
1353
    uint8_t *dest_y = s->dest[0];
1354
    uint8_t *dest_cb= s->dest[1];
1355
    uint8_t *dest_cr= s->dest[2];
1356
    
1357
//    if(s->pict_type==B_TYPE && !s->readable) return;
1358

    
1359
    /*
1360
       Diag Top
1361
       Left Center
1362
    */
1363
    if(!IS_SKIP(s->current_picture.mb_type[xy])){
1364
        qp_c= s->qscale;
1365
        s->dsp.h263_v_loop_filter(dest_y+8*linesize  , linesize, qp_c);
1366
        s->dsp.h263_v_loop_filter(dest_y+8*linesize+8, linesize, qp_c);
1367
    }else
1368
        qp_c= 0;
1369

    
1370
    if(s->mb_y){
1371
        int qp_dt, qp_t, qp_tc;
1372

    
1373
        if(IS_SKIP(s->current_picture.mb_type[xy-s->mb_stride]))
1374
            qp_t=0;
1375
        else 
1376
            qp_t= s->current_picture.qscale_table[xy-s->mb_stride];
1377

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

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

    
1435
static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr)
1436
{
1437
    int x, y, wrap, a, c, pred_dc, scale;
1438
    int16_t *dc_val, *ac_val;
1439

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

    
1482
static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1483
{
1484
    int x, y, wrap, a, c, pred_dc, scale, i;
1485
    int16_t *dc_val, *ac_val, *ac_val1;
1486

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

    
1569
int16_t *h263_pred_motion(MpegEncContext * s, int block, int dir,
1570
                        int *px, int *py)
1571
{
1572
    int wrap;
1573
    int16_t *A, *B, *C, (*mot_val)[2];
1574
    static const int off[4]= {2, 1, 1, -1};
1575

    
1576
    wrap = s->b8_stride;
1577
    mot_val = s->current_picture.motion_val[dir] + s->block_index[block];
1578

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

    
1627
#ifdef CONFIG_ENCODERS
1628
static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
1629
{
1630
    int range, l, bit_size, sign, code, bits;
1631

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

    
1655
        assert(val>=-l && val<l);
1656

    
1657
        if (val >= 0) {
1658
            sign = 0;
1659
        } else {
1660
            val = -val;
1661
            sign = 1;
1662
        }
1663
#endif
1664
        val--;
1665
        code = (val >> bit_size) + 1;
1666
        bits = val & (range - 1);
1667

    
1668
        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
1669
        if (bit_size > 0) {
1670
            put_bits(&s->pb, bit_size, bits);
1671
        }
1672
    }
1673

    
1674
}
1675

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

    
1715
static void init_mv_penalty_and_fcode(MpegEncContext *s)
1716
{
1717
    int f_code;
1718
    int mv;
1719
    
1720
    if(mv_penalty==NULL)
1721
        mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1722
    
1723
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
1724
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1725
            int len;
1726

    
1727
            if(mv==0) len= mvtab[0][1];
1728
            else{
1729
                int val, bit_size, range, code;
1730

    
1731
                bit_size = f_code - 1;
1732
                range = 1 << bit_size;
1733

    
1734
                val=mv;
1735
                if (val < 0) 
1736
                    val = -val;
1737
                val--;
1738
                code = (val >> bit_size) + 1;
1739
                if(code<33){
1740
                    len= mvtab[code][1] + 1 + bit_size;
1741
                }else{
1742
                    len= mvtab[32][1] + 2 + bit_size;
1743
                }
1744
            }
1745

    
1746
            mv_penalty[f_code][mv+MAX_MV]= len;
1747
        }
1748
    }
1749

    
1750
    for(f_code=MAX_FCODE; f_code>0; f_code--){
1751
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1752
            fcode_tab[mv+MAX_MV]= f_code;
1753
        }
1754
    }
1755

    
1756
    for(mv=0; mv<MAX_MV*2+1; mv++){
1757
        umv_fcode_tab[mv]= 1;
1758
    }
1759
}
1760
#endif
1761

    
1762
#ifdef CONFIG_ENCODERS
1763

    
1764
static void init_uni_dc_tab(void)
1765
{
1766
    int level, uni_code, uni_len;
1767

    
1768
    for(level=-256; level<256; level++){
1769
        int size, v, l;
1770
        /* find number of bits */
1771
        size = 0;
1772
        v = abs(level);
1773
        while (v) {
1774
            v >>= 1;
1775
            size++;
1776
        }
1777

    
1778
        if (level < 0)
1779
            l= (-level) ^ ((1 << size) - 1);
1780
        else
1781
            l= level;
1782

    
1783
        /* luminance */
1784
        uni_code= DCtab_lum[size][0];
1785
        uni_len = DCtab_lum[size][1];
1786

    
1787
        if (size > 0) {
1788
            uni_code<<=size; uni_code|=l;
1789
            uni_len+=size;
1790
            if (size > 8){
1791
                uni_code<<=1; uni_code|=1;
1792
                uni_len++;
1793
            }
1794
        }
1795
        uni_DCtab_lum_bits[level+256]= uni_code;
1796
        uni_DCtab_lum_len [level+256]= uni_len;
1797

    
1798
        /* chrominance */
1799
        uni_code= DCtab_chrom[size][0];
1800
        uni_len = DCtab_chrom[size][1];
1801
        
1802
        if (size > 0) {
1803
            uni_code<<=size; uni_code|=l;
1804
            uni_len+=size;
1805
            if (size > 8){
1806
                uni_code<<=1; uni_code|=1;
1807
                uni_len++;
1808
            }
1809
        }
1810
        uni_DCtab_chrom_bits[level+256]= uni_code;
1811
        uni_DCtab_chrom_len [level+256]= uni_len;
1812

    
1813
    }
1814
}
1815

    
1816
#endif //CONFIG_ENCODERS
1817

    
1818
#ifdef CONFIG_ENCODERS
1819
static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1820
    int slevel, run, last;
1821
    
1822
    assert(MAX_LEVEL >= 64);
1823
    assert(MAX_RUN   >= 63);
1824

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

    
1904
void h263_encode_init(MpegEncContext *s)
1905
{
1906
    static int done = 0;
1907

    
1908
    if (!done) {
1909
        done = 1;
1910

    
1911
        init_uni_dc_tab();
1912

    
1913
        init_rl(&rl_inter);
1914
        init_rl(&rl_intra);
1915
        init_rl(&rl_intra_aic);
1916
        
1917
        init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1918
        init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1919

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

    
1940
        if(s->flags & CODEC_FLAG_GLOBAL_HEADER){
1941

    
1942
            s->avctx->extradata= av_malloc(1024);
1943
            init_put_bits(&s->pb, s->avctx->extradata, 1024);
1944
            
1945
            mpeg4_encode_visual_object_header(s);
1946
            mpeg4_encode_vol_header(s, 0, 0);
1947

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

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

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

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

    
2082
                if(level < 128) 
2083
                    put_bits(&s->pb, 8, slevel & 0xff);
2084
                else{
2085
                    put_bits(&s->pb, 8, 128);
2086
                    put_bits(&s->pb, 5, slevel & 0x1f);
2087
                    put_bits(&s->pb, 6, (slevel>>5)&0x3f);
2088
                }
2089
              }else{
2090
                if(level < 64) { // 7-bit level
2091
                        put_bits(&s->pb, 1, 0);
2092
                        put_bits(&s->pb, 1, last);
2093
                        put_bits(&s->pb, 6, run);
2094

    
2095
                        put_bits(&s->pb, 7, slevel & 0x7f);
2096
                    } else {
2097
                        /* 11-bit level */
2098
                        put_bits(&s->pb, 1, 1);
2099
                        put_bits(&s->pb, 1, last);
2100
                        put_bits(&s->pb, 6, run);
2101

    
2102
                        put_bits(&s->pb, 11, slevel & 0x7ff);
2103
                    }
2104
              }
2105
            } else {
2106
                put_bits(&s->pb, 1, sign);
2107
            }
2108
            last_non_zero = i;
2109
        }
2110
    }
2111
}
2112
#endif
2113

    
2114
#ifdef CONFIG_ENCODERS
2115

    
2116
/***************************************************/
2117
/**
2118
 * add mpeg4 stuffing bits (01...1)
2119
 */
2120
void ff_mpeg4_stuffing(PutBitContext * pbc)
2121
{
2122
    int length;
2123
    put_bits(pbc, 1, 0);
2124
    length= (-put_bits_count(pbc))&7;
2125
    if(length) put_bits(pbc, length, (1<<length)-1);
2126
}
2127

    
2128
/* must be called before writing the header */
2129
void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
2130
    int time_div, time_mod;
2131

    
2132
    assert(s->current_picture_ptr->pts != AV_NOPTS_VALUE);
2133
    s->time= (s->current_picture_ptr->pts*s->time_increment_resolution + AV_TIME_BASE/2)/AV_TIME_BASE;
2134

    
2135
    time_div= s->time/s->time_increment_resolution;
2136
    time_mod= s->time%s->time_increment_resolution;
2137

    
2138
    if(s->pict_type==B_TYPE){
2139
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
2140
    }else{
2141
        s->last_time_base= s->time_base;
2142
        s->time_base= time_div;
2143
        s->pp_time= s->time - s->last_non_b_time;
2144
        s->last_non_b_time= s->time;
2145
    }
2146
}
2147

    
2148
static void mpeg4_encode_gop_header(MpegEncContext * s){
2149
    int hours, minutes, seconds;
2150
    int64_t time;
2151
    
2152
    put_bits(&s->pb, 16, 0);
2153
    put_bits(&s->pb, 16, GOP_STARTCODE);
2154
    
2155
    time= s->current_picture_ptr->pts;
2156
    if(s->reordered_input_picture[1])
2157
        time= FFMIN(time, s->reordered_input_picture[1]->pts);
2158
    time= (time*s->time_increment_resolution + AV_TIME_BASE/2)/AV_TIME_BASE;
2159

    
2160
    seconds= time/s->time_increment_resolution;
2161
    minutes= seconds/60; seconds %= 60;
2162
    hours= minutes/60; minutes %= 60;
2163
    hours%=24;
2164

    
2165
    put_bits(&s->pb, 5, hours);
2166
    put_bits(&s->pb, 6, minutes);
2167
    put_bits(&s->pb, 1, 1);
2168
    put_bits(&s->pb, 6, seconds);
2169
    
2170
    put_bits(&s->pb, 1, !!(s->flags&CODEC_FLAG_CLOSED_GOP)); 
2171
    put_bits(&s->pb, 1, 0); //broken link == NO
2172
    
2173
    s->last_time_base= time / s->time_increment_resolution; 
2174

    
2175
    ff_mpeg4_stuffing(&s->pb);
2176
}
2177

    
2178
static void mpeg4_encode_visual_object_header(MpegEncContext * s){
2179
    int profile_and_level_indication;
2180
    int vo_ver_id;
2181
    
2182
    if(s->max_b_frames || s->quarter_sample){
2183
        profile_and_level_indication= 0xF1; // adv simple level 1
2184
        vo_ver_id= 5;
2185
    }else{
2186
        profile_and_level_indication= 0x01; // simple level 1
2187
        vo_ver_id= 1;
2188
    }
2189
    //FIXME levels
2190

    
2191
    put_bits(&s->pb, 16, 0);
2192
    put_bits(&s->pb, 16, VOS_STARTCODE);
2193

    
2194
    put_bits(&s->pb, 8, profile_and_level_indication);
2195

    
2196
    put_bits(&s->pb, 16, 0);
2197
    put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
2198
    
2199
    put_bits(&s->pb, 1, 1);
2200
        put_bits(&s->pb, 4, vo_ver_id);
2201
        put_bits(&s->pb, 3, 1); //priority
2202
 
2203
    put_bits(&s->pb, 4, 1); //visual obj type== video obj
2204
    
2205
    put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
2206

    
2207
    ff_mpeg4_stuffing(&s->pb);
2208
}
2209

    
2210
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
2211
{
2212
    int vo_ver_id;
2213

    
2214
    if(s->max_b_frames || s->quarter_sample){
2215
        vo_ver_id= 5;
2216
        s->vo_type= ADV_SIMPLE_VO_TYPE;
2217
    }else{
2218
        vo_ver_id= 1;
2219
        s->vo_type= SIMPLE_VO_TYPE;
2220
    }
2221

    
2222
    put_bits(&s->pb, 16, 0);
2223
    put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
2224
    put_bits(&s->pb, 16, 0);
2225
    put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
2226

    
2227
    put_bits(&s->pb, 1, 0);                /* random access vol */
2228
    put_bits(&s->pb, 8, s->vo_type);        /* video obj type indication */
2229
    put_bits(&s->pb, 1, 1);                /* is obj layer id= yes */
2230
      put_bits(&s->pb, 4, vo_ver_id);        /* is obj layer ver id */
2231
      put_bits(&s->pb, 3, 1);                /* is obj layer priority */
2232
    
2233
    aspect_to_info(s, s->avctx->sample_aspect_ratio);
2234

    
2235
    put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
2236
    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
2237
        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
2238
        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
2239
    }
2240

    
2241
    if(s->low_delay){
2242
        put_bits(&s->pb, 1, 1);                /* vol control parameters= yes */
2243
        put_bits(&s->pb, 2, 1);                /* chroma format YUV 420/YV12 */
2244
        put_bits(&s->pb, 1, s->low_delay);
2245
        put_bits(&s->pb, 1, 0);                /* vbv parameters= no */
2246
    }else{
2247
        put_bits(&s->pb, 1, 0);                /* vol control parameters= no */
2248
    }
2249

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

    
2274
    if(s->mpeg_quant){
2275
        ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
2276
        ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
2277
    }
2278

    
2279
    if (vo_ver_id != 1)
2280
        put_bits(&s->pb, 1, s->quarter_sample);
2281
    put_bits(&s->pb, 1, 1);                /* complexity estimation disable */
2282
    s->resync_marker= s->rtp_mode;
2283
    put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
2284
    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
2285
    if(s->data_partitioning){
2286
        put_bits(&s->pb, 1, 0);                /* no rvlc */
2287
    }
2288

    
2289
    if (vo_ver_id != 1){
2290
        put_bits(&s->pb, 1, 0);                /* newpred */
2291
        put_bits(&s->pb, 1, 0);                /* reduced res vop */
2292
    }
2293
    put_bits(&s->pb, 1, 0);                /* scalability */
2294
    
2295
    ff_mpeg4_stuffing(&s->pb);
2296

    
2297
    /* user data */
2298
    if(!(s->flags & CODEC_FLAG_BITEXACT)){
2299
        put_bits(&s->pb, 16, 0);
2300
        put_bits(&s->pb, 16, 0x1B2);        /* user_data */
2301
        put_string(&s->pb, LIBAVCODEC_IDENT, 0);
2302
    }
2303
}
2304

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

    
2323
//printf("num:%d rate:%d base:%d\n", s->picture_number, s->frame_rate, FRAME_RATE_BASE);
2324
    
2325
    put_bits(&s->pb, 16, 0);                /* vop header */
2326
    put_bits(&s->pb, 16, VOP_STARTCODE);        /* vop header */
2327
    put_bits(&s->pb, 2, s->pict_type - 1);        /* pict type: I = 0 , P = 1 */
2328

    
2329
    time_div= s->time/s->time_increment_resolution;
2330
    time_mod= s->time%s->time_increment_resolution;
2331
    time_incr= time_div - s->last_time_base;
2332
    assert(time_incr >= 0);
2333
    while(time_incr--)
2334
        put_bits(&s->pb, 1, 1);
2335
        
2336
    put_bits(&s->pb, 1, 0);
2337

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

    
2353
    put_bits(&s->pb, 5, s->qscale);
2354

    
2355
    if (s->pict_type != I_TYPE)
2356
        put_bits(&s->pb, 3, s->f_code);        /* fcode_for */
2357
    if (s->pict_type == B_TYPE)
2358
        put_bits(&s->pb, 3, s->b_code);        /* fcode_back */
2359
    //    printf("****frame %d\n", picture_number);
2360
}
2361

    
2362
#endif //CONFIG_ENCODERS
2363

    
2364
/**
2365
 * set qscale and update qscale dependant variables.
2366
 */
2367
void ff_set_qscale(MpegEncContext * s, int qscale)
2368
{
2369
    if (qscale < 1)
2370
        qscale = 1;
2371
    else if (qscale > 31)
2372
        qscale = 31;
2373
        
2374
    s->qscale = qscale;
2375
    s->chroma_qscale= s->chroma_qscale_table[qscale];
2376

    
2377
    s->y_dc_scale= s->y_dc_scale_table[ qscale ];
2378
    s->c_dc_scale= s->c_dc_scale_table[ s->chroma_qscale ];
2379
}
2380

    
2381
/**
2382
 * predicts the dc.
2383
 * @param n block index (0-3 are luma, 4-5 are chroma)
2384
 * @param dc_val_ptr a pointer to the dc_val entry for the current MB will be stored here
2385
 * @param dir_ptr pointer to an integer where the prediction direction will be stored
2386
 * @return the quantized predicted dc
2387
 */
2388
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr)
2389
{
2390
    int a, b, c, wrap, pred, scale;
2391
    uint16_t *dc_val;
2392

    
2393
    /* find prediction */
2394
    if (n < 4) {
2395
        scale = s->y_dc_scale;
2396
    } else {
2397
        scale = s->c_dc_scale;
2398
    }
2399
    if(IS_3IV1)
2400
        scale= 8;
2401

    
2402
    wrap= s->block_wrap[n];
2403
    dc_val = s->dc_val[0] + s->block_index[n];
2404

    
2405
    /* B C
2406
     * A X 
2407
     */
2408
    a = dc_val[ - 1];
2409
    b = dc_val[ - 1 - wrap];
2410
    c = dc_val[ - wrap];
2411

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

    
2422
    if (abs(a - b) < abs(b - c)) {
2423
        pred = c;
2424
        *dir_ptr = 1; /* top */
2425
    } else {
2426
        pred = a;
2427
        *dir_ptr = 0; /* left */
2428
    }
2429
    /* we assume pred is positive */
2430
    pred = FASTDIV((pred + (scale >> 1)), scale);
2431

    
2432
    /* prepare address for prediction update */
2433
    *dc_val_ptr = &dc_val[0];
2434

    
2435
    return pred;
2436
}
2437

    
2438
/**
2439
 * predicts the ac.
2440
 * @param n block index (0-3 are luma, 4-5 are chroma)
2441
 * @param dir the ac prediction direction
2442
 */
2443
void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
2444
                   int dir)
2445
{
2446
    int i;
2447
    int16_t *ac_val, *ac_val1;
2448
    int8_t * const qscale_table= s->current_picture.qscale_table;
2449

    
2450
    /* find prediction */
2451
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
2452
    ac_val1 = ac_val;
2453
    if (s->ac_pred) {
2454
        if (dir == 0) {
2455
            const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
2456
            /* left prediction */
2457
            ac_val -= 16;
2458
            
2459
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
2460
                /* same qscale */
2461
                for(i=1;i<8;i++) {
2462
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
2463
                }
2464
            }else{
2465
                /* different qscale, we must rescale */
2466
                for(i=1;i<8;i++) {
2467
                    block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
2468
                }
2469
            }
2470
        } else {
2471
            const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
2472
            /* top prediction */
2473
            ac_val -= 16 * s->block_wrap[n];
2474

    
2475
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
2476
                /* same qscale */
2477
                for(i=1;i<8;i++) {
2478
                    block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
2479
                }
2480
            }else{
2481
                /* different qscale, we must rescale */
2482
                for(i=1;i<8;i++) {
2483
                    block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
2484
                }
2485
            }
2486
        }
2487
    }
2488
    /* left copy */
2489
    for(i=1;i<8;i++)
2490
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
2491

    
2492
    /* top copy */
2493
    for(i=1;i<8;i++)
2494
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
2495

    
2496
}
2497

    
2498
#ifdef CONFIG_ENCODERS
2499

    
2500
/**
2501
 * encodes the dc value.
2502
 * @param n block index (0-3 are luma, 4-5 are chroma)
2503
 */
2504
static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
2505
{
2506
#if 1
2507
//    if(level<-255 || level>255) printf("dc overflow\n");
2508
    level+=256;
2509
    if (n < 4) {
2510
        /* luminance */
2511
        put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
2512
    } else {
2513
        /* chrominance */
2514
        put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
2515
    }
2516
#else
2517
    int size, v;
2518
    /* find number of bits */
2519
    size = 0;
2520
    v = abs(level);
2521
    while (v) {
2522
        v >>= 1;
2523
        size++;
2524
    }
2525

    
2526
    if (n < 4) {
2527
        /* luminance */
2528
        put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
2529
    } else {
2530
        /* chrominance */
2531
        put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
2532
    }
2533

    
2534
    /* encode remaining bits */
2535
    if (size > 0) {
2536
        if (level < 0)
2537
            level = (-level) ^ ((1 << size) - 1);
2538
        put_bits(&s->pb, size, level);
2539
        if (size > 8)
2540
            put_bits(&s->pb, 1, 1);
2541
    }
2542
#endif
2543
}
2544

    
2545
/**
2546
 * encodes a 8x8 block
2547
 * @param n block index (0-3 are luma, 4-5 are chroma)
2548
 */
2549
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2550
                               uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
2551
{
2552
    int i, last_non_zero;
2553
#if 0 //variables for the outcommented version
2554
    int code, sign, last;
2555
#endif
2556
    const RLTable *rl;
2557
    uint32_t *bits_tab;
2558
    uint8_t *len_tab;
2559
    const int last_index = s->block_last_index[n];
2560

    
2561
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2562
        /* mpeg4 based DC predictor */
2563
        mpeg4_encode_dc(dc_pb, intra_dc, n);
2564
        if(last_index<1) return;
2565
        i = 1;
2566
        rl = &rl_intra;
2567
        bits_tab= uni_mpeg4_intra_rl_bits;
2568
        len_tab = uni_mpeg4_intra_rl_len;
2569
    } else {
2570
        if(last_index<0) return;
2571
        i = 0;
2572
        rl = &rl_inter;
2573
        bits_tab= uni_mpeg4_inter_rl_bits;
2574
        len_tab = uni_mpeg4_inter_rl_len;
2575
    }
2576

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

    
2665
static inline int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2666
                               uint8_t *scan_table)
2667
{
2668
    int i, last_non_zero;
2669
    const RLTable *rl;
2670
    uint8_t *len_tab;
2671
    const int last_index = s->block_last_index[n];
2672
    int len=0;
2673

    
2674
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2675
        /* mpeg4 based DC predictor */
2676
        //mpeg4_encode_dc(dc_pb, intra_dc, n); //FIXME
2677
        if(last_index<1) return len;
2678
        i = 1;
2679
        rl = &rl_intra;
2680
        len_tab = uni_mpeg4_intra_rl_len;
2681
    } else {
2682
        if(last_index<0) return 0;
2683
        i = 0;
2684
        rl = &rl_inter;
2685
        len_tab = uni_mpeg4_inter_rl_len;
2686
    }
2687

    
2688
    /* AC coefs */
2689
    last_non_zero = i - 1;
2690
    for (; i < last_index; i++) {
2691
        int level = block[ scan_table[i] ];
2692
        if (level) {
2693
            int run = i - last_non_zero - 1;
2694
            level+=64;
2695
            if((level&(~127)) == 0){
2696
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2697
                len += len_tab[index];
2698
            }else{ //ESC3
2699
                len += 7+2+1+6+1+12+1;
2700
            }
2701
            last_non_zero = i;
2702
        }
2703
    }
2704
    /*if(i<=last_index)*/{
2705
        int level = block[ scan_table[i] ];
2706
        int run = i - last_non_zero - 1;
2707
        level+=64;
2708
        if((level&(~127)) == 0){
2709
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2710
            len += len_tab[index];
2711
        }else{ //ESC3
2712
            len += 7+2+1+6+1+12+1;
2713
        }
2714
    }
2715
    
2716
    return len;
2717
}
2718

    
2719
#endif
2720

    
2721

    
2722
/***********************************************/
2723
/* decoding */
2724

    
2725
static VLC intra_MCBPC_vlc;
2726
static VLC inter_MCBPC_vlc;
2727
static VLC cbpy_vlc;
2728
static VLC mv_vlc;
2729
static VLC dc_lum, dc_chrom;
2730
static VLC sprite_trajectory;
2731
static VLC mb_type_b_vlc;
2732
static VLC h263_mbtype_b_vlc;
2733
static VLC cbpc_b_vlc;
2734

    
2735
void init_vlc_rl(RLTable *rl)
2736
{
2737
    int i, q;
2738
    
2739
    init_vlc(&rl->vlc, 9, rl->n + 1, 
2740
             &rl->table_vlc[0][1], 4, 2,
2741
             &rl->table_vlc[0][0], 4, 2);
2742

    
2743
    
2744
    for(q=0; q<32; q++){
2745
        int qmul= q*2;
2746
        int qadd= (q-1)|1;
2747
        
2748
        if(q==0){
2749
            qmul=1;
2750
            qadd=0;
2751
        }
2752
        
2753
        rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2754
        for(i=0; i<rl->vlc.table_size; i++){
2755
            int code= rl->vlc.table[i][0];
2756
            int len = rl->vlc.table[i][1];
2757
            int level, run;
2758
        
2759
            if(len==0){ // illegal code
2760
                run= 66;
2761
                level= MAX_LEVEL;
2762
            }else if(len<0){ //more bits needed
2763
                run= 0;
2764
                level= code;
2765
            }else{
2766
                if(code==rl->n){ //esc
2767
                    run= 66;
2768
                    level= 0;
2769
                }else{
2770
                    run=   rl->table_run  [code] + 1;
2771
                    level= rl->table_level[code] * qmul + qadd;
2772
                    if(code >= rl->last) run+=192;
2773
                }
2774
            }
2775
            rl->rl_vlc[q][i].len= len;
2776
            rl->rl_vlc[q][i].level= level;
2777
            rl->rl_vlc[q][i].run= run;
2778
        }
2779
    }
2780
}
2781

    
2782
/* init vlcs */
2783

    
2784
/* XXX: find a better solution to handle static init */
2785
void h263_decode_init_vlc(MpegEncContext *s)
2786
{
2787
    static int done = 0;
2788

    
2789
    if (!done) {
2790
        done = 1;
2791

    
2792
        init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 9, 
2793
                 intra_MCBPC_bits, 1, 1,
2794
                 intra_MCBPC_code, 1, 1);
2795
        init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 28, 
2796
                 inter_MCBPC_bits, 1, 1,
2797
                 inter_MCBPC_code, 1, 1);
2798
        init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,
2799
                 &cbpy_tab[0][1], 2, 1,
2800
                 &cbpy_tab[0][0], 2, 1);
2801
        init_vlc(&mv_vlc, MV_VLC_BITS, 33,
2802
                 &mvtab[0][1], 2, 1,
2803
                 &mvtab[0][0], 2, 1);
2804
        init_rl(&rl_inter);
2805
        init_rl(&rl_intra);
2806
        init_rl(&rvlc_rl_inter);
2807
        init_rl(&rvlc_rl_intra);
2808
        init_rl(&rl_intra_aic);
2809
        init_vlc_rl(&rl_inter);
2810
        init_vlc_rl(&rl_intra);
2811
        init_vlc_rl(&rvlc_rl_inter);
2812
        init_vlc_rl(&rvlc_rl_intra);
2813
        init_vlc_rl(&rl_intra_aic);
2814
        init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2815
                 &DCtab_lum[0][1], 2, 1,
2816
                 &DCtab_lum[0][0], 2, 1);
2817
        init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2818
                 &DCtab_chrom[0][1], 2, 1,
2819
                 &DCtab_chrom[0][0], 2, 1);
2820
        init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2821
                 &sprite_trajectory_tab[0][1], 4, 2,
2822
                 &sprite_trajectory_tab[0][0], 4, 2);
2823
        init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2824
                 &mb_type_b_tab[0][1], 2, 1,
2825
                 &mb_type_b_tab[0][0], 2, 1);
2826
        init_vlc(&h263_mbtype_b_vlc, H263_MBTYPE_B_VLC_BITS, 15,
2827
                 &h263_mbtype_b_tab[0][1], 2, 1,
2828
                 &h263_mbtype_b_tab[0][0], 2, 1);
2829
        init_vlc(&cbpc_b_vlc, CBPC_B_VLC_BITS, 4,
2830
                 &cbpc_b_tab[0][1], 2, 1,
2831
                 &cbpc_b_tab[0][0], 2, 1);
2832
    }
2833
}
2834

    
2835
/**
2836
 * Get the GOB height based on picture height.
2837
 */
2838
int ff_h263_get_gob_height(MpegEncContext *s){
2839
    if (s->height <= 400)
2840
        return 1;
2841
    else if (s->height <= 800)
2842
        return  2;
2843
    else
2844
        return 4;
2845
}
2846

    
2847
int ff_h263_decode_mba(MpegEncContext *s)
2848
{
2849
    int i, mb_pos;
2850

    
2851
    for(i=0; i<6; i++){
2852
        if(s->mb_num-1 <= ff_mba_max[i]) break;
2853
    }
2854
    mb_pos= get_bits(&s->gb, ff_mba_length[i]);
2855
    s->mb_x= mb_pos % s->mb_width;
2856
    s->mb_y= mb_pos / s->mb_width;
2857

    
2858
    return mb_pos;
2859
}
2860

    
2861
void ff_h263_encode_mba(MpegEncContext *s)
2862
{
2863
    int i, mb_pos;
2864

    
2865
    for(i=0; i<6; i++){
2866
        if(s->mb_num-1 <= ff_mba_max[i]) break;
2867
    }
2868
    mb_pos= s->mb_x + s->mb_width*s->mb_y;
2869
    put_bits(&s->pb, ff_mba_length[i], mb_pos);
2870
}
2871

    
2872
/**
2873
 * decodes the group of blocks header or slice header.
2874
 * @return <0 if an error occured
2875
 */
2876
static int h263_decode_gob_header(MpegEncContext *s)
2877
{
2878
    unsigned int val, gfid, gob_number;
2879
    int left;
2880
    
2881
    /* Check for GOB Start Code */
2882
    val = show_bits(&s->gb, 16);
2883
    if(val)
2884
        return -1;
2885

    
2886
        /* We have a GBSC probably with GSTUFF */
2887
    skip_bits(&s->gb, 16); /* Drop the zeros */
2888
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
2889
    //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2890
    for(;left>13; left--){
2891
        if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2892
    }
2893
    if(left<=13) 
2894
        return -1;
2895

    
2896
    if(s->h263_slice_structured){
2897
        if(get_bits1(&s->gb)==0)
2898
            return -1;
2899

    
2900
        ff_h263_decode_mba(s);
2901

    
2902
        if(s->mb_num > 1583)
2903
            if(get_bits1(&s->gb)==0)
2904
                return -1;
2905
        
2906
        s->qscale = get_bits(&s->gb, 5); /* SQUANT */
2907
        if(get_bits1(&s->gb)==0)
2908
            return -1;
2909
        gfid = get_bits(&s->gb, 2); /* GFID */
2910
    }else{
2911
        gob_number = get_bits(&s->gb, 5); /* GN */
2912
        s->mb_x= 0;
2913
        s->mb_y= s->gob_index* gob_number;
2914
        gfid = get_bits(&s->gb, 2); /* GFID */
2915
        s->qscale = get_bits(&s->gb, 5); /* GQUANT */
2916
    }
2917
        
2918
    if(s->mb_y >= s->mb_height) 
2919
        return -1;
2920

    
2921
    if(s->qscale==0) 
2922
        return -1;
2923

    
2924
    return 0;
2925
}
2926

    
2927
static inline void memsetw(short *tab, int val, int n)
2928
{
2929
    int i;
2930
    for(i=0;i<n;i++)
2931
        tab[i] = val;
2932
}
2933

    
2934
#ifdef CONFIG_ENCODERS
2935

    
2936
void ff_mpeg4_init_partitions(MpegEncContext *s)
2937
{
2938
    uint8_t *start= pbBufPtr(&s->pb);
2939
    uint8_t *end= s->pb.buf_end;
2940
    int size= end - start;
2941
    int pb_size = (((int)start + size/3)&(~3)) - (int)start;
2942
    int tex_size= (size - 2*pb_size)&(~3);
2943
    
2944
    set_put_bits_buffer_size(&s->pb, pb_size);
2945
    init_put_bits(&s->tex_pb, start + pb_size           , tex_size);
2946
    init_put_bits(&s->pb2   , start + pb_size + tex_size, pb_size);
2947
}
2948

    
2949
void ff_mpeg4_merge_partitions(MpegEncContext *s)
2950
{
2951
    const int pb2_len   = put_bits_count(&s->pb2   );
2952
    const int tex_pb_len= put_bits_count(&s->tex_pb);
2953
    const int bits= put_bits_count(&s->pb);
2954

    
2955
    if(s->pict_type==I_TYPE){
2956
        put_bits(&s->pb, 19, DC_MARKER);
2957
        s->misc_bits+=19 + pb2_len + bits - s->last_bits;
2958
        s->i_tex_bits+= tex_pb_len;
2959
    }else{
2960
        put_bits(&s->pb, 17, MOTION_MARKER);
2961
        s->misc_bits+=17 + pb2_len;
2962
        s->mv_bits+= bits - s->last_bits;
2963
        s->p_tex_bits+= tex_pb_len;
2964
    }
2965

    
2966
    flush_put_bits(&s->pb2);
2967
    flush_put_bits(&s->tex_pb);
2968

    
2969
    set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
2970
    ff_copy_bits(&s->pb, s->pb2.buf   , pb2_len);
2971
    ff_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
2972
    s->last_bits= put_bits_count(&s->pb);
2973
}
2974

    
2975
#endif //CONFIG_ENCODERS
2976

    
2977
int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
2978
    switch(s->pict_type){
2979
        case I_TYPE:
2980
            return 16;
2981
        case P_TYPE:
2982
        case S_TYPE:
2983
            return s->f_code+15;
2984
        case B_TYPE:
2985
            return FFMAX(FFMAX(s->f_code, s->b_code)+15, 17);
2986
        default:
2987
            return -1;
2988
    }
2989
}
2990

    
2991
#ifdef CONFIG_ENCODERS
2992

    
2993
void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
2994
{
2995
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2996

    
2997
    put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
2998
    put_bits(&s->pb, 1, 1);
2999
    
3000
    put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
3001
    put_bits(&s->pb, s->quant_precision, s->qscale);
3002
    put_bits(&s->pb, 1, 0); /* no HEC */
3003
}
3004

    
3005
#endif //CONFIG_ENCODERS
3006

    
3007
/**
3008
 * check if the next stuff is a resync marker or the end.
3009
 * @return 0 if not
3010
 */
3011
static inline int mpeg4_is_resync(MpegEncContext *s){
3012
    const int bits_count= get_bits_count(&s->gb);
3013
    
3014
    if(s->workaround_bugs&FF_BUG_NO_PADDING){
3015
        return 0;
3016
    }
3017

    
3018
    if(bits_count + 8 >= s->gb.size_in_bits){
3019
        int v= show_bits(&s->gb, 8);
3020
        v|= 0x7F >> (7-(bits_count&7));
3021
                
3022
        if(v==0x7F)
3023
            return 1;
3024
    }else{
3025
        if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){
3026
            int len;
3027
            GetBitContext gb= s->gb;
3028
        
3029
            skip_bits(&s->gb, 1);
3030
            align_get_bits(&s->gb);
3031
        
3032
            for(len=0; len<32; len++){
3033
                if(get_bits1(&s->gb)) break;
3034
            }
3035

    
3036
            s->gb= gb;
3037

    
3038
            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
3039
                return 1;
3040
        }
3041
    }
3042
    return 0;
3043
}
3044

    
3045
/**
3046
 * decodes the next video packet.
3047
 * @return <0 if something went wrong
3048
 */
3049
static int mpeg4_decode_video_packet_header(MpegEncContext *s)
3050
{
3051
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
3052
    int header_extension=0, mb_num, len;
3053
    
3054
    /* is there enough space left for a video packet + header */
3055
    if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
3056

    
3057
    for(len=0; len<32; len++){
3058
        if(get_bits1(&s->gb)) break;
3059
    }
3060

    
3061
    if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
3062
        av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
3063
        return -1;
3064
    }
3065
    
3066
    if(s->shape != RECT_SHAPE){
3067
        header_extension= get_bits1(&s->gb);
3068
        //FIXME more stuff here
3069
    }
3070

    
3071
    mb_num= get_bits(&s->gb, mb_num_bits);
3072
    if(mb_num>=s->mb_num){
3073
        av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
3074
        return -1;
3075
    }
3076
    if(s->pict_type == B_TYPE){
3077
        while(s->next_picture.mbskip_table[ s->mb_index2xy[ mb_num ] ]) mb_num++;
3078
        if(mb_num >= s->mb_num) return -1; // slice contains just skiped MBs which where allready decoded
3079
    }
3080
    
3081
    s->mb_x= mb_num % s->mb_width;
3082
    s->mb_y= mb_num / s->mb_width;
3083

    
3084
    if(s->shape != BIN_ONLY_SHAPE){
3085
        int qscale= get_bits(&s->gb, s->quant_precision); 
3086
        if(qscale)
3087
            s->chroma_qscale=s->qscale= qscale;
3088
    }
3089

    
3090
    if(s->shape == RECT_SHAPE){
3091
        header_extension= get_bits1(&s->gb);
3092
    }
3093
    if(header_extension){
3094
        int time_increment;
3095
        int time_incr=0;
3096

    
3097
        while (get_bits1(&s->gb) != 0) 
3098
            time_incr++;
3099

    
3100
        check_marker(&s->gb, "before time_increment in video packed header");
3101
        time_increment= get_bits(&s->gb, s->time_increment_bits);
3102
        check_marker(&s->gb, "before vop_coding_type in video packed header");
3103
        
3104
        skip_bits(&s->gb, 2); /* vop coding type */
3105
        //FIXME not rect stuff here
3106

    
3107
        if(s->shape != BIN_ONLY_SHAPE){
3108
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
3109
//FIXME dont just ignore everything
3110
            if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3111
                mpeg4_decode_sprite_trajectory(s, &s->gb);
3112
                av_log(s->avctx, AV_LOG_ERROR, "untested\n");
3113
            }
3114

    
3115
            //FIXME reduced res stuff here
3116
            
3117
            if (s->pict_type != I_TYPE) {
3118
                int f_code = get_bits(&s->gb, 3);        /* fcode_for */
3119
                if(f_code==0){
3120
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n");
3121
                }
3122
            }
3123
            if (s->pict_type == B_TYPE) {
3124
                int b_code = get_bits(&s->gb, 3);
3125
                if(b_code==0){
3126
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n");
3127
                }
3128
            }       
3129
        }
3130
    }
3131
    //FIXME new-pred stuff
3132
    
3133
//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));
3134

    
3135
    return 0;
3136
}
3137

    
3138
void ff_mpeg4_clean_buffers(MpegEncContext *s)
3139
{
3140
    int c_wrap, c_xy, l_wrap, l_xy;
3141

    
3142
    l_wrap= s->b8_stride;
3143
    l_xy= (2*s->mb_y-1)*l_wrap + s->mb_x*2 - 1;
3144
    c_wrap= s->mb_stride;
3145
    c_xy= (s->mb_y-1)*c_wrap + s->mb_x - 1;
3146

    
3147
#if 0
3148
    /* clean DC */
3149
    memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
3150
    memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
3151
    memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
3152
#endif
3153

    
3154
    /* clean AC */
3155
    memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(int16_t));
3156
    memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
3157
    memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
3158

    
3159
    /* clean MV */
3160
    // we cant clear the MVs as they might be needed by a b frame
3161
//    memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(int16_t));
3162
//    memset(s->motion_val, 0, 2*sizeof(int16_t)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
3163
    s->last_mv[0][0][0]=
3164
    s->last_mv[0][0][1]=
3165
    s->last_mv[1][0][0]=
3166
    s->last_mv[1][0][1]= 0;
3167
}
3168

    
3169
/**
3170
 * decodes the group of blocks / video packet header.
3171
 * @return <0 if no resync found
3172
 */
3173
int ff_h263_resync(MpegEncContext *s){
3174
    int left, ret;
3175
    
3176
    if(s->codec_id==CODEC_ID_MPEG4){
3177
        skip_bits1(&s->gb);
3178
        align_get_bits(&s->gb);
3179
    }
3180

    
3181
    if(show_bits(&s->gb, 16)==0){
3182
        if(s->codec_id==CODEC_ID_MPEG4)
3183
            ret= mpeg4_decode_video_packet_header(s);
3184
        else
3185
            ret= h263_decode_gob_header(s);
3186
        if(ret>=0)
3187
            return 0;
3188
    }
3189
    //ok, its not where its supposed to be ...
3190
    s->gb= s->last_resync_gb;
3191
    align_get_bits(&s->gb);
3192
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
3193
    
3194
    for(;left>16+1+5+5; left-=8){ 
3195
        if(show_bits(&s->gb, 16)==0){
3196
            GetBitContext bak= s->gb;
3197

    
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
            s->gb= bak;
3206
        }
3207
        skip_bits(&s->gb, 8);
3208
    }
3209
    
3210
    return -1;
3211
}
3212

    
3213
/**
3214
 * gets the average motion vector for a GMC MB.
3215
 * @param n either 0 for the x component or 1 for y
3216
 * @returns the average MV for a GMC MB
3217
 */
3218
static inline int get_amv(MpegEncContext *s, int n){
3219
    int x, y, mb_v, sum, dx, dy, shift;
3220
    int len = 1 << (s->f_code + 4);
3221
    const int a= s->sprite_warping_accuracy;
3222

    
3223
    if(s->real_sprite_warping_points==1){
3224
        if(s->divx_version==500 && s->divx_build==413)
3225
            sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
3226
        else
3227
            sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
3228
    }else{
3229
        dx= s->sprite_delta[n][0];
3230
        dy= s->sprite_delta[n][1];
3231
        shift= s->sprite_shift[0];
3232
        if(n) dy -= 1<<(shift + a + 1);
3233
        else  dx -= 1<<(shift + a + 1);
3234
        mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
3235

    
3236
        sum=0;
3237
        for(y=0; y<16; y++){
3238
            int v;
3239
        
3240
            v= mb_v + dy*y;
3241
            //XXX FIXME optimize
3242
            for(x=0; x<16; x++){
3243
                sum+= v>>shift;
3244
                v+= dx;
3245
            }
3246
        }
3247
        sum= RSHIFT(sum, a+8-s->quarter_sample);
3248
    }
3249

    
3250
    if      (sum < -len) sum= -len;
3251
    else if (sum >= len) sum= len-1;
3252

    
3253
    return sum;
3254
}
3255

    
3256
/**
3257
 * decodes first partition.
3258
 * @return number of MBs decoded or <0 if an error occured
3259
 */
3260
static int mpeg4_decode_partition_a(MpegEncContext *s){
3261
    int mb_num;
3262
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3263
    
3264
    /* decode first partition */
3265
    mb_num=0;
3266
    s->first_slice_line=1;
3267
    for(; s->mb_y<s->mb_height; s->mb_y++){
3268
        ff_init_block_index(s);
3269
        for(; s->mb_x<s->mb_width; s->mb_x++){
3270
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
3271
            int cbpc;
3272
            int dir=0;
3273
            
3274
            mb_num++;
3275
            ff_update_block_index(s);
3276
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3277
                s->first_slice_line=0;
3278
            
3279
            if(s->pict_type==I_TYPE){
3280
                int i;
3281

    
3282
                do{
3283
                    if(show_bits_long(&s->gb, 19)==DC_MARKER){
3284
                        return mb_num-1;
3285
                    }
3286

    
3287
                    cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
3288
                    if (cbpc < 0){
3289
                        av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
3290
                        return -1;
3291
                    }
3292
                }while(cbpc == 8);
3293
                
3294
                s->cbp_table[xy]= cbpc & 3;
3295
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3296
                s->mb_intra = 1;
3297

    
3298
                if(cbpc & 4) {
3299
                    ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3300
                }
3301
                s->current_picture.qscale_table[xy]= s->qscale;
3302

    
3303
                s->mbintra_table[xy]= 1;
3304
                for(i=0; i<6; i++){
3305
                    int dc_pred_dir;
3306
                    int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
3307
                    if(dc < 0){
3308
                        av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3309
                        return -1;
3310
                    }
3311
                    dir<<=1;
3312
                    if(dc_pred_dir) dir|=1;
3313
                }
3314
                s->pred_dir_table[xy]= dir;
3315
            }else{ /* P/S_TYPE */
3316
                int mx, my, pred_x, pred_y, bits;
3317
                int16_t * const mot_val= s->current_picture.motion_val[0][s->block_index[0]];
3318
                const int stride= s->b8_stride*2;
3319

    
3320
try_again:
3321
                bits= show_bits(&s->gb, 17);
3322
                if(bits==MOTION_MARKER){
3323
                    return mb_num-1;
3324
                }
3325
                skip_bits1(&s->gb);
3326
                if(bits&0x10000){
3327
                    /* skip mb */
3328
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3329
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
3330
                        mx= get_amv(s, 0);
3331
                        my= get_amv(s, 1);
3332
                    }else{
3333
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3334
                        mx=my=0;
3335
                    }
3336
                    mot_val[0       ]= mot_val[2       ]=
3337
                    mot_val[0+stride]= mot_val[2+stride]= mx;
3338
                    mot_val[1       ]= mot_val[3       ]=
3339
                    mot_val[1+stride]= mot_val[3+stride]= my;
3340

    
3341
                    if(s->mbintra_table[xy])
3342
                        ff_clean_intra_table_entries(s);
3343
                    continue;
3344
                }
3345

    
3346
                cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3347
                if (cbpc < 0){
3348
                    av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
3349
                    return -1;
3350
                }
3351
                if(cbpc == 20)
3352
                    goto try_again;
3353

    
3354
                s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
3355
    
3356
                s->mb_intra = ((cbpc & 4) != 0);
3357
        
3358
                if(s->mb_intra){
3359
                    s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3360
                    s->mbintra_table[xy]= 1;
3361
                    mot_val[0       ]= mot_val[2       ]= 
3362
                    mot_val[0+stride]= mot_val[2+stride]= 0;
3363
                    mot_val[1       ]= mot_val[3       ]=
3364
                    mot_val[1+stride]= mot_val[3+stride]= 0;
3365
                }else{
3366
                    if(s->mbintra_table[xy])
3367
                        ff_clean_intra_table_entries(s);
3368

    
3369
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
3370
                        s->mcsel= get_bits1(&s->gb);
3371
                    else s->mcsel= 0;
3372
        
3373
                    if ((cbpc & 16) == 0) {
3374
                        /* 16x16 motion prediction */
3375

    
3376
                        h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3377
                        if(!s->mcsel){
3378
                            mx = h263_decode_motion(s, pred_x, s->f_code);
3379
                            if (mx >= 0xffff)
3380
                                return -1;
3381

    
3382
                            my = h263_decode_motion(s, pred_y, s->f_code);
3383
                            if (my >= 0xffff)
3384
                                return -1;
3385
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
3386
                        } else {
3387
                            mx = get_amv(s, 0);
3388
                            my = get_amv(s, 1);
3389
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
3390
                        }
3391

    
3392
                        mot_val[0       ]= mot_val[2       ] =
3393
                        mot_val[0+stride]= mot_val[2+stride]= mx;
3394
                        mot_val[1       ]= mot_val[3       ]=
3395
                        mot_val[1+stride]= mot_val[3+stride]= my;
3396
                    } else {
3397
                        int i;
3398
                        s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
3399
                        for(i=0;i<4;i++) {
3400
                            int16_t *mot_val= h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3401
                            mx = h263_decode_motion(s, pred_x, s->f_code);
3402
                            if (mx >= 0xffff)
3403
                                return -1;
3404
                
3405
                            my = h263_decode_motion(s, pred_y, s->f_code);
3406
                            if (my >= 0xffff)
3407
                                return -1;
3408
                            mot_val[0] = mx;
3409
                            mot_val[1] = my;
3410
                        }
3411
                    }
3412
                }
3413
            }
3414
        }
3415
        s->mb_x= 0;
3416
    }
3417

    
3418
    return mb_num;
3419
}
3420

    
3421
/**
3422
 * decode second partition.
3423
 * @return <0 if an error occured
3424
 */
3425
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
3426
    int mb_num=0;
3427
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3428

    
3429
    s->mb_x= s->resync_mb_x;
3430
    s->first_slice_line=1;
3431
    for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
3432
        ff_init_block_index(s);
3433
        for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
3434
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
3435

    
3436
            mb_num++;
3437
            ff_update_block_index(s);
3438
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3439
                s->first_slice_line=0;
3440
            
3441
            if(s->pict_type==I_TYPE){
3442
                int ac_pred= get_bits1(&s->gb);
3443
                int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3444
                if(cbpy<0){
3445
                    av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3446
                    return -1;
3447
                }
3448
                
3449
                s->cbp_table[xy]|= cbpy<<2;
3450
                s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
3451
            }else{ /* P || S_TYPE */
3452
                if(IS_INTRA(s->current_picture.mb_type[xy])){          
3453
                    int dir=0,i;
3454
                    int ac_pred = get_bits1(&s->gb);
3455
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3456

    
3457
                    if(cbpy<0){
3458
                        av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3459
                        return -1;
3460
                    }
3461
                    
3462
                    if(s->cbp_table[xy] & 8) {
3463
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3464
                    }
3465
                    s->current_picture.qscale_table[xy]= s->qscale;
3466

    
3467
                    for(i=0; i<6; i++){
3468
                        int dc_pred_dir;
3469
                        int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
3470
                        if(dc < 0){
3471
                            av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3472
                            return -1;
3473
                        }
3474
                        dir<<=1;
3475
                        if(dc_pred_dir) dir|=1;
3476
                    }
3477
                    s->cbp_table[xy]&= 3; //remove dquant
3478
                    s->cbp_table[xy]|= cbpy<<2;
3479
                    s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
3480
                    s->pred_dir_table[xy]= dir;
3481
                }else if(IS_SKIP(s->current_picture.mb_type[xy])){
3482
                    s->current_picture.qscale_table[xy]= s->qscale;
3483
                    s->cbp_table[xy]= 0;
3484
                }else{
3485
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3486

    
3487
                    if(cbpy<0){
3488
                        av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3489
                        return -1;
3490
                    }
3491
                    
3492
                    if(s->cbp_table[xy] & 8) {
3493
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3494
                    }
3495
                    s->current_picture.qscale_table[xy]= s->qscale;
3496

    
3497
                    s->cbp_table[xy]&= 3; //remove dquant
3498
                    s->cbp_table[xy]|= (cbpy^0xf)<<2;
3499
                }
3500
            }
3501
        }
3502
        if(mb_num >= mb_count) return 0;
3503
        s->mb_x= 0;
3504
    }
3505
    return 0;
3506
}
3507

    
3508
/**
3509
 * decodes the first & second partition
3510
 * @return <0 if error (and sets error type in the error_status_table)
3511
 */
3512
int ff_mpeg4_decode_partitions(MpegEncContext *s)
3513
{
3514
    int mb_num;
3515
    const int part_a_error= s->pict_type==I_TYPE ? (DC_ERROR|MV_ERROR) : MV_ERROR;
3516
    const int part_a_end  = s->pict_type==I_TYPE ? (DC_END  |MV_END)   : MV_END;
3517
    
3518
    mb_num= mpeg4_decode_partition_a(s);    
3519
    if(mb_num<0){
3520
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3521
        return -1;
3522
    }
3523
    
3524
    if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
3525
        av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
3526
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3527
        return -1;
3528
    }
3529

    
3530
    s->mb_num_left= mb_num;
3531
        
3532
    if(s->pict_type==I_TYPE){
3533
        while(show_bits(&s->gb, 9) == 1)
3534
            skip_bits(&s->gb, 9);
3535
        if(get_bits_long(&s->gb, 19)!=DC_MARKER){
3536
            av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
3537
            return -1;
3538
        }
3539
    }else{
3540
        while(show_bits(&s->gb, 10) == 1)
3541
            skip_bits(&s->gb, 10);
3542
        if(get_bits(&s->gb, 17)!=MOTION_MARKER){
3543
            av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
3544
            return -1;
3545
        }
3546
    }
3547
    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, part_a_end);
3548
    
3549
    if( mpeg4_decode_partition_b(s, mb_num) < 0){
3550
        if(s->pict_type==P_TYPE)
3551
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, DC_ERROR);
3552
        return -1;
3553
    }else{
3554
        if(s->pict_type==P_TYPE)
3555
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, DC_END);
3556
    }
3557

    
3558
    return 0;        
3559
}
3560

    
3561
/**
3562
 * decode partition C of one MB.
3563
 * @return <0 if an error occured
3564
 */
3565
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
3566
{
3567
    int cbp, mb_type;
3568
    const int xy= s->mb_x + s->mb_y*s->mb_stride;
3569

    
3570
    mb_type= s->current_picture.mb_type[xy];
3571
    cbp = s->cbp_table[xy];
3572

    
3573
    if(s->current_picture.qscale_table[xy] != s->qscale){
3574
        ff_set_qscale(s, s->current_picture.qscale_table[xy] );
3575
    }
3576
    
3577
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3578
        int i;
3579
        for(i=0; i<4; i++){
3580
            s->mv[0][i][0] = s->current_picture.motion_val[0][ s->block_index[i] ][0];
3581
            s->mv[0][i][1] = s->current_picture.motion_val[0][ s->block_index[i] ][1];
3582
        }
3583
        s->mb_intra = IS_INTRA(mb_type);
3584

    
3585
        if (IS_SKIP(mb_type)) {
3586
            /* skip mb */
3587
            for(i=0;i<6;i++)
3588
                s->block_last_index[i] = -1;
3589
            s->mv_dir = MV_DIR_FORWARD;
3590
            s->mv_type = MV_TYPE_16X16;
3591
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3592
                s->mcsel=1;
3593
                s->mb_skiped = 0;
3594
            }else{
3595
                s->mcsel=0;
3596
                s->mb_skiped = 1;
3597
            }
3598
        }else if(s->mb_intra){
3599
            s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3600
        }else if(!s->mb_intra){
3601
//            s->mcsel= 0; //FIXME do we need to init that
3602
            
3603
            s->mv_dir = MV_DIR_FORWARD;
3604
            if (IS_8X8(mb_type)) {
3605
                s->mv_type = MV_TYPE_8X8;
3606
            } else {
3607
                s->mv_type = MV_TYPE_16X16;
3608
            }
3609
        }
3610
    } else { /* I-Frame */
3611
        s->mb_intra = 1;
3612
        s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3613
    }
3614

    
3615
    if (!IS_SKIP(mb_type)) {
3616
        int i;
3617
        /* decode each block */
3618
        for (i = 0; i < 6; i++) {
3619
            if(mpeg4_decode_block(s, block[i], i, cbp&32, s->mb_intra, s->rvlc) < 0){
3620
                av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra);
3621
                return -1;
3622
            }
3623
            cbp+=cbp;
3624
        }
3625
    }
3626

    
3627
    /* per-MB end of slice check */
3628

    
3629
    if(--s->mb_num_left <= 0){
3630
//printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size_in_bits - get_bits_count(&s->gb));
3631
        if(mpeg4_is_resync(s))
3632
            return SLICE_END;
3633
        else
3634
            return SLICE_NOEND;     
3635
    }else{
3636
        if(mpeg4_is_resync(s)){
3637
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
3638
            if(s->cbp_table[xy+delta])
3639
                return SLICE_END;
3640
        }
3641
        return SLICE_OK;
3642
    }
3643
}
3644

    
3645
/**
3646
 * read the next MVs for OBMC. yes this is a ugly hack, feel free to send a patch :)
3647
 */
3648
static void preview_obmc(MpegEncContext *s){
3649
    GetBitContext gb= s->gb;
3650
    
3651
    int cbpc, i, pred_x, pred_y, mx, my;
3652
    int16_t *mot_val;
3653
    const int xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
3654
    const int stride= s->b8_stride*2;
3655
    
3656
    for(i=0; i<4; i++)
3657
        s->block_index[i]+= 2;
3658
    for(i=4; i<6; i++)
3659
        s->block_index[i]+= 1;
3660
    s->mb_x++;
3661
    
3662
    assert(s->pict_type == P_TYPE);
3663

    
3664
    do{
3665
        if (get_bits1(&s->gb)) {
3666
            /* skip mb */
3667
            mot_val = s->current_picture.motion_val[0][ s->block_index[0] ];
3668
            mot_val[0       ]= mot_val[2       ]= 
3669
            mot_val[0+stride]= mot_val[2+stride]= 0;
3670
            mot_val[1       ]= mot_val[3       ]=
3671
            mot_val[1+stride]= mot_val[3+stride]= 0;
3672
            
3673
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3674
            goto end;
3675
        }
3676
        cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3677
    }while(cbpc == 20);
3678
    
3679
    if(cbpc & 4){
3680
        s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3681
    }else{
3682
        get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3683
        if (cbpc & 8) {
3684
            if(s->modified_quant){
3685
                if(get_bits1(&s->gb)) skip_bits(&s->gb, 1);
3686
                else                  skip_bits(&s->gb, 5);
3687
            }else
3688
                skip_bits(&s->gb, 2);
3689
        }
3690
        
3691
        if ((cbpc & 16) == 0) {
3692
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
3693
                /* 16x16 motion prediction */
3694
                mot_val= h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3695
                if (s->umvplus)
3696
                   mx = h263p_decode_umotion(s, pred_x);
3697
                else
3698
                   mx = h263_decode_motion(s, pred_x, 1);
3699
            
3700
                if (s->umvplus)
3701
                   my = h263p_decode_umotion(s, pred_y);
3702
                else
3703
                   my = h263_decode_motion(s, pred_y, 1);
3704
            
3705
                mot_val[0       ]= mot_val[2       ]= 
3706
                mot_val[0+stride]= mot_val[2+stride]= mx;
3707
                mot_val[1       ]= mot_val[3       ]=
3708
                mot_val[1+stride]= mot_val[3+stride]= my;
3709
        } else {
3710
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
3711
            for(i=0;i<4;i++) {
3712
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3713
                if (s->umvplus)
3714
                  mx = h263p_decode_umotion(s, pred_x);
3715
                else
3716
                  mx = h263_decode_motion(s, pred_x, 1);
3717
                
3718
                if (s->umvplus)
3719
                  my = h263p_decode_umotion(s, pred_y);
3720
                else    
3721
                  my = h263_decode_motion(s, pred_y, 1);
3722
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3723
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3724
                mot_val[0] = mx;
3725
                mot_val[1] = my;
3726
            }
3727
        }
3728
    }
3729
end:
3730
        
3731
    for(i=0; i<4; i++)
3732
        s->block_index[i]-= 2;
3733
    for(i=4; i<6; i++)
3734
        s->block_index[i]-= 1;
3735
    s->mb_x--;
3736

    
3737
    s->gb= gb;
3738
}
3739

    
3740
static void h263_decode_dquant(MpegEncContext *s){
3741
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3742

    
3743
    if(s->modified_quant){
3744
        if(get_bits1(&s->gb))
3745
            s->qscale= modified_quant_tab[get_bits1(&s->gb)][ s->qscale ];
3746
        else
3747
            s->qscale= get_bits(&s->gb, 5);
3748
    }else
3749
        s->qscale += quant_tab[get_bits(&s->gb, 2)];
3750
    ff_set_qscale(s, s->qscale);
3751
}
3752

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

    
3823
            if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3824
               skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */                   
3825
        } else {
3826
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
3827
            s->mv_type = MV_TYPE_8X8;
3828
            for(i=0;i<4;i++) {
3829
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3830
                if (s->umvplus)
3831
                  mx = h263p_decode_umotion(s, pred_x);
3832
                else
3833
                  mx = h263_decode_motion(s, pred_x, 1);
3834
                if (mx >= 0xffff)
3835
                    return -1;
3836
                
3837
                if (s->umvplus)
3838
                  my = h263p_decode_umotion(s, pred_y);
3839
                else    
3840
                  my = h263_decode_motion(s, pred_y, 1);
3841
                if (my >= 0xffff)
3842
                    return -1;
3843
                s->mv[0][i][0] = mx;
3844
                s->mv[0][i][1] = my;
3845
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3846
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3847
                mot_val[0] = mx;
3848
                mot_val[1] = my;
3849
            }
3850
        }
3851

    
3852
        /* decode each block */
3853
        for (i = 0; i < 6; i++) {
3854
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3855
                return -1;
3856
            cbp+=cbp;
3857
        }
3858

    
3859
        if(s->obmc){
3860
            if(s->pict_type == P_TYPE && s->mb_x+1<s->mb_width && s->mb_num_left != 1)
3861
                preview_obmc(s);
3862
        }
3863
    } else if(s->pict_type==B_TYPE) {
3864
        int mb_type;
3865
        const int stride= s->b8_stride;
3866
        int16_t *mot_val0 = s->current_picture.motion_val[0][ 2*(s->mb_x + s->mb_y*stride) ];
3867
        int16_t *mot_val1 = s->current_picture.motion_val[1][ 2*(s->mb_x + s->mb_y*stride) ];
3868
//        const int mv_xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
3869

    
3870
        //FIXME ugly 
3871
        mot_val0[0       ]= mot_val0[2       ]= mot_val0[0+2*stride]= mot_val0[2+2*stride]= 
3872
        mot_val0[1       ]= mot_val0[3       ]= mot_val0[1+2*stride]= mot_val0[3+2*stride]= 
3873
        mot_val1[0       ]= mot_val1[2       ]= mot_val1[0+2*stride]= mot_val1[2+2*stride]= 
3874
        mot_val1[1       ]= mot_val1[3       ]= mot_val1[1+2*stride]= mot_val1[3+2*stride]= 0;
3875

    
3876
        do{
3877
            mb_type= get_vlc2(&s->gb, h263_mbtype_b_vlc.table, H263_MBTYPE_B_VLC_BITS, 2);
3878
            if (mb_type < 0){
3879
                av_log(s->avctx, AV_LOG_ERROR, "b mb_type damaged at %d %d\n", s->mb_x, s->mb_y);
3880
                return -1;
3881
            }
3882

    
3883
            mb_type= h263_mb_type_b_map[ mb_type ];
3884
        }while(!mb_type);
3885

    
3886
        s->mb_intra = IS_INTRA(mb_type);
3887
        if(HAS_CBP(mb_type)){
3888
            cbpc = get_vlc2(&s->gb, cbpc_b_vlc.table, CBPC_B_VLC_BITS, 1);
3889
            if(s->mb_intra){
3890
                dquant = IS_QUANT(mb_type);
3891
                goto intra;
3892
            }
3893

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

    
3896
            if (cbpy < 0){
3897
                av_log(s->avctx, AV_LOG_ERROR, "b cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
3898
                return -1;
3899
            }
3900
        
3901
            if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
3902
                cbpy ^= 0xF;
3903
        
3904
            cbp = (cbpc & 3) | (cbpy << 2);
3905
        }else
3906
            cbp=0;
3907
            
3908
        assert(!s->mb_intra);
3909

    
3910
        if(IS_QUANT(mb_type)){
3911
            h263_decode_dquant(s);
3912
        }
3913

    
3914
        if(IS_DIRECT(mb_type)){
3915
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3916
            mb_type |= ff_mpeg4_set_direct_mv(s, 0, 0);
3917
        }else{
3918
            s->mv_dir = 0;
3919
            s->mv_type= MV_TYPE_16X16;
3920
//FIXME UMV
3921

    
3922
            if(USES_LIST(mb_type, 0)){
3923
                int16_t *mot_val= h263_pred_motion(s, 0, 0, &mx, &my);
3924
                s->mv_dir = MV_DIR_FORWARD;
3925

    
3926
                mx = h263_decode_motion(s, mx, 1);
3927
                my = h263_decode_motion(s, my, 1);
3928
                
3929
                s->mv[0][0][0] = mx;
3930
                s->mv[0][0][1] = my;
3931
                mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
3932
                mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
3933
            }
3934
    
3935
            if(USES_LIST(mb_type, 1)){
3936
                int16_t *mot_val= h263_pred_motion(s, 0, 1, &mx, &my);
3937
                s->mv_dir |= MV_DIR_BACKWARD;
3938
                
3939
                mx = h263_decode_motion(s, mx, 1);
3940
                my = h263_decode_motion(s, my, 1);
3941

    
3942
                s->mv[1][0][0] = mx;
3943
                s->mv[1][0][1] = my;
3944
                mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
3945
                mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
3946
            }
3947
        }
3948
          
3949
        s->current_picture.mb_type[xy]= mb_type;
3950

    
3951
        /* decode each block */
3952
        for (i = 0; i < 6; i++) {
3953
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3954
                return -1;
3955
            cbp+=cbp;
3956
        }
3957
    } else { /* I-Frame */
3958
        do{
3959
            cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
3960
            if (cbpc < 0){
3961
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
3962
                return -1;
3963
            }
3964
        }while(cbpc == 8);
3965

    
3966
        dquant = cbpc & 4;
3967
        s->mb_intra = 1;
3968
intra:
3969
        s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3970
        if (s->h263_aic) {
3971
            s->ac_pred = get_bits1(&s->gb);
3972
            if(s->ac_pred){
3973
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
3974
            
3975
                s->h263_aic_dir = get_bits1(&s->gb);
3976
            }
3977
        }else
3978
            s->ac_pred = 0;
3979
        
3980
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3981
        if(cbpy<0){
3982
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
3983
            return -1;
3984
        }
3985
        cbp = (cbpc & 3) | (cbpy << 2);
3986
        if (dquant) {
3987
            h263_decode_dquant(s);
3988
        }
3989

    
3990
        /* decode each block */
3991
        for (i = 0; i < 6; i++) {
3992
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3993
                return -1;
3994
            cbp+=cbp;
3995
        }
3996
    }
3997
end:
3998

    
3999
        /* per-MB end of slice check */
4000
    {
4001
        int v= show_bits(&s->gb, 16);
4002
    
4003
        if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
4004
            v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
4005
        }
4006

    
4007
        if(v==0)
4008
            return SLICE_END;
4009
    }
4010

    
4011
    return SLICE_OK;     
4012
}
4013

    
4014
int ff_mpeg4_decode_mb(MpegEncContext *s,
4015
                      DCTELEM block[6][64])
4016
{
4017
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
4018
    int16_t *mot_val;
4019
    static int8_t quant_tab[4] = { -1, -2, 1, 2 };
4020
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
4021
    
4022
    assert(s->h263_pred);
4023
    
4024
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
4025
        do{
4026
            if (get_bits1(&s->gb)) {
4027
                /* skip mb */
4028
                s->mb_intra = 0;
4029
                for(i=0;i<6;i++)
4030
                    s->block_last_index[i] = -1;
4031
                s->mv_dir = MV_DIR_FORWARD;
4032
                s->mv_type = MV_TYPE_16X16;
4033
                if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
4034
                    s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
4035
                    s->mcsel=1;
4036
                    s->mv[0][0][0]= get_amv(s, 0);
4037
                    s->mv[0][0][1]= get_amv(s, 1);
4038

    
4039
                    s->mb_skiped = 0;
4040
                }else{
4041
                    s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
4042
                    s->mcsel=0;
4043
                    s->mv[0][0][0] = 0;
4044
                    s->mv[0][0][1] = 0;
4045
                    s->mb_skiped = 1;
4046
                }
4047
                goto end;
4048
            }
4049
            cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
4050
            //fprintf(stderr, "\tCBPC: %d", cbpc);
4051
            if (cbpc < 0){
4052
                av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
4053
                return -1;
4054
            }
4055
        }while(cbpc == 20);
4056
        
4057
        dquant = cbpc & 8;
4058
        s->mb_intra = ((cbpc & 4) != 0);
4059
        if (s->mb_intra) goto intra;
4060
        
4061
        if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
4062
            s->mcsel= get_bits1(&s->gb);
4063
        else s->mcsel= 0;
4064
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
4065
        
4066
        cbp = (cbpc & 3) | (cbpy << 2);
4067
        if (dquant) {
4068
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
4069
        }
4070
        if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
4071
            s->interlaced_dct= get_bits1(&s->gb);
4072
        
4073
        s->mv_dir = MV_DIR_FORWARD;
4074
        if ((cbpc & 16) == 0) {
4075
            if(s->mcsel){
4076
                s->current_picture.mb_type[xy]= MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
4077
                /* 16x16 global motion prediction */
4078
                s->mv_type = MV_TYPE_16X16;
4079
                mx= get_amv(s, 0);
4080
                my= get_amv(s, 1);
4081
                s->mv[0][0][0] = mx;
4082
                s->mv[0][0][1] = my;
4083
            }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
4084
                s->current_picture.mb_type[xy]= MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; 
4085
                /* 16x8 field motion prediction */
4086
                s->mv_type= MV_TYPE_FIELD;
4087

    
4088
                s->field_select[0][0]= get_bits1(&s->gb);
4089
                s->field_select[0][1]= get_bits1(&s->gb);
4090

    
4091
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
4092
                
4093
                for(i=0; i<2; i++){
4094
                    mx = h263_decode_motion(s, pred_x, s->f_code);
4095
                    if (mx >= 0xffff)
4096
                        return -1;
4097
            
4098
                    my = h263_decode_motion(s, pred_y/2, s->f_code);
4099
                    if (my >= 0xffff)
4100
                        return -1;
4101

    
4102
                    s->mv[0][i][0] = mx;
4103
                    s->mv[0][i][1] = my;
4104
                }
4105
            }else{
4106
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
4107
                /* 16x16 motion prediction */
4108
                s->mv_type = MV_TYPE_16X16;
4109
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
4110
                mx = h263_decode_motion(s, pred_x, s->f_code);
4111
            
4112
                if (mx >= 0xffff)
4113
                    return -1;
4114
            
4115
                my = h263_decode_motion(s, pred_y, s->f_code);
4116
            
4117
                if (my >= 0xffff)
4118
                    return -1;
4119
                s->mv[0][0][0] = mx;
4120
                s->mv[0][0][1] = my;
4121
            }
4122
        } else {
4123
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
4124
            s->mv_type = MV_TYPE_8X8;
4125
            for(i=0;i<4;i++) {
4126
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
4127
                mx = h263_decode_motion(s, pred_x, s->f_code);
4128
                if (mx >= 0xffff)
4129
                    return -1;
4130
                
4131
                my = h263_decode_motion(s, pred_y, s->f_code);
4132
                if (my >= 0xffff)
4133
                    return -1;
4134
                s->mv[0][i][0] = mx;
4135
                s->mv[0][i][1] = my;
4136
                mot_val[0] = mx;
4137
                mot_val[1] = my;
4138
            }
4139
        }
4140
    } else if(s->pict_type==B_TYPE) {
4141
        int modb1; // first bit of modb
4142
        int modb2; // second bit of modb
4143
        int mb_type;
4144

    
4145
        s->mb_intra = 0; //B-frames never contain intra blocks
4146
        s->mcsel=0;      //     ...               true gmc blocks
4147

    
4148
        if(s->mb_x==0){
4149
            for(i=0; i<2; i++){
4150
                s->last_mv[i][0][0]= 
4151
                s->last_mv[i][0][1]= 
4152
                s->last_mv[i][1][0]= 
4153
                s->last_mv[i][1][1]= 0;
4154
            }
4155
        }
4156

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

    
4160
        if(s->mb_skiped){
4161
                /* skip mb */
4162
            for(i=0;i<6;i++)
4163
                s->block_last_index[i] = -1;
4164

    
4165
            s->mv_dir = MV_DIR_FORWARD;
4166
            s->mv_type = MV_TYPE_16X16;
4167
            s->mv[0][0][0] = 0;
4168
            s->mv[0][0][1] = 0;
4169
            s->mv[1][0][0] = 0;
4170
            s->mv[1][0][1] = 0;
4171
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; 
4172
            goto end;
4173
        }
4174

    
4175
        modb1= get_bits1(&s->gb); 
4176
        if(modb1){
4177
            mb_type= MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; //like MB_TYPE_B_DIRECT but no vectors coded
4178
            cbp=0;
4179
        }else{
4180
            modb2= get_bits1(&s->gb);
4181
            mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
4182
            if(mb_type<0){
4183
                av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
4184
                return -1;
4185
            }
4186
            mb_type= mb_type_b_map[ mb_type ];
4187
            if(modb2) cbp= 0;
4188
            else      cbp= get_bits(&s->gb, 6);
4189

    
4190
            if ((!IS_DIRECT(mb_type)) && cbp) {
4191
                if(get_bits1(&s->gb)){
4192
                    ff_set_qscale(s, s->qscale + get_bits1(&s->gb)*4 - 2);
4193
                }
4194
            }
4195

    
4196
            if(!s->progressive_sequence){
4197
                if(cbp)
4198
                    s->interlaced_dct= get_bits1(&s->gb);
4199

    
4200
                if(!IS_DIRECT(mb_type) && get_bits1(&s->gb)){
4201
                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
4202
                    mb_type &= ~MB_TYPE_16x16;
4203

    
4204
                    if(USES_LIST(mb_type, 0)){
4205
                        s->field_select[0][0]= get_bits1(&s->gb);
4206
                        s->field_select[0][1]= get_bits1(&s->gb);
4207
                    }
4208
                    if(USES_LIST(mb_type, 1)){
4209
                        s->field_select[1][0]= get_bits1(&s->gb);
4210
                        s->field_select[1][1]= get_bits1(&s->gb);
4211
                    }
4212
                }
4213
            }
4214

    
4215
            s->mv_dir = 0;
4216
            if((mb_type & (MB_TYPE_DIRECT2|MB_TYPE_INTERLACED)) == 0){
4217
                s->mv_type= MV_TYPE_16X16;
4218

    
4219
                if(USES_LIST(mb_type, 0)){
4220
                    s->mv_dir = MV_DIR_FORWARD;
4221

    
4222
                    mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
4223
                    my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
4224
                    s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
4225
                    s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
4226
                }
4227
    
4228
                if(USES_LIST(mb_type, 1)){
4229
                    s->mv_dir |= MV_DIR_BACKWARD;
4230

    
4231
                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
4232
                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
4233
                    s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
4234
                    s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
4235
                }
4236
            }else if(!IS_DIRECT(mb_type)){
4237
                s->mv_type= MV_TYPE_FIELD;
4238

    
4239
                if(USES_LIST(mb_type, 0)){
4240
                    s->mv_dir = MV_DIR_FORWARD;
4241
                
4242
                    for(i=0; i<2; i++){
4243
                        mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
4244
                        my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
4245
                        s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
4246
                        s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
4247
                    }
4248
                }
4249
    
4250
                if(USES_LIST(mb_type, 1)){
4251
                    s->mv_dir |= MV_DIR_BACKWARD;
4252

    
4253
                    for(i=0; i<2; i++){
4254
                        mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
4255
                        my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
4256
                        s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
4257
                        s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
4258
                    }
4259
                }
4260
            }
4261
        }
4262
          
4263
        if(IS_DIRECT(mb_type)){
4264
            if(IS_SKIP(mb_type))
4265
                mx=my=0;
4266
            else{
4267
                mx = h263_decode_motion(s, 0, 1);
4268
                my = h263_decode_motion(s, 0, 1);
4269
            }
4270
 
4271
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
4272
            mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
4273
        }
4274
        s->current_picture.mb_type[xy]= mb_type;
4275
    } else { /* I-Frame */
4276
        do{
4277
            cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
4278
            if (cbpc < 0){
4279
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
4280
                return -1;
4281
            }
4282
        }while(cbpc == 8);
4283

    
4284
        dquant = cbpc & 4;
4285
        s->mb_intra = 1;
4286
intra:
4287
        s->ac_pred = get_bits1(&s->gb);
4288
        if(s->ac_pred)
4289
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
4290
        else
4291
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
4292
        
4293
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
4294
        if(cbpy<0){
4295
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
4296
            return -1;
4297
        }
4298
        cbp = (cbpc & 3) | (cbpy << 2);
4299
        if (dquant) {
4300
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
4301
        }
4302
        
4303
        if(!s->progressive_sequence)
4304
            s->interlaced_dct= get_bits1(&s->gb);
4305

    
4306
        /* decode each block */
4307
        for (i = 0; i < 6; i++) {
4308
            if (mpeg4_decode_block(s, block[i], i, cbp&32, 1, 0) < 0)
4309
                return -1;
4310
            cbp+=cbp;
4311
        }
4312
        goto end;
4313
    }
4314

    
4315
    /* decode each block */
4316
    for (i = 0; i < 6; i++) {
4317
        if (mpeg4_decode_block(s, block[i], i, cbp&32, 0, 0) < 0)
4318
            return -1;
4319
        cbp+=cbp;
4320
    }
4321
end:
4322

    
4323
        /* per-MB end of slice check */
4324
    if(s->codec_id==CODEC_ID_MPEG4){
4325
        if(mpeg4_is_resync(s)){
4326
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
4327
            if(s->pict_type==B_TYPE && s->next_picture.mbskip_table[xy + delta])
4328
                return SLICE_OK;
4329
            return SLICE_END;
4330
        }
4331
    }
4332

    
4333
    return SLICE_OK;     
4334
}
4335

    
4336
static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
4337
{
4338
    int code, val, sign, shift, l;
4339
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
4340

    
4341
    if (code == 0)
4342
        return pred;
4343
    if (code < 0)
4344
        return 0xffff;
4345

    
4346
    sign = get_bits1(&s->gb);
4347
    shift = f_code - 1;
4348
    val = code;
4349
    if (shift) {
4350
        val = (val - 1) << shift;
4351
        val |= get_bits(&s->gb, shift);
4352
        val++;
4353
    }
4354
    if (sign)
4355
        val = -val;
4356
    val += pred;
4357

    
4358
    /* modulo decoding */
4359
    if (!s->h263_long_vectors) {
4360
        l = 1 << (f_code + 4);
4361
        val = ((val + l)&(l*2-1)) - l;
4362
    } else {
4363
        /* horrible h263 long vector mode */
4364
        if (pred < -31 && val < -63)
4365
            val += 64;
4366
        if (pred > 32 && val > 63)
4367
            val -= 64;
4368
        
4369
    }
4370
    return val;
4371
}
4372

    
4373
/* Decodes RVLC of H.263+ UMV */
4374
static int h263p_decode_umotion(MpegEncContext * s, int pred)
4375
{
4376
   int code = 0, sign;
4377
   
4378
   if (get_bits1(&s->gb)) /* Motion difference = 0 */
4379
      return pred;
4380
   
4381
   code = 2 + get_bits1(&s->gb);
4382
   
4383
   while (get_bits1(&s->gb))
4384
   {
4385
      code <<= 1;
4386
      code += get_bits1(&s->gb);
4387
   }
4388
   sign = code & 1;
4389
   code >>= 1;
4390
   
4391
   code = (sign) ? (pred - code) : (pred + code);
4392
#ifdef DEBUG
4393
   fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
4394
#endif
4395
   return code;   
4396

    
4397
}
4398

    
4399
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
4400
                             int n, int coded)
4401
{
4402
    int code, level, i, j, last, run;
4403
    RLTable *rl = &rl_inter;
4404
    const uint8_t *scan_table;
4405
    GetBitContext gb= s->gb;
4406

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

    
4527
/**
4528
 * decodes the dc value.
4529
 * @param n block index (0-3 are luma, 4-5 are chroma)
4530
 * @param dir_ptr the prediction direction will be stored here
4531
 * @return the quantized dc
4532
 */
4533
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
4534
{
4535
    int level, pred, code;
4536
    uint16_t *dc_val;
4537

    
4538
    if (n < 4) 
4539
        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
4540
    else 
4541
        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
4542
    if (code < 0 || code > 9 /* && s->nbit<9 */){
4543
        av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
4544
        return -1;
4545
    }
4546
    if (code == 0) {
4547
        level = 0;
4548
    } else {
4549
        if(IS_3IV1){
4550
            if(code==1)
4551
                level= 2*get_bits1(&s->gb)-1;
4552
            else{
4553
                if(get_bits1(&s->gb))
4554
                    level = get_bits(&s->gb, code-1) + (1<<(code-1));
4555
                else
4556
                    level = -get_bits(&s->gb, code-1) - (1<<(code-1));
4557
            }
4558
        }else{
4559
            level = get_xbits(&s->gb, code);
4560
        }
4561

    
4562
        if (code > 8){
4563
            if(get_bits1(&s->gb)==0){ /* marker */
4564
                if(s->error_resilience>=2){
4565
                    av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
4566
                    return -1;
4567
                }
4568
            }
4569
        }
4570
    }
4571
    pred = ff_mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
4572
    level += pred;
4573
    if (level < 0){
4574
        if(s->error_resilience>=3){
4575
            av_log(s->avctx, AV_LOG_ERROR, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
4576
            return -1;
4577
        }
4578
        level = 0;
4579
    }
4580
    if (n < 4) {
4581
        *dc_val = level * s->y_dc_scale;
4582
    } else {
4583
        *dc_val = level * s->c_dc_scale;
4584
    }
4585
    if(IS_3IV1)
4586
        *dc_val = level * 8;
4587
    
4588
    if(s->error_resilience>=3){
4589
        if(*dc_val > 2048 + s->y_dc_scale + s->c_dc_scale){
4590
            av_log(s->avctx, AV_LOG_ERROR, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
4591
            return -1;
4592
        }
4593
    }
4594
    return level;
4595
}
4596

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

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

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

    
4710
                level=  level * qmul + qadd;
4711
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1);
4712
                SKIP_COUNTER(re, &s->gb, 1+11+5+1);
4713

    
4714
                i+= run + 1;
4715
                if(last) i+=192;
4716
          }else{
4717
            int cache;
4718
            cache= GET_CACHE(re, &s->gb);
4719

    
4720
            if(IS_3IV1) 
4721
                cache ^= 0xC0000000;
4722

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

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

    
4740
                        level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
4741

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

    
4747
                        SKIP_COUNTER(re, &s->gb, 1+12+1);
4748
                    }
4749
 
4750
                    if(level*s->qscale>1024 || level*s->qscale<-1024){
4751
                        av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
4752
                        return -1;
4753
                    }
4754
#if 0
4755
                    if(s->error_resilience >= FF_ER_COMPLIANT){
4756
                        const int abs_level= ABS(level);
4757
                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN){
4758
                            const int run1= run - rl->max_run[last][abs_level] - 1;
4759
                            if(abs_level <= rl->max_level[last][run]){
4760
                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
4761
                                return -1;
4762
                            }
4763
                            if(s->error_resilience > FF_ER_COMPLIANT){
4764
                                if(abs_level <= rl->max_level[last][run]*2){
4765
                                    fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");
4766
                                    return -1;
4767
                                }
4768
                                if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
4769
                                    fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");
4770
                                    return -1;
4771
                                }
4772
                            }
4773
                        }
4774