Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h263.c @ 3f26d68a

History | View | Annotate | Download (211 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 h263p_encode_umotion(MpegEncContext * s, int val);
60
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
61
                               int n, int dc, uint8_t *scan_table, 
62
                               PutBitContext *dc_pb, PutBitContext *ac_pb);
63
#endif
64

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

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

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

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

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

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

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

    
119
int h263_get_picture_format(int width, int height)
120
{
121
    int format;
122

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

    
138
#ifdef CONFIG_ENCODERS
139

    
140
static void aspect_to_info(MpegEncContext * s, AVRational aspect){
141
    int i;
142

    
143
    if(aspect.num==0) aspect= (AVRational){1,1};
144

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

    
155
void ff_flv_encode_picture_header(MpegEncContext * s, int picture_number)
156
{
157
      int format;
158

    
159
      align_put_bits(&s->pb);
160

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

    
192
      if(s->h263_aic){
193
        s->y_dc_scale_table= 
194
          s->c_dc_scale_table= ff_aic_dc_scale_table;
195
      }else{
196
        s->y_dc_scale_table=
197
          s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
198
      }
199
}
200

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

    
225
    align_put_bits(&s->pb);
226

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

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

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

    
320
        put_bits(&s->pb, 5, s->qscale);
321
    }
322

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

    
325
    if(s->h263_slice_structured){
326
        put_bits(&s->pb, 1, 1);
327
        
328
        assert(s->mb_x == 0 && s->mb_y == 0);
329
        ff_h263_encode_mba(s);
330

    
331
        put_bits(&s->pb, 1, 1);
332
    }
333

    
334
    if(s->h263_aic){
335
         s->y_dc_scale_table= 
336
         s->c_dc_scale_table= ff_aic_dc_scale_table;
337
    }else{
338
        s->y_dc_scale_table=
339
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
340
    }
341
}
342

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

    
350
    if(s->h263_slice_structured){
351
        put_bits(&s->pb, 1, 1);
352

    
353
        ff_h263_encode_mba(s);
354

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

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

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

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

    
386
            last= j;
387
        }
388
    }
389
    
390
    return rate;
391
}
392

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

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

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

    
454
        for(i=63; i>0; i--) //FIXME optimize
455
            if(block[n][ st[n][i] ]) break;
456
        s->block_last_index[n]= i;
457

    
458
        score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
459
    }
460

    
461
    return score < 0;
462
}
463

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

    
469
    for(n=0; n<6; n++){
470
        int16_t *ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
471

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

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

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

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

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

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

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

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

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

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

    
668
#ifdef CONFIG_ENCODERS
669

    
670
static inline int h263_get_motion_length(MpegEncContext * s, int val, int f_code){
671
    int l, bit_size, code;
672

    
673
    if (val == 0) {
674
        return mvtab[0][1];
675
    } else {
676
        bit_size = f_code - 1;
677
        /* modulo encoding */
678
        l= INT_BIT - 6 - bit_size;
679
        val = (val<<l)>>l;
680
        val--;
681
        code = (val >> bit_size) + 1;
682

    
683
        return mvtab[code][1] + 1 + bit_size;
684
    }
685
}
686

    
687
static inline void ff_h263_encode_motion_vector(MpegEncContext * s, int x, int y, int f_code){
688
    if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
689
        skip_put_bits(&s->pb, 
690
            h263_get_motion_length(s, x, f_code)
691
           +h263_get_motion_length(s, y, f_code));
692
    }else{
693
        ff_h263_encode_motion(s, x, f_code);
694
        ff_h263_encode_motion(s, y, f_code);
695
    }
696
}
697

    
698
static inline int get_p_cbp(MpegEncContext * s,
699
                      DCTELEM block[6][64],
700
                      int motion_x, int motion_y){
701
    int cbp, i;
702

    
703
    if(s->flags & CODEC_FLAG_CBP_RD){
704
        int best_cbpy_score= INT_MAX;
705
        int best_cbpc_score= INT_MAX;
706
        int cbpc = (-1), cbpy= (-1);
707
        const int offset= (s->mv_type==MV_TYPE_16X16 ? 0 : 16) + (s->dquant ? 8 : 0);
708
        const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
709

    
710
        for(i=0; i<4; i++){
711
            int score= inter_MCBPC_bits[i + offset] * lambda;
712
            if(i&1) score += s->coded_score[5];
713
            if(i&2) score += s->coded_score[4];
714

    
715
            if(score < best_cbpc_score){
716
                best_cbpc_score= score;
717
                cbpc= i;
718
            }
719
        }
720

    
721
        for(i=0; i<16; i++){
722
            int score= cbpy_tab[i ^ 0xF][1] * lambda;
723
            if(i&1) score += s->coded_score[3];
724
            if(i&2) score += s->coded_score[2];
725
            if(i&4) score += s->coded_score[1];
726
            if(i&8) score += s->coded_score[0];
727

    
728
            if(score < best_cbpy_score){
729
                best_cbpy_score= score;
730
                cbpy= i;
731
            }
732
        }
733
        cbp= cbpc + 4*cbpy;
734
        if ((motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16){
735
            if(best_cbpy_score + best_cbpc_score + 2*lambda >= 0)
736
                cbp= 0;
737
        }
738

    
739
        for (i = 0; i < 6; i++) {
740
            if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
741
                s->block_last_index[i]= -1;
742
                memset(s->block[i], 0, sizeof(DCTELEM)*64);
743
            }
744
        }
745
    }else{
746
        cbp= 0;
747
        for (i = 0; i < 6; i++) {
748
            if (s->block_last_index[i] >= 0)
749
                cbp |= 1 << (5 - i);
750
        }
751
    }
752
    return cbp;
753
}
754

    
755
static inline int get_b_cbp(MpegEncContext * s, DCTELEM block[6][64],
756
                            int motion_x, int motion_y, int mb_type){
757
    int cbp=0, i;
758

    
759
    if(s->flags & CODEC_FLAG_CBP_RD){
760
        int score=0;
761
        const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
762
        
763
        for(i=0; i<6; i++){
764
            if(s->coded_score[i] < 0){
765
                score += s->coded_score[i];
766
                cbp |= 1 << (5 - i);
767
            }
768
        }
769
        
770
        if(cbp){
771
            int zero_score= -6;
772
            if ((motion_x | motion_y | s->dquant | mb_type) == 0){
773
                zero_score-= 4; //2*MV + mb_type + cbp bit
774
            }
775

    
776
            zero_score*= lambda;
777
            if(zero_score <= score){
778
                cbp=0;
779
            }
780
        }
781

    
782
        for (i = 0; i < 6; i++) {
783
            if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
784
                s->block_last_index[i]= -1;
785
                memset(s->block[i], 0, sizeof(DCTELEM)*64);
786
            }
787
        }
788
    }else{
789
        for (i = 0; i < 6; i++) {
790
            if (s->block_last_index[i] >= 0)
791
                cbp |= 1 << (5 - i);
792
        }
793
    }
794
    return cbp;
795
}
796

    
797
static inline void mpeg4_encode_blocks(MpegEncContext * s, DCTELEM block[6][64], int intra_dc[6], 
798
                               uint8_t **scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb){
799
    int i;
800
    
801
    if(scan_table){
802
        if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
803
            for (i = 0; i < 6; i++) {
804
                skip_put_bits(&s->pb, mpeg4_get_block_length(s, block[i], i, intra_dc[i], scan_table[i]));
805
            }
806
        }else{
807
            /* encode each block */
808
            for (i = 0; i < 6; i++) {
809
                mpeg4_encode_block(s, block[i], i, intra_dc[i], scan_table[i], dc_pb, ac_pb);
810
            }
811
        }
812
    }else{
813
        if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
814
            for (i = 0; i < 6; i++) {
815
                skip_put_bits(&s->pb, mpeg4_get_block_length(s, block[i], i, 0, s->intra_scantable.permutated));
816
            }
817
        }else{
818
            /* encode each block */
819
            for (i = 0; i < 6; i++) {
820
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, dc_pb, ac_pb);
821
            }
822
        }
823
    }
824
}
825

    
826
void mpeg4_encode_mb(MpegEncContext * s,
827
                    DCTELEM block[6][64],
828
                    int motion_x, int motion_y)
829
{
830
    int cbpc, cbpy, pred_x, pred_y;
831
    PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
832
    PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=B_TYPE ? &s->tex_pb : &s->pb;
833
    PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=I_TYPE ? &s->pb2    : &s->pb;
834
    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
835
    const int dquant_code[5]= {1,0,9,2,3};
836
    
837
    //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
838
    if (!s->mb_intra) {
839
        int i, cbp;
840
        
841
        if(s->pict_type==B_TYPE){
842
            static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
843
            int mb_type=  mb_type_table[s->mv_dir];
844

    
845
            if(s->mb_x==0){
846
                for(i=0; i<2; i++){
847
                    s->last_mv[i][0][0]= 
848
                    s->last_mv[i][0][1]= 
849
                    s->last_mv[i][1][0]= 
850
                    s->last_mv[i][1][1]= 0;
851
                }
852
            }
853
            
854
            assert(s->dquant>=-2 && s->dquant<=2);
855
            assert((s->dquant&1)==0);
856
            assert(mb_type>=0);
857

    
858
            /* nothing to do if this MB was skiped in the next P Frame */
859
            if(s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]){ //FIXME avoid DCT & ...
860
                s->skip_count++;
861
                s->mv[0][0][0]= 
862
                s->mv[0][0][1]= 
863
                s->mv[1][0][0]= 
864
                s->mv[1][0][1]= 0;
865
                s->mv_dir= MV_DIR_FORWARD; //doesnt matter
866
                s->qscale -= s->dquant;
867
//                s->mb_skiped=1;
868

    
869
                return;
870
            }
871
            
872
            cbp= get_b_cbp(s, block, motion_x, motion_y, mb_type);
873
            
874
            if ((cbp | motion_x | motion_y | mb_type) ==0) {
875
                /* direct MB with MV={0,0} */
876
                assert(s->dquant==0);
877
                
878
                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
879

    
880
                if(interleaved_stats){
881
                    s->misc_bits++;
882
                    s->last_bits++;
883
                }
884
                s->skip_count++;
885
                return;
886
            }
887
            
888
            put_bits(&s->pb, 1, 0);        /* mb coded modb1=0 */
889
            put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
890
            put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we dont need it :)
891
            if(cbp) put_bits(&s->pb, 6, cbp);
892
            
893
            if(cbp && mb_type){
894
                if(s->dquant)
895
                    put_bits(&s->pb, 2, (s->dquant>>2)+3);
896
                else
897
                    put_bits(&s->pb, 1, 0);
898
            }else
899
                s->qscale -= s->dquant;
900
            
901
            if(!s->progressive_sequence){
902
                if(cbp)
903
                    put_bits(&s->pb, 1, s->interlaced_dct);
904
                if(mb_type) // not diect mode
905
                    put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
906
            }
907

    
908
            if(interleaved_stats){
909
                s->misc_bits+= get_bits_diff(s);
910
            }
911

    
912
            if(mb_type == 0){
913
                assert(s->mv_dir & MV_DIRECT);
914
                ff_h263_encode_motion_vector(s, motion_x, motion_y, 1);
915
                s->b_count++;
916
                s->f_count++;
917
            }else{
918
                assert(mb_type > 0 && mb_type < 4);
919
                if(s->mv_type != MV_TYPE_FIELD){
920
                    if(s->mv_dir & MV_DIR_FORWARD){
921
                        ff_h263_encode_motion_vector(s, s->mv[0][0][0] - s->last_mv[0][0][0],
922
                                                        s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
923
                        s->last_mv[0][0][0]= s->last_mv[0][1][0]= s->mv[0][0][0];
924
                        s->last_mv[0][0][1]= s->last_mv[0][1][1]= s->mv[0][0][1];
925
                        s->f_count++;
926
                    }
927
                    if(s->mv_dir & MV_DIR_BACKWARD){
928
                        ff_h263_encode_motion_vector(s, s->mv[1][0][0] - s->last_mv[1][0][0],
929
                                                        s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
930
                        s->last_mv[1][0][0]= s->last_mv[1][1][0]= s->mv[1][0][0];
931
                        s->last_mv[1][0][1]= s->last_mv[1][1][1]= s->mv[1][0][1];
932
                        s->b_count++;
933
                    }
934
                }else{
935
                    if(s->mv_dir & MV_DIR_FORWARD){
936
                        put_bits(&s->pb, 1, s->field_select[0][0]);
937
                        put_bits(&s->pb, 1, s->field_select[0][1]);
938
                    }
939
                    if(s->mv_dir & MV_DIR_BACKWARD){
940
                        put_bits(&s->pb, 1, s->field_select[1][0]);
941
                        put_bits(&s->pb, 1, s->field_select[1][1]);
942
                    }
943
                    if(s->mv_dir & MV_DIR_FORWARD){
944
                        for(i=0; i<2; i++){
945
                            ff_h263_encode_motion_vector(s, s->mv[0][i][0] - s->last_mv[0][i][0]  ,
946
                                                            s->mv[0][i][1] - s->last_mv[0][i][1]/2, s->f_code);
947
                            s->last_mv[0][i][0]= s->mv[0][i][0];
948
                            s->last_mv[0][i][1]= s->mv[0][i][1]*2;
949
                        }
950
                        s->f_count++;
951
                    }
952
                    if(s->mv_dir & MV_DIR_BACKWARD){
953
                        for(i=0; i<2; i++){
954
                            ff_h263_encode_motion_vector(s, s->mv[1][i][0] - s->last_mv[1][i][0]  ,
955
                                                            s->mv[1][i][1] - s->last_mv[1][i][1]/2, s->b_code);
956
                            s->last_mv[1][i][0]= s->mv[1][i][0];
957
                            s->last_mv[1][i][1]= s->mv[1][i][1]*2;
958
                        }
959
                        s->b_count++;
960
                    }
961
                }
962
            }
963

    
964
            if(interleaved_stats){
965
                s->mv_bits+= get_bits_diff(s);
966
            }
967

    
968
            mpeg4_encode_blocks(s, block, NULL, NULL, NULL, &s->pb);
969

    
970
            if(interleaved_stats){
971
                s->p_tex_bits+= get_bits_diff(s);
972
            }
973

    
974
        }else{ /* s->pict_type==B_TYPE */
975
            cbp= get_p_cbp(s, block, motion_x, motion_y);
976
        
977
            if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
978
                /* check if the B frames can skip it too, as we must skip it if we skip here 
979
                   why didnt they just compress the skip-mb bits instead of reusing them ?! */
980
                if(s->max_b_frames>0){
981
                    int i;
982
                    int x,y, offset;
983
                    uint8_t *p_pic;
984

    
985
                    x= s->mb_x*16;
986
                    y= s->mb_y*16;
987
                    if(x+16 > s->width)  x= s->width-16;
988
                    if(y+16 > s->height) y= s->height-16;
989

    
990
                    offset= x + y*s->linesize;
991
                    p_pic= s->new_picture.data[0] + offset;
992
                    
993
                    s->mb_skiped=1;
994
                    for(i=0; i<s->max_b_frames; i++){
995
                        uint8_t *b_pic;
996
                        int diff;
997
                        Picture *pic= s->reordered_input_picture[i+1];
998

    
999
                        if(pic==NULL || pic->pict_type!=B_TYPE) break;
1000

    
1001
                        b_pic= pic->data[0] + offset + 16; //FIXME +16
1002
                        diff= s->dsp.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
1003
                        if(diff>s->qscale*70){ //FIXME check that 70 is optimal
1004
                            s->mb_skiped=0;
1005
                            break;
1006
                        }
1007
                    }
1008
                }else
1009
                    s->mb_skiped=1; 
1010

    
1011
                if(s->mb_skiped==1){
1012
                    /* skip macroblock */
1013
                    put_bits(&s->pb, 1, 1);
1014

    
1015
                    if(interleaved_stats){
1016
                        s->misc_bits++;
1017
                        s->last_bits++;
1018
                    }
1019
                    s->skip_count++;
1020
                    
1021
                    return;
1022
                }
1023
            }
1024

    
1025
            put_bits(&s->pb, 1, 0);        /* mb coded */
1026
            cbpc = cbp & 3;
1027
            cbpy = cbp >> 2;
1028
            cbpy ^= 0xf;
1029
            if(s->mv_type==MV_TYPE_16X16){
1030
                if(s->dquant) cbpc+= 8;
1031
                put_bits(&s->pb,
1032
                        inter_MCBPC_bits[cbpc],
1033
                        inter_MCBPC_code[cbpc]);
1034

    
1035
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1036
                if(s->dquant)
1037
                    put_bits(pb2, 2, dquant_code[s->dquant+2]);
1038

    
1039
                if(!s->progressive_sequence){
1040
                    if(cbp)
1041
                        put_bits(pb2, 1, s->interlaced_dct);
1042
                    put_bits(pb2, 1, 0);
1043
                }
1044
                    
1045
                if(interleaved_stats){
1046
                    s->misc_bits+= get_bits_diff(s);
1047
                }
1048

    
1049
                /* motion vectors: 16x16 mode */
1050
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1051
            
1052
                ff_h263_encode_motion_vector(s, motion_x - pred_x,
1053
                                                motion_y - pred_y, s->f_code);
1054
            }else if(s->mv_type==MV_TYPE_FIELD){
1055
                if(s->dquant) cbpc+= 8;
1056
                put_bits(&s->pb,
1057
                        inter_MCBPC_bits[cbpc],
1058
                        inter_MCBPC_code[cbpc]);
1059

    
1060
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1061
                if(s->dquant)
1062
                    put_bits(pb2, 2, dquant_code[s->dquant+2]);
1063

    
1064
                assert(!s->progressive_sequence);
1065
                if(cbp)
1066
                    put_bits(pb2, 1, s->interlaced_dct);
1067
                put_bits(pb2, 1, 1);
1068
                    
1069
                if(interleaved_stats){
1070
                    s->misc_bits+= get_bits_diff(s);
1071
                }
1072

    
1073
                /* motion vectors: 16x8 interlaced mode */
1074
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1075
                pred_y /=2;
1076
                
1077
                put_bits(&s->pb, 1, s->field_select[0][0]);
1078
                put_bits(&s->pb, 1, s->field_select[0][1]);
1079
            
1080
                ff_h263_encode_motion_vector(s, s->mv[0][0][0] - pred_x,
1081
                                                s->mv[0][0][1] - pred_y, s->f_code);
1082
                ff_h263_encode_motion_vector(s, s->mv[0][1][0] - pred_x,
1083
                                                s->mv[0][1][1] - pred_y, s->f_code);
1084
            }else{
1085
                assert(s->mv_type==MV_TYPE_8X8);
1086
                put_bits(&s->pb,
1087
                        inter_MCBPC_bits[cbpc+16],
1088
                        inter_MCBPC_code[cbpc+16]);
1089
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1090

    
1091
                if(!s->progressive_sequence){
1092
                    if(cbp)
1093
                        put_bits(pb2, 1, s->interlaced_dct);
1094
                }
1095
    
1096
                if(interleaved_stats){
1097
                    s->misc_bits+= get_bits_diff(s);
1098
                }
1099

    
1100
                for(i=0; i<4; i++){
1101
                    /* motion vectors: 8x8 mode*/
1102
                    h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1103

    
1104
                    ff_h263_encode_motion_vector(s, s->current_picture.motion_val[0][ s->block_index[i] ][0] - pred_x,
1105
                                                    s->current_picture.motion_val[0][ s->block_index[i] ][1] - pred_y, s->f_code);
1106
                }
1107
            }
1108

    
1109
            if(interleaved_stats){ 
1110
                s->mv_bits+= get_bits_diff(s);
1111
            }
1112

    
1113
            mpeg4_encode_blocks(s, block, NULL, NULL, NULL, tex_pb);
1114

    
1115
            if(interleaved_stats){
1116
                s->p_tex_bits+= get_bits_diff(s);
1117
            }
1118
            s->f_count++;
1119
        }
1120
    } else {
1121
        int cbp;
1122
        int dc_diff[6];   //dc values with the dc prediction subtracted 
1123
        int dir[6];  //prediction direction
1124
        int zigzag_last_index[6];
1125
        uint8_t *scan_table[6];
1126
        int i;
1127

    
1128
        for(i=0; i<6; i++){
1129
            dc_diff[i]= ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
1130
        }
1131

    
1132
        if(s->flags & CODEC_FLAG_AC_PRED){
1133
            s->ac_pred= decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
1134
            if(!s->ac_pred)
1135
                restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1136
        }else{
1137
            for(i=0; i<6; i++)
1138
                scan_table[i]= s->intra_scantable.permutated;
1139
        }
1140

    
1141
        /* compute cbp */
1142
        cbp = 0;
1143
        for (i = 0; i < 6; i++) {
1144
            if (s->block_last_index[i] >= 1)
1145
                cbp |= 1 << (5 - i);
1146
        }
1147

    
1148
        cbpc = cbp & 3;
1149
        if (s->pict_type == I_TYPE) {
1150
            if(s->dquant) cbpc+=4;
1151
            put_bits(&s->pb,
1152
                intra_MCBPC_bits[cbpc],
1153
                intra_MCBPC_code[cbpc]);
1154
        } else {
1155
            if(s->dquant) cbpc+=8;
1156
            put_bits(&s->pb, 1, 0);        /* mb coded */
1157
            put_bits(&s->pb,
1158
                inter_MCBPC_bits[cbpc + 4],
1159
                inter_MCBPC_code[cbpc + 4]);
1160
        }
1161
        put_bits(pb2, 1, s->ac_pred);
1162
        cbpy = cbp >> 2;
1163
        put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1164
        if(s->dquant)
1165
            put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
1166

    
1167
        if(!s->progressive_sequence){
1168
            put_bits(dc_pb, 1, s->interlaced_dct);
1169
        }
1170

    
1171
        if(interleaved_stats){
1172
            s->misc_bits+= get_bits_diff(s);
1173
        }
1174

    
1175
        mpeg4_encode_blocks(s, block, dc_diff, scan_table, dc_pb, tex_pb);
1176

    
1177
        if(interleaved_stats){
1178
            s->i_tex_bits+= get_bits_diff(s);
1179
        }
1180
        s->i_count++;
1181

    
1182
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
1183
        if(s->ac_pred)
1184
            restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1185
    }
1186
}
1187

    
1188
void h263_encode_mb(MpegEncContext * s,
1189
                    DCTELEM block[6][64],
1190
                    int motion_x, int motion_y)
1191
{
1192
    int cbpc, cbpy, i, cbp, pred_x, pred_y;
1193
    int16_t pred_dc;
1194
    int16_t rec_intradc[6];
1195
    uint16_t *dc_ptr[6];
1196
    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1);
1197
    const int dquant_code[5]= {1,0,9,2,3};
1198
           
1199
    //printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
1200
    if (!s->mb_intra) {
1201
        /* compute cbp */
1202
        cbp= get_p_cbp(s, block, motion_x, motion_y);
1203

    
1204
        if ((cbp | motion_x | motion_y | s->dquant | (s->mv_type - MV_TYPE_16X16)) == 0) {
1205
            /* skip macroblock */
1206
            put_bits(&s->pb, 1, 1);
1207
            if(interleaved_stats){
1208
                s->misc_bits++;
1209
                s->last_bits++;
1210
            }
1211
            s->skip_count++;
1212

    
1213
            return;
1214
        }
1215
        put_bits(&s->pb, 1, 0);        /* mb coded */
1216
        
1217
        cbpc = cbp & 3;
1218
        cbpy = cbp >> 2;
1219
        if(s->alt_inter_vlc==0 || cbpc!=3)
1220
            cbpy ^= 0xF;
1221
        if(s->dquant) cbpc+= 8;
1222
        if(s->mv_type==MV_TYPE_16X16){
1223
            put_bits(&s->pb,
1224
                    inter_MCBPC_bits[cbpc],
1225
                    inter_MCBPC_code[cbpc]);
1226

    
1227
            put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1228
            if(s->dquant)
1229
                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1230
                
1231
            if(interleaved_stats){
1232
                s->misc_bits+= get_bits_diff(s);
1233
            }
1234

    
1235
            /* motion vectors: 16x16 mode */
1236
            h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1237
            
1238
            if (!s->umvplus) {  
1239
                ff_h263_encode_motion_vector(s, motion_x - pred_x,
1240
                                                motion_y - pred_y, 1);
1241
            }
1242
            else {
1243
                h263p_encode_umotion(s, motion_x - pred_x);
1244
                h263p_encode_umotion(s, motion_y - pred_y);
1245
                if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1246
                    /* To prevent Start Code emulation */
1247
                    put_bits(&s->pb,1,1);
1248
            }
1249
        }else{
1250
            put_bits(&s->pb,
1251
                    inter_MCBPC_bits[cbpc+16],
1252
                    inter_MCBPC_code[cbpc+16]);
1253
            put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1254
            if(s->dquant)
1255
                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1256

    
1257
            if(interleaved_stats){
1258
                s->misc_bits+= get_bits_diff(s);
1259
            }
1260

    
1261
            for(i=0; i<4; i++){
1262
                /* motion vectors: 8x8 mode*/
1263
                h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1264

    
1265
                motion_x= s->current_picture.motion_val[0][ s->block_index[i] ][0];
1266
                motion_y= s->current_picture.motion_val[0][ s->block_index[i] ][1];
1267
                if (!s->umvplus) {  
1268
                    ff_h263_encode_motion_vector(s, motion_x - pred_x,
1269
                                                    motion_y - pred_y, 1);
1270
                }
1271
                else {
1272
                    h263p_encode_umotion(s, motion_x - pred_x);
1273
                    h263p_encode_umotion(s, motion_y - pred_y);
1274
                    if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1275
                        /* To prevent Start Code emulation */
1276
                        put_bits(&s->pb,1,1);
1277
                }
1278
            }
1279
        }
1280

    
1281
        if(interleaved_stats){
1282
            s->mv_bits+= get_bits_diff(s);
1283
        }
1284
    } else {
1285
        assert(s->mb_intra);
1286
        
1287
        cbp = 0;
1288
        if (s->h263_aic) {
1289
            /* Predict DC */
1290
            for(i=0; i<6; i++) {
1291
                int16_t level = block[i][0];
1292
                int scale;
1293
                
1294
                if(i<4) scale= s->y_dc_scale;
1295
                else    scale= s->c_dc_scale;
1296

    
1297
                pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
1298
                level -= pred_dc;
1299
                /* Quant */
1300
                if (level >= 0)
1301
                    level = (level + (scale>>1))/scale;
1302
                else
1303
                    level = (level - (scale>>1))/scale;
1304
                    
1305
                /* AIC can change CBP */
1306
                if (level == 0 && s->block_last_index[i] == 0)
1307
                    s->block_last_index[i] = -1;
1308

    
1309
                if(!s->modified_quant){
1310
                    if (level < -127)
1311
                        level = -127;
1312
                    else if (level > 127)
1313
                        level = 127;
1314
                }
1315

    
1316
                block[i][0] = level;
1317
                /* Reconstruction */ 
1318
                rec_intradc[i] = scale*level + pred_dc;
1319
                /* Oddify */
1320
                rec_intradc[i] |= 1;
1321
                //if ((rec_intradc[i] % 2) == 0)
1322
                //    rec_intradc[i]++;
1323
                /* Clipping */
1324
                if (rec_intradc[i] < 0)
1325
                    rec_intradc[i] = 0;
1326
                else if (rec_intradc[i] > 2047)
1327
                    rec_intradc[i] = 2047;
1328
                                
1329
                /* Update AC/DC tables */
1330
                *dc_ptr[i] = rec_intradc[i];
1331
                if (s->block_last_index[i] >= 0)
1332
                    cbp |= 1 << (5 - i);
1333
            }
1334
        }else{
1335
            for(i=0; i<6; i++) {
1336
                /* compute cbp */
1337
                if (s->block_last_index[i] >= 1)
1338
                    cbp |= 1 << (5 - i);
1339
            }
1340
        }
1341

    
1342
        cbpc = cbp & 3;
1343
        if (s->pict_type == I_TYPE) {
1344
            if(s->dquant) cbpc+=4;
1345
            put_bits(&s->pb,
1346
                intra_MCBPC_bits[cbpc],
1347
                intra_MCBPC_code[cbpc]);
1348
        } else {
1349
            if(s->dquant) cbpc+=8;
1350
            put_bits(&s->pb, 1, 0);        /* mb coded */
1351
            put_bits(&s->pb,
1352
                inter_MCBPC_bits[cbpc + 4],
1353
                inter_MCBPC_code[cbpc + 4]);
1354
        }
1355
        if (s->h263_aic) {
1356
            /* XXX: currently, we do not try to use ac prediction */
1357
            put_bits(&s->pb, 1, 0);        /* no AC prediction */
1358
        }
1359
        cbpy = cbp >> 2;
1360
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1361
        if(s->dquant)
1362
            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1363

    
1364
        if(interleaved_stats){
1365
            s->misc_bits+= get_bits_diff(s);
1366
        }
1367
    }
1368

    
1369
    for(i=0; i<6; i++) {
1370
        /* encode each block */
1371
        h263_encode_block(s, block[i], i);
1372
    
1373
        /* Update INTRADC for decoding */
1374
        if (s->h263_aic && s->mb_intra) {
1375
            block[i][0] = rec_intradc[i];
1376
            
1377
        }
1378
    }
1379

    
1380
    if(interleaved_stats){
1381
        if (!s->mb_intra) {
1382
            s->p_tex_bits+= get_bits_diff(s);
1383
            s->f_count++;
1384
        }else{
1385
            s->i_tex_bits+= get_bits_diff(s);
1386
            s->i_count++;
1387
        }
1388
    }
1389
}
1390
#endif
1391

    
1392
void ff_h263_loop_filter(MpegEncContext * s){
1393
    int qp_c;
1394
    const int linesize  = s->linesize;
1395
    const int uvlinesize= s->uvlinesize;
1396
    const int xy = s->mb_y * s->mb_stride + s->mb_x;
1397
    uint8_t *dest_y = s->dest[0];
1398
    uint8_t *dest_cb= s->dest[1];
1399
    uint8_t *dest_cr= s->dest[2];
1400
    
1401
//    if(s->pict_type==B_TYPE && !s->readable) return;
1402

    
1403
    /*
1404
       Diag Top
1405
       Left Center
1406
    */
1407
    if(!IS_SKIP(s->current_picture.mb_type[xy])){
1408
        qp_c= s->qscale;
1409
        s->dsp.h263_v_loop_filter(dest_y+8*linesize  , linesize, qp_c);
1410
        s->dsp.h263_v_loop_filter(dest_y+8*linesize+8, linesize, qp_c);
1411
    }else
1412
        qp_c= 0;
1413

    
1414
    if(s->mb_y){
1415
        int qp_dt, qp_t, qp_tc;
1416

    
1417
        if(IS_SKIP(s->current_picture.mb_type[xy-s->mb_stride]))
1418
            qp_t=0;
1419
        else 
1420
            qp_t= s->current_picture.qscale_table[xy-s->mb_stride];
1421

    
1422
        if(qp_c) 
1423
            qp_tc= qp_c;
1424
        else
1425
            qp_tc= qp_t;
1426
            
1427
        if(qp_tc){
1428
            const int chroma_qp= s->chroma_qscale_table[qp_tc];
1429
            s->dsp.h263_v_loop_filter(dest_y  ,   linesize, qp_tc);
1430
            s->dsp.h263_v_loop_filter(dest_y+8,   linesize, qp_tc);
1431
        
1432
            s->dsp.h263_v_loop_filter(dest_cb , uvlinesize, chroma_qp);
1433
            s->dsp.h263_v_loop_filter(dest_cr , uvlinesize, chroma_qp);
1434
        }
1435
        
1436
        if(qp_t)
1437
            s->dsp.h263_h_loop_filter(dest_y-8*linesize+8  ,   linesize, qp_t);
1438
        
1439
        if(s->mb_x){
1440
            if(qp_t || IS_SKIP(s->current_picture.mb_type[xy-1-s->mb_stride]))
1441
                qp_dt= qp_t;
1442
            else
1443
                qp_dt= s->current_picture.qscale_table[xy-1-s->mb_stride];
1444
            
1445
            if(qp_dt){
1446
                const int chroma_qp= s->chroma_qscale_table[qp_dt];
1447
                s->dsp.h263_h_loop_filter(dest_y -8*linesize  ,   linesize, qp_dt);
1448
                s->dsp.h263_h_loop_filter(dest_cb-8*uvlinesize, uvlinesize, chroma_qp);
1449
                s->dsp.h263_h_loop_filter(dest_cr-8*uvlinesize, uvlinesize, chroma_qp);
1450
            }
1451
        }
1452
    }
1453

    
1454
    if(qp_c){
1455
        s->dsp.h263_h_loop_filter(dest_y +8,   linesize, qp_c);
1456
        if(s->mb_y + 1 == s->mb_height)
1457
            s->dsp.h263_h_loop_filter(dest_y+8*linesize+8,   linesize, qp_c);
1458
    }
1459
    
1460
    if(s->mb_x){
1461
        int qp_lc;
1462
        if(qp_c || IS_SKIP(s->current_picture.mb_type[xy-1]))
1463
            qp_lc= qp_c;
1464
        else
1465
            qp_lc= s->current_picture.qscale_table[xy-1];
1466
        
1467
        if(qp_lc){
1468
            s->dsp.h263_h_loop_filter(dest_y,   linesize, qp_lc);
1469
            if(s->mb_y + 1 == s->mb_height){
1470
                const int chroma_qp= s->chroma_qscale_table[qp_lc];
1471
                s->dsp.h263_h_loop_filter(dest_y +8*  linesize,   linesize, qp_lc);
1472
                s->dsp.h263_h_loop_filter(dest_cb             , uvlinesize, chroma_qp);
1473
                s->dsp.h263_h_loop_filter(dest_cr             , uvlinesize, chroma_qp);
1474
            }
1475
        }
1476
    }
1477
}
1478

    
1479
static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr)
1480
{
1481
    int x, y, wrap, a, c, pred_dc, scale;
1482
    int16_t *dc_val, *ac_val;
1483

    
1484
    /* find prediction */
1485
    if (n < 4) {
1486
        x = 2 * s->mb_x + (n & 1);
1487
        y = 2 * s->mb_y + ((n & 2) >> 1);
1488
        wrap = s->b8_stride;
1489
        dc_val = s->dc_val[0];
1490
        ac_val = s->ac_val[0][0];
1491
        scale = s->y_dc_scale;
1492
    } else {
1493
        x = s->mb_x;
1494
        y = s->mb_y;
1495
        wrap = s->mb_stride;
1496
        dc_val = s->dc_val[n - 4 + 1];
1497
        ac_val = s->ac_val[n - 4 + 1][0];
1498
        scale = s->c_dc_scale;
1499
    }
1500
    /* B C
1501
     * A X 
1502
     */
1503
    a = dc_val[(x - 1) + (y) * wrap];
1504
    c = dc_val[(x) + (y - 1) * wrap];
1505
    
1506
    /* No prediction outside GOB boundary */
1507
    if(s->first_slice_line && n!=3){
1508
        if(n!=2) c= 1024;
1509
        if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
1510
    }
1511
    pred_dc = 1024;
1512
    /* just DC prediction */
1513
    if (a != 1024 && c != 1024)
1514
        pred_dc = (a + c) >> 1;
1515
    else if (a != 1024)
1516
        pred_dc = a;
1517
    else
1518
        pred_dc = c;
1519
    
1520
    /* we assume pred is positive */
1521
    //pred_dc = (pred_dc + (scale >> 1)) / scale;
1522
    *dc_val_ptr = &dc_val[x + y * wrap];
1523
    return pred_dc;
1524
}
1525

    
1526
static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1527
{
1528
    int x, y, wrap, a, c, pred_dc, scale, i;
1529
    int16_t *dc_val, *ac_val, *ac_val1;
1530

    
1531
    /* find prediction */
1532
    if (n < 4) {
1533
        x = 2 * s->mb_x + (n & 1);
1534
        y = 2 * s->mb_y + (n>> 1);
1535
        wrap = s->b8_stride;
1536
        dc_val = s->dc_val[0];
1537
        ac_val = s->ac_val[0][0];
1538
        scale = s->y_dc_scale;
1539
    } else {
1540
        x = s->mb_x;
1541
        y = s->mb_y;
1542
        wrap = s->mb_stride;
1543
        dc_val = s->dc_val[n - 4 + 1];
1544
        ac_val = s->ac_val[n - 4 + 1][0];
1545
        scale = s->c_dc_scale;
1546
    }
1547
    
1548
    ac_val += ((y) * wrap + (x)) * 16;
1549
    ac_val1 = ac_val;
1550
    
1551
    /* B C
1552
     * A X 
1553
     */
1554
    a = dc_val[(x - 1) + (y) * wrap];
1555
    c = dc_val[(x) + (y - 1) * wrap];
1556
    
1557
    /* No prediction outside GOB boundary */
1558
    if(s->first_slice_line && n!=3){
1559
        if(n!=2) c= 1024;
1560
        if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
1561
    }
1562
    
1563
    if (s->ac_pred) {
1564
        pred_dc = 1024;
1565
        if (s->h263_aic_dir) {
1566
            /* left prediction */
1567
            if (a != 1024) {
1568
                ac_val -= 16;
1569
                for(i=1;i<8;i++) {
1570
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1571
                }
1572
                pred_dc = a;
1573
            }
1574
        } else {
1575
            /* top prediction */
1576
            if (c != 1024) {
1577
                ac_val -= 16 * wrap;
1578
                for(i=1;i<8;i++) {
1579
                    block[s->dsp.idct_permutation[i   ]] += ac_val[i + 8];
1580
                }
1581
                pred_dc = c;
1582
            }
1583
        }
1584
    } else {
1585
        /* just DC prediction */
1586
        if (a != 1024 && c != 1024)
1587
            pred_dc = (a + c) >> 1;
1588
        else if (a != 1024)
1589
            pred_dc = a;
1590
        else
1591
            pred_dc = c;
1592
    }
1593
    
1594
    /* we assume pred is positive */
1595
    block[0]=block[0]*scale + pred_dc;
1596
    
1597
    if (block[0] < 0)
1598
        block[0] = 0;
1599
    else 
1600
        block[0] |= 1;
1601
    
1602
    /* Update AC/DC tables */
1603
    dc_val[(x) + (y) * wrap] = block[0];
1604
    
1605
    /* left copy */
1606
    for(i=1;i<8;i++)
1607
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1608
    /* top copy */
1609
    for(i=1;i<8;i++)
1610
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1611
}
1612

    
1613
int16_t *h263_pred_motion(MpegEncContext * s, int block, int dir,
1614
                        int *px, int *py)
1615
{
1616
    int wrap;
1617
    int16_t *A, *B, *C, (*mot_val)[2];
1618
    static const int off[4]= {2, 1, 1, -1};
1619

    
1620
    wrap = s->b8_stride;
1621
    mot_val = s->current_picture.motion_val[dir] + s->block_index[block];
1622

    
1623
    A = mot_val[ - 1];
1624
    /* special case for first (slice) line */
1625
    if (s->first_slice_line && block<3) {
1626
        // we cant just change some MVs to simulate that as we need them for the B frames (and ME)
1627
        // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1628
        if(block==0){ //most common case
1629
            if(s->mb_x  == s->resync_mb_x){ //rare
1630
                *px= *py = 0;
1631
            }else if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1632
                C = mot_val[off[block] - wrap];
1633
                if(s->mb_x==0){
1634
                    *px = C[0];
1635
                    *py = C[1];
1636
                }else{
1637
                    *px = mid_pred(A[0], 0, C[0]);
1638
                    *py = mid_pred(A[1], 0, C[1]);
1639
                }
1640
            }else{
1641
                *px = A[0];
1642
                *py = A[1];
1643
            }
1644
        }else if(block==1){
1645
            if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1646
                C = mot_val[off[block] - wrap];
1647
                *px = mid_pred(A[0], 0, C[0]);
1648
                *py = mid_pred(A[1], 0, C[1]);
1649
            }else{
1650
                *px = A[0];
1651
                *py = A[1];
1652
            }
1653
        }else{ /* block==2*/
1654
            B = mot_val[ - wrap];
1655
            C = mot_val[off[block] - wrap];
1656
            if(s->mb_x == s->resync_mb_x) //rare
1657
                A[0]=A[1]=0;
1658
    
1659
            *px = mid_pred(A[0], B[0], C[0]);
1660
            *py = mid_pred(A[1], B[1], C[1]);
1661
        }
1662
    } else {
1663
        B = mot_val[ - wrap];
1664
        C = mot_val[off[block] - wrap];
1665
        *px = mid_pred(A[0], B[0], C[0]);
1666
        *py = mid_pred(A[1], B[1], C[1]);
1667
    }
1668
    return *mot_val;
1669
}
1670

    
1671
#ifdef CONFIG_ENCODERS
1672
void ff_h263_encode_motion(MpegEncContext * s, int val, int f_code)
1673
{
1674
    int range, l, bit_size, sign, code, bits;
1675

    
1676
    if (val == 0) {
1677
        /* zero vector */
1678
        code = 0;
1679
        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1680
    } else {
1681
        bit_size = f_code - 1;
1682
        range = 1 << bit_size;
1683
        /* modulo encoding */
1684
        l= INT_BIT - 6 - bit_size;
1685
        val = (val<<l)>>l;
1686
        sign = val>>31;
1687
        val= (val^sign)-sign;
1688
        sign&=1;
1689

    
1690
        val--;
1691
        code = (val >> bit_size) + 1;
1692
        bits = val & (range - 1);
1693

    
1694
        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
1695
        if (bit_size > 0) {
1696
            put_bits(&s->pb, bit_size, bits);
1697
        }
1698
    }
1699
}
1700

    
1701
/* Encode MV differences on H.263+ with Unrestricted MV mode */
1702
static void h263p_encode_umotion(MpegEncContext * s, int val)
1703
{
1704
    short sval = 0; 
1705
    short i = 0;
1706
    short n_bits = 0;
1707
    short temp_val;
1708
    int code = 0;
1709
    int tcode;
1710
    
1711
    if ( val == 0)
1712
        put_bits(&s->pb, 1, 1);
1713
    else if (val == 1)
1714
        put_bits(&s->pb, 3, 0);
1715
    else if (val == -1)
1716
        put_bits(&s->pb, 3, 2);
1717
    else {
1718
        
1719
        sval = ((val < 0) ? (short)(-val):(short)val);
1720
        temp_val = sval;
1721
        
1722
        while (temp_val != 0) {
1723
            temp_val = temp_val >> 1;
1724
            n_bits++;
1725
        }
1726
        
1727
        i = n_bits - 1;
1728
        while (i > 0) {
1729
            tcode = (sval & (1 << (i-1))) >> (i-1);
1730
            tcode = (tcode << 1) | 1;
1731
            code = (code << 2) | tcode;
1732
            i--;
1733
        }
1734
        code = ((code << 1) | (val < 0)) << 1;
1735
        put_bits(&s->pb, (2*n_bits)+1, code);
1736
        //printf("\nVal = %d\tCode = %d", sval, code);
1737
    }
1738
}
1739

    
1740
static void init_mv_penalty_and_fcode(MpegEncContext *s)
1741
{
1742
    int f_code;
1743
    int mv;
1744
    
1745
    if(mv_penalty==NULL)
1746
        mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1747
    
1748
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
1749
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1750
            int len;
1751

    
1752
            if(mv==0) len= mvtab[0][1];
1753
            else{
1754
                int val, bit_size, range, code;
1755

    
1756
                bit_size = f_code - 1;
1757
                range = 1 << bit_size;
1758

    
1759
                val=mv;
1760
                if (val < 0) 
1761
                    val = -val;
1762
                val--;
1763
                code = (val >> bit_size) + 1;
1764
                if(code<33){
1765
                    len= mvtab[code][1] + 1 + bit_size;
1766
                }else{
1767
                    len= mvtab[32][1] + 2 + bit_size;
1768
                }
1769
            }
1770

    
1771
            mv_penalty[f_code][mv+MAX_MV]= len;
1772
        }
1773
    }
1774

    
1775
    for(f_code=MAX_FCODE; f_code>0; f_code--){
1776
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1777
            fcode_tab[mv+MAX_MV]= f_code;
1778
        }
1779
    }
1780

    
1781
    for(mv=0; mv<MAX_MV*2+1; mv++){
1782
        umv_fcode_tab[mv]= 1;
1783
    }
1784
}
1785
#endif
1786

    
1787
#ifdef CONFIG_ENCODERS
1788

    
1789
static void init_uni_dc_tab(void)
1790
{
1791
    int level, uni_code, uni_len;
1792

    
1793
    for(level=-256; level<256; level++){
1794
        int size, v, l;
1795
        /* find number of bits */
1796
        size = 0;
1797
        v = abs(level);
1798
        while (v) {
1799
            v >>= 1;
1800
            size++;
1801
        }
1802

    
1803
        if (level < 0)
1804
            l= (-level) ^ ((1 << size) - 1);
1805
        else
1806
            l= level;
1807

    
1808
        /* luminance */
1809
        uni_code= DCtab_lum[size][0];
1810
        uni_len = DCtab_lum[size][1];
1811

    
1812
        if (size > 0) {
1813
            uni_code<<=size; uni_code|=l;
1814
            uni_len+=size;
1815
            if (size > 8){
1816
                uni_code<<=1; uni_code|=1;
1817
                uni_len++;
1818
            }
1819
        }
1820
        uni_DCtab_lum_bits[level+256]= uni_code;
1821
        uni_DCtab_lum_len [level+256]= uni_len;
1822

    
1823
        /* chrominance */
1824
        uni_code= DCtab_chrom[size][0];
1825
        uni_len = DCtab_chrom[size][1];
1826
        
1827
        if (size > 0) {
1828
            uni_code<<=size; uni_code|=l;
1829
            uni_len+=size;
1830
            if (size > 8){
1831
                uni_code<<=1; uni_code|=1;
1832
                uni_len++;
1833
            }
1834
        }
1835
        uni_DCtab_chrom_bits[level+256]= uni_code;
1836
        uni_DCtab_chrom_len [level+256]= uni_len;
1837

    
1838
    }
1839
}
1840

    
1841
#endif //CONFIG_ENCODERS
1842

    
1843
#ifdef CONFIG_ENCODERS
1844
static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1845
    int slevel, run, last;
1846
    
1847
    assert(MAX_LEVEL >= 64);
1848
    assert(MAX_RUN   >= 63);
1849

    
1850
    for(slevel=-64; slevel<64; slevel++){
1851
        if(slevel==0) continue;
1852
        for(run=0; run<64; run++){
1853
            for(last=0; last<=1; last++){
1854
                const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1855
                int level= slevel < 0 ? -slevel : slevel;
1856
                int sign= slevel < 0 ? 1 : 0;
1857
                int bits, len, code;
1858
                int level1, run1;
1859
                
1860
                len_tab[index]= 100;
1861
                     
1862
                /* ESC0 */
1863
                code= get_rl_index(rl, last, run, level);
1864
                bits= rl->table_vlc[code][0];
1865
                len=  rl->table_vlc[code][1];
1866
                bits=bits*2+sign; len++;
1867
                
1868
                if(code!=rl->n && len < len_tab[index]){
1869
                    bits_tab[index]= bits;
1870
                    len_tab [index]= len;
1871
                }
1872
#if 1
1873
                /* ESC1 */
1874
                bits= rl->table_vlc[rl->n][0];
1875
                len=  rl->table_vlc[rl->n][1];
1876
                bits=bits*2;    len++; //esc1
1877
                level1= level - rl->max_level[last][run];
1878
                if(level1>0){
1879
                    code= get_rl_index(rl, last, run, level1);
1880
                    bits<<= rl->table_vlc[code][1];
1881
                    len  += rl->table_vlc[code][1];
1882
                    bits += rl->table_vlc[code][0];
1883
                    bits=bits*2+sign; len++;
1884
                
1885
                    if(code!=rl->n && len < len_tab[index]){
1886
                        bits_tab[index]= bits;
1887
                        len_tab [index]= len;
1888
                    }
1889
                }
1890
#endif 
1891
#if 1
1892
                /* ESC2 */
1893
                bits= rl->table_vlc[rl->n][0];
1894
                len=  rl->table_vlc[rl->n][1];
1895
                bits=bits*4+2;    len+=2; //esc2
1896
                run1 = run - rl->max_run[last][level] - 1;
1897
                if(run1>=0){
1898
                    code= get_rl_index(rl, last, run1, level);
1899
                    bits<<= rl->table_vlc[code][1];
1900
                    len  += rl->table_vlc[code][1];
1901
                    bits += rl->table_vlc[code][0];
1902
                    bits=bits*2+sign; len++;
1903
                
1904
                    if(code!=rl->n && len < len_tab[index]){
1905
                        bits_tab[index]= bits;
1906
                        len_tab [index]= len;
1907
                    }
1908
                }
1909
#endif           
1910
                /* ESC3 */        
1911
                bits= rl->table_vlc[rl->n][0];
1912
                len = rl->table_vlc[rl->n][1];
1913
                bits=bits*4+3;    len+=2; //esc3
1914
                bits=bits*2+last; len++;
1915
                bits=bits*64+run; len+=6;
1916
                bits=bits*2+1;    len++;  //marker
1917
                bits=bits*4096+(slevel&0xfff); len+=12;
1918
                bits=bits*2+1;    len++;  //marker
1919
                
1920
                if(len < len_tab[index]){
1921
                    bits_tab[index]= bits;
1922
                    len_tab [index]= len;
1923
                }
1924
            }
1925
        }
1926
    }
1927
}
1928

    
1929
static void init_uni_h263_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1930
    int slevel, run, last;
1931
    
1932
    assert(MAX_LEVEL >= 64);
1933
    assert(MAX_RUN   >= 63);
1934

    
1935
    for(slevel=-64; slevel<64; slevel++){
1936
        if(slevel==0) continue;
1937
        for(run=0; run<64; run++){
1938
            for(last=0; last<=1; last++){
1939
                const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1940
                int level= slevel < 0 ? -slevel : slevel;
1941
                int sign= slevel < 0 ? 1 : 0;
1942
                int bits, len, code;
1943
                int level1, run1;
1944
                
1945
                len_tab[index]= 100;
1946
                     
1947
                /* ESC0 */
1948
                code= get_rl_index(rl, last, run, level);
1949
                bits= rl->table_vlc[code][0];
1950
                len=  rl->table_vlc[code][1];
1951
                bits=bits*2+sign; len++;
1952
                
1953
                if(code!=rl->n && len < len_tab[index]){
1954
                    if(bits_tab) bits_tab[index]= bits;
1955
                    len_tab [index]= len;
1956
                }
1957
                /* ESC */
1958
                bits= rl->table_vlc[rl->n][0];
1959
                len = rl->table_vlc[rl->n][1];
1960
                bits=bits*2+last; len++;
1961
                bits=bits*64+run; len+=6;
1962
                bits=bits*256+(level&0xff); len+=8;
1963
                
1964
                if(len < len_tab[index]){
1965
                    if(bits_tab) bits_tab[index]= bits;
1966
                    len_tab [index]= len;
1967
                }
1968
            }
1969
        }
1970
    }
1971
}
1972

    
1973
void h263_encode_init(MpegEncContext *s)
1974
{
1975
    static int done = 0;
1976

    
1977
    if (!done) {
1978
        done = 1;
1979

    
1980
        init_uni_dc_tab();
1981

    
1982
        init_rl(&rl_inter, 1);
1983
        init_rl(&rl_intra, 1);
1984
        init_rl(&rl_intra_aic, 1);
1985
        
1986
        init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1987
        init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1988

    
1989
        init_uni_h263_rl_tab(&rl_intra_aic, NULL, uni_h263_intra_aic_rl_len);
1990
        init_uni_h263_rl_tab(&rl_inter    , NULL, uni_h263_inter_rl_len);
1991

    
1992
        init_mv_penalty_and_fcode(s);
1993
    }
1994
    s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
1995
    
1996
    s->intra_ac_vlc_length     =s->inter_ac_vlc_length     = uni_h263_inter_rl_len;
1997
    s->intra_ac_vlc_last_length=s->inter_ac_vlc_last_length= uni_h263_inter_rl_len + 128*64;
1998
    if(s->h263_aic){
1999
        s->intra_ac_vlc_length     = uni_h263_intra_aic_rl_len;
2000
        s->intra_ac_vlc_last_length= uni_h263_intra_aic_rl_len + 128*64;
2001
    }
2002
    s->ac_esc_length= 7+1+6+8;
2003

    
2004
    // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
2005
    switch(s->codec_id){
2006
    case CODEC_ID_MPEG4:
2007
        s->fcode_tab= fcode_tab;
2008
        s->min_qcoeff= -2048;
2009
        s->max_qcoeff=  2047;
2010
        s->intra_ac_vlc_length     = uni_mpeg4_intra_rl_len;
2011
        s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;
2012
        s->inter_ac_vlc_length     = uni_mpeg4_inter_rl_len;
2013
        s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;
2014
        s->luma_dc_vlc_length= uni_DCtab_lum_len;
2015
        s->chroma_dc_vlc_length= uni_DCtab_chrom_len;
2016
        s->ac_esc_length= 7+2+1+6+1+12+1;
2017
        s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table;
2018
        s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
2019

    
2020
        if(s->flags & CODEC_FLAG_GLOBAL_HEADER){
2021

    
2022
            s->avctx->extradata= av_malloc(1024);
2023
            init_put_bits(&s->pb, s->avctx->extradata, 1024);
2024
            
2025
            mpeg4_encode_visual_object_header(s);
2026
            mpeg4_encode_vol_header(s, 0, 0);
2027

    
2028
//            ff_mpeg4_stuffing(&s->pb); ?
2029
            flush_put_bits(&s->pb);
2030
            s->avctx->extradata_size= (put_bits_count(&s->pb)+7)>>3;
2031
        }
2032
        
2033
        break;
2034
    case CODEC_ID_H263P:
2035
        if(s->umvplus)
2036
            s->fcode_tab= umv_fcode_tab;
2037
        if(s->modified_quant){
2038
            s->min_qcoeff= -2047;
2039
            s->max_qcoeff=  2047;
2040
        }else{
2041
            s->min_qcoeff= -127;
2042
            s->max_qcoeff=  127;
2043
        }
2044
        break;
2045
        //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later 
2046
    case CODEC_ID_FLV1:
2047
        if (s->h263_flv > 1) {
2048
            s->min_qcoeff= -1023;
2049
            s->max_qcoeff=  1023;
2050
        } else {
2051
            s->min_qcoeff= -127;
2052
            s->max_qcoeff=  127;
2053
        }
2054
        s->y_dc_scale_table=
2055
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
2056
        break;
2057
    default: //nothing needed default table allready set in mpegvideo.c
2058
        s->min_qcoeff= -127;
2059
        s->max_qcoeff=  127;
2060
        s->y_dc_scale_table=
2061
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
2062
    }
2063
}
2064

    
2065
/**
2066
 * encodes a 8x8 block.
2067
 * @param block the 8x8 block
2068
 * @param n block index (0-3 are luma, 4-5 are chroma)
2069
 */
2070
static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
2071
{
2072
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
2073
    RLTable *rl;
2074

    
2075
    rl = &rl_inter;
2076
    if (s->mb_intra && !s->h263_aic) {
2077
        /* DC coef */
2078
        level = block[0];
2079
        /* 255 cannot be represented, so we clamp */
2080
        if (level > 254) {
2081
            level = 254;
2082
            block[0] = 254;
2083
        }
2084
        /* 0 cannot be represented also */
2085
        else if (level < 1) {
2086
            level = 1;
2087
            block[0] = 1;
2088
        }
2089
        if (level == 128) //FIXME check rv10
2090
            put_bits(&s->pb, 8, 0xff);
2091
        else
2092
            put_bits(&s->pb, 8, level);
2093
        i = 1;
2094
    } else {
2095
        i = 0;
2096
        if (s->h263_aic && s->mb_intra)
2097
            rl = &rl_intra_aic;
2098
            
2099
        if(s->alt_inter_vlc && !s->mb_intra){
2100
            int aic_vlc_bits=0;
2101
            int inter_vlc_bits=0;
2102
            int wrong_pos=-1;
2103
            int aic_code;
2104
            
2105
            last_index = s->block_last_index[n];
2106
            last_non_zero = i - 1;
2107
            for (; i <= last_index; i++) {
2108
                j = s->intra_scantable.permutated[i];
2109
                level = block[j];
2110
                if (level) {
2111
                    run = i - last_non_zero - 1;
2112
                    last = (i == last_index);
2113
                    
2114
                    if(level<0) level= -level;
2115
                
2116
                    code = get_rl_index(rl, last, run, level);
2117
                    aic_code = get_rl_index(&rl_intra_aic, last, run, level);
2118
                    inter_vlc_bits += rl->table_vlc[code][1]+1;
2119
                    aic_vlc_bits   += rl_intra_aic.table_vlc[aic_code][1]+1;
2120

    
2121
                    if (code == rl->n) {
2122
                        inter_vlc_bits += 1+6+8-1;
2123
                    }                
2124
                    if (aic_code == rl_intra_aic.n) {
2125
                        aic_vlc_bits += 1+6+8-1;
2126
                        wrong_pos += run + 1;
2127
                    }else
2128
                        wrong_pos += wrong_run[aic_code];
2129
                    last_non_zero = i;
2130
                }    
2131
            }
2132
            i = 0;
2133
            if(aic_vlc_bits < inter_vlc_bits && wrong_pos > 63)
2134
                rl = &rl_intra_aic;
2135
        }
2136
    }
2137
   
2138
    /* AC coefs */
2139
    last_index = s->block_last_index[n];
2140
    last_non_zero = i - 1;
2141
    for (; i <= last_index; i++) {
2142
        j = s->intra_scantable.permutated[i];
2143
        level = block[j];
2144
        if (level) {
2145
            run = i - last_non_zero - 1;
2146
            last = (i == last_index);
2147
            sign = 0;
2148
            slevel = level;
2149
            if (level < 0) {
2150
                sign = 1;
2151
                level = -level;
2152
            }
2153
            code = get_rl_index(rl, last, run, level);
2154
            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2155
            if (code == rl->n) {
2156
              if(s->h263_flv <= 1){
2157
                put_bits(&s->pb, 1, last);
2158
                put_bits(&s->pb, 6, run);
2159
                
2160
                assert(slevel != 0);
2161

    
2162
                if(level < 128) 
2163
                    put_bits(&s->pb, 8, slevel & 0xff);
2164
                else{
2165
                    put_bits(&s->pb, 8, 128);
2166
                    put_bits(&s->pb, 5, slevel & 0x1f);
2167
                    put_bits(&s->pb, 6, (slevel>>5)&0x3f);
2168
                }
2169
              }else{
2170
                if(level < 64) { // 7-bit level
2171
                        put_bits(&s->pb, 1, 0);
2172
                        put_bits(&s->pb, 1, last);
2173
                        put_bits(&s->pb, 6, run);
2174

    
2175
                        put_bits(&s->pb, 7, slevel & 0x7f);
2176
                    } else {
2177
                        /* 11-bit level */
2178
                        put_bits(&s->pb, 1, 1);
2179
                        put_bits(&s->pb, 1, last);
2180
                        put_bits(&s->pb, 6, run);
2181

    
2182
                        put_bits(&s->pb, 11, slevel & 0x7ff);
2183
                    }
2184
              }
2185
            } else {
2186
                put_bits(&s->pb, 1, sign);
2187
            }
2188
            last_non_zero = i;
2189
        }
2190
    }
2191
}
2192
#endif
2193

    
2194
#ifdef CONFIG_ENCODERS
2195

    
2196
/***************************************************/
2197
/**
2198
 * add mpeg4 stuffing bits (01...1)
2199
 */
2200
void ff_mpeg4_stuffing(PutBitContext * pbc)
2201
{
2202
    int length;
2203
    put_bits(pbc, 1, 0);
2204
    length= (-put_bits_count(pbc))&7;
2205
    if(length) put_bits(pbc, length, (1<<length)-1);
2206
}
2207

    
2208
/* must be called before writing the header */
2209
void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
2210
    int time_div, time_mod;
2211

    
2212
    assert(s->current_picture_ptr->pts != AV_NOPTS_VALUE);
2213
    s->time= (s->current_picture_ptr->pts*s->time_increment_resolution + AV_TIME_BASE/2)/AV_TIME_BASE;
2214

    
2215
    time_div= s->time/s->time_increment_resolution;
2216
    time_mod= s->time%s->time_increment_resolution;
2217

    
2218
    if(s->pict_type==B_TYPE){
2219
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
2220
        assert(s->pb_time > 0 && s->pb_time < s->pp_time);
2221
    }else{
2222
        s->last_time_base= s->time_base;
2223
        s->time_base= time_div;
2224
        s->pp_time= s->time - s->last_non_b_time;
2225
        s->last_non_b_time= s->time;
2226
        assert(picture_number==0 || s->pp_time > 0);
2227
    }
2228
}
2229

    
2230
static void mpeg4_encode_gop_header(MpegEncContext * s){
2231
    int hours, minutes, seconds;
2232
    int64_t time;
2233
    
2234
    put_bits(&s->pb, 16, 0);
2235
    put_bits(&s->pb, 16, GOP_STARTCODE);
2236
    
2237
    time= s->current_picture_ptr->pts;
2238
    if(s->reordered_input_picture[1])
2239
        time= FFMIN(time, s->reordered_input_picture[1]->pts);
2240
    time= (time*s->time_increment_resolution + AV_TIME_BASE/2)/AV_TIME_BASE;
2241

    
2242
    seconds= time/s->time_increment_resolution;
2243
    minutes= seconds/60; seconds %= 60;
2244
    hours= minutes/60; minutes %= 60;
2245
    hours%=24;
2246

    
2247
    put_bits(&s->pb, 5, hours);
2248
    put_bits(&s->pb, 6, minutes);
2249
    put_bits(&s->pb, 1, 1);
2250
    put_bits(&s->pb, 6, seconds);
2251
    
2252
    put_bits(&s->pb, 1, !!(s->flags&CODEC_FLAG_CLOSED_GOP)); 
2253
    put_bits(&s->pb, 1, 0); //broken link == NO
2254
    
2255
    s->last_time_base= time / s->time_increment_resolution; 
2256

    
2257
    ff_mpeg4_stuffing(&s->pb);
2258
}
2259

    
2260
static void mpeg4_encode_visual_object_header(MpegEncContext * s){
2261
    int profile_and_level_indication;
2262
    int vo_ver_id;
2263
    
2264
    if(s->avctx->profile != FF_PROFILE_UNKNOWN){
2265
        profile_and_level_indication = s->avctx->profile << 4;
2266
    }else if(s->max_b_frames || s->quarter_sample){
2267
        profile_and_level_indication= 0xF0; // adv simple
2268
    }else{
2269
        profile_and_level_indication= 0x00; // simple
2270
    }
2271

    
2272
    if(s->avctx->level != FF_LEVEL_UNKNOWN){
2273
        profile_and_level_indication |= s->avctx->level;
2274
    }else{
2275
        profile_and_level_indication |= 1; //level 1
2276
    }
2277

    
2278
    if(profile_and_level_indication>>4 == 0xF){
2279
        vo_ver_id= 5;
2280
    }else{
2281
        vo_ver_id= 1;
2282
    }
2283

    
2284
    //FIXME levels
2285

    
2286
    put_bits(&s->pb, 16, 0);
2287
    put_bits(&s->pb, 16, VOS_STARTCODE);
2288

    
2289
    put_bits(&s->pb, 8, profile_and_level_indication);
2290

    
2291
    put_bits(&s->pb, 16, 0);
2292
    put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
2293
    
2294
    put_bits(&s->pb, 1, 1);
2295
        put_bits(&s->pb, 4, vo_ver_id);
2296
        put_bits(&s->pb, 3, 1); //priority
2297
 
2298
    put_bits(&s->pb, 4, 1); //visual obj type== video obj
2299
    
2300
    put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
2301

    
2302
    ff_mpeg4_stuffing(&s->pb);
2303
}
2304

    
2305
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
2306
{
2307
    int vo_ver_id;
2308

    
2309
    if(s->max_b_frames || s->quarter_sample){
2310
        vo_ver_id= 5;
2311
        s->vo_type= ADV_SIMPLE_VO_TYPE;
2312
    }else{
2313
        vo_ver_id= 1;
2314
        s->vo_type= SIMPLE_VO_TYPE;
2315
    }
2316

    
2317
    put_bits(&s->pb, 16, 0);
2318
    put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
2319
    put_bits(&s->pb, 16, 0);
2320
    put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
2321

    
2322
    put_bits(&s->pb, 1, 0);                /* random access vol */
2323
    put_bits(&s->pb, 8, s->vo_type);        /* video obj type indication */
2324
    put_bits(&s->pb, 1, 1);                /* is obj layer id= yes */
2325
      put_bits(&s->pb, 4, vo_ver_id);        /* is obj layer ver id */
2326
      put_bits(&s->pb, 3, 1);                /* is obj layer priority */
2327
    
2328
    aspect_to_info(s, s->avctx->sample_aspect_ratio);
2329

    
2330
    put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
2331
    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
2332
        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
2333
        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
2334
    }
2335

    
2336
    put_bits(&s->pb, 1, 1);                /* vol control parameters= yes */
2337
    put_bits(&s->pb, 2, 1);                /* chroma format YUV 420/YV12 */
2338
    put_bits(&s->pb, 1, s->low_delay);
2339
    put_bits(&s->pb, 1, 0);                /* vbv parameters= no */
2340

    
2341
    put_bits(&s->pb, 2, RECT_SHAPE);        /* vol shape= rectangle */
2342
    put_bits(&s->pb, 1, 1);                /* marker bit */
2343
    
2344
    put_bits(&s->pb, 16, s->time_increment_resolution);
2345
    if (s->time_increment_bits < 1)
2346
        s->time_increment_bits = 1;
2347
    put_bits(&s->pb, 1, 1);                /* marker bit */
2348
    put_bits(&s->pb, 1, 0);                /* fixed vop rate=no */
2349
    put_bits(&s->pb, 1, 1);                /* marker bit */
2350
    put_bits(&s->pb, 13, s->width);        /* vol width */
2351
    put_bits(&s->pb, 1, 1);                /* marker bit */
2352
    put_bits(&s->pb, 13, s->height);        /* vol height */
2353
    put_bits(&s->pb, 1, 1);                /* marker bit */
2354
    put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
2355
    put_bits(&s->pb, 1, 1);                /* obmc disable */
2356
    if (vo_ver_id == 1) {
2357
        put_bits(&s->pb, 1, s->vol_sprite_usage);                /* sprite enable */
2358
    }else{
2359
        put_bits(&s->pb, 2, s->vol_sprite_usage);                /* sprite enable */
2360
    }
2361
    
2362
    put_bits(&s->pb, 1, 0);                /* not 8 bit == false */
2363
    put_bits(&s->pb, 1, s->mpeg_quant);        /* quant type= (0=h263 style)*/
2364

    
2365
    if(s->mpeg_quant){
2366
        ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
2367
        ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
2368
    }
2369

    
2370
    if (vo_ver_id != 1)
2371
        put_bits(&s->pb, 1, s->quarter_sample);
2372
    put_bits(&s->pb, 1, 1);                /* complexity estimation disable */
2373
    s->resync_marker= s->rtp_mode;
2374
    put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
2375
    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
2376
    if(s->data_partitioning){
2377
        put_bits(&s->pb, 1, 0);                /* no rvlc */
2378
    }
2379

    
2380
    if (vo_ver_id != 1){
2381
        put_bits(&s->pb, 1, 0);                /* newpred */
2382
        put_bits(&s->pb, 1, 0);                /* reduced res vop */
2383
    }
2384
    put_bits(&s->pb, 1, 0);                /* scalability */
2385
    
2386
    ff_mpeg4_stuffing(&s->pb);
2387

    
2388
    /* user data */
2389
    if(!(s->flags & CODEC_FLAG_BITEXACT)){
2390
        put_bits(&s->pb, 16, 0);
2391
        put_bits(&s->pb, 16, 0x1B2);        /* user_data */
2392
        put_string(&s->pb, LIBAVCODEC_IDENT, 0);
2393
    }
2394
}
2395

    
2396
/* write mpeg4 VOP header */
2397
void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
2398
{
2399
    int time_incr;
2400
    int time_div, time_mod;
2401
    
2402
    if(s->pict_type==I_TYPE){
2403
        if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
2404
            if(s->strict_std_compliance < 2) //HACK, the reference sw is buggy
2405
                mpeg4_encode_visual_object_header(s);
2406
            if(s->strict_std_compliance < 2 || picture_number==0) //HACK, the reference sw is buggy
2407
                mpeg4_encode_vol_header(s, 0, 0);
2408
        }
2409
        mpeg4_encode_gop_header(s);
2410
    }
2411
    
2412
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
2413

    
2414
//printf("num:%d rate:%d base:%d\n", s->picture_number, s->frame_rate, FRAME_RATE_BASE);
2415
    
2416
    put_bits(&s->pb, 16, 0);                /* vop header */
2417
    put_bits(&s->pb, 16, VOP_STARTCODE);        /* vop header */
2418
    put_bits(&s->pb, 2, s->pict_type - 1);        /* pict type: I = 0 , P = 1 */
2419

    
2420
    time_div= s->time/s->time_increment_resolution;
2421
    time_mod= s->time%s->time_increment_resolution;
2422
    time_incr= time_div - s->last_time_base;
2423
    assert(time_incr >= 0);
2424
    while(time_incr--)
2425
        put_bits(&s->pb, 1, 1);
2426
        
2427
    put_bits(&s->pb, 1, 0);
2428

    
2429
    put_bits(&s->pb, 1, 1);        /* marker */
2430
    put_bits(&s->pb, s->time_increment_bits, time_mod);        /* time increment */
2431
    put_bits(&s->pb, 1, 1);        /* marker */
2432
    put_bits(&s->pb, 1, 1);        /* vop coded */
2433
    if (    s->pict_type == P_TYPE 
2434
        || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
2435
        put_bits(&s->pb, 1, s->no_rounding);        /* rounding type */
2436
    }
2437
    put_bits(&s->pb, 3, 0);        /* intra dc VLC threshold */
2438
    if(!s->progressive_sequence){
2439
         put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
2440
         put_bits(&s->pb, 1, s->alternate_scan);
2441
    }
2442
    //FIXME sprite stuff
2443

    
2444
    put_bits(&s->pb, 5, s->qscale);
2445

    
2446
    if (s->pict_type != I_TYPE)
2447
        put_bits(&s->pb, 3, s->f_code);        /* fcode_for */
2448
    if (s->pict_type == B_TYPE)
2449
        put_bits(&s->pb, 3, s->b_code);        /* fcode_back */
2450
    //    printf("****frame %d\n", picture_number);
2451
}
2452

    
2453
#endif //CONFIG_ENCODERS
2454

    
2455
/**
2456
 * set qscale and update qscale dependant variables.
2457
 */
2458
void ff_set_qscale(MpegEncContext * s, int qscale)
2459
{
2460
    if (qscale < 1)
2461
        qscale = 1;
2462
    else if (qscale > 31)
2463
        qscale = 31;
2464
        
2465
    s->qscale = qscale;
2466
    s->chroma_qscale= s->chroma_qscale_table[qscale];
2467

    
2468
    s->y_dc_scale= s->y_dc_scale_table[ qscale ];
2469
    s->c_dc_scale= s->c_dc_scale_table[ s->chroma_qscale ];
2470
}
2471

    
2472
/**
2473
 * predicts the dc.
2474
 * encoding quantized level -> quantized diff
2475
 * decoding quantized diff -> quantized level  
2476
 * @param n block index (0-3 are luma, 4-5 are chroma)
2477
 * @param dir_ptr pointer to an integer where the prediction direction will be stored
2478
 */
2479
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, int level, int *dir_ptr, int encoding)
2480
{
2481
    int a, b, c, wrap, pred, scale, ret;
2482
    uint16_t *dc_val;
2483

    
2484
    /* find prediction */
2485
    if (n < 4) {
2486
        scale = s->y_dc_scale;
2487
    } else {
2488
        scale = s->c_dc_scale;
2489
    }
2490
    if(IS_3IV1)
2491
        scale= 8;
2492

    
2493
    wrap= s->block_wrap[n];
2494
    dc_val = s->dc_val[0] + s->block_index[n];
2495

    
2496
    /* B C
2497
     * A X 
2498
     */
2499
    a = dc_val[ - 1];
2500
    b = dc_val[ - 1 - wrap];
2501
    c = dc_val[ - wrap];
2502

    
2503
    /* outside slice handling (we cant do that by memset as we need the dc for error resilience) */
2504
    if(s->first_slice_line && n!=3){
2505
        if(n!=2) b=c= 1024;
2506
        if(n!=1 && s->mb_x == s->resync_mb_x) b=a= 1024;
2507
    }
2508
    if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1){
2509
        if(n==0 || n==4 || n==5)
2510
            b=1024;
2511
    }
2512

    
2513
    if (abs(a - b) < abs(b - c)) {
2514
        pred = c;
2515
        *dir_ptr = 1; /* top */
2516
    } else {
2517
        pred = a;
2518
        *dir_ptr = 0; /* left */
2519
    }
2520
    /* we assume pred is positive */
2521
    pred = FASTDIV((pred + (scale >> 1)), scale);
2522

    
2523
    if(encoding){
2524
        ret = level - pred;
2525
    }else{
2526
        level += pred;
2527
        ret= level;
2528
        if(s->error_resilience>=3){
2529
            if(level<0){
2530
                av_log(s->avctx, AV_LOG_ERROR, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
2531
                return -1;
2532
            }
2533
            if(level*scale > 2048 + scale){
2534
                av_log(s->avctx, AV_LOG_ERROR, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
2535
                return -1;
2536
            }
2537
        }
2538
    }
2539
    level *=scale;
2540
    if(level&(~2047)){
2541
        if(level<0) 
2542
            level=0;
2543
        else if(!(s->workaround_bugs&FF_BUG_DC_CLIP))
2544
            level=2047;
2545
    }
2546
    dc_val[0]= level;
2547

    
2548
    return ret;
2549
}
2550

    
2551
/**
2552
 * predicts the ac.
2553
 * @param n block index (0-3 are luma, 4-5 are chroma)
2554
 * @param dir the ac prediction direction
2555
 */
2556
void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
2557
                   int dir)
2558
{
2559
    int i;
2560
    int16_t *ac_val, *ac_val1;
2561
    int8_t * const qscale_table= s->current_picture.qscale_table;
2562

    
2563
    /* find prediction */
2564
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
2565
    ac_val1 = ac_val;
2566
    if (s->ac_pred) {
2567
        if (dir == 0) {
2568
            const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
2569
            /* left prediction */
2570
            ac_val -= 16;
2571
            
2572
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
2573
                /* same qscale */
2574
                for(i=1;i<8;i++) {
2575
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
2576
                }
2577
            }else{
2578
                /* different qscale, we must rescale */
2579
                for(i=1;i<8;i++) {
2580
                    block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
2581
                }
2582
            }
2583
        } else {
2584
            const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
2585
            /* top prediction */
2586
            ac_val -= 16 * s->block_wrap[n];
2587

    
2588
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
2589
                /* same qscale */
2590
                for(i=1;i<8;i++) {
2591
                    block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
2592
                }
2593
            }else{
2594
                /* different qscale, we must rescale */
2595
                for(i=1;i<8;i++) {
2596
                    block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
2597
                }
2598
            }
2599
        }
2600
    }
2601
    /* left copy */
2602
    for(i=1;i<8;i++)
2603
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
2604

    
2605
    /* top copy */
2606
    for(i=1;i<8;i++)
2607
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
2608

    
2609
}
2610

    
2611
#ifdef CONFIG_ENCODERS
2612

    
2613
/**
2614
 * encodes the dc value.
2615
 * @param n block index (0-3 are luma, 4-5 are chroma)
2616
 */
2617
static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
2618
{
2619
#if 1
2620
//    if(level<-255 || level>255) printf("dc overflow\n");
2621
    level+=256;
2622
    if (n < 4) {
2623
        /* luminance */
2624
        put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
2625
    } else {
2626
        /* chrominance */
2627
        put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
2628
    }
2629
#else
2630
    int size, v;
2631
    /* find number of bits */
2632
    size = 0;
2633
    v = abs(level);
2634
    while (v) {
2635
        v >>= 1;
2636
        size++;
2637
    }
2638

    
2639
    if (n < 4) {
2640
        /* luminance */
2641
        put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
2642
    } else {
2643
        /* chrominance */
2644
        put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
2645
    }
2646

    
2647
    /* encode remaining bits */
2648
    if (size > 0) {
2649
        if (level < 0)
2650
            level = (-level) ^ ((1 << size) - 1);
2651
        put_bits(&s->pb, size, level);
2652
        if (size > 8)
2653
            put_bits(&s->pb, 1, 1);
2654
    }
2655
#endif
2656
}
2657

    
2658
static inline int mpeg4_get_dc_length(int level, int n){
2659
    if (n < 4) {
2660
        return uni_DCtab_lum_len[level + 256];
2661
    } else {
2662
        return uni_DCtab_chrom_len[level + 256];
2663
    }
2664
}
2665

    
2666
/**
2667
 * encodes a 8x8 block
2668
 * @param n block index (0-3 are luma, 4-5 are chroma)
2669
 */
2670
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2671
                               uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
2672
{
2673
    int i, last_non_zero;
2674
#if 0 //variables for the outcommented version
2675
    int code, sign, last;
2676
#endif
2677
    const RLTable *rl;
2678
    uint32_t *bits_tab;
2679
    uint8_t *len_tab;
2680
    const int last_index = s->block_last_index[n];
2681

    
2682
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2683
        /* mpeg4 based DC predictor */
2684
        mpeg4_encode_dc(dc_pb, intra_dc, n);
2685
        if(last_index<1) return;
2686
        i = 1;
2687
        rl = &rl_intra;
2688
        bits_tab= uni_mpeg4_intra_rl_bits;
2689
        len_tab = uni_mpeg4_intra_rl_len;
2690
    } else {
2691
        if(last_index<0) return;
2692
        i = 0;
2693
        rl = &rl_inter;
2694
        bits_tab= uni_mpeg4_inter_rl_bits;
2695
        len_tab = uni_mpeg4_inter_rl_len;
2696
    }
2697

    
2698
    /* AC coefs */
2699
    last_non_zero = i - 1;
2700
#if 1
2701
    for (; i < last_index; i++) {
2702
        int level = block[ scan_table[i] ];
2703
        if (level) {
2704
            int run = i - last_non_zero - 1;
2705
            level+=64;
2706
            if((level&(~127)) == 0){
2707
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2708
                put_bits(ac_pb, len_tab[index], bits_tab[index]);
2709
            }else{ //ESC3
2710
                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);
2711
            }
2712
            last_non_zero = i;
2713
        }
2714
    }
2715
    /*if(i<=last_index)*/{
2716
        int level = block[ scan_table[i] ];
2717
        int run = i - last_non_zero - 1;
2718
        level+=64;
2719
        if((level&(~127)) == 0){
2720
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2721
            put_bits(ac_pb, len_tab[index], bits_tab[index]);
2722
        }else{ //ESC3
2723
            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);
2724
        }
2725
    }
2726
#else
2727
    for (; i <= last_index; i++) {
2728
        const int slevel = block[ scan_table[i] ];
2729
        if (slevel) {
2730
            int level;
2731
            int run = i - last_non_zero - 1;
2732
            last = (i == last_index);
2733
            sign = 0;
2734
            level = slevel;
2735
            if (level < 0) {
2736
                sign = 1;
2737
                level = -level;
2738
            }
2739
            code = get_rl_index(rl, last, run, level);
2740
            put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2741
            if (code == rl->n) {
2742
                int level1, run1;
2743
                level1 = level - rl->max_level[last][run];
2744
                if (level1 < 1) 
2745
                    goto esc2;
2746
                code = get_rl_index(rl, last, run, level1);
2747
                if (code == rl->n) {
2748
                esc2:
2749
                    put_bits(ac_pb, 1, 1);
2750
                    if (level > MAX_LEVEL)
2751
                        goto esc3;
2752
                    run1 = run - rl->max_run[last][level] - 1;
2753
                    if (run1 < 0)
2754
                        goto esc3;
2755
                    code = get_rl_index(rl, last, run1, level);
2756
                    if (code == rl->n) {
2757
                    esc3:
2758
                        /* third escape */
2759
                        put_bits(ac_pb, 1, 1);
2760
                        put_bits(ac_pb, 1, last);
2761
                        put_bits(ac_pb, 6, run);
2762
                        put_bits(ac_pb, 1, 1);
2763
                        put_bits(ac_pb, 12, slevel & 0xfff);
2764
                        put_bits(ac_pb, 1, 1);
2765
                    } else {
2766
                        /* second escape */
2767
                        put_bits(ac_pb, 1, 0);
2768
                        put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2769
                        put_bits(ac_pb, 1, sign);
2770
                    }
2771
                } else {
2772
                    /* first escape */
2773
                    put_bits(ac_pb, 1, 0);
2774
                    put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2775
                    put_bits(ac_pb, 1, sign);
2776
                }
2777
            } else {
2778
                put_bits(ac_pb, 1, sign);
2779
            }
2780
            last_non_zero = i;
2781
        }
2782
    }
2783
#endif
2784
}
2785

    
2786
static int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2787
                               uint8_t *scan_table)
2788
{
2789
    int i, last_non_zero;
2790
    const RLTable *rl;
2791
    uint8_t *len_tab;
2792
    const int last_index = s->block_last_index[n];
2793
    int len=0;
2794

    
2795
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2796
        /* mpeg4 based DC predictor */
2797
        len += mpeg4_get_dc_length(intra_dc, n);
2798
        if(last_index<1) return len;
2799
        i = 1;
2800
        rl = &rl_intra;
2801
        len_tab = uni_mpeg4_intra_rl_len;
2802
    } else {
2803
        if(last_index<0) return 0;
2804
        i = 0;
2805
        rl = &rl_inter;
2806
        len_tab = uni_mpeg4_inter_rl_len;
2807
    }
2808

    
2809
    /* AC coefs */
2810
    last_non_zero = i - 1;
2811
    for (; i < last_index; i++) {
2812
        int level = block[ scan_table[i] ];
2813
        if (level) {
2814
            int run = i - last_non_zero - 1;
2815
            level+=64;
2816
            if((level&(~127)) == 0){
2817
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2818
                len += len_tab[index];
2819
            }else{ //ESC3
2820
                len += 7+2+1+6+1+12+1;
2821
            }
2822
            last_non_zero = i;
2823
        }
2824
    }
2825
    /*if(i<=last_index)*/{
2826
        int level = block[ scan_table[i] ];
2827
        int run = i - last_non_zero - 1;
2828
        level+=64;
2829
        if((level&(~127)) == 0){
2830
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2831
            len += len_tab[index];
2832
        }else{ //ESC3
2833
            len += 7+2+1+6+1+12+1;
2834
        }
2835
    }
2836
    
2837
    return len;
2838
}
2839

    
2840
#endif
2841

    
2842

    
2843
/***********************************************/
2844
/* decoding */
2845

    
2846
static VLC intra_MCBPC_vlc;
2847
static VLC inter_MCBPC_vlc;
2848
static VLC cbpy_vlc;
2849
static VLC mv_vlc;
2850
static VLC dc_lum, dc_chrom;
2851
static VLC sprite_trajectory;
2852
static VLC mb_type_b_vlc;
2853
static VLC h263_mbtype_b_vlc;
2854
static VLC cbpc_b_vlc;
2855

    
2856
void init_vlc_rl(RLTable *rl, int use_static)
2857
{
2858
    int i, q;
2859
 
2860
    /* Return if static table is already initialized */
2861
    if(use_static && rl->rl_vlc[0])
2862
        return;    
2863

    
2864
    init_vlc(&rl->vlc, 9, rl->n + 1, 
2865
             &rl->table_vlc[0][1], 4, 2,
2866
             &rl->table_vlc[0][0], 4, 2, use_static);
2867

    
2868
    
2869
    for(q=0; q<32; q++){
2870
        int qmul= q*2;
2871
        int qadd= (q-1)|1;
2872
        
2873
        if(q==0){
2874
            qmul=1;
2875
            qadd=0;
2876
        }
2877
        if(use_static)        
2878
            rl->rl_vlc[q]= av_mallocz_static(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2879
        else
2880
            rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2881
        for(i=0; i<rl->vlc.table_size; i++){
2882
            int code= rl->vlc.table[i][0];
2883
            int len = rl->vlc.table[i][1];
2884
            int level, run;
2885
        
2886
            if(len==0){ // illegal code
2887
                run= 66;
2888
                level= MAX_LEVEL;
2889
            }else if(len<0){ //more bits needed
2890
                run= 0;
2891
                level= code;
2892
            }else{
2893
                if(code==rl->n){ //esc
2894
                    run= 66;
2895
                    level= 0;
2896
                }else{
2897
                    run=   rl->table_run  [code] + 1;
2898
                    level= rl->table_level[code] * qmul + qadd;
2899
                    if(code >= rl->last) run+=192;
2900
                }
2901
            }
2902
            rl->rl_vlc[q][i].len= len;
2903
            rl->rl_vlc[q][i].level= level;
2904
            rl->rl_vlc[q][i].run= run;
2905
        }
2906
    }
2907
}
2908

    
2909
/* init vlcs */
2910

    
2911
/* XXX: find a better solution to handle static init */
2912
void h263_decode_init_vlc(MpegEncContext *s)
2913
{
2914
    static int done = 0;
2915

    
2916
    if (!done) {
2917
        done = 1;
2918

    
2919
        init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 9, 
2920
                 intra_MCBPC_bits, 1, 1,
2921
                 intra_MCBPC_code, 1, 1, 1);
2922
        init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 28, 
2923
                 inter_MCBPC_bits, 1, 1,
2924
                 inter_MCBPC_code, 1, 1, 1);
2925
        init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,
2926
                 &cbpy_tab[0][1], 2, 1,
2927
                 &cbpy_tab[0][0], 2, 1, 1);
2928
        init_vlc(&mv_vlc, MV_VLC_BITS, 33,
2929
                 &mvtab[0][1], 2, 1,
2930
                 &mvtab[0][0], 2, 1, 1);
2931
        init_rl(&rl_inter, 1);
2932
        init_rl(&rl_intra, 1);
2933
        init_rl(&rvlc_rl_inter, 1);
2934
        init_rl(&rvlc_rl_intra, 1);
2935
        init_rl(&rl_intra_aic, 1);
2936
        init_vlc_rl(&rl_inter, 1);
2937
        init_vlc_rl(&rl_intra, 1);
2938
        init_vlc_rl(&rvlc_rl_inter, 1);
2939
        init_vlc_rl(&rvlc_rl_intra, 1);
2940
        init_vlc_rl(&rl_intra_aic, 1);
2941
        init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2942
                 &DCtab_lum[0][1], 2, 1,
2943
                 &DCtab_lum[0][0], 2, 1, 1);
2944
        init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2945
                 &DCtab_chrom[0][1], 2, 1,
2946
                 &DCtab_chrom[0][0], 2, 1, 1);
2947
        init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2948
                 &sprite_trajectory_tab[0][1], 4, 2,
2949
                 &sprite_trajectory_tab[0][0], 4, 2, 1);
2950
        init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2951
                 &mb_type_b_tab[0][1], 2, 1,
2952
                 &mb_type_b_tab[0][0], 2, 1, 1);
2953
        init_vlc(&h263_mbtype_b_vlc, H263_MBTYPE_B_VLC_BITS, 15,
2954
                 &h263_mbtype_b_tab[0][1], 2, 1,
2955
                 &h263_mbtype_b_tab[0][0], 2, 1, 1);
2956
        init_vlc(&cbpc_b_vlc, CBPC_B_VLC_BITS, 4,
2957
                 &cbpc_b_tab[0][1], 2, 1,
2958
                 &cbpc_b_tab[0][0], 2, 1, 1);
2959
    }
2960
}
2961

    
2962
/**
2963
 * Get the GOB height based on picture height.
2964
 */
2965
int ff_h263_get_gob_height(MpegEncContext *s){
2966
    if (s->height <= 400)
2967
        return 1;
2968
    else if (s->height <= 800)
2969
        return  2;
2970
    else
2971
        return 4;
2972
}
2973

    
2974
int ff_h263_decode_mba(MpegEncContext *s)
2975
{
2976
    int i, mb_pos;
2977

    
2978
    for(i=0; i<6; i++){
2979
        if(s->mb_num-1 <= ff_mba_max[i]) break;
2980
    }
2981
    mb_pos= get_bits(&s->gb, ff_mba_length[i]);
2982
    s->mb_x= mb_pos % s->mb_width;
2983
    s->mb_y= mb_pos / s->mb_width;
2984

    
2985
    return mb_pos;
2986
}
2987

    
2988
void ff_h263_encode_mba(MpegEncContext *s)
2989
{
2990
    int i, mb_pos;
2991

    
2992
    for(i=0; i<6; i++){
2993
        if(s->mb_num-1 <= ff_mba_max[i]) break;
2994
    }
2995
    mb_pos= s->mb_x + s->mb_width*s->mb_y;
2996
    put_bits(&s->pb, ff_mba_length[i], mb_pos);
2997
}
2998

    
2999
/**
3000
 * decodes the group of blocks header or slice header.
3001
 * @return <0 if an error occured
3002
 */
3003
static int h263_decode_gob_header(MpegEncContext *s)
3004
{
3005
    unsigned int val, gfid, gob_number;
3006
    int left;
3007
    
3008
    /* Check for GOB Start Code */
3009
    val = show_bits(&s->gb, 16);
3010
    if(val)
3011
        return -1;
3012

    
3013
        /* We have a GBSC probably with GSTUFF */
3014
    skip_bits(&s->gb, 16); /* Drop the zeros */
3015
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
3016
    //MN: we must check the bits left or we might end in a infinite loop (or segfault)
3017
    for(;left>13; left--){
3018
        if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
3019
    }
3020
    if(left<=13) 
3021
        return -1;
3022

    
3023
    if(s->h263_slice_structured){
3024
        if(get_bits1(&s->gb)==0)
3025
            return -1;
3026

    
3027
        ff_h263_decode_mba(s);
3028

    
3029
        if(s->mb_num > 1583)
3030
            if(get_bits1(&s->gb)==0)
3031
                return -1;
3032
        
3033
        s->qscale = get_bits(&s->gb, 5); /* SQUANT */
3034
        if(get_bits1(&s->gb)==0)
3035
            return -1;
3036
        gfid = get_bits(&s->gb, 2); /* GFID */
3037
    }else{
3038
        gob_number = get_bits(&s->gb, 5); /* GN */
3039
        s->mb_x= 0;
3040
        s->mb_y= s->gob_index* gob_number;
3041
        gfid = get_bits(&s->gb, 2); /* GFID */
3042
        s->qscale = get_bits(&s->gb, 5); /* GQUANT */
3043
    }
3044
        
3045
    if(s->mb_y >= s->mb_height) 
3046
        return -1;
3047

    
3048
    if(s->qscale==0) 
3049
        return -1;
3050

    
3051
    return 0;
3052
}
3053

    
3054
static inline void memsetw(short *tab, int val, int n)
3055
{
3056
    int i;
3057
    for(i=0;i<n;i++)
3058
        tab[i] = val;
3059
}
3060

    
3061
#ifdef CONFIG_ENCODERS
3062

    
3063
void ff_mpeg4_init_partitions(MpegEncContext *s)
3064
{
3065
    uint8_t *start= pbBufPtr(&s->pb);
3066
    uint8_t *end= s->pb.buf_end;
3067
    int size= end - start;
3068
    int pb_size = (((long)start + size/3)&(~3)) - (long)start;
3069
    int tex_size= (size - 2*pb_size)&(~3);
3070
    
3071
    set_put_bits_buffer_size(&s->pb, pb_size);
3072
    init_put_bits(&s->tex_pb, start + pb_size           , tex_size);
3073
    init_put_bits(&s->pb2   , start + pb_size + tex_size, pb_size);
3074
}
3075

    
3076
void ff_mpeg4_merge_partitions(MpegEncContext *s)
3077
{
3078
    const int pb2_len   = put_bits_count(&s->pb2   );
3079
    const int tex_pb_len= put_bits_count(&s->tex_pb);
3080
    const int bits= put_bits_count(&s->pb);
3081

    
3082
    if(s->pict_type==I_TYPE){
3083
        put_bits(&s->pb, 19, DC_MARKER);
3084
        s->misc_bits+=19 + pb2_len + bits - s->last_bits;
3085
        s->i_tex_bits+= tex_pb_len;
3086
    }else{
3087
        put_bits(&s->pb, 17, MOTION_MARKER);
3088
        s->misc_bits+=17 + pb2_len;
3089
        s->mv_bits+= bits - s->last_bits;
3090
        s->p_tex_bits+= tex_pb_len;
3091
    }
3092

    
3093
    flush_put_bits(&s->pb2);
3094
    flush_put_bits(&s->tex_pb);
3095

    
3096
    set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
3097
    ff_copy_bits(&s->pb, s->pb2.buf   , pb2_len);
3098
    ff_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
3099
    s->last_bits= put_bits_count(&s->pb);
3100
}
3101

    
3102
#endif //CONFIG_ENCODERS
3103

    
3104
int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
3105
    switch(s->pict_type){
3106
        case I_TYPE:
3107
            return 16;
3108
        case P_TYPE:
3109
        case S_TYPE:
3110
            return s->f_code+15;
3111
        case B_TYPE:
3112
            return FFMAX(FFMAX(s->f_code, s->b_code)+15, 17);
3113
        default:
3114
            return -1;
3115
    }
3116
}
3117

    
3118
#ifdef CONFIG_ENCODERS
3119

    
3120
void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
3121
{
3122
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
3123

    
3124
    put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
3125
    put_bits(&s->pb, 1, 1);
3126
    
3127
    put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
3128
    put_bits(&s->pb, s->quant_precision, s->qscale);
3129
    put_bits(&s->pb, 1, 0); /* no HEC */
3130
}
3131

    
3132
#endif //CONFIG_ENCODERS
3133

    
3134
/**
3135
 * check if the next stuff is a resync marker or the end.
3136
 * @return 0 if not
3137
 */
3138
static inline int mpeg4_is_resync(MpegEncContext *s){
3139
    const int bits_count= get_bits_count(&s->gb);
3140
    
3141
    if(s->workaround_bugs&FF_BUG_NO_PADDING){
3142
        return 0;
3143
    }
3144

    
3145
    if(bits_count + 8 >= s->gb.size_in_bits){
3146
        int v= show_bits(&s->gb, 8);
3147
        v|= 0x7F >> (7-(bits_count&7));
3148
                
3149
        if(v==0x7F)
3150
            return 1;
3151
    }else{
3152
        if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){
3153
            int len;
3154
            GetBitContext gb= s->gb;
3155
        
3156
            skip_bits(&s->gb, 1);
3157
            align_get_bits(&s->gb);
3158
        
3159
            for(len=0; len<32; len++){
3160
                if(get_bits1(&s->gb)) break;
3161
            }
3162

    
3163
            s->gb= gb;
3164

    
3165
            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
3166
                return 1;
3167
        }
3168
    }
3169
    return 0;
3170
}
3171

    
3172
/**
3173
 * decodes the next video packet.
3174
 * @return <0 if something went wrong
3175
 */
3176
static int mpeg4_decode_video_packet_header(MpegEncContext *s)
3177
{
3178
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
3179
    int header_extension=0, mb_num, len;
3180
    
3181
    /* is there enough space left for a video packet + header */
3182
    if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
3183

    
3184
    for(len=0; len<32; len++){
3185
        if(get_bits1(&s->gb)) break;
3186
    }
3187

    
3188
    if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
3189
        av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
3190
        return -1;
3191
    }
3192
    
3193
    if(s->shape != RECT_SHAPE){
3194
        header_extension= get_bits1(&s->gb);
3195
        //FIXME more stuff here
3196
    }
3197

    
3198
    mb_num= get_bits(&s->gb, mb_num_bits);
3199
    if(mb_num>=s->mb_num){
3200
        av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
3201
        return -1;
3202
    }
3203
    if(s->pict_type == B_TYPE){
3204
        while(s->next_picture.mbskip_table[ s->mb_index2xy[ mb_num ] ]) mb_num++;
3205
        if(mb_num >= s->mb_num) return -1; // slice contains just skiped MBs which where allready decoded
3206
    }
3207
    
3208
    s->mb_x= mb_num % s->mb_width;
3209
    s->mb_y= mb_num / s->mb_width;
3210

    
3211
    if(s->shape != BIN_ONLY_SHAPE){
3212
        int qscale= get_bits(&s->gb, s->quant_precision); 
3213
        if(qscale)
3214
            s->chroma_qscale=s->qscale= qscale;
3215
    }
3216

    
3217
    if(s->shape == RECT_SHAPE){
3218
        header_extension= get_bits1(&s->gb);
3219
    }
3220
    if(header_extension){
3221
        int time_increment;
3222
        int time_incr=0;
3223

    
3224
        while (get_bits1(&s->gb) != 0) 
3225
            time_incr++;
3226

    
3227
        check_marker(&s->gb, "before time_increment in video packed header");
3228
        time_increment= get_bits(&s->gb, s->time_increment_bits);
3229
        check_marker(&s->gb, "before vop_coding_type in video packed header");
3230
        
3231
        skip_bits(&s->gb, 2); /* vop coding type */
3232
        //FIXME not rect stuff here
3233

    
3234
        if(s->shape != BIN_ONLY_SHAPE){
3235
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
3236
//FIXME dont just ignore everything
3237
            if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3238
                mpeg4_decode_sprite_trajectory(s, &s->gb);
3239
                av_log(s->avctx, AV_LOG_ERROR, "untested\n");
3240
            }
3241

    
3242
            //FIXME reduced res stuff here
3243
            
3244
            if (s->pict_type != I_TYPE) {
3245
                int f_code = get_bits(&s->gb, 3);        /* fcode_for */
3246
                if(f_code==0){
3247
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n");
3248
                }
3249
            }
3250
            if (s->pict_type == B_TYPE) {
3251
                int b_code = get_bits(&s->gb, 3);
3252
                if(b_code==0){
3253
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n");
3254
                }
3255
            }       
3256
        }
3257
    }
3258
    //FIXME new-pred stuff
3259
    
3260
//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));
3261

    
3262
    return 0;
3263
}
3264

    
3265
void ff_mpeg4_clean_buffers(MpegEncContext *s)
3266
{
3267
    int c_wrap, c_xy, l_wrap, l_xy;
3268

    
3269
    l_wrap= s->b8_stride;
3270
    l_xy= (2*s->mb_y-1)*l_wrap + s->mb_x*2 - 1;
3271
    c_wrap= s->mb_stride;
3272
    c_xy= (s->mb_y-1)*c_wrap + s->mb_x - 1;
3273

    
3274
#if 0
3275
    /* clean DC */
3276
    memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
3277
    memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
3278
    memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
3279
#endif
3280

    
3281
    /* clean AC */
3282
    memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(int16_t));
3283
    memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
3284
    memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
3285

    
3286
    /* clean MV */
3287
    // we cant clear the MVs as they might be needed by a b frame
3288
//    memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(int16_t));
3289
//    memset(s->motion_val, 0, 2*sizeof(int16_t)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
3290
    s->last_mv[0][0][0]=
3291
    s->last_mv[0][0][1]=
3292
    s->last_mv[1][0][0]=
3293
    s->last_mv[1][0][1]= 0;
3294
}
3295

    
3296
/**
3297
 * decodes the group of blocks / video packet header.
3298
 * @return <0 if no resync found
3299
 */
3300
int ff_h263_resync(MpegEncContext *s){
3301
    int left, ret;
3302
    
3303
    if(s->codec_id==CODEC_ID_MPEG4){
3304
        skip_bits1(&s->gb);
3305
        align_get_bits(&s->gb);
3306
    }
3307

    
3308
    if(show_bits(&s->gb, 16)==0){
3309
        if(s->codec_id==CODEC_ID_MPEG4)
3310
            ret= mpeg4_decode_video_packet_header(s);
3311
        else
3312
            ret= h263_decode_gob_header(s);
3313
        if(ret>=0)
3314
            return 0;
3315
    }
3316
    //ok, its not where its supposed to be ...
3317
    s->gb= s->last_resync_gb;
3318
    align_get_bits(&s->gb);
3319
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
3320
    
3321
    for(;left>16+1+5+5; left-=8){ 
3322
        if(show_bits(&s->gb, 16)==0){
3323
            GetBitContext bak= s->gb;
3324

    
3325
            if(s->codec_id==CODEC_ID_MPEG4)
3326
                ret= mpeg4_decode_video_packet_header(s);
3327
            else
3328
                ret= h263_decode_gob_header(s);
3329
            if(ret>=0)
3330
                return 0;
3331

    
3332
            s->gb= bak;
3333
        }
3334
        skip_bits(&s->gb, 8);
3335
    }
3336
    
3337
    return -1;
3338
}
3339

    
3340
/**
3341
 * gets the average motion vector for a GMC MB.
3342
 * @param n either 0 for the x component or 1 for y
3343
 * @returns the average MV for a GMC MB
3344
 */
3345
static inline int get_amv(MpegEncContext *s, int n){
3346
    int x, y, mb_v, sum, dx, dy, shift;
3347
    int len = 1 << (s->f_code + 4);
3348
    const int a= s->sprite_warping_accuracy;
3349
    
3350
    if(s->workaround_bugs & FF_BUG_AMV)
3351
        len >>= s->quarter_sample;
3352

    
3353
    if(s->real_sprite_warping_points==1){
3354
        if(s->divx_version==500 && s->divx_build==413)
3355
            sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
3356
        else
3357
            sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
3358
    }else{
3359
        dx= s->sprite_delta[n][0];
3360
        dy= s->sprite_delta[n][1];
3361
        shift= s->sprite_shift[0];
3362
        if(n) dy -= 1<<(shift + a + 1);
3363
        else  dx -= 1<<(shift + a + 1);
3364
        mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
3365

    
3366
        sum=0;
3367
        for(y=0; y<16; y++){
3368
            int v;
3369
        
3370
            v= mb_v + dy*y;
3371
            //XXX FIXME optimize
3372
            for(x=0; x<16; x++){
3373
                sum+= v>>shift;
3374
                v+= dx;
3375
            }
3376
        }
3377
        sum= RSHIFT(sum, a+8-s->quarter_sample);
3378
    }
3379

    
3380
    if      (sum < -len) sum= -len;
3381
    else if (sum >= len) sum= len-1;
3382

    
3383
    return sum;
3384
}
3385

    
3386
/**
3387
 * decodes first partition.
3388
 * @return number of MBs decoded or <0 if an error occured
3389
 */
3390
static int mpeg4_decode_partition_a(MpegEncContext *s){
3391
    int mb_num;
3392
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3393
    
3394
    /* decode first partition */
3395
    mb_num=0;
3396
    s->first_slice_line=1;
3397
    for(; s->mb_y<s->mb_height; s->mb_y++){
3398
        ff_init_block_index(s);
3399
        for(; s->mb_x<s->mb_width; s->mb_x++){
3400
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
3401
            int cbpc;
3402
            int dir=0;
3403
            
3404
            mb_num++;
3405
            ff_update_block_index(s);
3406
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3407
                s->first_slice_line=0;
3408
            
3409
            if(s->pict_type==I_TYPE){
3410
                int i;
3411

    
3412
                do{
3413
                    if(show_bits_long(&s->gb, 19)==DC_MARKER){
3414
                        return mb_num-1;
3415
                    }
3416

    
3417
                    cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
3418
                    if (cbpc < 0){
3419
                        av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
3420
                        return -1;
3421
                    }
3422
                }while(cbpc == 8);
3423
                
3424
                s->cbp_table[xy]= cbpc & 3;
3425
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3426
                s->mb_intra = 1;
3427

    
3428
                if(cbpc & 4) {
3429
                    ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3430
                }
3431
                s->current_picture.qscale_table[xy]= s->qscale;
3432

    
3433
                s->mbintra_table[xy]= 1;
3434
                for(i=0; i<6; i++){
3435
                    int dc_pred_dir;
3436
                    int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
3437
                    if(dc < 0){
3438
                        av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3439
                        return -1;
3440
                    }
3441
                    dir<<=1;
3442
                    if(dc_pred_dir) dir|=1;
3443
                }
3444
                s->pred_dir_table[xy]= dir;
3445
            }else{ /* P/S_TYPE */
3446
                int mx, my, pred_x, pred_y, bits;
3447
                int16_t * const mot_val= s->current_picture.motion_val[0][s->block_index[0]];
3448
                const int stride= s->b8_stride*2;
3449

    
3450
try_again:
3451
                bits= show_bits(&s->gb, 17);
3452
                if(bits==MOTION_MARKER){
3453
                    return mb_num-1;
3454
                }
3455
                skip_bits1(&s->gb);
3456
                if(bits&0x10000){
3457
                    /* skip mb */
3458
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3459
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
3460
                        mx= get_amv(s, 0);
3461
                        my= get_amv(s, 1);
3462
                    }else{
3463
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3464
                        mx=my=0;
3465
                    }
3466
                    mot_val[0       ]= mot_val[2       ]=
3467
                    mot_val[0+stride]= mot_val[2+stride]= mx;
3468
                    mot_val[1       ]= mot_val[3       ]=
3469
                    mot_val[1+stride]= mot_val[3+stride]= my;
3470

    
3471
                    if(s->mbintra_table[xy])
3472
                        ff_clean_intra_table_entries(s);
3473
                    continue;
3474
                }
3475

    
3476
                cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3477
                if (cbpc < 0){
3478
                    av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
3479
                    return -1;
3480
                }
3481
                if(cbpc == 20)
3482
                    goto try_again;
3483

    
3484
                s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
3485
    
3486
                s->mb_intra = ((cbpc & 4) != 0);
3487
        
3488
                if(s->mb_intra){
3489
                    s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3490
                    s->mbintra_table[xy]= 1;
3491
                    mot_val[0       ]= mot_val[2       ]= 
3492
                    mot_val[0+stride]= mot_val[2+stride]= 0;
3493
                    mot_val[1       ]= mot_val[3       ]=
3494
                    mot_val[1+stride]= mot_val[3+stride]= 0;
3495
                }else{
3496
                    if(s->mbintra_table[xy])
3497
                        ff_clean_intra_table_entries(s);
3498

    
3499
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
3500
                        s->mcsel= get_bits1(&s->gb);
3501
                    else s->mcsel= 0;
3502
        
3503
                    if ((cbpc & 16) == 0) {
3504
                        /* 16x16 motion prediction */
3505

    
3506
                        h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3507
                        if(!s->mcsel){
3508
                            mx = h263_decode_motion(s, pred_x, s->f_code);
3509
                            if (mx >= 0xffff)
3510
                                return -1;
3511

    
3512
                            my = h263_decode_motion(s, pred_y, s->f_code);
3513
                            if (my >= 0xffff)
3514
                                return -1;
3515
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
3516
                        } else {
3517
                            mx = get_amv(s, 0);
3518
                            my = get_amv(s, 1);
3519
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
3520
                        }
3521

    
3522
                        mot_val[0       ]= mot_val[2       ] =
3523
                        mot_val[0+stride]= mot_val[2+stride]= mx;
3524
                        mot_val[1       ]= mot_val[3       ]=
3525
                        mot_val[1+stride]= mot_val[3+stride]= my;
3526
                    } else {
3527
                        int i;
3528
                        s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
3529
                        for(i=0;i<4;i++) {
3530
                            int16_t *mot_val= h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3531
                            mx = h263_decode_motion(s, pred_x, s->f_code);
3532
                            if (mx >= 0xffff)
3533
                                return -1;
3534
                
3535
                            my = h263_decode_motion(s, pred_y, s->f_code);
3536
                            if (my >= 0xffff)
3537
                                return -1;
3538
                            mot_val[0] = mx;
3539
                            mot_val[1] = my;
3540
                        }
3541
                    }
3542
                }
3543
            }
3544
        }
3545
        s->mb_x= 0;
3546
    }
3547

    
3548
    return mb_num;
3549
}
3550

    
3551
/**
3552
 * decode second partition.
3553
 * @return <0 if an error occured
3554
 */
3555
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
3556
    int mb_num=0;
3557
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3558

    
3559
    s->mb_x= s->resync_mb_x;
3560
    s->first_slice_line=1;
3561
    for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
3562
        ff_init_block_index(s);
3563
        for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
3564
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
3565

    
3566
            mb_num++;
3567
            ff_update_block_index(s);
3568
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3569
                s->first_slice_line=0;
3570
            
3571
            if(s->pict_type==I_TYPE){
3572
                int ac_pred= get_bits1(&s->gb);
3573
                int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3574
                if(cbpy<0){
3575
                    av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3576
                    return -1;
3577
                }
3578
                
3579
                s->cbp_table[xy]|= cbpy<<2;
3580
                s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
3581
            }else{ /* P || S_TYPE */
3582
                if(IS_INTRA(s->current_picture.mb_type[xy])){          
3583
                    int dir=0,i;
3584
                    int ac_pred = get_bits1(&s->gb);
3585
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3586

    
3587
                    if(cbpy<0){
3588
                        av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3589
                        return -1;
3590
                    }
3591
                    
3592
                    if(s->cbp_table[xy] & 8) {
3593
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3594
                    }
3595
                    s->current_picture.qscale_table[xy]= s->qscale;
3596

    
3597
                    for(i=0; i<6; i++){
3598
                        int dc_pred_dir;
3599
                        int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
3600
                        if(dc < 0){
3601
                            av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3602
                            return -1;
3603
                        }
3604
                        dir<<=1;
3605
                        if(dc_pred_dir) dir|=1;
3606
                    }
3607
                    s->cbp_table[xy]&= 3; //remove dquant
3608
                    s->cbp_table[xy]|= cbpy<<2;
3609
                    s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
3610
                    s->pred_dir_table[xy]= dir;
3611
                }else if(IS_SKIP(s->current_picture.mb_type[xy])){
3612
                    s->current_picture.qscale_table[xy]= s->qscale;
3613
                    s->cbp_table[xy]= 0;
3614
                }else{
3615
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3616

    
3617
                    if(cbpy<0){
3618
                        av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3619
                        return -1;
3620
                    }
3621
                    
3622
                    if(s->cbp_table[xy] & 8) {
3623
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3624
                    }
3625
                    s->current_picture.qscale_table[xy]= s->qscale;
3626

    
3627
                    s->cbp_table[xy]&= 3; //remove dquant
3628
                    s->cbp_table[xy]|= (cbpy^0xf)<<2;
3629
                }
3630
            }
3631
        }
3632
        if(mb_num >= mb_count) return 0;
3633
        s->mb_x= 0;
3634
    }
3635
    return 0;
3636
}
3637

    
3638
/**
3639
 * decodes the first & second partition
3640
 * @return <0 if error (and sets error type in the error_status_table)
3641
 */
3642
int ff_mpeg4_decode_partitions(MpegEncContext *s)
3643
{
3644
    int mb_num;
3645
    const int part_a_error= s->pict_type==I_TYPE ? (DC_ERROR|MV_ERROR) : MV_ERROR;
3646
    const int part_a_end  = s->pict_type==I_TYPE ? (DC_END  |MV_END)   : MV_END;
3647
    
3648
    mb_num= mpeg4_decode_partition_a(s);    
3649
    if(mb_num<0){
3650
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3651
        return -1;
3652
    }
3653
    
3654
    if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
3655
        av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
3656
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3657
        return -1;
3658
    }
3659

    
3660
    s->mb_num_left= mb_num;
3661
        
3662
    if(s->pict_type==I_TYPE){
3663
        while(show_bits(&s->gb, 9) == 1)
3664
            skip_bits(&s->gb, 9);
3665
        if(get_bits_long(&s->gb, 19)!=DC_MARKER){
3666
            av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
3667
            return -1;
3668
        }
3669
    }else{
3670
        while(show_bits(&s->gb, 10) == 1)
3671
            skip_bits(&s->gb, 10);
3672
        if(get_bits(&s->gb, 17)!=MOTION_MARKER){
3673
            av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
3674
            return -1;
3675
        }
3676
    }
3677
    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, part_a_end);
3678
    
3679
    if( mpeg4_decode_partition_b(s, mb_num) < 0){
3680
        if(s->pict_type==P_TYPE)
3681
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, DC_ERROR);
3682
        return -1;
3683
    }else{
3684
        if(s->pict_type==P_TYPE)
3685
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, DC_END);
3686
    }
3687

    
3688
    return 0;        
3689
}
3690

    
3691
/**
3692
 * decode partition C of one MB.
3693
 * @return <0 if an error occured
3694
 */
3695
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
3696
{
3697
    int cbp, mb_type;
3698
    const int xy= s->mb_x + s->mb_y*s->mb_stride;
3699

    
3700
    mb_type= s->current_picture.mb_type[xy];
3701
    cbp = s->cbp_table[xy];
3702

    
3703
    if(s->current_picture.qscale_table[xy] != s->qscale){
3704
        ff_set_qscale(s, s->current_picture.qscale_table[xy] );
3705
    }
3706
    
3707
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3708
        int i;
3709
        for(i=0; i<4; i++){
3710
            s->mv[0][i][0] = s->current_picture.motion_val[0][ s->block_index[i] ][0];
3711
            s->mv[0][i][1] = s->current_picture.motion_val[0][ s->block_index[i] ][1];
3712
        }
3713
        s->mb_intra = IS_INTRA(mb_type);
3714

    
3715
        if (IS_SKIP(mb_type)) {
3716
            /* skip mb */
3717
            for(i=0;i<6;i++)
3718
                s->block_last_index[i] = -1;
3719
            s->mv_dir = MV_DIR_FORWARD;
3720
            s->mv_type = MV_TYPE_16X16;
3721
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3722
                s->mcsel=1;
3723
                s->mb_skiped = 0;
3724
            }else{
3725
                s->mcsel=0;
3726
                s->mb_skiped = 1;
3727
            }
3728
        }else if(s->mb_intra){
3729
            s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3730
        }else if(!s->mb_intra){
3731
//            s->mcsel= 0; //FIXME do we need to init that
3732
            
3733
            s->mv_dir = MV_DIR_FORWARD;
3734
            if (IS_8X8(mb_type)) {
3735
                s->mv_type = MV_TYPE_8X8;
3736
            } else {
3737
                s->mv_type = MV_TYPE_16X16;
3738
            }
3739
        }
3740
    } else { /* I-Frame */
3741
        s->mb_intra = 1;
3742
        s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3743
    }
3744

    
3745
    if (!IS_SKIP(mb_type)) {
3746
        int i;
3747
        /* decode each block */
3748
        for (i = 0; i < 6; i++) {
3749
            if(mpeg4_decode_block(s, block[i], i, cbp&32, s->mb_intra, s->rvlc) < 0){
3750
                av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra);
3751
                return -1;
3752
            }
3753
            cbp+=cbp;
3754
        }
3755
    }
3756

    
3757
    /* per-MB end of slice check */
3758

    
3759
    if(--s->mb_num_left <= 0){
3760
//printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size_in_bits - get_bits_count(&s->gb));
3761
        if(mpeg4_is_resync(s))
3762
            return SLICE_END;
3763
        else
3764
            return SLICE_NOEND;     
3765
    }else{
3766
        if(mpeg4_is_resync(s)){
3767
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
3768
            if(s->cbp_table[xy+delta])
3769
                return SLICE_END;
3770
        }
3771
        return SLICE_OK;
3772
    }
3773
}
3774

    
3775
/**
3776
 * read the next MVs for OBMC. yes this is a ugly hack, feel free to send a patch :)
3777
 */
3778
static void preview_obmc(MpegEncContext *s){
3779
    GetBitContext gb= s->gb;
3780
    
3781
    int cbpc, i, pred_x, pred_y, mx, my;
3782
    int16_t *mot_val;
3783
    const int xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
3784
    const int stride= s->b8_stride*2;
3785
    
3786
    for(i=0; i<4; i++)
3787
        s->block_index[i]+= 2;
3788
    for(i=4; i<6; i++)
3789
        s->block_index[i]+= 1;
3790
    s->mb_x++;
3791
    
3792
    assert(s->pict_type == P_TYPE);
3793

    
3794
    do{
3795
        if (get_bits1(&s->gb)) {
3796
            /* skip mb */
3797
            mot_val = s->current_picture.motion_val[0][ s->block_index[0] ];
3798
            mot_val[0       ]= mot_val[2       ]= 
3799
            mot_val[0+stride]= mot_val[2+stride]= 0;
3800
            mot_val[1       ]= mot_val[3       ]=
3801
            mot_val[1+stride]= mot_val[3+stride]= 0;
3802
            
3803
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3804
            goto end;
3805
        }
3806
        cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3807
    }while(cbpc == 20);
3808
    
3809
    if(cbpc & 4){
3810
        s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3811
    }else{
3812
        get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3813
        if (cbpc & 8) {
3814
            if(s->modified_quant){
3815
                if(get_bits1(&s->gb)) skip_bits(&s->gb, 1);
3816
                else                  skip_bits(&s->gb, 5);
3817
            }else
3818
                skip_bits(&s->gb, 2);
3819
        }
3820
        
3821
        if ((cbpc & 16) == 0) {
3822
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
3823
                /* 16x16 motion prediction */
3824
                mot_val= h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3825
                if (s->umvplus)
3826
                   mx = h263p_decode_umotion(s, pred_x);
3827
                else
3828
                   mx = h263_decode_motion(s, pred_x, 1);
3829
            
3830
                if (s->umvplus)
3831
                   my = h263p_decode_umotion(s, pred_y);
3832
                else
3833
                   my = h263_decode_motion(s, pred_y, 1);
3834
            
3835
                mot_val[0       ]= mot_val[2       ]= 
3836
                mot_val[0+stride]= mot_val[2+stride]= mx;
3837
                mot_val[1       ]= mot_val[3       ]=
3838
                mot_val[1+stride]= mot_val[3+stride]= my;
3839
        } else {
3840
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
3841
            for(i=0;i<4;i++) {
3842
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3843
                if (s->umvplus)
3844
                  mx = h263p_decode_umotion(s, pred_x);
3845
                else
3846
                  mx = h263_decode_motion(s, pred_x, 1);
3847
                
3848
                if (s->umvplus)
3849
                  my = h263p_decode_umotion(s, pred_y);
3850
                else    
3851
                  my = h263_decode_motion(s, pred_y, 1);
3852
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3853
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3854
                mot_val[0] = mx;
3855
                mot_val[1] = my;
3856
            }
3857
        }
3858
    }
3859
end:
3860
        
3861
    for(i=0; i<4; i++)
3862
        s->block_index[i]-= 2;
3863
    for(i=4; i<6; i++)
3864
        s->block_index[i]-= 1;
3865
    s->mb_x--;
3866

    
3867
    s->gb= gb;
3868
}
3869

    
3870
static void h263_decode_dquant(MpegEncContext *s){
3871
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3872

    
3873
    if(s->modified_quant){
3874
        if(get_bits1(&s->gb))
3875
            s->qscale= modified_quant_tab[get_bits1(&s->gb)][ s->qscale ];
3876
        else
3877
            s->qscale= get_bits(&s->gb, 5);
3878
    }else
3879
        s->qscale += quant_tab[get_bits(&s->gb, 2)];
3880
    ff_set_qscale(s, s->qscale);
3881
}
3882

    
3883
int ff_h263_decode_mb(MpegEncContext *s,
3884
                      DCTELEM block[6][64])
3885
{
3886
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
3887
    int16_t *mot_val;
3888
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
3889
    
3890
    assert(!s->h263_pred);
3891
    
3892
    if (s->pict_type == P_TYPE) {
3893
        do{
3894
            if (get_bits1(&s->gb)) {
3895
                /* skip mb */
3896
                s->mb_intra = 0;
3897
                for(i=0;i<6;i++)
3898
                    s->block_last_index[i] = -1;
3899
                s->mv_dir = MV_DIR_FORWARD;
3900
                s->mv_type = MV_TYPE_16X16;
3901
                s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3902
                s->mv[0][0][0] = 0;
3903
                s->mv[0][0][1] = 0;
3904
                s->mb_skiped = !(s->obmc | s->loop_filter);
3905
                goto end;
3906
            }
3907
            cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3908
            //fprintf(stderr, "\tCBPC: %d", cbpc);
3909
            if (cbpc < 0){
3910
                av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
3911
                return -1;
3912
            }
3913
        }while(cbpc == 20);
3914
        
3915
        dquant = cbpc & 8;
3916
        s->mb_intra = ((cbpc & 4) != 0);
3917
        if (s->mb_intra) goto intra;
3918
        
3919
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3920
        
3921
        if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
3922
            cbpy ^= 0xF;
3923
        
3924
        cbp = (cbpc & 3) | (cbpy << 2);
3925
        if (dquant) {
3926
            h263_decode_dquant(s);
3927
        }
3928
        
3929
        s->mv_dir = MV_DIR_FORWARD;
3930
        if ((cbpc & 16) == 0) {
3931
            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
3932
            /* 16x16 motion prediction */
3933
            s->mv_type = MV_TYPE_16X16;
3934
            h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3935
            if (s->umvplus)
3936
               mx = h263p_decode_umotion(s, pred_x);
3937
            else
3938
               mx = h263_decode_motion(s, pred_x, 1);
3939
            
3940
            if (mx >= 0xffff)
3941
                return -1;
3942
            
3943
            if (s->umvplus)
3944
               my = h263p_decode_umotion(s, pred_y);
3945
            else
3946
               my = h263_decode_motion(s, pred_y, 1);
3947
            
3948
            if (my >= 0xffff)
3949
                return -1;
3950
            s->mv[0][0][0] = mx;
3951
            s->mv[0][0][1] = my;
3952

    
3953
            if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3954
               skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */                   
3955
        } else {
3956
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
3957
            s->mv_type = MV_TYPE_8X8;
3958
            for(i=0;i<4;i++) {
3959
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3960
                if (s->umvplus)
3961
                  mx = h263p_decode_umotion(s, pred_x);
3962
                else
3963
                  mx = h263_decode_motion(s, pred_x, 1);
3964
                if (mx >= 0xffff)
3965
                    return -1;
3966
                
3967
                if (s->umvplus)
3968
                  my = h263p_decode_umotion(s, pred_y);
3969
                else    
3970
                  my = h263_decode_motion(s, pred_y, 1);
3971
                if (my >= 0xffff)
3972
                    return -1;
3973
                s->mv[0][i][0] = mx;
3974
                s->mv[0][i][1] = my;
3975
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3976
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3977
                mot_val[0] = mx;
3978
                mot_val[1] = my;
3979
            }
3980
        }
3981

    
3982
        /* decode each block */
3983
        for (i = 0; i < 6; i++) {
3984
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3985
                return -1;
3986
            cbp+=cbp;
3987
        }
3988

    
3989
        if(s->obmc){
3990
            if(s->pict_type == P_TYPE && s->mb_x+1<s->mb_width && s->mb_num_left != 1)
3991
                preview_obmc(s);
3992
        }
3993
    } else if(s->pict_type==B_TYPE) {
3994
        int mb_type;
3995
        const int stride= s->b8_stride;
3996
        int16_t *mot_val0 = s->current_picture.motion_val[0][ 2*(s->mb_x + s->mb_y*stride) ];
3997
        int16_t *mot_val1 = s->current_picture.motion_val[1][ 2*(s->mb_x + s->mb_y*stride) ];
3998
//        const int mv_xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
3999

    
4000
        //FIXME ugly 
4001
        mot_val0[0       ]= mot_val0[2       ]= mot_val0[0+2*stride]= mot_val0[2+2*stride]= 
4002
        mot_val0[1       ]= mot_val0[3       ]= mot_val0[1+2*stride]= mot_val0[3+2*stride]= 
4003
        mot_val1[0       ]= mot_val1[2       ]= mot_val1[0+2*stride]= mot_val1[2+2*stride]= 
4004
        mot_val1[1       ]= mot_val1[3       ]= mot_val1[1+2*stride]= mot_val1[3+2*stride]= 0;
4005

    
4006
        do{
4007
            mb_type= get_vlc2(&s->gb, h263_mbtype_b_vlc.table, H263_MBTYPE_B_VLC_BITS, 2);
4008
            if (mb_type < 0){
4009
                av_log(s->avctx, AV_LOG_ERROR, "b mb_type damaged at %d %d\n", s->mb_x, s->mb_y);
4010
                return -1;
4011
            }
4012

    
4013
            mb_type= h263_mb_type_b_map[ mb_type ];
4014
        }while(!mb_type);
4015

    
4016
        s->mb_intra = IS_INTRA(mb_type);
4017
        if(HAS_CBP(mb_type)){
4018
            cbpc = get_vlc2(&s->gb, cbpc_b_vlc.table, CBPC_B_VLC_BITS, 1);
4019
            if(s->mb_intra){
4020
                dquant = IS_QUANT(mb_type);
4021
                goto intra;
4022
            }
4023

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

    
4026
            if (cbpy < 0){
4027
                av_log(s->avctx, AV_LOG_ERROR, "b cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
4028
                return -1;
4029
            }
4030
        
4031
            if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
4032
                cbpy ^= 0xF;
4033
        
4034
            cbp = (cbpc & 3) | (cbpy << 2);
4035
        }else
4036
            cbp=0;
4037
            
4038
        assert(!s->mb_intra);
4039

    
4040
        if(IS_QUANT(mb_type)){
4041
            h263_decode_dquant(s);
4042
        }
4043

    
4044
        if(IS_DIRECT(mb_type)){
4045
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
4046
            mb_type |= ff_mpeg4_set_direct_mv(s, 0, 0);
4047
        }else{
4048
            s->mv_dir = 0;
4049
            s->mv_type= MV_TYPE_16X16;
4050
//FIXME UMV
4051

    
4052
            if(USES_LIST(mb_type, 0)){
4053
                int16_t *mot_val= h263_pred_motion(s, 0, 0, &mx, &my);
4054
                s->mv_dir = MV_DIR_FORWARD;
4055

    
4056
                mx = h263_decode_motion(s, mx, 1);
4057
                my = h263_decode_motion(s, my, 1);
4058
                
4059
                s->mv[0][0][0] = mx;
4060
                s->mv[0][0][1] = my;
4061
                mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
4062
                mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
4063
            }
4064
    
4065
            if(USES_LIST(mb_type, 1)){
4066
                int16_t *mot_val= h263_pred_motion(s, 0, 1, &mx, &my);
4067
                s->mv_dir |= MV_DIR_BACKWARD;
4068
                
4069
                mx = h263_decode_motion(s, mx, 1);
4070
                my = h263_decode_motion(s, my, 1);
4071

    
4072
                s->mv[1][0][0] = mx;
4073
                s->mv[1][0][1] = my;
4074
                mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
4075
                mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
4076
            }
4077
        }
4078
          
4079
        s->current_picture.mb_type[xy]= mb_type;
4080

    
4081
        /* decode each block */
4082
        for (i = 0; i < 6; i++) {
4083
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
4084
                return -1;
4085
            cbp+=cbp;
4086
        }
4087
    } else { /* I-Frame */
4088
        do{
4089
            cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
4090
            if (cbpc < 0){
4091
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
4092
                return -1;
4093
            }
4094
        }while(cbpc == 8);
4095

    
4096
        dquant = cbpc & 4;
4097
        s->mb_intra = 1;
4098
intra:
4099
        s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
4100
        if (s->h263_aic) {
4101
            s->ac_pred = get_bits1(&s->gb);
4102
            if(s->ac_pred){
4103
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
4104
            
4105
                s->h263_aic_dir = get_bits1(&s->gb);
4106
            }
4107
        }else
4108
            s->ac_pred = 0;
4109
        
4110
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
4111
        if(cbpy<0){
4112
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
4113
            return -1;
4114
        }
4115
        cbp = (cbpc & 3) | (cbpy << 2);
4116
        if (dquant) {
4117
            h263_decode_dquant(s);
4118
        }
4119

    
4120
        /* decode each block */
4121
        for (i = 0; i < 6; i++) {
4122
            if (h263_decode_block(s, block[i], i, cbp&32) < 0)
4123
                return -1;
4124
            cbp+=cbp;
4125
        }
4126
    }
4127
end:
4128

    
4129
        /* per-MB end of slice check */
4130
    {
4131
        int v= show_bits(&s->gb, 16);
4132
    
4133
        if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
4134
            v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
4135
        }
4136

    
4137
        if(v==0)
4138
            return SLICE_END;
4139
    }
4140

    
4141
    return SLICE_OK;     
4142
}
4143

    
4144
int ff_mpeg4_decode_mb(MpegEncContext *s,
4145
                      DCTELEM block[6][64])
4146
{
4147
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
4148
    int16_t *mot_val;
4149
    static int8_t quant_tab[4] = { -1, -2, 1, 2 };
4150
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
4151
    
4152
    assert(s->h263_pred);
4153
    
4154
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
4155
        do{
4156
            if (get_bits1(&s->gb)) {
4157
                /* skip mb */
4158
                s->mb_intra = 0;
4159
                for(i=0;i<6;i++)
4160
                    s->block_last_index[i] = -1;
4161
                s->mv_dir = MV_DIR_FORWARD;
4162
                s->mv_type = MV_TYPE_16X16;
4163
                if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
4164
                    s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
4165
                    s->mcsel=1;
4166
                    s->mv[0][0][0]= get_amv(s, 0);
4167
                    s->mv[0][0][1]= get_amv(s, 1);
4168

    
4169
                    s->mb_skiped = 0;
4170
                }else{
4171
                    s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
4172
                    s->mcsel=0;
4173
                    s->mv[0][0][0] = 0;
4174
                    s->mv[0][0][1] = 0;
4175
                    s->mb_skiped = 1;
4176
                }
4177
                goto end;
4178
            }
4179
            cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
4180
            //fprintf(stderr, "\tCBPC: %d", cbpc);
4181
            if (cbpc < 0){
4182
                av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
4183
                return -1;
4184
            }
4185
        }while(cbpc == 20);
4186
        
4187
        dquant = cbpc & 8;
4188
        s->mb_intra = ((cbpc & 4) != 0);
4189
        if (s->mb_intra) goto intra;
4190
        
4191
        if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
4192
            s->mcsel= get_bits1(&s->gb);
4193
        else s->mcsel= 0;
4194
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
4195
        
4196
        cbp = (cbpc & 3) | (cbpy << 2);
4197
        if (dquant) {
4198
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
4199
        }
4200
        if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
4201
            s->interlaced_dct= get_bits1(&s->gb);
4202
        
4203
        s->mv_dir = MV_DIR_FORWARD;
4204
        if ((cbpc & 16) == 0) {
4205
            if(s->mcsel){
4206
                s->current_picture.mb_type[xy]= MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
4207
                /* 16x16 global motion prediction */
4208
                s->mv_type = MV_TYPE_16X16;
4209
                mx= get_amv(s, 0);
4210
                my= get_amv(s, 1);
4211
                s->mv[0][0][0] = mx;
4212
                s->mv[0][0][1] = my;
4213
            }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
4214
                s->current_picture.mb_type[xy]= MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; 
4215
                /* 16x8 field motion prediction */
4216
                s->mv_type= MV_TYPE_FIELD;
4217

    
4218
                s->field_select[0][0]= get_bits1(&s->gb);
4219
                s->field_select[0][1]= get_bits1(&s->gb);
4220

    
4221
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
4222
                
4223
                for(i=0; i<2; i++){
4224
                    mx = h263_decode_motion(s, pred_x, s->f_code);
4225
                    if (mx >= 0xffff)
4226
                        return -1;
4227
            
4228
                    my = h263_decode_motion(s, pred_y/2, s->f_code);
4229
                    if (my >= 0xffff)
4230
                        return -1;
4231

    
4232
                    s->mv[0][i][0] = mx;
4233
                    s->mv[0][i][1] = my;
4234
                }
4235
            }else{
4236
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
4237
                /* 16x16 motion prediction */
4238
                s->mv_type = MV_TYPE_16X16;
4239
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
4240
                mx = h263_decode_motion(s, pred_x, s->f_code);
4241
            
4242
                if (mx >= 0xffff)
4243
                    return -1;
4244
            
4245
                my = h263_decode_motion(s, pred_y, s->f_code);
4246
            
4247
                if (my >= 0xffff)
4248
                    return -1;
4249
                s->mv[0][0][0] = mx;
4250
                s->mv[0][0][1] = my;
4251
            }
4252
        } else {
4253
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
4254
            s->mv_type = MV_TYPE_8X8;
4255
            for(i=0;i<4;i++) {
4256
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
4257
                mx = h263_decode_motion(s, pred_x, s->f_code);
4258
                if (mx >= 0xffff)
4259
                    return -1;
4260
                
4261
                my = h263_decode_motion(s, pred_y, s->f_code);
4262
                if (my >= 0xffff)
4263
                    return -1;
4264
                s->mv[0][i][0] = mx;
4265
                s->mv[0][i][1] = my;
4266
                mot_val[0] = mx;
4267
                mot_val[1] = my;
4268
            }
4269
        }
4270
    } else if(s->pict_type==B_TYPE) {
4271
        int modb1; // first bit of modb
4272
        int modb2; // second bit of modb
4273
        int mb_type;
4274

    
4275
        s->mb_intra = 0; //B-frames never contain intra blocks
4276
        s->mcsel=0;      //     ...               true gmc blocks
4277

    
4278
        if(s->mb_x==0){
4279
            for(i=0; i<2; i++){
4280
                s->last_mv[i][0][0]= 
4281
                s->last_mv[i][0][1]= 
4282
                s->last_mv[i][1][0]= 
4283
                s->last_mv[i][1][1]= 0;
4284
            }
4285
        }
4286

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

    
4290
        if(s->mb_skiped){
4291
                /* skip mb */
4292
            for(i=0;i<6;i++)
4293
                s->block_last_index[i] = -1;
4294

    
4295
            s->mv_dir = MV_DIR_FORWARD;
4296
            s->mv_type = MV_TYPE_16X16;
4297
            s->mv[0][0][0] = 0;
4298
            s->mv[0][0][1] = 0;
4299
            s->mv[1][0][0] = 0;
4300
            s->mv[1][0][1] = 0;
4301
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; 
4302
            goto end;
4303
        }
4304

    
4305
        modb1= get_bits1(&s->gb); 
4306
        if(modb1){
4307
            mb_type= MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; //like MB_TYPE_B_DIRECT but no vectors coded
4308
            cbp=0;
4309
        }else{
4310
            modb2= get_bits1(&s->gb);
4311
            mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
4312
            if(mb_type<0){
4313
                av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
4314
                return -1;
4315
            }
4316
            mb_type= mb_type_b_map[ mb_type ];
4317
            if(modb2) cbp= 0;
4318
            else      cbp= get_bits(&s->gb, 6);
4319

    
4320
            if ((!IS_DIRECT(mb_type)) && cbp) {
4321
                if(get_bits1(&s->gb)){
4322
                    ff_set_qscale(s, s->qscale + get_bits1(&s->gb)*4 - 2);
4323
                }
4324
            }
4325

    
4326
            if(!s->progressive_sequence){
4327
                if(cbp)
4328
                    s->interlaced_dct= get_bits1(&s->gb);
4329

    
4330
                if(!IS_DIRECT(mb_type) && get_bits1(&s->gb)){
4331
                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
4332
                    mb_type &= ~MB_TYPE_16x16;
4333

    
4334
                    if(USES_LIST(mb_type, 0)){
4335
                        s->field_select[0][0]= get_bits1(&s->gb);
4336
                        s->field_select[0][1]= get_bits1(&s->gb);
4337
                    }
4338
                    if(USES_LIST(mb_type, 1)){
4339
                        s->field_select[1][0]= get_bits1(&s->gb);
4340
                        s->field_select[1][1]= get_bits1(&s->gb);
4341
                    }
4342
                }
4343
            }
4344

    
4345
            s->mv_dir = 0;
4346
            if((mb_type & (MB_TYPE_DIRECT2|MB_TYPE_INTERLACED)) == 0){
4347
                s->mv_type= MV_TYPE_16X16;
4348

    
4349
                if(USES_LIST(mb_type, 0)){
4350
                    s->mv_dir = MV_DIR_FORWARD;
4351

    
4352
                    mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
4353
                    my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
4354
                    s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
4355
                    s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
4356
                }
4357
    
4358
                if(USES_LIST(mb_type, 1)){
4359
                    s->mv_dir |= MV_DIR_BACKWARD;
4360

    
4361
                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
4362
                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
4363
                    s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
4364
                    s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
4365
                }
4366
            }else if(!IS_DIRECT(mb_type)){
4367
                s->mv_type= MV_TYPE_FIELD;
4368

    
4369
                if(USES_LIST(mb_type, 0)){
4370
                    s->mv_dir = MV_DIR_FORWARD;
4371
                
4372
                    for(i=0; i<2; i++){
4373
                        mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
4374
                        my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
4375
                        s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
4376
                        s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
4377
                    }
4378
                }
4379
    
4380
                if(USES_LIST(mb_type, 1)){
4381
                    s->mv_dir |= MV_DIR_BACKWARD;
4382

    
4383
                    for(i=0; i<2; i++){
4384
                        mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
4385
                        my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
4386
                        s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
4387
                        s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
4388
                    }
4389
                }
4390
            }
4391
        }
4392
          
4393
        if(IS_DIRECT(mb_type)){
4394
            if(IS_SKIP(mb_type))
4395
                mx=my=0;
4396
            else{
4397
                mx = h263_decode_motion(s, 0, 1);
4398
                my = h263_decode_motion(s, 0, 1);
4399
            }
4400
 
4401
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
4402
            mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
4403
        }
4404
        s->current_picture.mb_type[xy]= mb_type;
4405
    } else { /* I-Frame */
4406
        do{
4407
            cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
4408
            if (cbpc < 0){
4409
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
4410
                return -1;
4411
            }
4412
        }while(cbpc == 8);
4413

    
4414
        dquant = cbpc & 4;
4415
        s->mb_intra = 1;
4416
intra:
4417
        s->ac_pred = get_bits1(&s->gb);
4418
        if(s->ac_pred)
4419
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
4420
        else
4421
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
4422
        
4423
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
4424
        if(cbpy<0){
4425
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
4426
            return -1;
4427
        }
4428
        cbp = (cbpc & 3) | (cbpy << 2);
4429
        if (dquant) {
4430
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
4431
        }
4432
        
4433
        if(!s->progressive_sequence)
4434
            s->interlaced_dct= get_bits1(&s->gb);
4435

    
4436
        /* decode each block */
4437
        for (i = 0; i < 6; i++) {
4438
            if (mpeg4_decode_block(s, block[i], i, cbp&32, 1, 0) < 0)
4439
                return -1;
4440
            cbp+=cbp;
4441
        }
4442
        goto end;
4443
    }
4444

    
4445
    /* decode each block */
4446
    for (i = 0; i < 6; i++) {
4447
        if (mpeg4_decode_block(s, block[i], i, cbp&32, 0, 0) < 0)
4448
            return -1;
4449
        cbp+=cbp;
4450
    }
4451
end:
4452

    
4453
        /* per-MB end of slice check */
4454
    if(s->codec_id==CODEC_ID_MPEG4){
4455
        if(mpeg4_is_resync(s)){
4456
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
4457
            if(s->pict_type==B_TYPE && s->next_picture.mbskip_table[xy + delta])
4458
                return SLICE_OK;
4459
            return SLICE_END;
4460
        }
4461
    }
4462

    
4463
    return SLICE_OK;     
4464
}
4465

    
4466
static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
4467
{
4468
    int code, val, sign, shift, l;
4469
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
4470

    
4471
    if (code == 0)
4472
        return pred;
4473
    if (code < 0)
4474
        return 0xffff;
4475

    
4476
    sign = get_bits1(&s->gb);
4477
    shift = f_code - 1;
4478
    val = code;
4479
    if (shift) {
4480
        val = (val - 1) << shift;
4481
        val |= get_bits(&s->gb, shift);
4482
        val++;
4483
    }
4484
    if (sign)
4485
        val = -val;
4486
    val += pred;
4487

    
4488
    /* modulo decoding */
4489
    if (!s->h263_long_vectors) {
4490
        l = INT_BIT - 5 - f_code;
4491
        val = (val<<l)>>l;
4492
    } else {
4493
        /* horrible h263 long vector mode */
4494
        if (pred < -31 && val < -63)
4495
            val += 64;
4496
        if (pred > 32 && val > 63)
4497
            val -= 64;
4498
        
4499
    }
4500
    return val;
4501
}
4502

    
4503
/* Decodes RVLC of H.263+ UMV */
4504
static int h263p_decode_umotion(MpegEncContext * s, int pred)
4505
{
4506
   int code = 0, sign;
4507
   
4508
   if (get_bits1(&s->gb)) /* Motion difference = 0 */
4509
      return pred;
4510
   
4511
   code = 2 + get_bits1(&s->gb);
4512
   
4513
   while (get_bits1(&s->gb))
4514
   {
4515
      code <<= 1;
4516
      code += get_bits1(&s->gb);
4517
   }
4518
   sign = code & 1;
4519
   code >>= 1;
4520
   
4521
   code = (sign) ? (pred - code) : (pred + code);
4522
#ifdef DEBUG
4523
   fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
4524
#endif
4525
   return code;   
4526

    
4527
}
4528

    
4529
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
4530
                             int n, int coded)
4531
{
4532
    int code, level, i, j, last, run;
4533
    RLTable *rl = &rl_inter;
4534
    const uint8_t *scan_table;
4535
    GetBitContext gb= s->gb;
4536

    
4537
    scan_table = s->intra_scantable.permutated;
4538
    if (s->h263_aic && s->mb_intra) {
4539
        rl = &rl_intra_aic;
4540
        i = 0;
4541
        if (s->ac_pred) {
4542
            if (s->h263_aic_dir) 
4543
                scan_table = s->intra_v_scantable.permutated; /* left */
4544
            else
4545
                scan_table = s->intra_h_scantable.permutated; /* top */
4546
        }
4547
    } else if (s->mb_intra) {
4548
        /* DC coef */
4549
        if(s->codec_id == CODEC_ID_RV10){
4550
          if (s->rv10_version == 3 && s->pict_type == I_TYPE) {
4551
            int component, diff;
4552
            component = (n <= 3 ? 0 : n - 4 + 1);
4553
            level = s->last_dc[component];
4554
            if (s->rv10_first_dc_coded[component]) {
4555
                diff = rv_decode_dc(s, n);
4556
                if (diff == 0xffff)
4557
                    return -1;
4558
                level += diff;
4559
                level = level & 0xff; /* handle wrap round */
4560
                s->last_dc[component] = level;
4561
            } else {
4562
                s->rv10_first_dc_coded[component] = 1;
4563
            }
4564
          } else {
4565
                level = get_bits(&s->gb, 8);
4566
                if (level == 255)
4567
                    level = 128;
4568
          }
4569
        }else{
4570
            level = get_bits(&s->gb, 8);
4571
            if((level&0x7F) == 0){
4572
                av_log(s->avctx, AV_LOG_ERROR, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);
4573
                if(s->error_resilience >= FF_ER_COMPLIANT)
4574
                    return -1;
4575
            }
4576
            if (level == 255)
4577
                level = 128;
4578
        }
4579
        block[0] = level;
4580
        i = 1;
4581
    } else {
4582
        i = 0;
4583
    }
4584
    if (!coded) {
4585
        if (s->mb_intra && s->h263_aic)
4586
            goto not_coded;
4587
        s->block_last_index[n] = i - 1;
4588
        return 0;
4589
    }
4590
retry:
4591
    for(;;) {
4592
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
4593
        if (code < 0){
4594
            av_log(s->avctx, AV_LOG_ERROR, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
4595
            return -1;
4596
        }
4597
        if (code == rl->n) {
4598
            /* escape */
4599
            if (s->h263_flv > 1) {
4600
                int is11 = get_bits1(&s->gb);
4601
                last = get_bits1(&s->gb);
4602
                run = get_bits(&s->gb, 6);
4603
                if(is11){
4604
                    level = get_sbits(&s->gb, 11);
4605
                } else {
4606
                    level = get_sbits(&s->gb, 7);
4607
                }
4608
            } else {
4609
                last = get_bits1(&s->gb);
4610
                run = get_bits(&s->gb, 6);
4611
                level = (int8_t)get_bits(&s->gb, 8);
4612
                if(level == -128){
4613
                    if (s->codec_id == CODEC_ID_RV10) {
4614
                        /* XXX: should patch encoder too */
4615
                        level = get_sbits(&s->gb, 12);
4616
                    }else{
4617
                        level = get_bits(&s->gb, 5);
4618
                        level |= get_sbits(&s->gb, 6)<<5;
4619
                    }
4620
                }
4621
            }
4622
        } else {
4623
            run = rl->table_run[code];
4624
            level = rl->table_level[code];
4625
            last = code >= rl->last;
4626
            if (get_bits1(&s->gb))
4627
                level = -level;
4628
        }
4629
        i += run;
4630
        if (i >= 64){
4631
            if(s->alt_inter_vlc && rl == &rl_inter && !s->mb_intra){
4632
                //looks like a hack but no, its the way its supposed to work ...
4633
                rl = &rl_intra_aic;
4634
                i = 0;
4635
                s->gb= gb;
4636
                memset(block, 0, sizeof(DCTELEM)*64);
4637
                goto retry;
4638
            }
4639
            av_log(s->avctx, AV_LOG_ERROR, "run overflow at %dx%d i:%d\n", s->mb_x, s->mb_y, s->mb_intra);
4640
            return -1;
4641
        }
4642
        j = scan_table[i];
4643
        block[j] = level;
4644
        if (last)
4645
            break;
4646
        i++;
4647
    }
4648
not_coded:    
4649
    if (s->mb_intra && s->h263_aic) {
4650
        h263_pred_acdc(s, block, n);
4651
        i = 63;
4652
    }
4653
    s->block_last_index[n] = i;
4654
    return 0;
4655
}
4656

    
4657
/**
4658
 * decodes the dc value.
4659
 * @param n block index (0-3 are luma, 4-5 are chroma)
4660
 * @param dir_ptr the prediction direction will be stored here
4661
 * @return the quantized dc
4662
 */
4663
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
4664
{
4665
    int level, code;
4666

    
4667
    if (n < 4) 
4668
        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
4669
    else 
4670
        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
4671
    if (code < 0 || code > 9 /* && s->nbit<9 */){
4672
        av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
4673
        return -1;
4674
    }
4675
    if (code == 0) {
4676
        level = 0;
4677
    } else {
4678
        if(IS_3IV1){
4679
            if(code==1)
4680
                level= 2*get_bits1(&s->gb)-1;
4681
            else{
4682
                if(get_bits1(&s->gb))
4683
                    level = get_bits(&s->gb, code-1) + (1<<(code-1));
4684
                else
4685
                    level = -get_bits(&s->gb, code-1) - (1<<(code-1));
4686
            }
4687
        }else{
4688
            level = get_xbits(&s->gb, code);
4689
        }
4690

    
4691
        if (code > 8){
4692
            if(get_bits1(&s->gb)==0){ /* marker */
4693
                if(s->error_resilience>=2){
4694
                    av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
4695
                    return -1;
4696
                }
4697
            }
4698
        }
4699
    }
4700

    
4701
    return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
4702
}
4703

    
4704
/**
4705
 * decodes a block.
4706
 * @return <0 if an error occured
4707
 */
4708
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
4709
                              int n, int coded, int intra, int rvlc)
4710
{
4711
    int level, i, last, run;
4712
    int dc_pred_dir;
4713
    RLTable * rl;
4714
    RL_VLC_ELEM * rl_vlc;
4715
    const uint8_t * scan_table;
4716
    int qmul, qadd;
4717

    
4718
    //Note intra & rvlc should be optimized away if this is inlined
4719
    
4720
    if(intra) {
4721
      if(s->qscale < s->intra_dc_threshold){
4722
        /* DC coef */
4723
        if(s->partitioned_frame){
4724
            level = s->dc_val[0][ s->block_index[n] ];
4725
            if(n<4) level= FASTDIV((level + (s->y_dc_scale>>1)), s->y_dc_scale);
4726
            else    level= FASTDIV((level + (s->c_dc_scale>>1)), s->c_dc_scale);
4727
            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_stride]<<n)&32;
4728
        }else{
4729
            level = mpeg4_decode_dc(s, n, &dc_pred_dir);
4730
            if (level < 0)
4731
                return -1;
4732
        }
4733
        block[0] = level;
4734
        i = 0;
4735
      }else{
4736
            i = -1;
4737
      }  
4738
        if (!coded) 
4739
            goto not_coded;
4740
        
4741
        if(rvlc){        
4742
            rl = &rvlc_rl_intra;
4743
            rl_vlc = rvlc_rl_intra.rl_vlc[0];
4744
        }else{
4745
            rl = &rl_intra;
4746
            rl_vlc = rl_intra.rl_vlc[0];
4747
        }
4748
        if (s->ac_pred) {
4749
            if (dc_pred_dir == 0) 
4750
                scan_table = s->intra_v_scantable.permutated; /* left */
4751
            else
4752
                scan_table = s->intra_h_scantable.permutated; /* top */
4753
        } else {
4754
            scan_table = s->intra_scantable.permutated;
4755
        }
4756
        qmul=1;
4757
        qadd=0;
4758
    } else {
4759
        i = -1;
4760
        if (!coded) {
4761
            s->block_last_index[n] = i;
4762
            return 0;
4763
        }
4764
        if(rvlc) rl = &rvlc_rl_inter;
4765
        else     rl = &rl_inter;
4766
   
4767
        scan_table = s->intra_scantable.permutated;
4768

    
4769
        if(s->mpeg_quant){
4770
            qmul=1;
4771
            qadd=0;
4772
            if(rvlc){        
4773
                rl_vlc = rvlc_rl_inter.rl_vlc[0];        
4774
            }else{
4775
                rl_vlc = rl_inter.rl_vlc[0];        
4776
            }