Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h263.c @ fb079883

History | View | Annotate | Download (201 KB)

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

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

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

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

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

    
55
#ifdef CONFIG_ENCODERS
56
static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
57
                              int n);
58
static void h263_encode_motion(MpegEncContext * s, int val, int fcode);
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 h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr);
73
#ifdef CONFIG_ENCODERS
74
static void mpeg4_encode_visual_object_header(MpegEncContext * s);
75
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number);
76
#endif //CONFIG_ENCODERS
77
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s);
78
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr);
79

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

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

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

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

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

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

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

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

    
134
#ifdef CONFIG_ENCODERS
135

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

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

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

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

    
155
      align_put_bits(&s->pb);
156

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

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

    
197
void h263_encode_picture_header(MpegEncContext * s, int picture_number)
198
{
199
    int format;
200

    
201
    align_put_bits(&s->pb);
202

    
203
    /* Update the pointer to last GOB */
204
    s->ptr_lastgob = pbBufPtr(&s->pb);
205
    put_bits(&s->pb, 22, 0x20); /* PSC */
206
    put_bits(&s->pb, 8, (((int64_t)s->picture_number * 30 * s->avctx->frame_rate_base) / 
207
                         s->avctx->frame_rate) & 0xff);
208

    
209
    put_bits(&s->pb, 1, 1);        /* marker */
210
    put_bits(&s->pb, 1, 0);        /* h263 id */
211
    put_bits(&s->pb, 1, 0);        /* split screen off */
212
    put_bits(&s->pb, 1, 0);        /* camera  off */
213
    put_bits(&s->pb, 1, 0);        /* freeze picture release off */
214
    
215
    format = h263_get_picture_format(s->width, s->height);
216
    if (!s->h263_plus) {
217
        /* H.263v1 */
218
        put_bits(&s->pb, 3, format);
219
        put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
220
        /* By now UMV IS DISABLED ON H.263v1, since the restrictions
221
        of H.263v1 UMV implies to check the predicted MV after
222
        calculation of the current MB to see if we're on the limits */
223
        put_bits(&s->pb, 1, 0);        /* unrestricted motion vector: off */
224
        put_bits(&s->pb, 1, 0);        /* SAC: off */
225
        put_bits(&s->pb, 1, s->obmc);        /* advanced prediction mode */
226
        put_bits(&s->pb, 1, 0);        /* not PB frame */
227
        put_bits(&s->pb, 5, s->qscale);
228
        put_bits(&s->pb, 1, 0);        /* Continuous Presence Multipoint mode: off */
229
    } else {
230
        /* H.263v2 */
231
        /* H.263 Plus PTYPE */
232
        put_bits(&s->pb, 3, 7);
233
        put_bits(&s->pb,3,1); /* Update Full Extended PTYPE */
234
        if (format == 7)
235
            put_bits(&s->pb,3,6); /* Custom Source Format */
236
        else
237
            put_bits(&s->pb, 3, format);
238
            
239
        put_bits(&s->pb,1,0); /* Custom PCF: off */
240
        put_bits(&s->pb,1, s->umvplus); /* Unrestricted Motion Vector */
241
        put_bits(&s->pb,1,0); /* SAC: off */
242
        put_bits(&s->pb,1,s->obmc); /* Advanced Prediction Mode */
243
        put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
244
        put_bits(&s->pb,1,s->loop_filter); /* Deblocking Filter */
245
        put_bits(&s->pb,1,s->h263_slice_structured); /* Slice Structured */
246
        put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
247
        put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
248
        put_bits(&s->pb,1,s->alt_inter_vlc); /* Alternative Inter VLC */
249
        put_bits(&s->pb,1,s->modified_quant); /* Modified Quantization: */
250
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
251
        put_bits(&s->pb,3,0); /* Reserved */
252
                
253
        put_bits(&s->pb, 3, s->pict_type == P_TYPE);
254
                
255
        put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
256
        put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
257
        put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
258
        put_bits(&s->pb,2,0); /* Reserved */
259
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
260
                
261
        /* This should be here if PLUSPTYPE */
262
        put_bits(&s->pb, 1, 0);        /* Continuous Presence Multipoint mode: off */
263
                
264
                if (format == 7) {
265
            /* Custom Picture Format (CPFMT) */
266
            aspect_to_info(s, s->avctx->sample_aspect_ratio);
267

    
268
            put_bits(&s->pb,4,s->aspect_ratio_info);
269
            put_bits(&s->pb,9,(s->width >> 2) - 1);
270
            put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
271
            put_bits(&s->pb,9,(s->height >> 2));
272
            if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
273
                put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
274
                put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
275
            }
276
        }
277
        
278
        /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
279
        if (s->umvplus)
280
//            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
281
//FIXME check actual requested range
282
            put_bits(&s->pb,2,1); /* unlimited */
283
        if(s->h263_slice_structured)
284
            put_bits(&s->pb,2,0); /* no weird submodes */
285

    
286
        put_bits(&s->pb, 5, s->qscale);
287
    }
288

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

    
291
    if(s->h263_aic){
292
         s->y_dc_scale_table= 
293
         s->c_dc_scale_table= ff_aic_dc_scale_table;
294
    }else{
295
        s->y_dc_scale_table=
296
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
297
    }
298
}
299

    
300
/**
301
 * Encodes a group of blocks header.
302
 */
303
void h263_encode_gob_header(MpegEncContext * s, int mb_line)
304
{
305
    put_bits(&s->pb, 17, 1); /* GBSC */
306

    
307
    if(s->h263_slice_structured){
308
        put_bits(&s->pb, 1, 1);
309

    
310
        ff_h263_encode_mba(s);
311

    
312
        if(s->mb_num > 1583)
313
            put_bits(&s->pb, 1, 1);
314
        put_bits(&s->pb, 5, s->qscale); /* GQUANT */
315
        put_bits(&s->pb, 1, 1);
316
        put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
317
    }else{
318
        int gob_number= mb_line / s->gob_index;
319

    
320
        put_bits(&s->pb, 5, gob_number); /* GN */
321
        put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
322
        put_bits(&s->pb, 5, s->qscale); /* GQUANT */
323
    }
324
}
325

    
326
static inline int get_block_rate(MpegEncContext * s, DCTELEM block[64], int block_last_index, uint8_t scantable[64]){
327
    int last=0;
328
    int j;
329
    int rate=0;
330

    
331
    for(j=1; j<=block_last_index; j++){
332
        const int index= scantable[j];
333
        int level= block[index];
334
        if(level){
335
            level+= 64;
336
            if((level&(~127)) == 0){
337
                if(j<block_last_index) rate+= s->intra_ac_vlc_length     [UNI_AC_ENC_INDEX(j-last-1, level)];
338
                else                   rate+= s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j-last-1, level)];
339
            }else
340
                rate += s->ac_esc_length;
341
            level-= 64;
342

    
343
            last= j;
344
        }
345
    }
346
    
347
    return rate;
348
}
349

    
350
static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
351
{
352
    int score= 0;
353
    int i, n;
354
    int8_t * const qscale_table= s->current_picture.qscale_table;
355

    
356
    memcpy(zigzag_last_index, s->block_last_index, sizeof(int)*6);
357
    
358
    for(n=0; n<6; n++){
359
        int16_t *ac_val, *ac_val1;
360
        
361
        score -= get_block_rate(s, block[n], s->block_last_index[n], s->intra_scantable.permutated);
362

    
363
        ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
364
        ac_val1= ac_val;
365
        if(dir[n]){
366
            const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
367
            /* top prediction */
368
            ac_val-= s->block_wrap[n]*16;
369
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
370
                /* same qscale */
371
                for(i=1; i<8; i++){
372
                    const int level= block[n][s->dsp.idct_permutation[i   ]];
373
                    block[n][s->dsp.idct_permutation[i   ]] = level - ac_val[i+8];
374
                    ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
375
                    ac_val1[i+8]= level;
376
                }
377
            }else{
378
                /* different qscale, we must rescale */
379
                for(i=1; i<8; i++){
380
                    const int level= block[n][s->dsp.idct_permutation[i   ]];
381
                    block[n][s->dsp.idct_permutation[i   ]] = level - ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
382
                    ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
383
                    ac_val1[i+8]= level;
384
                }
385
            }
386
            st[n]= s->intra_h_scantable.permutated;
387
        }else{
388
            const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
389
            /* left prediction */
390
            ac_val-= 16;
391
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
392
                /* same qscale */
393
                for(i=1; i<8; i++){
394
                    const int level= block[n][s->dsp.idct_permutation[i<<3]];
395
                    block[n][s->dsp.idct_permutation[i<<3]]= level - ac_val[i];
396
                    ac_val1[i  ]= level;
397
                    ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
398
                }
399
            }else{
400
                /* different qscale, we must rescale */
401
                for(i=1; i<8; i++){
402
                    const int level= block[n][s->dsp.idct_permutation[i<<3]];
403
                    block[n][s->dsp.idct_permutation[i<<3]]= level - ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
404
                    ac_val1[i  ]= level;
405
                    ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
406
                }
407
            }
408
            st[n]= s->intra_v_scantable.permutated;
409
        }
410

    
411
        for(i=63; i>0; i--) //FIXME optimize
412
            if(block[n][ st[n][i] ]) break;
413
        s->block_last_index[n]= i;
414

    
415
        score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
416
    }
417

    
418
    return score < 0;
419
}
420

    
421
static inline void restore_ac_coeffs(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
422
{
423
    int i, n;
424
    memcpy(s->block_last_index, zigzag_last_index, sizeof(int)*6);
425

    
426
    for(n=0; n<6; n++){
427
        int16_t *ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
428

    
429
        st[n]= s->intra_scantable.permutated;
430
        if(dir[n]){
431
            /* top prediction */
432
            for(i=1; i<8; i++){
433
                block[n][s->dsp.idct_permutation[i   ]] = ac_val[i+8];
434
            }
435
        }else{
436
            /* left prediction */
437
            for(i=1; i<8; i++){
438
                block[n][s->dsp.idct_permutation[i<<3]]= ac_val[i  ];
439
            }
440
        }
441
    }
442
}
443

    
444
/**
445
 * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
446
 */
447
void ff_clean_h263_qscales(MpegEncContext *s){
448
    int i;
449
    int8_t * const qscale_table= s->current_picture.qscale_table;
450
    
451
    for(i=1; i<s->mb_num; i++){
452
        if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i-1] ] >2)
453
            qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i-1] ]+2;
454
    }
455
    for(i=s->mb_num-2; i>=0; i--){
456
        if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i+1] ] >2)
457
            qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i+1] ]+2;
458
    }
459
}
460

    
461
/**
462
 * modify mb_type & qscale so that encoding is acually possible in mpeg4
463
 */
464
void ff_clean_mpeg4_qscales(MpegEncContext *s){
465
    int i;
466
    int8_t * const qscale_table= s->current_picture.qscale_table;
467

    
468
    ff_clean_h263_qscales(s);
469
    
470
    for(i=1; i<s->mb_num; i++){
471
        int mb_xy= s->mb_index2xy[i];
472
    
473
        if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&MB_TYPE_INTER4V)){
474
            s->mb_type[mb_xy]&= ~MB_TYPE_INTER4V;
475
            s->mb_type[mb_xy]|= MB_TYPE_INTER;
476
        }
477
    }
478

    
479
    if(s->pict_type== B_TYPE){
480
        int odd=0;
481
        /* ok, come on, this isnt funny anymore, theres more code for handling this mpeg4 mess than
482
           for the actual adaptive quantization */
483
        
484
        for(i=0; i<s->mb_num; i++){
485
            int mb_xy= s->mb_index2xy[i];
486
            odd += qscale_table[mb_xy]&1;
487
        }
488
        
489
        if(2*odd > s->mb_num) odd=1;
490
        else                  odd=0;
491
        
492
        for(i=0; i<s->mb_num; i++){
493
            int mb_xy= s->mb_index2xy[i];
494
            if((qscale_table[mb_xy]&1) != odd)
495
                qscale_table[mb_xy]++;
496
            if(qscale_table[mb_xy] > 31)
497
                qscale_table[mb_xy]= 31;
498
        }            
499
    
500
        for(i=1; i<s->mb_num; i++){
501
            int mb_xy= s->mb_index2xy[i];
502
            if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&MB_TYPE_DIRECT)){
503
                s->mb_type[mb_xy]&= ~MB_TYPE_DIRECT;
504
                s->mb_type[mb_xy]|= MB_TYPE_BIDIR;
505
            }
506
        }
507
    }
508
}
509

    
510
#endif //CONFIG_ENCODERS
511
/**
512
 *
513
 * @return the mb_type
514
 */
515
int ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
516
    const int mb_index= s->mb_x + s->mb_y*s->mb_stride;
517
    const int colocated_mb_type= s->next_picture.mb_type[mb_index]; //FIXME or next?
518
    int xy= s->block_index[0];
519
    uint16_t time_pp= s->pp_time;
520
    uint16_t time_pb= s->pb_time;
521
    int i;
522
    
523
    //FIXME avoid divides
524
    
525
    if(IS_8X8(colocated_mb_type)){
526
        s->mv_type = MV_TYPE_8X8;
527
        for(i=0; i<4; i++){
528
            xy= s->block_index[i];
529
            s->mv[0][i][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
530
            s->mv[0][i][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
531
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->motion_val[xy][0]
532
                                : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
533
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->motion_val[xy][1] 
534
                                : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
535
        }
536
        return MB_TYPE_DIRECT2 | MB_TYPE_8x8 | MB_TYPE_L0L1;
537
    } else if(IS_INTERLACED(colocated_mb_type)){
538
        s->mv_type = MV_TYPE_FIELD;
539
        for(i=0; i<2; i++){
540
            if(s->top_field_first){
541
                time_pp= s->pp_field_time - s->field_select_table[mb_index][i] + i;
542
                time_pb= s->pb_field_time - s->field_select_table[mb_index][i] + i;
543
            }else{
544
                time_pp= s->pp_field_time + s->field_select_table[mb_index][i] - i;
545
                time_pb= s->pb_field_time + s->field_select_table[mb_index][i] - i;
546
            }
547
            s->mv[0][i][0] = s->field_mv_table[mb_index][i][0]*time_pb/time_pp + mx;
548
            s->mv[0][i][1] = s->field_mv_table[mb_index][i][1]*time_pb/time_pp + my;
549
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->field_mv_table[mb_index][i][0]
550
                                : s->field_mv_table[mb_index][i][0]*(time_pb - time_pp)/time_pp;
551
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->field_mv_table[mb_index][i][1] 
552
                                : s->field_mv_table[mb_index][i][1]*(time_pb - time_pp)/time_pp;
553
        }
554
        return MB_TYPE_DIRECT2 | MB_TYPE_16x8 | MB_TYPE_L0L1 | MB_TYPE_INTERLACED;
555
    }else{
556
        s->mv[0][0][0] = s->mv[0][1][0] = s->mv[0][2][0] = s->mv[0][3][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
557
        s->mv[0][0][1] = s->mv[0][1][1] = s->mv[0][2][1] = s->mv[0][3][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
558
        s->mv[1][0][0] = s->mv[1][1][0] = s->mv[1][2][0] = s->mv[1][3][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
559
                            : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
560
        s->mv[1][0][1] = s->mv[1][1][1] = s->mv[1][2][1] = s->mv[1][3][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1] 
561
                            : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
562
        if((s->avctx->workaround_bugs & FF_BUG_DIRECT_BLOCKSIZE) || !s->quarter_sample)
563
            s->mv_type= MV_TYPE_16X16;
564
        else
565
            s->mv_type= MV_TYPE_8X8;
566
        return MB_TYPE_DIRECT2 | MB_TYPE_16x16 | MB_TYPE_L0L1; //Note see prev line
567
    }
568
}
569

    
570
void ff_h263_update_motion_val(MpegEncContext * s){
571
    const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
572
               //FIXME a lot of thet is only needed for !low_delay
573
    const int wrap = s->block_wrap[0];
574
    const int xy = s->block_index[0];
575
    
576
    s->current_picture.mbskip_table[mb_xy]= s->mb_skiped; 
577

    
578
    if(s->mv_type != MV_TYPE_8X8){
579
        int motion_x, motion_y;
580
        if (s->mb_intra) {
581
            motion_x = 0;
582
            motion_y = 0;
583
        } else if (s->mv_type == MV_TYPE_16X16) {
584
            motion_x = s->mv[0][0][0];
585
            motion_y = s->mv[0][0][1];
586
        } else /*if (s->mv_type == MV_TYPE_FIELD)*/ {
587
            int i;
588
            motion_x = s->mv[0][0][0] + s->mv[0][1][0];
589
            motion_y = s->mv[0][0][1] + s->mv[0][1][1];
590
            motion_x = (motion_x>>1) | (motion_x&1);
591
            for(i=0; i<2; i++){
592
                s->field_mv_table[mb_xy][i][0]= s->mv[0][i][0];
593
                s->field_mv_table[mb_xy][i][1]= s->mv[0][i][1];
594
                s->field_select_table[mb_xy][i]= s->field_select[0][i];
595
            }
596
        }
597
        
598
        /* no update if 8X8 because it has been done during parsing */
599
        s->motion_val[xy][0] = motion_x;
600
        s->motion_val[xy][1] = motion_y;
601
        s->motion_val[xy + 1][0] = motion_x;
602
        s->motion_val[xy + 1][1] = motion_y;
603
        s->motion_val[xy + wrap][0] = motion_x;
604
        s->motion_val[xy + wrap][1] = motion_y;
605
        s->motion_val[xy + 1 + wrap][0] = motion_x;
606
        s->motion_val[xy + 1 + wrap][1] = motion_y;
607
    }
608

    
609
    if(s->encoding){ //FIXME encoding MUST be cleaned up
610
        if (s->mv_type == MV_TYPE_8X8) 
611
            s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_8x8;
612
        else if(s->mb_intra)
613
            s->current_picture.mb_type[mb_xy]= MB_TYPE_INTRA;
614
        else
615
            s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_16x16;
616
    }
617
}
618

    
619
#ifdef CONFIG_ENCODERS
620

    
621
static inline int get_p_cbp(MpegEncContext * s,
622
                      DCTELEM block[6][64],
623
                      int motion_x, int motion_y){
624
    int cbp, i;
625

    
626
    if(s->flags & CODEC_FLAG_CBP_RD){
627
        int best_cbpy_score= INT_MAX;
628
        int best_cbpc_score= INT_MAX;
629
        int cbpc = (-1), cbpy= (-1);
630
        const int offset= (s->mv_type==MV_TYPE_16X16 ? 0 : 16) + (s->dquant ? 8 : 0);
631
        const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
632

    
633
        for(i=0; i<4; i++){
634
            int score= inter_MCBPC_bits[i + offset] * lambda;
635
            if(i&1) score += s->coded_score[5];
636
            if(i&2) score += s->coded_score[4];
637

    
638
            if(score < best_cbpc_score){
639
                best_cbpc_score= score;
640
                cbpc= i;
641
            }
642
        }
643

    
644
        for(i=0; i<16; i++){
645
            int score= cbpy_tab[i ^ 0xF][1] * lambda;
646
            if(i&1) score += s->coded_score[3];
647
            if(i&2) score += s->coded_score[2];
648
            if(i&4) score += s->coded_score[1];
649
            if(i&8) score += s->coded_score[0];
650

    
651
            if(score < best_cbpy_score){
652
                best_cbpy_score= score;
653
                cbpy= i;
654
            }
655
        }
656
        cbp= cbpc + 4*cbpy;
657
        if ((motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16){
658
            if(best_cbpy_score + best_cbpc_score + 2*lambda >= 0)
659
                cbp= 0;
660
        }
661

    
662
        for (i = 0; i < 6; i++) {
663
            if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
664
                s->block_last_index[i]= -1;
665
                memset(s->block[i], 0, sizeof(DCTELEM)*64);
666
            }
667
        }
668
    }else{
669
        cbp= 0;
670
        for (i = 0; i < 6; i++) {
671
            if (s->block_last_index[i] >= 0)
672
                cbp |= 1 << (5 - i);
673
        }
674
    }
675
    return cbp;
676
}
677

    
678
static inline int get_b_cbp(MpegEncContext * s, DCTELEM block[6][64],
679
                            int motion_x, int motion_y, int mb_type){
680
    int cbp=0, i;
681

    
682
    if(s->flags & CODEC_FLAG_CBP_RD){
683
        int score=0;
684
        const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
685
        
686
        for(i=0; i<6; i++){
687
            if(s->coded_score[i] < 0){
688
                score += s->coded_score[i];
689
                cbp |= 1 << (5 - i);
690
            }
691
        }
692
        
693
        if(cbp){
694
            int zero_score= -6;
695
            if ((motion_x | motion_y | s->dquant | mb_type) == 0){
696
                zero_score-= 4; //2*MV + mb_type + cbp bit
697
            }
698

    
699
            zero_score*= lambda;
700
            if(zero_score <= score){
701
                cbp=0;
702
            }
703
        }
704

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

    
720
void mpeg4_encode_mb(MpegEncContext * s,
721
                    DCTELEM block[6][64],
722
                    int motion_x, int motion_y)
723
{
724
    int cbpc, cbpy, pred_x, pred_y;
725
    PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
726
    PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=B_TYPE ? &s->tex_pb : &s->pb;
727
    PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=I_TYPE ? &s->pb2    : &s->pb;
728
    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
729
    const int dquant_code[5]= {1,0,9,2,3};
730
    
731
    //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
732
    if (!s->mb_intra) {
733
        int i, cbp;
734
        
735
        if(s->pict_type==B_TYPE){
736
            static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
737
            int mb_type=  mb_type_table[s->mv_dir];
738
            
739
            if(s->mb_x==0){
740
                s->last_mv[0][0][0]= 
741
                s->last_mv[0][0][1]= 
742
                s->last_mv[1][0][0]= 
743
                s->last_mv[1][0][1]= 0;
744
            }
745
            
746
            assert(s->dquant>=-2 && s->dquant<=2);
747
            assert((s->dquant&1)==0);
748
            assert(mb_type>=0);
749

    
750
            /* nothing to do if this MB was skiped in the next P Frame */
751
            if(s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]){ //FIXME avoid DCT & ...
752
                s->skip_count++;
753
                s->mv[0][0][0]= 
754
                s->mv[0][0][1]= 
755
                s->mv[1][0][0]= 
756
                s->mv[1][0][1]= 0;
757
                s->mv_dir= MV_DIR_FORWARD; //doesnt matter
758
                s->qscale -= s->dquant;
759
//                s->mb_skiped=1;
760

    
761
                return;
762
            }
763
            
764
            cbp= get_b_cbp(s, block, motion_x, motion_y, mb_type);
765
            
766
            if ((cbp | motion_x | motion_y | mb_type) ==0) {
767
                /* direct MB with MV={0,0} */
768
                assert(s->dquant==0);
769
                
770
                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
771

    
772
                if(interleaved_stats){
773
                    s->misc_bits++;
774
                    s->last_bits++;
775
                }
776
                s->skip_count++;
777
                return;
778
            }
779
            
780
            put_bits(&s->pb, 1, 0);        /* mb coded modb1=0 */
781
            put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
782
            put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we dont need it :)
783
            if(cbp) put_bits(&s->pb, 6, cbp);
784
            
785
            if(cbp && mb_type){
786
                if(s->dquant)
787
                    put_bits(&s->pb, 2, (s->dquant>>2)+3);
788
                else
789
                    put_bits(&s->pb, 1, 0);
790
            }else
791
                s->qscale -= s->dquant;
792
            
793
            if(!s->progressive_sequence){
794
                if(cbp)
795
                    put_bits(&s->pb, 1, s->interlaced_dct);
796
                if(mb_type) // not diect mode
797
                    put_bits(&s->pb, 1, 0); // no interlaced ME yet
798
            }
799

    
800
            if(interleaved_stats){
801
                s->misc_bits+= get_bits_diff(s);
802
            }
803

    
804
            switch(mb_type)
805
            {
806
            case 0: /* direct */
807
                h263_encode_motion(s, motion_x, 1);
808
                h263_encode_motion(s, motion_y, 1);                
809
                s->b_count++;
810
                s->f_count++;
811
                break;
812
            case 1: /* bidir */
813
                h263_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
814
                h263_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
815
                h263_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
816
                h263_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
817
                s->last_mv[0][0][0]= s->mv[0][0][0];
818
                s->last_mv[0][0][1]= s->mv[0][0][1];
819
                s->last_mv[1][0][0]= s->mv[1][0][0];
820
                s->last_mv[1][0][1]= s->mv[1][0][1];
821
                s->b_count++;
822
                s->f_count++;
823
                break;
824
            case 2: /* backward */
825
                h263_encode_motion(s, motion_x - s->last_mv[1][0][0], s->b_code);
826
                h263_encode_motion(s, motion_y - s->last_mv[1][0][1], s->b_code);
827
                s->last_mv[1][0][0]= motion_x;
828
                s->last_mv[1][0][1]= motion_y;
829
                s->b_count++;
830
                break;
831
            case 3: /* forward */
832
                h263_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);
833
                h263_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);
834
                s->last_mv[0][0][0]= motion_x;
835
                s->last_mv[0][0][1]= motion_y;
836
                s->f_count++;
837
                break;
838
            default:
839
                av_log(s->avctx, AV_LOG_ERROR, "unknown mb type\n");
840
                return;
841
            }
842

    
843
            if(interleaved_stats){
844
                s->mv_bits+= get_bits_diff(s);
845
            }
846

    
847
            /* encode each block */
848
            for (i = 0; i < 6; i++) {
849
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, &s->pb);
850
            }
851

    
852
            if(interleaved_stats){
853
                s->p_tex_bits+= get_bits_diff(s);
854
            }
855
        }else{ /* s->pict_type==B_TYPE */
856
            cbp= get_p_cbp(s, block, motion_x, motion_y);
857
        
858
            if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
859
                /* check if the B frames can skip it too, as we must skip it if we skip here 
860
                   why didnt they just compress the skip-mb bits instead of reusing them ?! */
861
                if(s->max_b_frames>0){
862
                    int i;
863
                    int x,y, offset;
864
                    uint8_t *p_pic;
865

    
866
                    x= s->mb_x*16;
867
                    y= s->mb_y*16;
868
                    if(x+16 > s->width)  x= s->width-16;
869
                    if(y+16 > s->height) y= s->height-16;
870

    
871
                    offset= x + y*s->linesize;
872
                    p_pic= s->new_picture.data[0] + offset;
873
                    
874
                    s->mb_skiped=1;
875
                    for(i=0; i<s->max_b_frames; i++){
876
                        uint8_t *b_pic;
877
                        int diff;
878
                        Picture *pic= s->reordered_input_picture[i+1];
879

    
880
                        if(pic==NULL || pic->pict_type!=B_TYPE) break;
881

    
882
                        b_pic= pic->data[0] + offset + 16; //FIXME +16
883
                        diff= s->dsp.pix_abs16x16(p_pic, b_pic, s->linesize);
884
                        if(diff>s->qscale*70){ //FIXME check that 70 is optimal
885
                            s->mb_skiped=0;
886
                            break;
887
                        }
888
                    }
889
                }else
890
                    s->mb_skiped=1; 
891

    
892
                if(s->mb_skiped==1){
893
                    /* skip macroblock */
894
                    put_bits(&s->pb, 1, 1);
895

    
896
                    if(interleaved_stats){
897
                        s->misc_bits++;
898
                        s->last_bits++;
899
                    }
900
                    s->skip_count++;
901
                    
902
                    return;
903
                }
904
            }
905

    
906
            put_bits(&s->pb, 1, 0);        /* mb coded */
907
            cbpc = cbp & 3;
908
            cbpy = cbp >> 2;
909
            cbpy ^= 0xf;
910
            if(s->mv_type==MV_TYPE_16X16){
911
                if(s->dquant) cbpc+= 8;
912
                put_bits(&s->pb,
913
                        inter_MCBPC_bits[cbpc],
914
                        inter_MCBPC_code[cbpc]);
915

    
916
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
917
                if(s->dquant)
918
                    put_bits(pb2, 2, dquant_code[s->dquant+2]);
919

    
920
                if(!s->progressive_sequence){
921
                    if(cbp)
922
                        put_bits(pb2, 1, s->interlaced_dct);
923
                    put_bits(pb2, 1, 0); // no interlaced ME yet
924
                }
925
                    
926
                if(interleaved_stats){
927
                    s->misc_bits+= get_bits_diff(s);
928
                }
929

    
930
                /* motion vectors: 16x16 mode */
931
                h263_pred_motion(s, 0, &pred_x, &pred_y);
932
            
933
                h263_encode_motion(s, motion_x - pred_x, s->f_code);
934
                h263_encode_motion(s, motion_y - pred_y, s->f_code);
935
            }else{
936
                put_bits(&s->pb,
937
                        inter_MCBPC_bits[cbpc+16],
938
                        inter_MCBPC_code[cbpc+16]);
939
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
940

    
941
                if(!s->progressive_sequence){
942
                    if(cbp)
943
                        put_bits(pb2, 1, s->interlaced_dct);
944
                }
945
    
946
                if(interleaved_stats){
947
                    s->misc_bits+= get_bits_diff(s);
948
                }
949

    
950
                for(i=0; i<4; i++){
951
                    /* motion vectors: 8x8 mode*/
952
                    h263_pred_motion(s, i, &pred_x, &pred_y);
953

    
954
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x, s->f_code);
955
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y, s->f_code);
956
                }
957
            }
958

    
959
            if(interleaved_stats){ 
960
                s->mv_bits+= get_bits_diff(s);
961
            }
962

    
963
            /* encode each block */
964
            for (i = 0; i < 6; i++) {
965
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, tex_pb);
966
            }
967

    
968
            if(interleaved_stats){
969
                s->p_tex_bits+= get_bits_diff(s);
970
            }
971
            s->f_count++;
972
        }
973
    } else {
974
        int cbp;
975
        int dc_diff[6];   //dc values with the dc prediction subtracted 
976
        int dir[6];  //prediction direction
977
        int zigzag_last_index[6];
978
        uint8_t *scan_table[6];
979
        int i;
980

    
981
        for(i=0; i<6; i++){
982
            const int level= block[i][0];
983
            uint16_t *dc_ptr;
984

    
985
            dc_diff[i]= level - ff_mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
986
            if (i < 4) {
987
                *dc_ptr = level * s->y_dc_scale;
988
            } else {
989
                *dc_ptr = level * s->c_dc_scale;
990
            }
991
        }
992

    
993
        if(s->flags & CODEC_FLAG_AC_PRED){
994
            s->ac_pred= decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
995
            if(!s->ac_pred)
996
                restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
997
        }else{
998
            for(i=0; i<6; i++)
999
                scan_table[i]= s->intra_scantable.permutated;
1000
        }
1001

    
1002
        /* compute cbp */
1003
        cbp = 0;
1004
        for (i = 0; i < 6; i++) {
1005
            if (s->block_last_index[i] >= 1)
1006
                cbp |= 1 << (5 - i);
1007
        }
1008

    
1009
        cbpc = cbp & 3;
1010
        if (s->pict_type == I_TYPE) {
1011
            if(s->dquant) cbpc+=4;
1012
            put_bits(&s->pb,
1013
                intra_MCBPC_bits[cbpc],
1014
                intra_MCBPC_code[cbpc]);
1015
        } else {
1016
            if(s->dquant) cbpc+=8;
1017
            put_bits(&s->pb, 1, 0);        /* mb coded */
1018
            put_bits(&s->pb,
1019
                inter_MCBPC_bits[cbpc + 4],
1020
                inter_MCBPC_code[cbpc + 4]);
1021
        }
1022
        put_bits(pb2, 1, s->ac_pred);
1023
        cbpy = cbp >> 2;
1024
        put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1025
        if(s->dquant)
1026
            put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
1027

    
1028
        if(!s->progressive_sequence){
1029
            put_bits(dc_pb, 1, s->interlaced_dct);
1030
        }
1031

    
1032
        if(interleaved_stats){
1033
            s->misc_bits+= get_bits_diff(s);
1034
        }
1035

    
1036
        /* encode each block */
1037
        for (i = 0; i < 6; i++) {
1038
            mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
1039
        }
1040

    
1041
        if(interleaved_stats){
1042
            s->i_tex_bits+= get_bits_diff(s);
1043
        }
1044
        s->i_count++;
1045

    
1046
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
1047
        if(s->ac_pred)
1048
            restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1049
    }
1050
}
1051

    
1052
void h263_encode_mb(MpegEncContext * s,
1053
                    DCTELEM block[6][64],
1054
                    int motion_x, int motion_y)
1055
{
1056
    int cbpc, cbpy, i, cbp, pred_x, pred_y;
1057
    int16_t pred_dc;
1058
    int16_t rec_intradc[6];
1059
    uint16_t *dc_ptr[6];
1060
    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1);
1061
    const int dquant_code[5]= {1,0,9,2,3};
1062
           
1063
    //printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
1064
    if (!s->mb_intra) {
1065
        /* compute cbp */
1066
        cbp= get_p_cbp(s, block, motion_x, motion_y);
1067

    
1068
        if ((cbp | motion_x | motion_y | s->dquant) == 0) {
1069
            /* skip macroblock */
1070
            put_bits(&s->pb, 1, 1);
1071
            if(interleaved_stats){
1072
                s->misc_bits++;
1073
                s->last_bits++;
1074
            }
1075
            return;
1076
        }
1077
        put_bits(&s->pb, 1, 0);        /* mb coded */
1078
        
1079
        cbpc = cbp & 3;
1080
        cbpy = cbp >> 2;
1081
        if(s->alt_inter_vlc==0 || cbpc!=3)
1082
            cbpy ^= 0xF;
1083
        if(s->dquant) cbpc+= 8;
1084
        if(s->mv_type==MV_TYPE_16X16){
1085
            put_bits(&s->pb,
1086
                    inter_MCBPC_bits[cbpc],
1087
                    inter_MCBPC_code[cbpc]);
1088

    
1089
            put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1090
            if(s->dquant)
1091
                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1092
                
1093
            if(interleaved_stats){
1094
                s->misc_bits+= get_bits_diff(s);
1095
            }
1096

    
1097
            /* motion vectors: 16x16 mode */
1098
            h263_pred_motion(s, 0, &pred_x, &pred_y);
1099
            
1100
            if (!s->umvplus) {  
1101
                h263_encode_motion(s, motion_x - pred_x, 1);
1102
                h263_encode_motion(s, motion_y - pred_y, 1);
1103
            }
1104
            else {
1105
                h263p_encode_umotion(s, motion_x - pred_x);
1106
                h263p_encode_umotion(s, motion_y - pred_y);
1107
                if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1108
                    /* To prevent Start Code emulation */
1109
                    put_bits(&s->pb,1,1);
1110
            }
1111
        }else{
1112
            put_bits(&s->pb,
1113
                    inter_MCBPC_bits[cbpc+16],
1114
                    inter_MCBPC_code[cbpc+16]);
1115
            put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1116
            if(s->dquant)
1117
                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1118

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

    
1123
            for(i=0; i<4; i++){
1124
                /* motion vectors: 8x8 mode*/
1125
                h263_pred_motion(s, i, &pred_x, &pred_y);
1126

    
1127
                motion_x= s->motion_val[ s->block_index[i] ][0];
1128
                motion_y= s->motion_val[ s->block_index[i] ][1];
1129
                if (!s->umvplus) {  
1130
                    h263_encode_motion(s, motion_x - pred_x, 1);
1131
                    h263_encode_motion(s, motion_y - pred_y, 1);
1132
                }
1133
                else {
1134
                    h263p_encode_umotion(s, motion_x - pred_x);
1135
                    h263p_encode_umotion(s, motion_y - pred_y);
1136
                    if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1137
                        /* To prevent Start Code emulation */
1138
                        put_bits(&s->pb,1,1);
1139
                }
1140
            }
1141
        }
1142

    
1143
        if(interleaved_stats){
1144
            s->mv_bits+= get_bits_diff(s);
1145
        }
1146
    } else {
1147
        assert(s->mb_intra);
1148
        
1149
        cbp = 0;
1150
        if (s->h263_aic) {
1151
            /* Predict DC */
1152
            for(i=0; i<6; i++) {
1153
                int16_t level = block[i][0];
1154
                int scale;
1155
                
1156
                if(i<4) scale= s->y_dc_scale;
1157
                else    scale= s->c_dc_scale;
1158

    
1159
                pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
1160
                level -= pred_dc;
1161
                /* Quant */
1162
                if (level >= 0)
1163
                    level = (level + (scale>>1))/scale;
1164
                else
1165
                    level = (level - (scale>>1))/scale;
1166
                    
1167
                /* AIC can change CBP */
1168
                if (level == 0 && s->block_last_index[i] == 0)
1169
                    s->block_last_index[i] = -1;
1170

    
1171
                if(!s->modified_quant){
1172
                    if (level < -127)
1173
                        level = -127;
1174
                    else if (level > 127)
1175
                        level = 127;
1176
                }
1177

    
1178
                block[i][0] = level;
1179
                /* Reconstruction */ 
1180
                rec_intradc[i] = scale*level + pred_dc;
1181
                /* Oddify */
1182
                rec_intradc[i] |= 1;
1183
                //if ((rec_intradc[i] % 2) == 0)
1184
                //    rec_intradc[i]++;
1185
                /* Clipping */
1186
                if (rec_intradc[i] < 0)
1187
                    rec_intradc[i] = 0;
1188
                else if (rec_intradc[i] > 2047)
1189
                    rec_intradc[i] = 2047;
1190
                                
1191
                /* Update AC/DC tables */
1192
                *dc_ptr[i] = rec_intradc[i];
1193
                if (s->block_last_index[i] >= 0)
1194
                    cbp |= 1 << (5 - i);
1195
            }
1196
        }else{
1197
            for(i=0; i<6; i++) {
1198
                /* compute cbp */
1199
                if (s->block_last_index[i] >= 1)
1200
                    cbp |= 1 << (5 - i);
1201
            }
1202
        }
1203

    
1204
        cbpc = cbp & 3;
1205
        if (s->pict_type == I_TYPE) {
1206
            if(s->dquant) cbpc+=4;
1207
            put_bits(&s->pb,
1208
                intra_MCBPC_bits[cbpc],
1209
                intra_MCBPC_code[cbpc]);
1210
        } else {
1211
            if(s->dquant) cbpc+=8;
1212
            put_bits(&s->pb, 1, 0);        /* mb coded */
1213
            put_bits(&s->pb,
1214
                inter_MCBPC_bits[cbpc + 4],
1215
                inter_MCBPC_code[cbpc + 4]);
1216
        }
1217
        if (s->h263_aic) {
1218
            /* XXX: currently, we do not try to use ac prediction */
1219
            put_bits(&s->pb, 1, 0);        /* no AC prediction */
1220
        }
1221
        cbpy = cbp >> 2;
1222
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1223
        if(s->dquant)
1224
            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1225

    
1226
        if(interleaved_stats){
1227
            s->misc_bits+= get_bits_diff(s);
1228
        }
1229
    }
1230

    
1231
    for(i=0; i<6; i++) {
1232
        /* encode each block */
1233
        h263_encode_block(s, block[i], i);
1234
    
1235
        /* Update INTRADC for decoding */
1236
        if (s->h263_aic && s->mb_intra) {
1237
            block[i][0] = rec_intradc[i];
1238
            
1239
        }
1240
    }
1241

    
1242
    if(interleaved_stats){
1243
        if (!s->mb_intra) {
1244
            s->p_tex_bits+= get_bits_diff(s);
1245
            s->f_count++;
1246
        }else{
1247
            s->i_tex_bits+= get_bits_diff(s);
1248
            s->i_count++;
1249
        }
1250
    }
1251
}
1252
#endif
1253

    
1254
void ff_h263_loop_filter(MpegEncContext * s){
1255
    int qp_c;
1256
    const int linesize  = s->linesize;
1257
    const int uvlinesize= s->uvlinesize;
1258
    const int xy = s->mb_y * s->mb_stride + s->mb_x;
1259
    uint8_t *dest_y = s->dest[0];
1260
    uint8_t *dest_cb= s->dest[1];
1261
    uint8_t *dest_cr= s->dest[2];
1262
    
1263
//    if(s->pict_type==B_TYPE && !s->readable) return;
1264

    
1265
    /*
1266
       Diag Top
1267
       Left Center
1268
    */
1269
    if(!IS_SKIP(s->current_picture.mb_type[xy])){
1270
        qp_c= s->qscale;
1271
        s->dsp.h263_v_loop_filter(dest_y+8*linesize  , linesize, qp_c);
1272
        s->dsp.h263_v_loop_filter(dest_y+8*linesize+8, linesize, qp_c);
1273
    }else
1274
        qp_c= 0;
1275

    
1276
    if(s->mb_y){
1277
        int qp_dt, qp_t, qp_tc;
1278

    
1279
        if(IS_SKIP(s->current_picture.mb_type[xy-s->mb_stride]))
1280
            qp_t=0;
1281
        else 
1282
            qp_t= s->current_picture.qscale_table[xy-s->mb_stride];
1283

    
1284
        if(qp_c) 
1285
            qp_tc= qp_c;
1286
        else
1287
            qp_tc= qp_t;
1288
            
1289
        if(qp_tc){
1290
            const int chroma_qp= s->chroma_qscale_table[qp_tc];
1291
            s->dsp.h263_v_loop_filter(dest_y  ,   linesize, qp_tc);
1292
            s->dsp.h263_v_loop_filter(dest_y+8,   linesize, qp_tc);
1293
        
1294
            s->dsp.h263_v_loop_filter(dest_cb , uvlinesize, chroma_qp);
1295
            s->dsp.h263_v_loop_filter(dest_cr , uvlinesize, chroma_qp);
1296
        }
1297
        
1298
        if(qp_t)
1299
            s->dsp.h263_h_loop_filter(dest_y-8*linesize+8  ,   linesize, qp_t);
1300
        
1301
        if(s->mb_x){
1302
            if(qp_t || IS_SKIP(s->current_picture.mb_type[xy-1-s->mb_stride]))
1303
                qp_dt= qp_t;
1304
            else
1305
                qp_dt= s->current_picture.qscale_table[xy-1-s->mb_stride];
1306
            
1307
            if(qp_dt){
1308
                const int chroma_qp= s->chroma_qscale_table[qp_dt];
1309
                s->dsp.h263_h_loop_filter(dest_y -8*linesize  ,   linesize, qp_dt);
1310
                s->dsp.h263_h_loop_filter(dest_cb-8*uvlinesize, uvlinesize, chroma_qp);
1311
                s->dsp.h263_h_loop_filter(dest_cb-8*uvlinesize, uvlinesize, chroma_qp);
1312
            }
1313
        }
1314
    }
1315

    
1316
    if(qp_c){
1317
        s->dsp.h263_h_loop_filter(dest_y +8,   linesize, qp_c);
1318
        if(s->mb_y + 1 == s->mb_height)
1319
            s->dsp.h263_h_loop_filter(dest_y+8*linesize+8,   linesize, qp_c);
1320
    }
1321
    
1322
    if(s->mb_x){
1323
        int qp_lc;
1324
        if(qp_c || IS_SKIP(s->current_picture.mb_type[xy-1]))
1325
            qp_lc= qp_c;
1326
        else
1327
            qp_lc= s->current_picture.qscale_table[xy-1];
1328
        
1329
        if(qp_lc){
1330
            s->dsp.h263_h_loop_filter(dest_y,   linesize, qp_lc);
1331
            if(s->mb_y + 1 == s->mb_height){
1332
                const int chroma_qp= s->chroma_qscale_table[qp_lc];
1333
                s->dsp.h263_h_loop_filter(dest_y +8*  linesize,   linesize, qp_lc);
1334
                s->dsp.h263_h_loop_filter(dest_cb             , uvlinesize, chroma_qp);
1335
                s->dsp.h263_h_loop_filter(dest_cr             , uvlinesize, chroma_qp);
1336
            }
1337
        }
1338
    }
1339
}
1340

    
1341
static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr)
1342
{
1343
    int x, y, wrap, a, c, pred_dc, scale;
1344
    int16_t *dc_val, *ac_val;
1345

    
1346
    /* find prediction */
1347
    if (n < 4) {
1348
        x = 2 * s->mb_x + 1 + (n & 1);
1349
        y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
1350
        wrap = s->mb_width * 2 + 2;
1351
        dc_val = s->dc_val[0];
1352
        ac_val = s->ac_val[0][0];
1353
        scale = s->y_dc_scale;
1354
    } else {
1355
        x = s->mb_x + 1;
1356
        y = s->mb_y + 1;
1357
        wrap = s->mb_width + 2;
1358
        dc_val = s->dc_val[n - 4 + 1];
1359
        ac_val = s->ac_val[n - 4 + 1][0];
1360
        scale = s->c_dc_scale;
1361
    }
1362
    /* B C
1363
     * A X 
1364
     */
1365
    a = dc_val[(x - 1) + (y) * wrap];
1366
    c = dc_val[(x) + (y - 1) * wrap];
1367
    
1368
    /* No prediction outside GOB boundary */
1369
    if (s->first_slice_line && ((n < 2) || (n > 3)))
1370
        c = 1024;
1371
    pred_dc = 1024;
1372
    /* just DC prediction */
1373
    if (a != 1024 && c != 1024)
1374
        pred_dc = (a + c) >> 1;
1375
    else if (a != 1024)
1376
        pred_dc = a;
1377
    else
1378
        pred_dc = c;
1379
    
1380
    /* we assume pred is positive */
1381
    //pred_dc = (pred_dc + (scale >> 1)) / scale;
1382
    *dc_val_ptr = &dc_val[x + y * wrap];
1383
    return pred_dc;
1384
}
1385

    
1386
static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1387
{
1388
    int x, y, wrap, a, c, pred_dc, scale, i;
1389
    int16_t *dc_val, *ac_val, *ac_val1;
1390

    
1391
    /* find prediction */
1392
    if (n < 4) {
1393
        x = 2 * s->mb_x + 1 + (n & 1);
1394
        y = 2 * s->mb_y + 1 + (n>> 1);
1395
        wrap = s->mb_width * 2 + 2;
1396
        dc_val = s->dc_val[0];
1397
        ac_val = s->ac_val[0][0];
1398
        scale = s->y_dc_scale;
1399
    } else {
1400
        x = s->mb_x + 1;
1401
        y = s->mb_y + 1;
1402
        wrap = s->mb_width + 2;
1403
        dc_val = s->dc_val[n - 4 + 1];
1404
        ac_val = s->ac_val[n - 4 + 1][0];
1405
        scale = s->c_dc_scale;
1406
    }
1407
    
1408
    ac_val += ((y) * wrap + (x)) * 16;
1409
    ac_val1 = ac_val;
1410
    
1411
    /* B C
1412
     * A X 
1413
     */
1414
    a = dc_val[(x - 1) + (y) * wrap];
1415
    c = dc_val[(x) + (y - 1) * wrap];
1416
    
1417
    /* No prediction outside GOB boundary */
1418
    if(s->first_slice_line && n!=3){
1419
        if(n!=2) c= 1024;
1420
        if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
1421
    }
1422
    
1423
    if (s->ac_pred) {
1424
        pred_dc = 1024;
1425
        if (s->h263_aic_dir) {
1426
            /* left prediction */
1427
            if (a != 1024) {
1428
                ac_val -= 16;
1429
                for(i=1;i<8;i++) {
1430
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1431
                }
1432
                pred_dc = a;
1433
            }
1434
        } else {
1435
            /* top prediction */
1436
            if (c != 1024) {
1437
                ac_val -= 16 * wrap;
1438
                for(i=1;i<8;i++) {
1439
                    block[s->dsp.idct_permutation[i   ]] += ac_val[i + 8];
1440
                }
1441
                pred_dc = c;
1442
            }
1443
        }
1444
    } else {
1445
        /* just DC prediction */
1446
        if (a != 1024 && c != 1024)
1447
            pred_dc = (a + c) >> 1;
1448
        else if (a != 1024)
1449
            pred_dc = a;
1450
        else
1451
            pred_dc = c;
1452
    }
1453
    
1454
    /* we assume pred is positive */
1455
    block[0]=block[0]*scale + pred_dc;
1456
    
1457
    if (block[0] < 0)
1458
        block[0] = 0;
1459
    else 
1460
        block[0] |= 1;
1461
    
1462
    /* Update AC/DC tables */
1463
    dc_val[(x) + (y) * wrap] = block[0];
1464
    
1465
    /* left copy */
1466
    for(i=1;i<8;i++)
1467
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1468
    /* top copy */
1469
    for(i=1;i<8;i++)
1470
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1471
}
1472

    
1473
int16_t *h263_pred_motion(MpegEncContext * s, int block, 
1474
                        int *px, int *py)
1475
{
1476
    int xy, wrap;
1477
    int16_t *A, *B, *C, *mot_val;
1478
    static const int off[4]= {2, 1, 1, -1};
1479

    
1480
    wrap = s->block_wrap[0];
1481
    xy = s->block_index[block];
1482

    
1483
    mot_val = s->motion_val[xy];
1484

    
1485
    A = s->motion_val[xy - 1];
1486
    /* special case for first (slice) line */
1487
    if (s->first_slice_line && block<3) {
1488
        // we cant just change some MVs to simulate that as we need them for the B frames (and ME)
1489
        // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1490
        if(block==0){ //most common case
1491
            if(s->mb_x  == s->resync_mb_x){ //rare
1492
                *px= *py = 0;
1493
            }else if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1494
                C = s->motion_val[xy + off[block] - wrap];
1495
                if(s->mb_x==0){
1496
                    *px = C[0];
1497
                    *py = C[1];
1498
                }else{
1499
                    *px = mid_pred(A[0], 0, C[0]);
1500
                    *py = mid_pred(A[1], 0, C[1]);
1501
                }
1502
            }else{
1503
                *px = A[0];
1504
                *py = A[1];
1505
            }
1506
        }else if(block==1){
1507
            if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1508
                C = s->motion_val[xy + off[block] - wrap];
1509
                *px = mid_pred(A[0], 0, C[0]);
1510
                *py = mid_pred(A[1], 0, C[1]);
1511
            }else{
1512
                *px = A[0];
1513
                *py = A[1];
1514
            }
1515
        }else{ /* block==2*/
1516
            B = s->motion_val[xy - wrap];
1517
            C = s->motion_val[xy + off[block] - wrap];
1518
            if(s->mb_x == s->resync_mb_x) //rare
1519
                A[0]=A[1]=0;
1520
    
1521
            *px = mid_pred(A[0], B[0], C[0]);
1522
            *py = mid_pred(A[1], B[1], C[1]);
1523
        }
1524
    } else {
1525
        B = s->motion_val[xy - wrap];
1526
        C = s->motion_val[xy + off[block] - wrap];
1527
        *px = mid_pred(A[0], B[0], C[0]);
1528
        *py = mid_pred(A[1], B[1], C[1]);
1529
    }
1530
    return mot_val;
1531
}
1532

    
1533
// identical to above but with s->current_picture->motion_val, the above one will be removed, and this renamed to it
1534
int16_t *h263_pred_motion2(MpegEncContext * s, int block, int dir,
1535
                        int *px, int *py)
1536
{
1537
    int xy, wrap;
1538
    int16_t *A, *B, *C, (*mot_val)[2];
1539
    static const int off[4]= {2, 1, 1, -1};
1540

    
1541
    wrap = s->b8_stride;
1542
    xy = s->mb_x + s->mb_y * wrap;
1543

    
1544
    mot_val = s->current_picture.motion_val[dir] + xy;
1545

    
1546
    A = mot_val[ - 1];
1547
    /* special case for first (slice) line */
1548
    if (s->first_slice_line && block<3) {
1549
        // we cant just change some MVs to simulate that as we need them for the B frames (and ME)
1550
        // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1551
        if(block==0){ //most common case
1552
            if(s->mb_x  == s->resync_mb_x){ //rare
1553
                *px= *py = 0;
1554
            }else if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1555
                C = mot_val[off[block] - wrap];
1556
                if(s->mb_x==0){
1557
                    *px = C[0];
1558
                    *py = C[1];
1559
                }else{
1560
                    *px = mid_pred(A[0], 0, C[0]);
1561
                    *py = mid_pred(A[1], 0, C[1]);
1562
                }
1563
            }else{
1564
                *px = A[0];
1565
                *py = A[1];
1566
            }
1567
        }else if(block==1){
1568
            if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1569
                C = mot_val[off[block] - wrap];
1570
                *px = mid_pred(A[0], 0, C[0]);
1571
                *py = mid_pred(A[1], 0, C[1]);
1572
            }else{
1573
                *px = A[0];
1574
                *py = A[1];
1575
            }
1576
        }else{ /* block==2*/
1577
            B = mot_val[ - wrap];
1578
            C = mot_val[off[block] - wrap];
1579
            if(s->mb_x == s->resync_mb_x) //rare
1580
                A[0]=A[1]=0;
1581
    
1582
            *px = mid_pred(A[0], B[0], C[0]);
1583
            *py = mid_pred(A[1], B[1], C[1]);
1584
        }
1585
    } else {
1586
        B = mot_val[ - wrap];
1587
        C = mot_val[off[block] - wrap];
1588
        *px = mid_pred(A[0], B[0], C[0]);
1589
        *py = mid_pred(A[1], B[1], C[1]);
1590
    }
1591
    return *mot_val;
1592
}
1593

    
1594
#ifdef CONFIG_ENCODERS
1595
static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
1596
{
1597
    int range, l, bit_size, sign, code, bits;
1598

    
1599
    if (val == 0) {
1600
        /* zero vector */
1601
        code = 0;
1602
        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1603
    } else {
1604
        bit_size = f_code - 1;
1605
        range = 1 << bit_size;
1606
        /* modulo encoding */
1607
        l = range * 32;
1608
#if 1
1609
        val+= l;
1610
        val&= 2*l-1;
1611
        val-= l;
1612
        sign = val>>31;
1613
        val= (val^sign)-sign;
1614
        sign&=1;
1615
#else
1616
        if (val < -l) {
1617
            val += 2*l;
1618
        } else if (val >= l) {
1619
            val -= 2*l;
1620
        }
1621

    
1622
        assert(val>=-l && val<l);
1623

    
1624
        if (val >= 0) {
1625
            sign = 0;
1626
        } else {
1627
            val = -val;
1628
            sign = 1;
1629
        }
1630
#endif
1631
        val--;
1632
        code = (val >> bit_size) + 1;
1633
        bits = val & (range - 1);
1634

    
1635
        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
1636
        if (bit_size > 0) {
1637
            put_bits(&s->pb, bit_size, bits);
1638
        }
1639
    }
1640

    
1641
}
1642

    
1643
/* Encode MV differences on H.263+ with Unrestricted MV mode */
1644
static void h263p_encode_umotion(MpegEncContext * s, int val)
1645
{
1646
    short sval = 0; 
1647
    short i = 0;
1648
    short n_bits = 0;
1649
    short temp_val;
1650
    int code = 0;
1651
    int tcode;
1652
    
1653
    if ( val == 0)
1654
        put_bits(&s->pb, 1, 1);
1655
    else if (val == 1)
1656
        put_bits(&s->pb, 3, 0);
1657
    else if (val == -1)
1658
        put_bits(&s->pb, 3, 2);
1659
    else {
1660
        
1661
        sval = ((val < 0) ? (short)(-val):(short)val);
1662
        temp_val = sval;
1663
        
1664
        while (temp_val != 0) {
1665
            temp_val = temp_val >> 1;
1666
            n_bits++;
1667
        }
1668
        
1669
        i = n_bits - 1;
1670
        while (i > 0) {
1671
            tcode = (sval & (1 << (i-1))) >> (i-1);
1672
            tcode = (tcode << 1) | 1;
1673
            code = (code << 2) | tcode;
1674
            i--;
1675
        }
1676
        code = ((code << 1) | (val < 0)) << 1;
1677
        put_bits(&s->pb, (2*n_bits)+1, code);
1678
        //printf("\nVal = %d\tCode = %d", sval, code);
1679
    }
1680
}
1681

    
1682
static void init_mv_penalty_and_fcode(MpegEncContext *s)
1683
{
1684
    int f_code;
1685
    int mv;
1686
    
1687
    if(mv_penalty==NULL)
1688
        mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1689
    
1690
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
1691
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1692
            int len;
1693

    
1694
            if(mv==0) len= mvtab[0][1];
1695
            else{
1696
                int val, bit_size, range, code;
1697

    
1698
                bit_size = s->f_code - 1;
1699
                range = 1 << bit_size;
1700

    
1701
                val=mv;
1702
                if (val < 0) 
1703
                    val = -val;
1704
                val--;
1705
                code = (val >> bit_size) + 1;
1706
                if(code<33){
1707
                    len= mvtab[code][1] + 1 + bit_size;
1708
                }else{
1709
                    len= mvtab[32][1] + 2 + bit_size;
1710
                }
1711
            }
1712

    
1713
            mv_penalty[f_code][mv+MAX_MV]= len;
1714
        }
1715
    }
1716

    
1717
    for(f_code=MAX_FCODE; f_code>0; f_code--){
1718
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1719
            fcode_tab[mv+MAX_MV]= f_code;
1720
        }
1721
    }
1722

    
1723
    for(mv=0; mv<MAX_MV*2+1; mv++){
1724
        umv_fcode_tab[mv]= 1;
1725
    }
1726
}
1727
#endif
1728

    
1729
#ifdef CONFIG_ENCODERS
1730

    
1731
static void init_uni_dc_tab(void)
1732
{
1733
    int level, uni_code, uni_len;
1734

    
1735
    for(level=-256; level<256; level++){
1736
        int size, v, l;
1737
        /* find number of bits */
1738
        size = 0;
1739
        v = abs(level);
1740
        while (v) {
1741
            v >>= 1;
1742
            size++;
1743
        }
1744

    
1745
        if (level < 0)
1746
            l= (-level) ^ ((1 << size) - 1);
1747
        else
1748
            l= level;
1749

    
1750
        /* luminance */
1751
        uni_code= DCtab_lum[size][0];
1752
        uni_len = DCtab_lum[size][1];
1753

    
1754
        if (size > 0) {
1755
            uni_code<<=size; uni_code|=l;
1756
            uni_len+=size;
1757
            if (size > 8){
1758
                uni_code<<=1; uni_code|=1;
1759
                uni_len++;
1760
            }
1761
        }
1762
        uni_DCtab_lum_bits[level+256]= uni_code;
1763
        uni_DCtab_lum_len [level+256]= uni_len;
1764

    
1765
        /* chrominance */
1766
        uni_code= DCtab_chrom[size][0];
1767
        uni_len = DCtab_chrom[size][1];
1768
        
1769
        if (size > 0) {
1770
            uni_code<<=size; uni_code|=l;
1771
            uni_len+=size;
1772
            if (size > 8){
1773
                uni_code<<=1; uni_code|=1;
1774
                uni_len++;
1775
            }
1776
        }
1777
        uni_DCtab_chrom_bits[level+256]= uni_code;
1778
        uni_DCtab_chrom_len [level+256]= uni_len;
1779

    
1780
    }
1781
}
1782

    
1783
#endif //CONFIG_ENCODERS
1784

    
1785
#ifdef CONFIG_ENCODERS
1786
static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1787
    int slevel, run, last;
1788
    
1789
    assert(MAX_LEVEL >= 64);
1790
    assert(MAX_RUN   >= 63);
1791

    
1792
    for(slevel=-64; slevel<64; slevel++){
1793
        if(slevel==0) continue;
1794
        for(run=0; run<64; run++){
1795
            for(last=0; last<=1; last++){
1796
                const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1797
                int level= slevel < 0 ? -slevel : slevel;
1798
                int sign= slevel < 0 ? 1 : 0;
1799
                int bits, len, code;
1800
                int level1, run1;
1801
                
1802
                len_tab[index]= 100;
1803
                     
1804
                /* ESC0 */
1805
                code= get_rl_index(rl, last, run, level);
1806
                bits= rl->table_vlc[code][0];
1807
                len=  rl->table_vlc[code][1];
1808
                bits=bits*2+sign; len++;
1809
                
1810
                if(code!=rl->n && len < len_tab[index]){
1811
                    bits_tab[index]= bits;
1812
                    len_tab [index]= len;
1813
                }
1814
#if 1
1815
                /* ESC1 */
1816
                bits= rl->table_vlc[rl->n][0];
1817
                len=  rl->table_vlc[rl->n][1];
1818
                bits=bits*2;    len++; //esc1
1819
                level1= level - rl->max_level[last][run];
1820
                if(level1>0){
1821
                    code= get_rl_index(rl, last, run, level1);
1822
                    bits<<= rl->table_vlc[code][1];
1823
                    len  += rl->table_vlc[code][1];
1824
                    bits += rl->table_vlc[code][0];
1825
                    bits=bits*2+sign; len++;
1826
                
1827
                    if(code!=rl->n && len < len_tab[index]){
1828
                        bits_tab[index]= bits;
1829
                        len_tab [index]= len;
1830
                    }
1831
                }
1832
#endif 
1833
#if 1
1834
                /* ESC2 */
1835
                bits= rl->table_vlc[rl->n][0];
1836
                len=  rl->table_vlc[rl->n][1];
1837
                bits=bits*4+2;    len+=2; //esc2
1838
                run1 = run - rl->max_run[last][level] - 1;
1839
                if(run1>=0){
1840
                    code= get_rl_index(rl, last, run1, level);
1841
                    bits<<= rl->table_vlc[code][1];
1842
                    len  += rl->table_vlc[code][1];
1843
                    bits += rl->table_vlc[code][0];
1844
                    bits=bits*2+sign; len++;
1845
                
1846
                    if(code!=rl->n && len < len_tab[index]){
1847
                        bits_tab[index]= bits;
1848
                        len_tab [index]= len;
1849
                    }
1850
                }
1851
#endif           
1852
                /* ESC3 */        
1853
                bits= rl->table_vlc[rl->n][0];
1854
                len = rl->table_vlc[rl->n][1];
1855
                bits=bits*4+3;    len+=2; //esc3
1856
                bits=bits*2+last; len++;
1857
                bits=bits*64+run; len+=6;
1858
                bits=bits*2+1;    len++;  //marker
1859
                bits=bits*4096+(slevel&0xfff); len+=12;
1860
                bits=bits*2+1;    len++;  //marker
1861
                
1862
                if(len < len_tab[index]){
1863
                    bits_tab[index]= bits;
1864
                    len_tab [index]= len;
1865
                }
1866
            }
1867
        }
1868
    }
1869
}
1870

    
1871
void h263_encode_init(MpegEncContext *s)
1872
{
1873
    static int done = 0;
1874

    
1875
    if (!done) {
1876
        done = 1;
1877

    
1878
        init_uni_dc_tab();
1879

    
1880
        init_rl(&rl_inter);
1881
        init_rl(&rl_intra);
1882
        init_rl(&rl_intra_aic);
1883
        
1884
        init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1885
        init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1886

    
1887
        init_mv_penalty_and_fcode(s);
1888
    }
1889
    s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
1890
    
1891
    // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
1892
    switch(s->codec_id){
1893
    case CODEC_ID_MPEG4:
1894
        s->fcode_tab= fcode_tab;
1895
        s->min_qcoeff= -2048;
1896
        s->max_qcoeff=  2047;
1897
        s->intra_ac_vlc_length     = uni_mpeg4_intra_rl_len;
1898
        s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;
1899
        s->inter_ac_vlc_length     = uni_mpeg4_inter_rl_len;
1900
        s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;
1901
        s->luma_dc_vlc_length= uni_DCtab_lum_len;
1902
        s->chroma_dc_vlc_length= uni_DCtab_chrom_len;
1903
        s->ac_esc_length= 7+2+1+6+1+12+1;
1904
        
1905
        if(s->flags & CODEC_FLAG_GLOBAL_HEADER){
1906

    
1907
            s->avctx->extradata= av_malloc(1024);
1908
            init_put_bits(&s->pb, s->avctx->extradata, 1024);
1909
            
1910
            mpeg4_encode_visual_object_header(s);
1911
            mpeg4_encode_vol_header(s, 0, 0);
1912

    
1913
//            ff_mpeg4_stuffing(&s->pb); ?
1914
            flush_put_bits(&s->pb);
1915
            s->avctx->extradata_size= (get_bit_count(&s->pb)+7)>>3;
1916
        }
1917
        
1918
        break;
1919
    case CODEC_ID_H263P:
1920
        if(s->umvplus)
1921
            s->fcode_tab= umv_fcode_tab;
1922
        else
1923
            s->fcode_tab= fcode_tab;
1924
        if(s->modified_quant){
1925
            s->min_qcoeff= -2047;
1926
            s->max_qcoeff=  2047;
1927
        }else{
1928
            s->min_qcoeff= -127;
1929
            s->max_qcoeff=  127;
1930
        }
1931
        break;
1932
        //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later 
1933
    case CODEC_ID_FLV1:
1934
        if (s->h263_flv > 1) {
1935
            s->min_qcoeff= -1023;
1936
            s->max_qcoeff=  1023;
1937
        } else {
1938
            s->min_qcoeff= -127;
1939
            s->max_qcoeff=  127;
1940
        }
1941
        s->y_dc_scale_table=
1942
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1943
        break;
1944
    default: //nothing needed default table allready set in mpegvideo.c
1945
        s->min_qcoeff= -127;
1946
        s->max_qcoeff=  127;
1947
        s->y_dc_scale_table=
1948
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1949
    }
1950
}
1951

    
1952
/**
1953
 * encodes a 8x8 block.
1954
 * @param block the 8x8 block
1955
 * @param n block index (0-3 are luma, 4-5 are chroma)
1956
 */
1957
static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
1958
{
1959
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
1960
    RLTable *rl;
1961

    
1962
    rl = &rl_inter;
1963
    if (s->mb_intra && !s->h263_aic) {
1964
        /* DC coef */
1965
        level = block[0];
1966
        /* 255 cannot be represented, so we clamp */
1967
        if (level > 254) {
1968
            level = 254;
1969
            block[0] = 254;
1970
        }
1971
        /* 0 cannot be represented also */
1972
        else if (level < 1) {
1973
            level = 1;
1974
            block[0] = 1;
1975
        }
1976
        if (level == 128) //FIXME check rv10
1977
            put_bits(&s->pb, 8, 0xff);
1978
        else
1979
            put_bits(&s->pb, 8, level & 0xff);
1980
        i = 1;
1981
    } else {
1982
        i = 0;
1983
        if (s->h263_aic && s->mb_intra)
1984
            rl = &rl_intra_aic;
1985
            
1986
        if(s->alt_inter_vlc && !s->mb_intra){
1987
            int aic_vlc_bits=0;
1988
            int inter_vlc_bits=0;
1989
            int wrong_pos=-1;
1990
            int aic_code;
1991
            
1992
            last_index = s->block_last_index[n];
1993
            last_non_zero = i - 1;
1994
            for (; i <= last_index; i++) {
1995
                j = s->intra_scantable.permutated[i];
1996
                level = block[j];
1997
                if (level) {
1998
                    run = i - last_non_zero - 1;
1999
                    last = (i == last_index);
2000
                    
2001
                    if(level<0) level= -level;
2002
                
2003
                    code = get_rl_index(rl, last, run, level);
2004
                    aic_code = get_rl_index(&rl_intra_aic, last, run, level);
2005
                    inter_vlc_bits += rl->table_vlc[code][1]+1;
2006
                    aic_vlc_bits   += rl_intra_aic.table_vlc[aic_code][1]+1;
2007

    
2008
                    if (code == rl->n) {
2009
                        inter_vlc_bits += 1+6+8-1;
2010
                    }                
2011
                    if (aic_code == rl_intra_aic.n) {
2012
                        aic_vlc_bits += 1+6+8-1;
2013
                        wrong_pos += run + 1;
2014
                    }else
2015
                        wrong_pos += wrong_run[aic_code];
2016
                    last_non_zero = i;
2017
                }    
2018
            }
2019
            i = 0;
2020
            if(aic_vlc_bits < inter_vlc_bits && wrong_pos > 63)
2021
                rl = &rl_intra_aic;
2022
        }
2023
    }
2024
   
2025
    /* AC coefs */
2026
    last_index = s->block_last_index[n];
2027
    last_non_zero = i - 1;
2028
    for (; i <= last_index; i++) {
2029
        j = s->intra_scantable.permutated[i];
2030
        level = block[j];
2031
        if (level) {
2032
            run = i - last_non_zero - 1;
2033
            last = (i == last_index);
2034
            sign = 0;
2035
            slevel = level;
2036
            if (level < 0) {
2037
                sign = 1;
2038
                level = -level;
2039
            }
2040
            code = get_rl_index(rl, last, run, level);
2041
            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2042
            if (code == rl->n) {
2043
              if(s->h263_flv <= 1){
2044
                put_bits(&s->pb, 1, last);
2045
                put_bits(&s->pb, 6, run);
2046
                
2047
                assert(slevel != 0);
2048

    
2049
                if(slevel < 128 && slevel > -128) 
2050
                    put_bits(&s->pb, 8, slevel & 0xff);
2051
                else{
2052
                    put_bits(&s->pb, 8, 128);
2053
                    put_bits(&s->pb, 5, slevel & 0x1f);
2054
                    put_bits(&s->pb, 6, (slevel>>5)&0x3f);
2055
                }
2056
              }else{
2057
                    if(slevel < 64 && slevel > -64) {
2058
                        /* 7-bit level */
2059
                        put_bits(&s->pb, 1, 0);
2060
                        put_bits(&s->pb, 1, last);
2061
                        put_bits(&s->pb, 6, run);
2062

    
2063
                        put_bits(&s->pb, 7, slevel & 0x7f);
2064
                    } else {
2065
                        /* 11-bit level */
2066
                        put_bits(&s->pb, 1, 1);
2067
                        put_bits(&s->pb, 1, last);
2068
                        put_bits(&s->pb, 6, run);
2069

    
2070
                        put_bits(&s->pb, 11, slevel & 0x7ff);
2071
                    }
2072
              }
2073
            } else {
2074
                put_bits(&s->pb, 1, sign);
2075
            }
2076
            last_non_zero = i;
2077
        }
2078
    }
2079
}
2080
#endif
2081

    
2082
#ifdef CONFIG_ENCODERS
2083

    
2084
/***************************************************/
2085
/**
2086
 * add mpeg4 stuffing bits (01...1)
2087
 */
2088
void ff_mpeg4_stuffing(PutBitContext * pbc)
2089
{
2090
    int length;
2091
    put_bits(pbc, 1, 0);
2092
    length= (-get_bit_count(pbc))&7;
2093
    if(length) put_bits(pbc, length, (1<<length)-1);
2094
}
2095

    
2096
/* must be called before writing the header */
2097
void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
2098
    int time_div, time_mod;
2099

    
2100
    if(s->current_picture_ptr->pts)
2101
        s->time= (s->current_picture_ptr->pts*s->time_increment_resolution + 500*1000)/(1000*1000);
2102
    else
2103
        s->time= av_rescale(picture_number*(int64_t)s->avctx->frame_rate_base, s->time_increment_resolution, s->avctx->frame_rate);
2104
    time_div= s->time/s->time_increment_resolution;
2105
    time_mod= s->time%s->time_increment_resolution;
2106

    
2107
    if(s->pict_type==B_TYPE){
2108
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
2109
    }else{
2110
        s->last_time_base= s->time_base;
2111
        s->time_base= time_div;
2112
        s->pp_time= s->time - s->last_non_b_time;
2113
        s->last_non_b_time= s->time;
2114
    }
2115
}
2116

    
2117
static void mpeg4_encode_gop_header(MpegEncContext * s){
2118
    int hours, minutes, seconds;
2119
    
2120
    put_bits(&s->pb, 16, 0);
2121
    put_bits(&s->pb, 16, GOP_STARTCODE);
2122
    
2123
    seconds= s->time/s->time_increment_resolution;
2124
    minutes= seconds/60; seconds %= 60;
2125
    hours= minutes/60; minutes %= 60;
2126
    hours%=24;
2127

    
2128
    put_bits(&s->pb, 5, hours);
2129
    put_bits(&s->pb, 6, minutes);
2130
    put_bits(&s->pb, 1, 1);
2131
    put_bits(&s->pb, 6, seconds);
2132
    
2133
    put_bits(&s->pb, 1, 0); //closed gov == NO
2134
    put_bits(&s->pb, 1, 0); //broken link == NO
2135

    
2136
    ff_mpeg4_stuffing(&s->pb);
2137
}
2138

    
2139
static void mpeg4_encode_visual_object_header(MpegEncContext * s){
2140
    int profile_and_level_indication;
2141
    int vo_ver_id;
2142
    
2143
    if(s->max_b_frames || s->quarter_sample){
2144
        profile_and_level_indication= 0xF1; // adv simple level 1
2145
        vo_ver_id= 5;
2146
    }else{
2147
        profile_and_level_indication= 0x01; // simple level 1
2148
        vo_ver_id= 1;
2149
    }
2150
    //FIXME levels
2151

    
2152
    put_bits(&s->pb, 16, 0);
2153
    put_bits(&s->pb, 16, VOS_STARTCODE);
2154

    
2155
    put_bits(&s->pb, 8, profile_and_level_indication);
2156

    
2157
    put_bits(&s->pb, 16, 0);
2158
    put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
2159
    
2160
    put_bits(&s->pb, 1, 1);
2161
        put_bits(&s->pb, 4, vo_ver_id);
2162
        put_bits(&s->pb, 3, 1); //priority
2163
 
2164
    put_bits(&s->pb, 4, 1); //visual obj type== video obj
2165
    
2166
    put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
2167

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

    
2171
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
2172
{
2173
    int vo_ver_id;
2174

    
2175
    if(s->max_b_frames || s->quarter_sample){
2176
        vo_ver_id= 5;
2177
        s->vo_type= ADV_SIMPLE_VO_TYPE;
2178
    }else{
2179
        vo_ver_id= 1;
2180
        s->vo_type= SIMPLE_VO_TYPE;
2181
    }
2182

    
2183
    put_bits(&s->pb, 16, 0);
2184
    put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
2185
    put_bits(&s->pb, 16, 0);
2186
    put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
2187

    
2188
    put_bits(&s->pb, 1, 0);                /* random access vol */
2189
    put_bits(&s->pb, 8, s->vo_type);        /* video obj type indication */
2190
    put_bits(&s->pb, 1, 1);                /* is obj layer id= yes */
2191
      put_bits(&s->pb, 4, vo_ver_id);        /* is obj layer ver id */
2192
      put_bits(&s->pb, 3, 1);                /* is obj layer priority */
2193
    
2194
    aspect_to_info(s, s->avctx->sample_aspect_ratio);
2195

    
2196
    put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
2197
    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
2198
        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
2199
        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
2200
    }
2201

    
2202
    if(s->low_delay){
2203
        put_bits(&s->pb, 1, 1);                /* vol control parameters= yes */
2204
        put_bits(&s->pb, 2, 1);                /* chroma format YUV 420/YV12 */
2205
        put_bits(&s->pb, 1, s->low_delay);
2206
        put_bits(&s->pb, 1, 0);                /* vbv parameters= no */
2207
    }else{
2208
        put_bits(&s->pb, 1, 0);                /* vol control parameters= no */
2209
    }
2210

    
2211
    put_bits(&s->pb, 2, RECT_SHAPE);        /* vol shape= rectangle */
2212
    put_bits(&s->pb, 1, 1);                /* marker bit */
2213
    
2214
    put_bits(&s->pb, 16, s->time_increment_resolution);
2215
    if (s->time_increment_bits < 1)
2216
        s->time_increment_bits = 1;
2217
    put_bits(&s->pb, 1, 1);                /* marker bit */
2218
    put_bits(&s->pb, 1, 0);                /* fixed vop rate=no */
2219
    put_bits(&s->pb, 1, 1);                /* marker bit */
2220
    put_bits(&s->pb, 13, s->width);        /* vol width */
2221
    put_bits(&s->pb, 1, 1);                /* marker bit */
2222
    put_bits(&s->pb, 13, s->height);        /* vol height */
2223
    put_bits(&s->pb, 1, 1);                /* marker bit */
2224
    put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
2225
    put_bits(&s->pb, 1, 1);                /* obmc disable */
2226
    if (vo_ver_id == 1) {
2227
        put_bits(&s->pb, 1, s->vol_sprite_usage=0);                /* sprite enable */
2228
    }else{
2229
        put_bits(&s->pb, 2, s->vol_sprite_usage=0);                /* sprite enable */
2230
    }
2231
    
2232
    s->quant_precision=5;
2233
    put_bits(&s->pb, 1, 0);                /* not 8 bit == false */
2234
    put_bits(&s->pb, 1, s->mpeg_quant);        /* quant type= (0=h263 style)*/
2235

    
2236
    if(s->mpeg_quant){
2237
        ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
2238
        ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
2239
    }
2240

    
2241
    if (vo_ver_id != 1)
2242
        put_bits(&s->pb, 1, s->quarter_sample);
2243
    put_bits(&s->pb, 1, 1);                /* complexity estimation disable */
2244
    s->resync_marker= s->rtp_mode;
2245
    put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
2246
    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
2247
    if(s->data_partitioning){
2248
        put_bits(&s->pb, 1, 0);                /* no rvlc */
2249
    }
2250

    
2251
    if (vo_ver_id != 1){
2252
        put_bits(&s->pb, 1, 0);                /* newpred */
2253
        put_bits(&s->pb, 1, 0);                /* reduced res vop */
2254
    }
2255
    put_bits(&s->pb, 1, 0);                /* scalability */
2256
    
2257
    ff_mpeg4_stuffing(&s->pb);
2258

    
2259
    /* user data */
2260
    if(!(s->flags & CODEC_FLAG_BITEXACT)){
2261
        put_bits(&s->pb, 16, 0);
2262
        put_bits(&s->pb, 16, 0x1B2);        /* user_data */
2263
        put_string(&s->pb, LIBAVCODEC_IDENT);
2264
        ff_mpeg4_stuffing(&s->pb);
2265
    }
2266
}
2267

    
2268
/* write mpeg4 VOP header */
2269
void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
2270
{
2271
    int time_incr;
2272
    int time_div, time_mod;
2273
    
2274
    if(s->pict_type==I_TYPE){
2275
        if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
2276
            if(s->strict_std_compliance < 2) //HACK, the reference sw is buggy
2277
                mpeg4_encode_visual_object_header(s);
2278
            if(s->strict_std_compliance < 2 || picture_number==0) //HACK, the reference sw is buggy
2279
                mpeg4_encode_vol_header(s, 0, 0);
2280
        }
2281
        mpeg4_encode_gop_header(s);
2282
    }
2283
    
2284
    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
2285

    
2286
//printf("num:%d rate:%d base:%d\n", s->picture_number, s->frame_rate, FRAME_RATE_BASE);
2287
    
2288
    put_bits(&s->pb, 16, 0);                /* vop header */
2289
    put_bits(&s->pb, 16, VOP_STARTCODE);        /* vop header */
2290
    put_bits(&s->pb, 2, s->pict_type - 1);        /* pict type: I = 0 , P = 1 */
2291

    
2292
    time_div= s->time/s->time_increment_resolution;
2293
    time_mod= s->time%s->time_increment_resolution;
2294
    time_incr= time_div - s->last_time_base;
2295
    while(time_incr--)
2296
        put_bits(&s->pb, 1, 1);
2297
        
2298
    put_bits(&s->pb, 1, 0);
2299

    
2300
    put_bits(&s->pb, 1, 1);        /* marker */
2301
    put_bits(&s->pb, s->time_increment_bits, time_mod);        /* time increment */
2302
    put_bits(&s->pb, 1, 1);        /* marker */
2303
    put_bits(&s->pb, 1, 1);        /* vop coded */
2304
    if (    s->pict_type == P_TYPE 
2305
        || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
2306
        put_bits(&s->pb, 1, s->no_rounding);        /* rounding type */
2307
    }
2308
    put_bits(&s->pb, 3, 0);        /* intra dc VLC threshold */
2309
    if(!s->progressive_sequence){
2310
         put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
2311
         put_bits(&s->pb, 1, s->alternate_scan);
2312
    }
2313
    //FIXME sprite stuff
2314

    
2315
    put_bits(&s->pb, 5, s->qscale);
2316

    
2317
    if (s->pict_type != I_TYPE)
2318
        put_bits(&s->pb, 3, s->f_code);        /* fcode_for */
2319
    if (s->pict_type == B_TYPE)
2320
        put_bits(&s->pb, 3, s->b_code);        /* fcode_back */
2321
    //    printf("****frame %d\n", picture_number);
2322

    
2323
     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support 
2324
     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
2325
}
2326

    
2327
#endif //CONFIG_ENCODERS
2328

    
2329
/**
2330
 * set qscale and update qscale dependant variables.
2331
 */
2332
void ff_set_qscale(MpegEncContext * s, int qscale)
2333
{
2334
    if (qscale < 1)
2335
        qscale = 1;
2336
    else if (qscale > 31)
2337
        qscale = 31;
2338
        
2339
    s->qscale = qscale;
2340
    s->chroma_qscale= s->chroma_qscale_table[qscale];
2341

    
2342
    s->y_dc_scale= s->y_dc_scale_table[ qscale ];
2343
    s->c_dc_scale= s->c_dc_scale_table[ s->chroma_qscale ];
2344
}
2345

    
2346
/**
2347
 * predicts the dc.
2348
 * @param n block index (0-3 are luma, 4-5 are chroma)
2349
 * @param dc_val_ptr a pointer to the dc_val entry for the current MB will be stored here
2350
 * @param dir_ptr pointer to an integer where the prediction direction will be stored
2351
 * @return the quantized predicted dc
2352
 */
2353
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr)
2354
{
2355
    int a, b, c, wrap, pred, scale;
2356
    uint16_t *dc_val;
2357

    
2358
    /* find prediction */
2359
    if (n < 4) {
2360
        scale = s->y_dc_scale;
2361
    } else {
2362
        scale = s->c_dc_scale;
2363
    }
2364
    if(IS_3IV1)
2365
        scale= 8;
2366

    
2367
    wrap= s->block_wrap[n];
2368
    dc_val = s->dc_val[0] + s->block_index[n];
2369

    
2370
    /* B C
2371
     * A X 
2372
     */
2373
    a = dc_val[ - 1];
2374
    b = dc_val[ - 1 - wrap];
2375
    c = dc_val[ - wrap];
2376

    
2377
    /* outside slice handling (we cant do that by memset as we need the dc for error resilience) */
2378
    if(s->first_slice_line && n!=3){
2379
        if(n!=2) b=c= 1024;
2380
        if(n!=1 && s->mb_x == s->resync_mb_x) b=a= 1024;
2381
    }
2382
    if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1){
2383
        if(n==0 || n==4 || n==5)
2384
            b=1024;
2385
    }
2386

    
2387
    if (abs(a - b) < abs(b - c)) {
2388
        pred = c;
2389
        *dir_ptr = 1; /* top */
2390
    } else {
2391
        pred = a;
2392
        *dir_ptr = 0; /* left */
2393
    }
2394
    /* we assume pred is positive */
2395
    pred = FASTDIV((pred + (scale >> 1)), scale);
2396

    
2397
    /* prepare address for prediction update */
2398
    *dc_val_ptr = &dc_val[0];
2399

    
2400
    return pred;
2401
}
2402

    
2403
/**
2404
 * predicts the ac.
2405
 * @param n block index (0-3 are luma, 4-5 are chroma)
2406
 * @param dir the ac prediction direction
2407
 */
2408
void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
2409
                   int dir)
2410
{
2411
    int i;
2412
    int16_t *ac_val, *ac_val1;
2413
    int8_t * const qscale_table= s->current_picture.qscale_table;
2414

    
2415
    /* find prediction */
2416
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
2417
    ac_val1 = ac_val;
2418
    if (s->ac_pred) {
2419
        if (dir == 0) {
2420
            const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
2421
            /* left prediction */
2422
            ac_val -= 16;
2423
            
2424
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
2425
                /* same qscale */
2426
                for(i=1;i<8;i++) {
2427
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
2428
                }
2429
            }else{
2430
                /* different qscale, we must rescale */
2431
                for(i=1;i<8;i++) {
2432
                    block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
2433
                }
2434
            }
2435
        } else {
2436
            const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
2437
            /* top prediction */
2438
            ac_val -= 16 * s->block_wrap[n];
2439

    
2440
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
2441
                /* same qscale */
2442
                for(i=1;i<8;i++) {
2443
                    block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
2444
                }
2445
            }else{
2446
                /* different qscale, we must rescale */
2447
                for(i=1;i<8;i++) {
2448
                    block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
2449
                }
2450
            }
2451
        }
2452
    }
2453
    /* left copy */
2454
    for(i=1;i<8;i++)
2455
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
2456

    
2457
    /* top copy */
2458
    for(i=1;i<8;i++)
2459
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
2460

    
2461
}
2462

    
2463
#ifdef CONFIG_ENCODERS
2464

    
2465
/**
2466
 * encodes the dc value.
2467
 * @param n block index (0-3 are luma, 4-5 are chroma)
2468
 */
2469
static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
2470
{
2471
#if 1
2472
//    if(level<-255 || level>255) printf("dc overflow\n");
2473
    level+=256;
2474
    if (n < 4) {
2475
        /* luminance */
2476
        put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
2477
    } else {
2478
        /* chrominance */
2479
        put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
2480
    }
2481
#else
2482
    int size, v;
2483
    /* find number of bits */
2484
    size = 0;
2485
    v = abs(level);
2486
    while (v) {
2487
        v >>= 1;
2488
        size++;
2489
    }
2490

    
2491
    if (n < 4) {
2492
        /* luminance */
2493
        put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
2494
    } else {
2495
        /* chrominance */
2496
        put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
2497
    }
2498

    
2499
    /* encode remaining bits */
2500
    if (size > 0) {
2501
        if (level < 0)
2502
            level = (-level) ^ ((1 << size) - 1);
2503
        put_bits(&s->pb, size, level);
2504
        if (size > 8)
2505
            put_bits(&s->pb, 1, 1);
2506
    }
2507
#endif
2508
}
2509

    
2510
/**
2511
 * encodes a 8x8 block
2512
 * @param n block index (0-3 are luma, 4-5 are chroma)
2513
 */
2514
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2515
                               uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
2516
{
2517
    int i, last_non_zero;
2518
#if 0 //variables for the outcommented version
2519
    int code, sign, last;
2520
#endif
2521
    const RLTable *rl;
2522
    uint32_t *bits_tab;
2523
    uint8_t *len_tab;
2524
    const int last_index = s->block_last_index[n];
2525

    
2526
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2527
        /* mpeg4 based DC predictor */
2528
        mpeg4_encode_dc(dc_pb, intra_dc, n);
2529
        if(last_index<1) return;
2530
        i = 1;
2531
        rl = &rl_intra;
2532
        bits_tab= uni_mpeg4_intra_rl_bits;
2533
        len_tab = uni_mpeg4_intra_rl_len;
2534
    } else {
2535
        if(last_index<0) return;
2536
        i = 0;
2537
        rl = &rl_inter;
2538
        bits_tab= uni_mpeg4_inter_rl_bits;
2539
        len_tab = uni_mpeg4_inter_rl_len;
2540
    }
2541

    
2542
    /* AC coefs */
2543
    last_non_zero = i - 1;
2544
#if 1
2545
    for (; i < last_index; i++) {
2546
        int level = block[ scan_table[i] ];
2547
        if (level) {
2548
            int run = i - last_non_zero - 1;
2549
            level+=64;
2550
            if((level&(~127)) == 0){
2551
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2552
                put_bits(ac_pb, len_tab[index], bits_tab[index]);
2553
            }else{ //ESC3
2554
                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);
2555
            }
2556
            last_non_zero = i;
2557
        }
2558
    }
2559
    /*if(i<=last_index)*/{
2560
        int level = block[ scan_table[i] ];
2561
        int run = i - last_non_zero - 1;
2562
        level+=64;
2563
        if((level&(~127)) == 0){
2564
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2565
            put_bits(ac_pb, len_tab[index], bits_tab[index]);
2566
        }else{ //ESC3
2567
            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);
2568
        }
2569
    }
2570
#else
2571
    for (; i <= last_index; i++) {
2572
        const int slevel = block[ scan_table[i] ];
2573
        if (slevel) {
2574
            int level;
2575
            int run = i - last_non_zero - 1;
2576
            last = (i == last_index);
2577
            sign = 0;
2578
            level = slevel;
2579
            if (level < 0) {
2580
                sign = 1;
2581
                level = -level;
2582
            }
2583
            code = get_rl_index(rl, last, run, level);
2584
            put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2585
            if (code == rl->n) {
2586
                int level1, run1;
2587
                level1 = level - rl->max_level[last][run];
2588
                if (level1 < 1) 
2589
                    goto esc2;
2590
                code = get_rl_index(rl, last, run, level1);
2591
                if (code == rl->n) {
2592
                esc2:
2593
                    put_bits(ac_pb, 1, 1);
2594
                    if (level > MAX_LEVEL)
2595
                        goto esc3;
2596
                    run1 = run - rl->max_run[last][level] - 1;
2597
                    if (run1 < 0)
2598
                        goto esc3;
2599
                    code = get_rl_index(rl, last, run1, level);
2600
                    if (code == rl->n) {
2601
                    esc3:
2602
                        /* third escape */
2603
                        put_bits(ac_pb, 1, 1);
2604
                        put_bits(ac_pb, 1, last);
2605
                        put_bits(ac_pb, 6, run);
2606
                        put_bits(ac_pb, 1, 1);
2607
                        put_bits(ac_pb, 12, slevel & 0xfff);
2608
                        put_bits(ac_pb, 1, 1);
2609
                    } else {
2610
                        /* second escape */
2611
                        put_bits(ac_pb, 1, 0);
2612
                        put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2613
                        put_bits(ac_pb, 1, sign);
2614
                    }
2615
                } else {
2616
                    /* first escape */
2617
                    put_bits(ac_pb, 1, 0);
2618
                    put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2619
                    put_bits(ac_pb, 1, sign);
2620
                }
2621
            } else {
2622
                put_bits(ac_pb, 1, sign);
2623
            }
2624
            last_non_zero = i;
2625
        }
2626
    }
2627
#endif
2628
}
2629

    
2630
static inline int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2631
                               uint8_t *scan_table)
2632
{
2633
    int i, last_non_zero;
2634
    const RLTable *rl;
2635
    uint8_t *len_tab;
2636
    const int last_index = s->block_last_index[n];
2637
    int len=0;
2638

    
2639
    if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2640
        /* mpeg4 based DC predictor */
2641
        //mpeg4_encode_dc(dc_pb, intra_dc, n); //FIXME
2642
        if(last_index<1) return len;
2643
        i = 1;
2644
        rl = &rl_intra;
2645
        len_tab = uni_mpeg4_intra_rl_len;
2646
    } else {
2647
        if(last_index<0) return 0;
2648
        i = 0;
2649
        rl = &rl_inter;
2650
        len_tab = uni_mpeg4_inter_rl_len;
2651
    }
2652

    
2653
    /* AC coefs */
2654
    last_non_zero = i - 1;
2655
    for (; i < last_index; i++) {
2656
        int level = block[ scan_table[i] ];
2657
        if (level) {
2658
            int run = i - last_non_zero - 1;
2659
            level+=64;
2660
            if((level&(~127)) == 0){
2661
                const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2662
                len += len_tab[index];
2663
            }else{ //ESC3
2664
                len += 7+2+1+6+1+12+1;
2665
            }
2666
            last_non_zero = i;
2667
        }
2668
    }
2669
    /*if(i<=last_index)*/{
2670
        int level = block[ scan_table[i] ];
2671
        int run = i - last_non_zero - 1;
2672
        level+=64;
2673
        if((level&(~127)) == 0){
2674
            const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2675
            len += len_tab[index];
2676
        }else{ //ESC3
2677
            len += 7+2+1+6+1+12+1;
2678
        }
2679
    }
2680
    
2681
    return len;
2682
}
2683

    
2684
#endif
2685

    
2686

    
2687
/***********************************************/
2688
/* decoding */
2689

    
2690
static VLC intra_MCBPC_vlc;
2691
static VLC inter_MCBPC_vlc;
2692
static VLC cbpy_vlc;
2693
static VLC mv_vlc;
2694
static VLC dc_lum, dc_chrom;
2695
static VLC sprite_trajectory;
2696
static VLC mb_type_b_vlc;
2697
static VLC h263_mbtype_b_vlc;
2698
static VLC cbpc_b_vlc;
2699

    
2700
void init_vlc_rl(RLTable *rl)
2701
{
2702
    int i, q;
2703
    
2704
    init_vlc(&rl->vlc, 9, rl->n + 1, 
2705
             &rl->table_vlc[0][1], 4, 2,
2706
             &rl->table_vlc[0][0], 4, 2);
2707

    
2708
    
2709
    for(q=0; q<32; q++){
2710
        int qmul= q*2;
2711
        int qadd= (q-1)|1;
2712
        
2713
        if(q==0){
2714
            qmul=1;
2715
            qadd=0;
2716
        }
2717
        
2718
        rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2719
        for(i=0; i<rl->vlc.table_size; i++){
2720
            int code= rl->vlc.table[i][0];
2721
            int len = rl->vlc.table[i][1];
2722
            int level, run;
2723
        
2724
            if(len==0){ // illegal code
2725
                run= 66;
2726
                level= MAX_LEVEL;
2727
            }else if(len<0){ //more bits needed
2728
                run= 0;
2729
                level= code;
2730
            }else{
2731
                if(code==rl->n){ //esc
2732
                    run= 66;
2733
                    level= 0;
2734
                }else{
2735
                    run=   rl->table_run  [code] + 1;
2736
                    level= rl->table_level[code] * qmul + qadd;
2737
                    if(code >= rl->last) run+=192;
2738
                }
2739
            }
2740
            rl->rl_vlc[q][i].len= len;
2741
            rl->rl_vlc[q][i].level= level;
2742
            rl->rl_vlc[q][i].run= run;
2743
        }
2744
    }
2745
}
2746

    
2747
/* init vlcs */
2748

    
2749
/* XXX: find a better solution to handle static init */
2750
void h263_decode_init_vlc(MpegEncContext *s)
2751
{
2752
    static int done = 0;
2753

    
2754
    if (!done) {
2755
        done = 1;
2756

    
2757
        init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 9, 
2758
                 intra_MCBPC_bits, 1, 1,
2759
                 intra_MCBPC_code, 1, 1);
2760
        init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 28, 
2761
                 inter_MCBPC_bits, 1, 1,
2762
                 inter_MCBPC_code, 1, 1);
2763
        init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,
2764
                 &cbpy_tab[0][1], 2, 1,
2765
                 &cbpy_tab[0][0], 2, 1);
2766
        init_vlc(&mv_vlc, MV_VLC_BITS, 33,
2767
                 &mvtab[0][1], 2, 1,
2768
                 &mvtab[0][0], 2, 1);
2769
        init_rl(&rl_inter);
2770
        init_rl(&rl_intra);
2771
        init_rl(&rvlc_rl_inter);
2772
        init_rl(&rvlc_rl_intra);
2773
        init_rl(&rl_intra_aic);
2774
        init_vlc_rl(&rl_inter);
2775
        init_vlc_rl(&rl_intra);
2776
        init_vlc_rl(&rvlc_rl_inter);
2777
        init_vlc_rl(&rvlc_rl_intra);
2778
        init_vlc_rl(&rl_intra_aic);
2779
        init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2780
                 &DCtab_lum[0][1], 2, 1,
2781
                 &DCtab_lum[0][0], 2, 1);
2782
        init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2783
                 &DCtab_chrom[0][1], 2, 1,
2784
                 &DCtab_chrom[0][0], 2, 1);
2785
        init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2786
                 &sprite_trajectory_tab[0][1], 4, 2,
2787
                 &sprite_trajectory_tab[0][0], 4, 2);
2788
        init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2789
                 &mb_type_b_tab[0][1], 2, 1,
2790
                 &mb_type_b_tab[0][0], 2, 1);
2791
        init_vlc(&h263_mbtype_b_vlc, H263_MBTYPE_B_VLC_BITS, 15,
2792
                 &h263_mbtype_b_tab[0][1], 2, 1,
2793
                 &h263_mbtype_b_tab[0][0], 2, 1);
2794
        init_vlc(&cbpc_b_vlc, CBPC_B_VLC_BITS, 4,
2795
                 &cbpc_b_tab[0][1], 2, 1,
2796
                 &cbpc_b_tab[0][0], 2, 1);
2797
    }
2798
}
2799

    
2800
/**
2801
 * Get the GOB height based on picture height.
2802
 */
2803
int ff_h263_get_gob_height(MpegEncContext *s){
2804
    if (s->height <= 400)
2805
        return 1;
2806
    else if (s->height <= 800)
2807
        return  2;
2808
    else
2809
        return 4;
2810
}
2811

    
2812
int ff_h263_decode_mba(MpegEncContext *s)
2813
{
2814
    int i, mb_pos;
2815

    
2816
    for(i=0; i<6; i++){
2817
        if(s->mb_num < ff_mba_max[i]) break;
2818
    }
2819
    mb_pos= get_bits(&s->gb, ff_mba_length[i]);
2820
    s->mb_x= mb_pos % s->mb_width;
2821
    s->mb_y= mb_pos / s->mb_width;
2822

    
2823
    return mb_pos;
2824
}
2825

    
2826
void ff_h263_encode_mba(MpegEncContext *s)
2827
{
2828
    int i, mb_pos;
2829

    
2830
    for(i=0; i<6; i++){
2831
        if(s->mb_num < ff_mba_max[i]) break;
2832
    }
2833
    mb_pos= s->mb_x + s->mb_width*s->mb_y;
2834
    put_bits(&s->pb, ff_mba_length[i], mb_pos);
2835
}
2836

    
2837
/**
2838
 * decodes the group of blocks header or slice header.
2839
 * @return <0 if an error occured
2840
 */
2841
static int h263_decode_gob_header(MpegEncContext *s)
2842
{
2843
    unsigned int val, gfid, gob_number;
2844
    int left;
2845
    
2846
    /* Check for GOB Start Code */
2847
    val = show_bits(&s->gb, 16);
2848
    if(val)
2849
        return -1;
2850

    
2851
        /* We have a GBSC probably with GSTUFF */
2852
    skip_bits(&s->gb, 16); /* Drop the zeros */
2853
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
2854
    //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2855
    for(;left>13; left--){
2856
        if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2857
    }
2858
    if(left<=13) 
2859
        return -1;
2860

    
2861
    if(s->h263_slice_structured){
2862
        if(get_bits1(&s->gb)==0)
2863
            return -1;
2864

    
2865
        ff_h263_decode_mba(s);
2866

    
2867
        if(s->mb_num > 1583)
2868
            if(get_bits1(&s->gb)==0)
2869
                return -1;
2870
        
2871
        s->qscale = get_bits(&s->gb, 5); /* SQUANT */
2872
        if(get_bits1(&s->gb)==0)
2873
            return -1;
2874
        gfid = get_bits(&s->gb, 2); /* GFID */
2875
    }else{
2876
        gob_number = get_bits(&s->gb, 5); /* GN */
2877
        s->mb_x= 0;
2878
        s->mb_y= s->gob_index* gob_number;
2879
        gfid = get_bits(&s->gb, 2); /* GFID */
2880
        s->qscale = get_bits(&s->gb, 5); /* GQUANT */
2881
    }
2882
        
2883
    if(s->mb_y >= s->mb_height) 
2884
        return -1;
2885

    
2886
    if(s->qscale==0) 
2887
        return -1;
2888

    
2889
    return 0;
2890
}
2891

    
2892
static inline void memsetw(short *tab, int val, int n)
2893
{
2894
    int i;
2895
    for(i=0;i<n;i++)
2896
        tab[i] = val;
2897
}
2898

    
2899
#ifdef CONFIG_ENCODERS
2900

    
2901
void ff_mpeg4_init_partitions(MpegEncContext *s)
2902
{
2903
    init_put_bits(&s->tex_pb, s->tex_pb_buffer, PB_BUFFER_SIZE);
2904
    init_put_bits(&s->pb2   , s->pb2_buffer   , PB_BUFFER_SIZE);
2905
}
2906

    
2907
void ff_mpeg4_merge_partitions(MpegEncContext *s)
2908
{
2909
    const int pb2_len   = get_bit_count(&s->pb2   );
2910
    const int tex_pb_len= get_bit_count(&s->tex_pb);
2911
    const int bits= get_bit_count(&s->pb);
2912

    
2913
    if(s->pict_type==I_TYPE){
2914
        put_bits(&s->pb, 19, DC_MARKER);
2915
        s->misc_bits+=19 + pb2_len + bits - s->last_bits;
2916
        s->i_tex_bits+= tex_pb_len;
2917
    }else{
2918
        put_bits(&s->pb, 17, MOTION_MARKER);
2919
        s->misc_bits+=17 + pb2_len;
2920
        s->mv_bits+= bits - s->last_bits;
2921
        s->p_tex_bits+= tex_pb_len;
2922
    }
2923

    
2924
    flush_put_bits(&s->pb2);
2925
    flush_put_bits(&s->tex_pb);
2926

    
2927
    ff_copy_bits(&s->pb, s->pb2_buffer   , pb2_len);
2928
    ff_copy_bits(&s->pb, s->tex_pb_buffer, tex_pb_len);
2929
    s->last_bits= get_bit_count(&s->pb);
2930
}
2931

    
2932
#endif //CONFIG_ENCODERS
2933

    
2934
int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
2935
    switch(s->pict_type){
2936
        case I_TYPE:
2937
            return 16;
2938
        case P_TYPE:
2939
        case S_TYPE:
2940
            return s->f_code+15;
2941
        case B_TYPE:
2942
            return FFMAX(FFMAX(s->f_code, s->b_code)+15, 17);
2943
        default:
2944
            return -1;
2945
    }
2946
}
2947

    
2948
#ifdef CONFIG_ENCODERS
2949

    
2950
void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
2951
{
2952
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2953

    
2954
    put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
2955
    put_bits(&s->pb, 1, 1);
2956
    
2957
    put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
2958
    put_bits(&s->pb, s->quant_precision, s->qscale);
2959
    put_bits(&s->pb, 1, 0); /* no HEC */
2960
}
2961

    
2962
#endif //CONFIG_ENCODERS
2963

    
2964
/**
2965
 * check if the next stuff is a resync marker or the end.
2966
 * @return 0 if not
2967
 */
2968
static inline int mpeg4_is_resync(MpegEncContext *s){
2969
    const int bits_count= get_bits_count(&s->gb);
2970
    
2971
    if(s->workaround_bugs&FF_BUG_NO_PADDING){
2972
        return 0;
2973
    }
2974

    
2975
    if(bits_count + 8 >= s->gb.size_in_bits){
2976
        int v= show_bits(&s->gb, 8);
2977
        v|= 0x7F >> (7-(bits_count&7));
2978
                
2979
        if(v==0x7F)
2980
            return 1;
2981
    }else{
2982
        if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){
2983
            int len;
2984
            GetBitContext gb= s->gb;
2985
        
2986
            skip_bits(&s->gb, 1);
2987
            align_get_bits(&s->gb);
2988
        
2989
            for(len=0; len<32; len++){
2990
                if(get_bits1(&s->gb)) break;
2991
            }
2992

    
2993
            s->gb= gb;
2994

    
2995
            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
2996
                return 1;
2997
        }
2998
    }
2999
    return 0;
3000
}
3001

    
3002
/**
3003
 * decodes the next video packet.
3004
 * @return <0 if something went wrong
3005
 */
3006
static int mpeg4_decode_video_packet_header(MpegEncContext *s)
3007
{
3008
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
3009
    int header_extension=0, mb_num, len;
3010
    
3011
    /* is there enough space left for a video packet + header */
3012
    if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
3013

    
3014
    for(len=0; len<32; len++){
3015
        if(get_bits1(&s->gb)) break;
3016
    }
3017

    
3018
    if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
3019
        av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
3020
        return -1;
3021
    }
3022
    
3023
    if(s->shape != RECT_SHAPE){
3024
        header_extension= get_bits1(&s->gb);
3025
        //FIXME more stuff here
3026
    }
3027

    
3028
    mb_num= get_bits(&s->gb, mb_num_bits);
3029
    if(mb_num>=s->mb_num){
3030
        av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
3031
        return -1;
3032
    }
3033
    if(s->pict_type == B_TYPE){
3034
        while(s->next_picture.mbskip_table[ s->mb_index2xy[ mb_num ] ]) mb_num++;
3035
        if(mb_num >= s->mb_num) return -1; // slice contains just skiped MBs which where allready decoded
3036
    }
3037
    
3038
    s->mb_x= mb_num % s->mb_width;
3039
    s->mb_y= mb_num / s->mb_width;
3040

    
3041
    if(s->shape != BIN_ONLY_SHAPE){
3042
        int qscale= get_bits(&s->gb, s->quant_precision); 
3043
        if(qscale)
3044
            s->chroma_qscale=s->qscale= qscale;
3045
    }
3046

    
3047
    if(s->shape == RECT_SHAPE){
3048
        header_extension= get_bits1(&s->gb);
3049
    }
3050
    if(header_extension){
3051
        int time_increment;
3052
        int time_incr=0;
3053

    
3054
        while (get_bits1(&s->gb) != 0) 
3055
            time_incr++;
3056

    
3057
        check_marker(&s->gb, "before time_increment in video packed header");
3058
        time_increment= get_bits(&s->gb, s->time_increment_bits);
3059
        check_marker(&s->gb, "before vop_coding_type in video packed header");
3060
        
3061
        skip_bits(&s->gb, 2); /* vop coding type */
3062
        //FIXME not rect stuff here
3063

    
3064
        if(s->shape != BIN_ONLY_SHAPE){
3065
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
3066
//FIXME dont just ignore everything
3067
            if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3068
                mpeg4_decode_sprite_trajectory(s);
3069
                av_log(s->avctx, AV_LOG_ERROR, "untested\n");
3070
            }
3071

    
3072
            //FIXME reduced res stuff here
3073
            
3074
            if (s->pict_type != I_TYPE) {
3075
                int f_code = get_bits(&s->gb, 3);        /* fcode_for */
3076
                if(f_code==0){
3077
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n");
3078
                }
3079
            }
3080
            if (s->pict_type == B_TYPE) {
3081
                int b_code = get_bits(&s->gb, 3);
3082
                if(b_code==0){
3083
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n");
3084
                }
3085
            }       
3086
        }
3087
    }
3088
    //FIXME new-pred stuff
3089
    
3090
//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));
3091

    
3092
    return 0;
3093
}
3094

    
3095
void ff_mpeg4_clean_buffers(MpegEncContext *s)
3096
{
3097
    int c_wrap, c_xy, l_wrap, l_xy;
3098

    
3099
    l_wrap= s->block_wrap[0];
3100
    l_xy= s->mb_y*l_wrap*2 + s->mb_x*2;
3101
    c_wrap= s->block_wrap[4];
3102
    c_xy= s->mb_y*c_wrap + s->mb_x;
3103

    
3104
#if 0
3105
    /* clean DC */
3106
    memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
3107
    memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
3108
    memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
3109
#endif
3110

    
3111
    /* clean AC */
3112
    memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(int16_t));
3113
    memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
3114
    memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
3115

    
3116
    /* clean MV */
3117
    // we cant clear the MVs as they might be needed by a b frame
3118
//    memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(int16_t));
3119
//    memset(s->motion_val, 0, 2*sizeof(int16_t)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
3120
    s->last_mv[0][0][0]=
3121
    s->last_mv[0][0][1]=
3122
    s->last_mv[1][0][0]=
3123
    s->last_mv[1][0][1]= 0;
3124
}
3125

    
3126
/**
3127
 * decodes the group of blocks / video packet header.
3128
 * @return <0 if no resync found
3129
 */
3130
int ff_h263_resync(MpegEncContext *s){
3131
    int left, ret;
3132
    
3133
    if(s->codec_id==CODEC_ID_MPEG4){
3134
        skip_bits1(&s->gb);
3135
        align_get_bits(&s->gb);
3136
    }
3137

    
3138
    if(show_bits(&s->gb, 16)==0){
3139
        if(s->codec_id==CODEC_ID_MPEG4)
3140
            ret= mpeg4_decode_video_packet_header(s);
3141
        else
3142
            ret= h263_decode_gob_header(s);
3143
        if(ret>=0)
3144
            return 0;
3145
    }
3146
    //ok, its not where its supposed to be ...
3147
    s->gb= s->last_resync_gb;
3148
    align_get_bits(&s->gb);
3149
    left= s->gb.size_in_bits - get_bits_count(&s->gb);
3150
    
3151
    for(;left>16+1+5+5; left-=8){ 
3152
        if(show_bits(&s->gb, 16)==0){
3153
            GetBitContext bak= s->gb;
3154

    
3155
            if(s->codec_id==CODEC_ID_MPEG4)
3156
                ret= mpeg4_decode_video_packet_header(s);
3157
            else
3158
                ret= h263_decode_gob_header(s);
3159
            if(ret>=0)
3160
                return 0;
3161

    
3162
            s->gb= bak;
3163
        }
3164
        skip_bits(&s->gb, 8);
3165
    }
3166
    
3167
    return -1;
3168
}
3169

    
3170
/**
3171
 * gets the average motion vector for a GMC MB.
3172
 * @param n either 0 for the x component or 1 for y
3173
 * @returns the average MV for a GMC MB
3174
 */
3175
static inline int get_amv(MpegEncContext *s, int n){
3176
    int x, y, mb_v, sum, dx, dy, shift;
3177
    int len = 1 << (s->f_code + 4);
3178
    const int a= s->sprite_warping_accuracy;
3179

    
3180
    if(s->real_sprite_warping_points==1){
3181
        if(s->divx_version==500 && s->divx_build==413)
3182
            sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
3183
        else
3184
            sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
3185
    }else{
3186
        dx= s->sprite_delta[n][0];
3187
        dy= s->sprite_delta[n][1];
3188
        shift= s->sprite_shift[0];
3189
        if(n) dy -= 1<<(shift + a + 1);
3190
        else  dx -= 1<<(shift + a + 1);
3191
        mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
3192

    
3193
        sum=0;
3194
        for(y=0; y<16; y++){
3195
            int v;
3196
        
3197
            v= mb_v + dy*y;
3198
            //XXX FIXME optimize
3199
            for(x=0; x<16; x++){
3200
                sum+= v>>shift;
3201
                v+= dx;
3202
            }
3203
        }
3204
        sum= RSHIFT(sum, a+8-s->quarter_sample);
3205
    }
3206

    
3207
    if      (sum < -len) sum= -len;
3208
    else if (sum >= len) sum= len-1;
3209

    
3210
    return sum;
3211
}
3212

    
3213
/**
3214
 * decodes first partition.
3215
 * @return number of MBs decoded or <0 if an error occured
3216
 */
3217
static int mpeg4_decode_partition_a(MpegEncContext *s){
3218
    int mb_num;
3219
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3220
    
3221
    /* decode first partition */
3222
    mb_num=0;
3223
    s->first_slice_line=1;
3224
    for(; s->mb_y<s->mb_height; s->mb_y++){
3225
        ff_init_block_index(s);
3226
        for(; s->mb_x<s->mb_width; s->mb_x++){
3227
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
3228
            int cbpc;
3229
            int dir=0;
3230
            
3231
            mb_num++;
3232
            ff_update_block_index(s);
3233
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3234
                s->first_slice_line=0;
3235
            
3236
            if(s->pict_type==I_TYPE){
3237
                int i;
3238

    
3239
                if(show_bits_long(&s->gb, 19)==DC_MARKER){
3240
                    return mb_num-1;
3241
                }
3242

    
3243
                do{
3244
                    cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
3245
                    if (cbpc < 0){
3246
                        av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
3247
                        return -1;
3248
                    }
3249
                }while(cbpc == 8);
3250

    
3251
                s->cbp_table[xy]= cbpc & 3;
3252
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3253
                s->mb_intra = 1;
3254

    
3255
                if(cbpc & 4) {
3256
                    ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3257
                }
3258
                s->current_picture.qscale_table[xy]= s->qscale;
3259

    
3260
                s->mbintra_table[xy]= 1;
3261
                for(i=0; i<6; i++){
3262
                    int dc_pred_dir;
3263
                    int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
3264
                    if(dc < 0){
3265
                        av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3266
                        return -1;
3267
                    }
3268
                    dir<<=1;
3269
                    if(dc_pred_dir) dir|=1;
3270
                }
3271
                s->pred_dir_table[xy]= dir;
3272
            }else{ /* P/S_TYPE */
3273
                int mx, my, pred_x, pred_y, bits;
3274
                int16_t * const mot_val= s->motion_val[s->block_index[0]];
3275
                const int stride= s->block_wrap[0]*2;
3276

    
3277
//              do{ //FIXME
3278
                bits= show_bits(&s->gb, 17);
3279
                if(bits==MOTION_MARKER){
3280
                    return mb_num-1;
3281
                }
3282
                skip_bits1(&s->gb);
3283
                if(bits&0x10000){
3284
                    /* skip mb */
3285
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3286
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
3287
                        mx= get_amv(s, 0);
3288
                        my= get_amv(s, 1);
3289
                    }else{
3290
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3291
                        mx=my=0;
3292
                    }
3293
                    mot_val[0       ]= mot_val[2       ]=
3294
                    mot_val[0+stride]= mot_val[2+stride]= mx;
3295
                    mot_val[1       ]= mot_val[3       ]=
3296
                    mot_val[1+stride]= mot_val[3+stride]= my;
3297

    
3298
                    if(s->mbintra_table[xy])
3299
                        ff_clean_intra_table_entries(s);
3300
                    continue;
3301
                }
3302

    
3303
                cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3304
                if (cbpc < 0){
3305
                    av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
3306
                    return -1;
3307
                }
3308
//              }while(cbpc == 20);
3309

    
3310
                s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
3311
    
3312
                s->mb_intra = ((cbpc & 4) != 0);
3313
        
3314
                if(s->mb_intra){
3315
                    s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3316
                    s->mbintra_table[xy]= 1;
3317
                    mot_val[0       ]= mot_val[2       ]= 
3318
                    mot_val[0+stride]= mot_val[2+stride]= 0;
3319
                    mot_val[1       ]= mot_val[3       ]=
3320
                    mot_val[1+stride]= mot_val[3+stride]= 0;
3321
                }else{
3322
                    if(s->mbintra_table[xy])
3323
                        ff_clean_intra_table_entries(s);
3324

    
3325
                    if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
3326
                        s->mcsel= get_bits1(&s->gb);
3327
                    else s->mcsel= 0;
3328
        
3329
                    if ((cbpc & 16) == 0) {
3330
                        /* 16x16 motion prediction */
3331

    
3332
                        h263_pred_motion(s, 0, &pred_x, &pred_y);
3333
                        if(!s->mcsel){
3334
                            mx = h263_decode_motion(s, pred_x, s->f_code);
3335
                            if (mx >= 0xffff)
3336
                                return -1;
3337

    
3338
                            my = h263_decode_motion(s, pred_y, s->f_code);
3339
                            if (my >= 0xffff)
3340
                                return -1;
3341
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
3342
                        } else {
3343
                            mx = get_amv(s, 0);
3344
                            my = get_amv(s, 1);
3345
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
3346
                        }
3347

    
3348
                        mot_val[0       ]= mot_val[2       ] =
3349
                        mot_val[0+stride]= mot_val[2+stride]= mx;
3350
                        mot_val[1       ]= mot_val[3       ]=
3351
                        mot_val[1+stride]= mot_val[3+stride]= my;
3352
                    } else {
3353
                        int i;
3354
                        s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
3355
                        for(i=0;i<4;i++) {
3356
                            int16_t *mot_val= h263_pred_motion(s, i, &pred_x, &pred_y);
3357
                            mx = h263_decode_motion(s, pred_x, s->f_code);
3358
                            if (mx >= 0xffff)
3359
                                return -1;
3360
                
3361
                            my = h263_decode_motion(s, pred_y, s->f_code);
3362
                            if (my >= 0xffff)
3363
                                return -1;
3364
                            mot_val[0] = mx;
3365
                            mot_val[1] = my;
3366
                        }
3367
                    }
3368
                }
3369
            }
3370
        }
3371
        s->mb_x= 0;
3372
    }
3373

    
3374
    return mb_num;
3375
}
3376

    
3377
/**
3378
 * decode second partition.
3379
 * @return <0 if an error occured
3380
 */
3381
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
3382
    int mb_num=0;
3383
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3384

    
3385
    s->mb_x= s->resync_mb_x;
3386
    s->first_slice_line=1;
3387
    for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
3388
        ff_init_block_index(s);
3389
        for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
3390
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
3391

    
3392
            mb_num++;
3393
            ff_update_block_index(s);
3394
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3395
                s->first_slice_line=0;
3396
            
3397
            if(s->pict_type==I_TYPE){
3398
                int ac_pred= get_bits1(&s->gb);
3399
                int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3400
                if(cbpy<0){
3401
                    av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3402
                    return -1;
3403
                }
3404
                
3405
                s->cbp_table[xy]|= cbpy<<2;
3406
                s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
3407
            }else{ /* P || S_TYPE */
3408
                if(IS_INTRA(s->current_picture.mb_type[xy])){          
3409
                    int dir=0,i;
3410
                    int ac_pred = get_bits1(&s->gb);
3411
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3412

    
3413
                    if(cbpy<0){
3414
                        av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3415
                        return -1;
3416
                    }
3417
                    
3418
                    if(s->cbp_table[xy] & 8) {
3419
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3420
                    }
3421
                    s->current_picture.qscale_table[xy]= s->qscale;
3422

    
3423
                    for(i=0; i<6; i++){
3424
                        int dc_pred_dir;
3425
                        int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
3426
                        if(dc < 0){
3427
                            av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3428
                            return -1;
3429
                        }
3430
                        dir<<=1;
3431
                        if(dc_pred_dir) dir|=1;
3432
                    }
3433
                    s->cbp_table[xy]&= 3; //remove dquant
3434
                    s->cbp_table[xy]|= cbpy<<2;
3435
                    s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
3436
                    s->pred_dir_table[xy]= dir;
3437
                }else if(IS_SKIP(s->current_picture.mb_type[xy])){
3438
                    s->current_picture.qscale_table[xy]= s->qscale;
3439
                    s->cbp_table[xy]= 0;
3440
                }else{
3441
                    int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3442

    
3443
                    if(cbpy<0){
3444
                        av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3445
                        return -1;
3446
                    }
3447
                    
3448
                    if(s->cbp_table[xy] & 8) {
3449
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3450
                    }
3451
                    s->current_picture.qscale_table[xy]= s->qscale;
3452

    
3453
                    s->cbp_table[xy]&= 3; //remove dquant
3454
                    s->cbp_table[xy]|= (cbpy^0xf)<<2;
3455
                }
3456
            }
3457
        }
3458
        if(mb_num >= mb_count) return 0;
3459
        s->mb_x= 0;
3460
    }
3461
    return 0;
3462
}
3463

    
3464
/**
3465
 * decodes the first & second partition
3466
 * @return <0 if error (and sets error type in the error_status_table)
3467
 */
3468
int ff_mpeg4_decode_partitions(MpegEncContext *s)
3469
{
3470
    int mb_num;
3471
    const int part_a_error= s->pict_type==I_TYPE ? (DC_ERROR|MV_ERROR) : MV_ERROR;
3472
    const int part_a_end  = s->pict_type==I_TYPE ? (DC_END  |MV_END)   : MV_END;
3473
    
3474
    mb_num= mpeg4_decode_partition_a(s);    
3475
    if(mb_num<0){
3476
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3477
        return -1;
3478
    }
3479
    
3480
    if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
3481
        av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
3482
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3483
        return -1;
3484
    }
3485

    
3486
    s->mb_num_left= mb_num;
3487
        
3488
    if(s->pict_type==I_TYPE){
3489
        if(get_bits_long(&s->gb, 19)!=DC_MARKER){
3490
            av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
3491
            return -1;
3492
        }
3493
    }else{
3494
        if(get_bits(&s->gb, 17)!=MOTION_MARKER){
3495
            av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
3496
            return -1;
3497
        }
3498
    }
3499
    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, part_a_end);
3500
    
3501
    if( mpeg4_decode_partition_b(s, mb_num) < 0){
3502
        if(s->pict_type==P_TYPE)
3503
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, DC_ERROR);
3504
        return -1;
3505
    }else{
3506
        if(s->pict_type==P_TYPE)
3507
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, DC_END);
3508
    }
3509

    
3510
    return 0;        
3511
}
3512

    
3513
/**
3514
 * decode partition C of one MB.
3515
 * @return <0 if an error occured
3516
 */
3517
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
3518
{
3519
    int cbp, mb_type;
3520
    const int xy= s->mb_x + s->mb_y*s->mb_stride;
3521

    
3522
    mb_type= s->current_picture.mb_type[xy];
3523
    cbp = s->cbp_table[xy];
3524

    
3525
    if(s->current_picture.qscale_table[xy] != s->qscale){
3526
        ff_set_qscale(s, s->current_picture.qscale_table[xy] );
3527
    }
3528
    
3529
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3530
        int i;
3531
        for(i=0; i<4; i++){
3532
            s->mv[0][i][0] = s->motion_val[ s->block_index[i] ][0];
3533
            s->mv[0][i][1] = s->motion_val[ s->block_index[i] ][1];
3534
        }
3535
        s->mb_intra = IS_INTRA(mb_type);
3536

    
3537
        if (IS_SKIP(mb_type)) {
3538
            /* skip mb */
3539
            for(i=0;i<6;i++)
3540
                s->block_last_index[i] = -1;
3541
            s->mv_dir = MV_DIR_FORWARD;
3542
            s->mv_type = MV_TYPE_16X16;
3543
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3544
                s->mcsel=1;
3545
                s->mb_skiped = 0;
3546
            }else{
3547
                s->mcsel=0;
3548
                s->mb_skiped = 1;
3549
            }
3550
        }else if(s->mb_intra){
3551
            s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3552
        }else if(!s->mb_intra){
3553
//            s->mcsel= 0; //FIXME do we need to init that
3554
            
3555
            s->mv_dir = MV_DIR_FORWARD;
3556
            if (IS_8X8(mb_type)) {
3557
                s->mv_type = MV_TYPE_8X8;
3558
            } else {
3559
                s->mv_type = MV_TYPE_16X16;
3560
            }
3561
        }
3562
    } else { /* I-Frame */
3563
        s->mb_intra = 1;
3564
        s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3565
    }
3566

    
3567
    if (!IS_SKIP(mb_type)) {
3568
        int i;
3569
        /* decode each block */
3570
        for (i = 0; i < 6; i++) {
3571
            if(mpeg4_decode_block(s, block[i], i, cbp&32, s->mb_intra, s->rvlc) < 0){
3572
                av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra);
3573
                return -1;
3574
            }
3575
            cbp+=cbp;
3576
        }
3577
    }
3578

    
3579
    /* per-MB end of slice check */
3580

    
3581
    if(--s->mb_num_left <= 0){
3582
//printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size_in_bits - get_bits_count(&s->gb));
3583
        if(mpeg4_is_resync(s))
3584
            return SLICE_END;
3585
        else
3586
            return SLICE_NOEND;     
3587
    }else{
3588
        if(mpeg4_is_resync(s)){
3589
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
3590
            if(s->cbp_table[xy+delta])
3591
                return SLICE_END;
3592
        }
3593
        return SLICE_OK;
3594
    }
3595
}
3596

    
3597
/**
3598
 * read the next MVs for OBMC. yes this is a ugly hack, feel free to send a patch :)
3599
 */
3600
static void preview_obmc(MpegEncContext *s){
3601
    GetBitContext gb= s->gb;
3602
    
3603
    int cbpc, i, pred_x, pred_y, mx, my;
3604
    int16_t *mot_val;
3605
    const int xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
3606
    const int stride= s->block_wrap[0]*2;
3607
    
3608
    for(i=0; i<4; i++)
3609
        s->block_index[i]+= 2;
3610
    for(i=4; i<6; i++)
3611
        s->block_index[i]+= 1;
3612
    s->mb_x++;
3613
    
3614
    assert(s->pict_type == P_TYPE);
3615

    
3616
    do{
3617
        if (get_bits1(&s->gb)) {
3618
            /* skip mb */
3619
            mot_val = s->motion_val[ s->block_index[0] ];
3620
            mot_val[0       ]= mot_val[2       ]= 
3621
            mot_val[0+stride]= mot_val[2+stride]= 0;
3622
            mot_val[1       ]= mot_val[3       ]=
3623
            mot_val[1+stride]= mot_val[3+stride]= 0;
3624
            
3625
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3626
            goto end;
3627
        }
3628
        cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3629
    }while(cbpc == 20);
3630
    
3631
    if(cbpc & 4){
3632
        s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3633
    }else{
3634
        get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3635
        if (cbpc & 8) {
3636
            if(s->modified_quant){
3637
                if(get_bits1(&s->gb)) skip_bits(&s->gb, 1);
3638
                else                  skip_bits(&s->gb, 5);
3639
            }else
3640
                skip_bits(&s->gb, 2);
3641
        }
3642
        
3643
        if ((cbpc & 16) == 0) {
3644
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
3645
                /* 16x16 motion prediction */
3646
                mot_val= h263_pred_motion(s, 0, &pred_x, &pred_y);
3647
                if (s->umvplus)
3648
                   mx = h263p_decode_umotion(s, pred_x);
3649
                else
3650
                   mx = h263_decode_motion(s, pred_x, 1);
3651
            
3652
                if (s->umvplus)
3653
                   my = h263p_decode_umotion(s, pred_y);
3654
                else
3655
                   my = h263_decode_motion(s, pred_y, 1);
3656
            
3657
                mot_val[0       ]= mot_val[2       ]= 
3658
                mot_val[0+stride]= mot_val[2+stride]= mx;
3659
                mot_val[1       ]= mot_val[3       ]=
3660
                mot_val[1+stride]= mot_val[3+stride]= my;
3661
        } else {
3662
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
3663
            for(i=0;i<4;i++) {
3664
                mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
3665
                if (s->umvplus)
3666
                  mx = h263p_decode_umotion(s, pred_x);
3667
                else
3668
                  mx = h263_decode_motion(s, pred_x, 1);
3669
                
3670
                if (s->umvplus)
3671
                  my = h263p_decode_umotion(s, pred_y);
3672
                else    
3673
                  my = h263_decode_motion(s, pred_y, 1);
3674
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3675
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3676
                mot_val[0] = mx;
3677
                mot_val[1] = my;
3678
            }
3679
        }
3680
    }
3681
end:
3682
        
3683
    for(i=0; i<4; i++)
3684
        s->block_index[i]-= 2;
3685
    for(i=4; i<6; i++)
3686
        s->block_index[i]-= 1;
3687
    s->mb_x--;
3688

    
3689
    s->gb= gb;
3690
}
3691

    
3692
static void h263_decode_dquant(MpegEncContext *s){
3693
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3694

    
3695
    if(s->modified_quant){
3696
        if(get_bits1(&s->gb))
3697
            s->qscale= modified_quant_tab[get_bits1(&s->gb)][ s->qscale ];
3698
        else
3699
            s->qscale= get_bits(&s->gb, 5);
3700
    }else
3701
        s->qscale += quant_tab[get_bits(&s->gb, 2)];
3702
    ff_set_qscale(s, s->qscale);
3703
}
3704

    
3705
int ff_h263_decode_mb(MpegEncContext *s,
3706
                      DCTELEM block[6][64])
3707
{
3708
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
3709
    int16_t *mot_val;
3710
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
3711
    
3712
    assert(!s->h263_pred);
3713
    
3714
    if (s->pict_type == P_TYPE) {
3715
        do{
3716
            if (get_bits1(&s->gb)) {
3717
                /* skip mb */
3718
                s->mb_intra = 0;
3719
                for(i=0;i<6;i++)
3720
                    s->block_last_index[i] = -1;
3721
                s->mv_dir = MV_DIR_FORWARD;
3722
                s->mv_type = MV_TYPE_16X16;
3723
                s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3724
                s->mv[0][0][0] = 0;
3725
                s->mv[0][0][1] = 0;
3726
                s->mb_skiped = !(s->obmc | s->loop_filter);
3727
                goto end;
3728
            }
3729
            cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3730
            //fprintf(stderr, "\tCBPC: %d", cbpc);
3731
            if (cbpc < 0){
3732
                av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
3733
                return -1;
3734
            }
3735
        }while(cbpc == 20);
3736
        
3737
        dquant = cbpc & 8;
3738
        s->mb_intra = ((cbpc & 4) != 0);
3739
        if (s->mb_intra) goto intra;
3740
        
3741
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3742
        
3743
        if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
3744
            cbpy ^= 0xF;
3745
        
3746
        cbp = (cbpc & 3) | (cbpy << 2);
3747
        if (dquant) {
3748
            h263_decode_dquant(s);
3749
        }
3750
        
3751
        s->mv_dir = MV_DIR_FORWARD;
3752
        if ((cbpc & 16) == 0) {
3753
            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
3754
            /* 16x16 motion prediction */
3755
            s->mv_type = MV_TYPE_16X16;
3756
            h263_pred_motion(s, 0, &pred_x, &pred_y);
3757
            if (s->umvplus)
3758
               mx = h263p_decode_umotion(s, pred_x);
3759
            else
3760
               mx = h263_decode_motion(s, pred_x, 1);
3761
            
3762
            if (mx >= 0xffff)
3763
                return -1;
3764
            
3765
            if (s->umvplus)
3766
               my = h263p_decode_umotion(s, pred_y);
3767
            else
3768
               my = h263_decode_motion(s, pred_y, 1);
3769
            
3770
            if (my >= 0xffff)
3771
                return -1;
3772
            s->mv[0][0][0] = mx;
3773
            s->mv[0][0][1] = my;
3774

    
3775
            if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3776
               skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */                   
3777
        } else {
3778
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
3779
            s->mv_type = MV_TYPE_8X8;
3780
            for(i=0;i<4;i++) {
3781
                mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
3782
                if (s->umvplus)
3783
                  mx = h263p_decode_umotion(s, pred_x);
3784
                else
3785
                  mx = h263_decode_motion(s, pred_x, 1);
3786
                if (mx >= 0xffff)
3787
                    return -1;
3788
                
3789
                if (s->umvplus)
3790
                  my = h263p_decode_umotion(s, pred_y);
3791
                else    
3792
                  my = h263_decode_motion(s, pred_y, 1);
3793
                if (my >= 0xffff)
3794
                    return -1;
3795
                s->mv[0][i][0] = mx;
3796
                s->mv[0][i][1] = my;
3797
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3798
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3799
                mot_val[0] = mx;
3800
                mot_val[1] = my;
3801
            }
3802
        }
3803

    
3804
        if(s->obmc){
3805
            if(s->pict_type == P_TYPE && s->mb_x+1<s->mb_width)
3806
                preview_obmc(s);
3807
        }
3808
    } else if(s->pict_type==B_TYPE) {
3809
        int mb_type;
3810
        const int stride= s->b8_stride;
3811
        int16_t *mot_val0 = s->current_picture.motion_val[0][ s->mb_x + s->mb_y*stride ];
3812
        int16_t *mot_val1 = s->current_picture.motion_val[1][ s->mb_x + s->mb_y*stride ];
3813
//        const int mv_xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
3814

    
3815
        //FIXME ugly 
3816
        mot_val0[0       ]= mot_val0[2       ]= mot_val0[0+stride]= mot_val0[2+stride]= 0;
3817
        mot_val0[1       ]= mot_val0[3       ]= mot_val0[1+stride]= mot_val0[3+stride]= 0;
3818
        mot_val1[0       ]= mot_val1[2       ]= mot_val1[0+stride]= mot_val1[2+stride]= 0;
3819
        mot_val1[1       ]= mot_val1[3       ]= mot_val1[1+stride]= mot_val1[3+stride]= 0;
3820

    
3821
        do{
3822
            mb_type= get_vlc2(&s->gb, h263_mbtype_b_vlc.table, H263_MBTYPE_B_VLC_BITS, 2);
3823
            if (mb_type < 0){
3824
                av_log(s->avctx, AV_LOG_ERROR, "b mb_type damaged at %d %d\n", s->mb_x, s->mb_y);
3825
                return -1;
3826
            }
3827

    
3828
            mb_type= h263_mb_type_b_map[ mb_type ];
3829
        }while(!mb_type);
3830

    
3831
        s->mb_intra = IS_INTRA(mb_type);
3832
        if(HAS_CBP(mb_type)){
3833
            cbpc = get_vlc2(&s->gb, cbpc_b_vlc.table, CBPC_B_VLC_BITS, 1);
3834
            if(s->mb_intra){
3835
                dquant = IS_QUANT(mb_type);
3836
                goto intra;
3837
            }
3838

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

    
3841
            if (cbpy < 0){
3842
                av_log(s->avctx, AV_LOG_ERROR, "b cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
3843
                return -1;
3844
            }
3845
        
3846
            if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
3847
                cbpy ^= 0xF;
3848
        
3849
            cbp = (cbpc & 3) | (cbpy << 2);
3850
        }else
3851
            cbp=0;
3852
            
3853
        assert(!s->mb_intra);
3854

    
3855
        if(IS_QUANT(mb_type)){
3856
            h263_decode_dquant(s);
3857
        }
3858

    
3859
        if(IS_DIRECT(mb_type)){
3860
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3861
            mb_type |= ff_mpeg4_set_direct_mv(s, 0, 0);
3862
        }else{
3863
            s->mv_dir = 0;
3864
            s->mv_type= MV_TYPE_16X16;
3865
//FIXME UMV
3866

    
3867
            if(USES_LIST(mb_type, 0)){
3868
                int16_t *mot_val= h263_pred_motion2(s, 0, 0, &mx, &my);
3869
                s->mv_dir = MV_DIR_FORWARD;
3870

    
3871
                mx = h263_decode_motion(s, mx, 1);
3872
                my = h263_decode_motion(s, my, 1);
3873
                s->mv[0][0][0] = mx;
3874
                s->mv[0][0][1] = my;
3875
                mot_val[0       ]= mot_val[2       ]= mot_val[0+stride]= mot_val[2+stride]= mx;
3876
                mot_val[1       ]= mot_val[3       ]= mot_val[1+stride]= mot_val[3+stride]= my;
3877
            }
3878
    
3879
            if(USES_LIST(mb_type, 1)){
3880
                int16_t *mot_val= h263_pred_motion2(s, 0, 1, &mx, &my);
3881
                s->mv_dir |= MV_DIR_BACKWARD;
3882

    
3883
                mx = h263_decode_motion(s, mx, 1);
3884
                my = h263_decode_motion(s, my, 1);
3885
                s->mv[1][0][0] = mx;
3886
                s->mv[1][0][1] = my;
3887
                mot_val[0       ]= mot_val[2       ]= mot_val[0+stride]= mot_val[2+stride]= mx;
3888
                mot_val[1       ]= mot_val[3       ]= mot_val[1+stride]= mot_val[3+stride]= my;
3889
            }
3890
        }
3891
          
3892
        s->current_picture.mb_type[xy]= mb_type;
3893
    } else { /* I-Frame */
3894
        do{
3895
            cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
3896
            if (cbpc < 0){
3897
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
3898
                return -1;
3899
            }
3900
        }while(cbpc == 8);
3901

    
3902
        dquant = cbpc & 4;
3903
        s->mb_intra = 1;
3904
intra:
3905
        s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3906
        if (s->h263_aic) {
3907
            s->ac_pred = get_bits1(&s->gb);
3908
            if(s->ac_pred){
3909
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
3910
            
3911
                s->h263_aic_dir = get_bits1(&s->gb);
3912
            }
3913
        }else
3914
            s->ac_pred = 0;
3915
        
3916
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3917
        if(cbpy<0){
3918
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
3919
            return -1;
3920
        }
3921
        cbp = (cbpc & 3) | (cbpy << 2);
3922
        if (dquant) {
3923
            h263_decode_dquant(s);
3924
        }
3925
    }
3926

    
3927
    /* decode each block */
3928
    for (i = 0; i < 6; i++) {
3929
        if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3930
            return -1;
3931
        cbp+=cbp;
3932
    }
3933
end:
3934

    
3935
        /* per-MB end of slice check */
3936
    {
3937
        int v= show_bits(&s->gb, 16);
3938
    
3939
        if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
3940
            v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
3941
        }
3942

    
3943
        if(v==0)
3944
            return SLICE_END;
3945
    }
3946

    
3947
    return SLICE_OK;     
3948
}
3949

    
3950
int ff_mpeg4_decode_mb(MpegEncContext *s,
3951
                      DCTELEM block[6][64])
3952
{
3953
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
3954
    int16_t *mot_val;
3955
    static int8_t quant_tab[4] = { -1, -2, 1, 2 };
3956
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
3957
    
3958
    assert(s->h263_pred);
3959
    
3960
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3961
        do{
3962
            if (get_bits1(&s->gb)) {
3963
                /* skip mb */
3964
                s->mb_intra = 0;
3965
                for(i=0;i<6;i++)
3966
                    s->block_last_index[i] = -1;
3967
                s->mv_dir = MV_DIR_FORWARD;
3968
                s->mv_type = MV_TYPE_16X16;
3969
                if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3970
                    s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
3971
                    s->mcsel=1;
3972
                    s->mv[0][0][0]= get_amv(s, 0);
3973
                    s->mv[0][0][1]= get_amv(s, 1);
3974

    
3975
                    s->mb_skiped = 0;
3976
                }else{
3977
                    s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3978
                    s->mcsel=0;
3979
                    s->mv[0][0][0] = 0;
3980
                    s->mv[0][0][1] = 0;
3981
                    s->mb_skiped = 1;
3982
                }
3983
                goto end;
3984
            }
3985
            cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3986
            //fprintf(stderr, "\tCBPC: %d", cbpc);
3987
            if (cbpc < 0){
3988
                av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
3989
                return -1;
3990
            }
3991
        }while(cbpc == 20);
3992
        
3993
        dquant = cbpc & 8;
3994
        s->mb_intra = ((cbpc & 4) != 0);
3995
        if (s->mb_intra) goto intra;
3996
        
3997
        if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
3998
            s->mcsel= get_bits1(&s->gb);
3999
        else s->mcsel= 0;
4000
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
4001
        
4002
        cbp = (cbpc & 3) | (cbpy << 2);
4003
        if (dquant) {
4004
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
4005
        }
4006
        if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
4007
            s->interlaced_dct= get_bits1(&s->gb);
4008
        
4009
        s->mv_dir = MV_DIR_FORWARD;
4010
        if ((cbpc & 16) == 0) {
4011
            if(s->mcsel){
4012
                s->current_picture.mb_type[xy]= MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
4013
                /* 16x16 global motion prediction */
4014
                s->mv_type = MV_TYPE_16X16;
4015
                mx= get_amv(s, 0);
4016
                my= get_amv(s, 1);
4017
                s->mv[0][0][0] = mx;
4018
                s->mv[0][0][1] = my;
4019
            }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
4020
                s->current_picture.mb_type[xy]= MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; 
4021
                /* 16x8 field motion prediction */
4022
                s->mv_type= MV_TYPE_FIELD;
4023

    
4024
                s->field_select[0][0]= get_bits1(&s->gb);
4025
                s->field_select[0][1]= get_bits1(&s->gb);
4026

    
4027
                h263_pred_motion(s, 0, &pred_x, &pred_y);
4028
                
4029
                for(i=0; i<2; i++){
4030
                    mx = h263_decode_motion(s, pred_x, s->f_code);
4031
                    if (mx >= 0xffff)
4032
                        return -1;
4033
            
4034
                    my = h263_decode_motion(s, pred_y/2, s->f_code);
4035
                    if (my >= 0xffff)
4036
                        return -1;
4037

    
4038
                    s->mv[0][i][0] = mx;
4039
                    s->mv[0][i][1] = my;
4040
                }
4041
            }else{
4042
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
4043
                /* 16x16 motion prediction */
4044
                s->mv_type = MV_TYPE_16X16;
4045
                h263_pred_motion(s, 0, &pred_x, &pred_y);
4046
                mx = h263_decode_motion(s, pred_x, s->f_code);
4047
            
4048
                if (mx >= 0xffff)
4049
                    return -1;
4050
            
4051
                my = h263_decode_motion(s, pred_y, s->f_code);
4052
            
4053
                if (my >= 0xffff)
4054
                    return -1;
4055
                s->mv[0][0][0] = mx;
4056
                s->mv[0][0][1] = my;
4057
            }
4058
        } else {
4059
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
4060
            s->mv_type = MV_TYPE_8X8;
4061
            for(i=0;i<4;i++) {
4062
                mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
4063
                mx = h263_decode_motion(s, pred_x, s->f_code);
4064
                if (mx >= 0xffff)
4065
                    return -1;
4066
                
4067
                my = h263_decode_motion(s, pred_y, s->f_code);
4068
                if (my >= 0xffff)
4069
                    return -1;
4070
                s->mv[0][i][0] = mx;
4071
                s->mv[0][i][1] = my;
4072
                mot_val[0] = mx;
4073
                mot_val[1] = my;
4074
            }
4075
        }
4076
    } else if(s->pict_type==B_TYPE) {
4077
        int modb1; // first bit of modb
4078
        int modb2; // second bit of modb
4079
        int mb_type;
4080

    
4081
        s->mb_intra = 0; //B-frames never contain intra blocks
4082
        s->mcsel=0;      //     ...               true gmc blocks
4083

    
4084
        if(s->mb_x==0){
4085
            for(i=0; i<2; i++){
4086
                s->last_mv[i][0][0]= 
4087
                s->last_mv[i][0][1]= 
4088
                s->last_mv[i][1][0]= 
4089
                s->last_mv[i][1][1]= 0;
4090
            }
4091
        }
4092

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

    
4096
        if(s->mb_skiped){
4097
                /* skip mb */
4098
            for(i=0;i<6;i++)
4099
                s->block_last_index[i] = -1;
4100

    
4101
            s->mv_dir = MV_DIR_FORWARD;
4102
            s->mv_type = MV_TYPE_16X16;
4103
            s->mv[0][0][0] = 0;
4104
            s->mv[0][0][1] = 0;
4105
            s->mv[1][0][0] = 0;
4106
            s->mv[1][0][1] = 0;
4107
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; 
4108
            goto end;
4109
        }
4110

    
4111
        modb1= get_bits1(&s->gb); 
4112
        if(modb1){
4113
            mb_type= MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; //like MB_TYPE_B_DIRECT but no vectors coded
4114
            cbp=0;
4115
        }else{
4116
            modb2= get_bits1(&s->gb);
4117
            mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
4118
            if(mb_type<0){
4119
                av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
4120
                return -1;
4121
            }
4122
            mb_type= mb_type_b_map[ mb_type ];
4123
            if(modb2) cbp= 0;
4124
            else      cbp= get_bits(&s->gb, 6);
4125

    
4126
            if ((!IS_DIRECT(mb_type)) && cbp) {
4127
                if(get_bits1(&s->gb)){
4128
                    ff_set_qscale(s, s->qscale + get_bits1(&s->gb)*4 - 2);
4129
                }
4130
            }
4131

    
4132
            if(!s->progressive_sequence){
4133
                if(cbp)
4134
                    s->interlaced_dct= get_bits1(&s->gb);
4135

    
4136
                if(!IS_DIRECT(mb_type) && get_bits1(&s->gb)){
4137
                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
4138
                    mb_type &= ~MB_TYPE_16x16;
4139

    
4140
                    if(USES_LIST(mb_type, 0)){
4141
                        s->field_select[0][0]= get_bits1(&s->gb);
4142
                        s->field_select[0][1]= get_bits1(&s->gb);
4143
                    }
4144
                    if(USES_LIST(mb_type, 1)){
4145
                        s->field_select[1][0]= get_bits1(&s->gb);
4146
                        s->field_select[1][1]= get_bits1(&s->gb);
4147
                    }
4148
                }
4149
            }
4150

    
4151
            s->mv_dir = 0;
4152
            if((mb_type & (MB_TYPE_DIRECT2|MB_TYPE_INTERLACED)) == 0){
4153
                s->mv_type= MV_TYPE_16X16;
4154

    
4155
                if(USES_LIST(mb_type, 0)){
4156
                    s->mv_dir = MV_DIR_FORWARD;
4157

    
4158
                    mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
4159
                    my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
4160
                    s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
4161
                    s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
4162
                }
4163
    
4164
                if(USES_LIST(mb_type, 1)){
4165
                    s->mv_dir |= MV_DIR_BACKWARD;
4166

    
4167
                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
4168
                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
4169
                    s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
4170
                    s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
4171
                }
4172
            }else if(!IS_DIRECT(mb_type)){
4173
                s->mv_type= MV_TYPE_FIELD;
4174

    
4175
                if(USES_LIST(mb_type, 0)){
4176
                    s->mv_dir = MV_DIR_FORWARD;
4177
                
4178
                    for(i=0; i<2; i++){
4179
                        mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
4180
                        my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
4181
                        s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
4182
                        s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
4183
                    }
4184
                }
4185
    
4186
                if(USES_LIST(mb_type, 1)){
4187
                    s->mv_dir |= MV_DIR_BACKWARD;
4188

    
4189
                    for(i=0; i<2; i++){
4190
                        mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
4191
                        my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
4192
                        s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
4193
                        s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
4194
                    }
4195
                }
4196
            }
4197
        }
4198
          
4199
        if(IS_DIRECT(mb_type)){
4200
            if(IS_SKIP(mb_type))
4201
                mx=my=0;
4202
            else{
4203
                mx = h263_decode_motion(s, 0, 1);
4204
                my = h263_decode_motion(s, 0, 1);
4205
            }
4206
 
4207
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
4208
            mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
4209
        }
4210
        s->current_picture.mb_type[xy]= mb_type;
4211
    } else { /* I-Frame */
4212
        do{
4213
            cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
4214
            if (cbpc < 0){
4215
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
4216
                return -1;
4217
            }
4218
        }while(cbpc == 8);
4219

    
4220
        dquant = cbpc & 4;
4221
        s->mb_intra = 1;
4222
intra:
4223
        s->ac_pred = get_bits1(&s->gb);
4224
        if(s->ac_pred)
4225
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
4226
        else
4227
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
4228
        
4229
        cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
4230
        if(cbpy<0){
4231
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
4232
            return -1;
4233
        }
4234
        cbp = (cbpc & 3) | (cbpy << 2);
4235
        if (dquant) {
4236
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
4237
        }
4238
        
4239
        if(!s->progressive_sequence)
4240
            s->interlaced_dct= get_bits1(&s->gb);
4241

    
4242
        /* decode each block */
4243
        for (i = 0; i < 6; i++) {
4244
            if (mpeg4_decode_block(s, block[i], i, cbp&32, 1, 0) < 0)
4245
                return -1;
4246
            cbp+=cbp;
4247
        }
4248
        goto end;
4249
    }
4250

    
4251
    /* decode each block */
4252
    for (i = 0; i < 6; i++) {
4253
        if (mpeg4_decode_block(s, block[i], i, cbp&32, 0, 0) < 0)
4254
            return -1;
4255
        cbp+=cbp;
4256
    }
4257
end:
4258

    
4259
        /* per-MB end of slice check */
4260
    if(s->codec_id==CODEC_ID_MPEG4){
4261
        if(mpeg4_is_resync(s)){
4262
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
4263
            if(s->pict_type==B_TYPE && s->next_picture.mbskip_table[xy + delta])
4264
                return SLICE_OK;
4265
            return SLICE_END;
4266
        }
4267
    }
4268

    
4269
    return SLICE_OK;     
4270
}
4271

    
4272
static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
4273
{
4274
    int code, val, sign, shift, l;
4275
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
4276

    
4277
    if (code == 0)
4278
        return pred;
4279
    if (code < 0)
4280
        return 0xffff;
4281

    
4282
    sign = get_bits1(&s->gb);
4283
    shift = f_code - 1;
4284
    val = code;
4285
    if (shift) {
4286
        val = (val - 1) << shift;
4287
        val |= get_bits(&s->gb, shift);
4288
        val++;
4289
    }
4290
    if (sign)
4291
        val = -val;
4292
    val += pred;
4293

    
4294
    /* modulo decoding */
4295
    if (!s->h263_long_vectors) {
4296
        l = 1 << (f_code + 4);
4297
        val = ((val + l)&(l*2-1)) - l;
4298
    } else {
4299
        /* horrible h263 long vector mode */
4300
        if (pred < -31 && val < -63)
4301
            val += 64;
4302
        if (pred > 32 && val > 63)
4303
            val -= 64;
4304
        
4305
    }
4306
    return val;
4307
}
4308

    
4309
/* Decodes RVLC of H.263+ UMV */
4310
static int h263p_decode_umotion(MpegEncContext * s, int pred)
4311
{
4312
   int code = 0, sign;
4313
   
4314
   if (get_bits1(&s->gb)) /* Motion difference = 0 */
4315
      return pred;
4316
   
4317
   code = 2 + get_bits1(&s->gb);
4318
   
4319
   while (get_bits1(&s->gb))
4320
   {
4321
      code <<= 1;
4322
      code += get_bits1(&s->gb);
4323
   }
4324
   sign = code & 1;
4325
   code >>= 1;
4326
   
4327
   code = (sign) ? (pred - code) : (pred + code);
4328
#ifdef DEBUG
4329
   fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
4330
#endif
4331
   return code;   
4332

    
4333
}
4334

    
4335
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
4336
                             int n, int coded)
4337
{
4338
    int code, level, i, j, last, run;
4339
    RLTable *rl = &rl_inter;
4340
    const uint8_t *scan_table;
4341
    GetBitContext gb= s->gb;
4342

    
4343
    scan_table = s->intra_scantable.permutated;
4344
    if (s->h263_aic && s->mb_intra) {
4345
        rl = &rl_intra_aic;
4346
        i = 0;
4347
        if (s->ac_pred) {
4348
            if (s->h263_aic_dir) 
4349
                scan_table = s->intra_v_scantable.permutated; /* left */
4350
            else
4351
                scan_table = s->intra_h_scantable.permutated; /* top */
4352
        }
4353
    } else if (s->mb_intra) {
4354
        /* DC coef */
4355
        if(s->codec_id == CODEC_ID_RV10){
4356
          if (s->rv10_version == 3 && s->pict_type == I_TYPE) {
4357
            int component, diff;
4358
            component = (n <= 3 ? 0 : n - 4 + 1);
4359
            level = s->last_dc[component];
4360
            if (s->rv10_first_dc_coded[component]) {
4361
                diff = rv_decode_dc(s, n);
4362
                if (diff == 0xffff)
4363
                    return -1;
4364
                level += diff;
4365
                level = level & 0xff; /* handle wrap round */
4366
                s->last_dc[component] = level;
4367
            } else {
4368
                s->rv10_first_dc_coded[component] = 1;
4369
            }
4370
          } else {
4371
                level = get_bits(&s->gb, 8);
4372
          }
4373
        }else{
4374
            level = get_bits(&s->gb, 8);
4375
            if((level&0x7F) == 0){
4376
                av_log(s->avctx, AV_LOG_ERROR, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);
4377
                return -1;
4378
            }
4379
            if (level == 255)
4380
                level = 128;
4381
        }
4382
        block[0] = level;
4383
        i = 1;
4384
    } else {
4385
        i = 0;
4386
    }
4387
    if (!coded) {
4388
        if (s->mb_intra && s->h263_aic)
4389
            goto not_coded;
4390
        s->block_last_index[n] = i - 1;
4391
        return 0;
4392
    }
4393
retry:
4394
    for(;;) {
4395
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
4396
        if (code < 0){
4397
            av_log(s->avctx, AV_LOG_ERROR, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
4398
            return -1;
4399
        }
4400
        if (code == rl->n) {
4401
            /* escape */
4402
            if (s->h263_flv > 1) {
4403
                int is11 = get_bits1(&s->gb);
4404
                last = get_bits1(&s->gb);
4405
                run = get_bits(&s->gb, 6);
4406
                if(is11){
4407
                    level = get_sbits(&s->gb, 11);
4408
                } else {
4409
                    level = get_sbits(&s->gb, 7);
4410
                }
4411
            } else {
4412
                last = get_bits1(&s->gb);
4413
                run = get_bits(&s->gb, 6);
4414
                level = (int8_t)get_bits(&s->gb, 8);
4415
                if(level == -128){
4416
                    if (s->codec_id == CODEC_ID_RV10) {
4417
                        /* XXX: should patch encoder too */
4418
                        level = get_sbits(&s->gb, 12);
4419
                    }else{
4420
                        level = get_bits(&s->gb, 5);
4421
                        level |= get_sbits(&s->gb, 6)<<5;
4422
                    }
4423
                }
4424
            }
4425
        } else {
4426
            run = rl->table_run[code];
4427
            level = rl->table_level[code];
4428
            last = code >= rl->last;
4429
            if (get_bits1(&s->gb))
4430
                level = -level;
4431
        }
4432
        i += run;
4433
        if (i >= 64){
4434
            if(s->alt_inter_vlc && rl == &rl_inter && !s->mb_intra){
4435
                //looks like a hack but no, its the way its supposed to work ...
4436
                rl = &rl_intra_aic;
4437
                i = 0;
4438
                s->gb= gb;
4439
                memset(block, 0, sizeof(DCTELEM)*64);
4440
                goto retry;
4441
            }
4442
            av_log(s->avctx, AV_LOG_ERROR, "run overflow at %dx%d\n", s->mb_x, s->mb_y);
4443
            return -1;
4444
        }
4445
        j = scan_table[i];
4446
        block[j] = level;
4447
        if (last)
4448
            break;
4449
        i++;
4450
    }
4451
not_coded:    
4452
    if (s->mb_intra && s->h263_aic) {
4453
        h263_pred_acdc(s, block, n);
4454
        i = 63;
4455
    }
4456
    s->block_last_index[n] = i;
4457
    return 0;
4458
}
4459

    
4460
/**
4461
 * decodes the dc value.
4462
 * @param n block index (0-3 are luma, 4-5 are chroma)
4463
 * @param dir_ptr the prediction direction will be stored here
4464
 * @return the quantized dc
4465
 */
4466
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
4467
{
4468
    int level, pred, code;
4469
    uint16_t *dc_val;
4470

    
4471
    if (n < 4) 
4472
        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
4473
    else 
4474
        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
4475
    if (code < 0 || code > 9 /* && s->nbit<9 */){
4476
        av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
4477
        return -1;
4478
    }
4479
    if (code == 0) {
4480
        level = 0;
4481
    } else {
4482
        if(IS_3IV1){
4483
            if(code==1)
4484
                level= 2*get_bits1(&s->gb)-1;
4485
            else{
4486
                if(get_bits1(&s->gb))
4487
                    level = get_bits(&s->gb, code-1) + (1<<(code-1));
4488
                else
4489
                    level = -get_bits(&s->gb, code-1) - (1<<(code-1));
4490
            }
4491
        }else{
4492
            level = get_xbits(&s->gb, code);
4493
        }
4494

    
4495
        if (code > 8){
4496
            if(get_bits1(&s->gb)==0){ /* marker */
4497
                if(s->error_resilience>=2){
4498
                    av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
4499
                    return -1;
4500
                }
4501
            }
4502
        }
4503
    }
4504
    pred = ff_mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
4505
    level += pred;
4506
    if (level < 0){
4507
        if(s->error_resilience>=3){
4508
            av_log(s->avctx, AV_LOG_ERROR, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
4509
            return -1;
4510
        }
4511
        level = 0;
4512
    }
4513
    if (n < 4) {
4514
        *dc_val = level * s->y_dc_scale;
4515
    } else {
4516
        *dc_val = level * s->c_dc_scale;
4517
    }
4518
    if(IS_3IV1)
4519
        *dc_val = level * 8;
4520
    
4521
    if(s->error_resilience>=3){
4522
        if(*dc_val > 2048 + s->y_dc_scale + s->c_dc_scale){
4523
            av_log(s->avctx, AV_LOG_ERROR, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
4524
            return -1;
4525
        }
4526
    }
4527
    return level;
4528
}
4529

    
4530
/**
4531
 * decodes a block.
4532
 * @return <0 if an error occured
4533
 */
4534
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
4535
                              int n, int coded, int intra, int rvlc)
4536
{
4537
    int level, i, last, run;
4538
    int dc_pred_dir;
4539
    RLTable * rl;
4540
    RL_VLC_ELEM * rl_vlc;
4541
    const uint8_t * scan_table;
4542
    int qmul, qadd;
4543

    
4544
    //Note intra & rvlc should be optimized away if this is inlined
4545
    
4546
    if(intra) {
4547
      if(s->qscale < s->intra_dc_threshold){
4548
        /* DC coef */
4549
        if(s->partitioned_frame){
4550
            level = s->dc_val[0][ s->block_index[n] ];
4551
            if(n<4) level= FASTDIV((level + (s->y_dc_scale>>1)), s->y_dc_scale);
4552
            else    level= FASTDIV((level + (s->c_dc_scale>>1)), s->c_dc_scale);
4553
            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_stride]<<n)&32;
4554
        }else{
4555
            level = mpeg4_decode_dc(s, n, &dc_pred_dir);
4556
            if (level < 0)
4557
                return -1;
4558
        }
4559
        block[0] = level;
4560
        i = 0;
4561
      }else{
4562
            i = -1;
4563
      }  
4564
        if (!coded) 
4565
            goto not_coded;
4566
        
4567
        if(rvlc){        
4568
            rl = &rvlc_rl_intra;
4569
            rl_vlc = rvlc_rl_intra.rl_vlc[0];
4570
        }else{
4571
            rl = &rl_intra;
4572
            rl_vlc = rl_intra.rl_vlc[0];
4573
        }
4574
        if (s->ac_pred) {
4575
            if (dc_pred_dir == 0) 
4576
                scan_table = s->intra_v_scantable.permutated; /* left */
4577
            else
4578
                scan_table = s->intra_h_scantable.permutated; /* top */
4579
        } else {
4580
            scan_table = s->intra_scantable.permutated;
4581
        }
4582
        qmul=1;
4583
        qadd=0;
4584
    } else {
4585
        i = -1;
4586
        if (!coded) {
4587
            s->block_last_index[n] = i;
4588
            return 0;
4589
        }
4590
        if(rvlc) rl = &rvlc_rl_inter;
4591
        else     rl = &rl_inter;
4592
   
4593
        scan_table = s->intra_scantable.permutated;
4594

    
4595
        if(s->mpeg_quant){
4596
            qmul=1;
4597
            qadd=0;
4598
            if(rvlc){        
4599
                rl_vlc = rvlc_rl_inter.rl_vlc[0];        
4600
            }else{
4601
                rl_vlc = rl_inter.rl_vlc[0];        
4602
            }
4603
        }else{
4604
            qmul = s->qscale << 1;
4605
            qadd = (s->qscale - 1) | 1;
4606
            if(rvlc){        
4607
                rl_vlc = rvlc_rl_inter.rl_vlc[s->qscale];        
4608
            }else{
4609
                rl_vlc = rl_inter.rl_vlc[s->qscale];        
4610
            }
4611
        }
4612
    }
4613
  {
4614
    OPEN_READER(re, &s->gb);
4615
    for(;;) {
4616
        UPDATE_CACHE(re, &s->gb);
4617
        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
4618
        if (level==0) {
4619
          /* escape */                
4620
          if(rvlc){
4621
                if(SHOW_UBITS(re, &s->gb, 1)==0){
4622
                    av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n");
4623
                    return -1;
4624
                }; SKIP_CACHE(re, &s->gb, 1);
4625
 
4626
                last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
4627
                run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
4628
                SKIP_COUNTER(re, &s->gb, 1+1+6);
4629
                UPDATE_CACHE(re, &s->gb);
4630
              
4631
                if(SHOW_UBITS(re, &s->gb, 1)==0){
4632
                    av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n");
4633
                    return -1;
4634
                }; SKIP_CACHE(re, &s->gb, 1);
4635
 
4636
                level= SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11);
4637
 
4638
                if(SHOW_UBITS(re, &s->gb, 5)!=0x10){
4639
                    av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
4640
                    return -1;
4641
                }; SKIP_CACHE(re, &s->gb, 5);
4642

    
4643
                level=  level * qmul + qadd;
4644
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1);
4645
                SKIP_COUNTER(re, &s->gb, 1+11+5+1);
4646

    
4647
                i+= run + 1;
4648
                if(last) i+=192;
4649
          }else{
4650
            int cache;
4651
            cache= GET_CACHE(re, &s->gb);
4652

    
4653
            if(IS_3IV1) 
4654
                cache ^= 0xC0000000;
4655

    
4656
            if (cache&0x80000000) {
4657
                if (cache&0x40000000) {
4658
                    /* third escape */
4659
                    SKIP_CACHE(re, &s->gb, 2);
4660
                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
4661
                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
4662
                    SKIP_COUNTER(re, &s->gb, 2+1+6);
4663
                    UPDATE_CACHE(re, &s->gb);
4664

    
4665
                    if(IS_3IV1){
4666
                        level= SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12);
4667
                    }else{
4668
                        if(SHOW_UBITS(re, &s->gb, 1)==0){
4669
                            av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n");
4670
                            return -1;
4671
                        }; SKIP_CACHE(re, &s->gb, 1);
4672

    
4673
                        level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
4674

    
4675
                        if(SHOW_UBITS(re, &s->gb, 1)==0){
4676
                            av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n");
4677
                            return -1;
4678
                        }; LAST_SKIP_CACHE(re, &s->gb, 1);
4679

    
4680
                        SKIP_COUNTER(re, &s->gb, 1+12+1);
4681
                    }
4682
 
4683
                    if(level*s->qscale>1024 || level*s->qscale<-1024){
4684
                        av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
4685
                        return -1;
4686
                    }
4687
#if 0
4688
                    if(s->error_resilience >= FF_ER_COMPLIANT){
4689
                        const int abs_level= ABS(level);
4690
                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN){
4691
                            const int run1= run - rl->max_run[last][abs_level] - 1;
4692
                            if(abs_level <= rl->max_level[last][run]){
4693
                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
4694
                                return -1;
4695
                            }
4696
                            if(s->error_resilience > FF_ER_COMPLIANT){
4697
                                if(abs_level <= rl->max_level[last][run]*2){
4698
                                    fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");
4699
                                    return -1;
4700
                                }
4701
                                if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
4702
                                    fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");
4703
                                    return -1;
4704
                                }
4705
                            }
4706
                        }
4707
                    }
4708
#endif
4709
                    if (level>0) level= level * qmul + qadd;
4710
                    else         level= level * qmul - qadd;
4711

    
4712
                    i+= run + 1;
4713
                    if(last) i+=192;
4714
                } else {
4715
                    /* second escape */
4716
#if MIN_CACHE_BITS < 20
4717
                    LAST_SKIP_BITS(re, &s->gb, 2);
4718
                    UPDATE_CACHE(re, &s->gb);
4719
#else
4720
                    SKIP_BITS(re, &s->gb, 2);
4721
#endif
4722
                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
4723
                    i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
4724
                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
4725
                    LAST_SKIP_BITS(re, &s->gb, 1);
4726
                }
4727
            } else {
4728
                /* first escape */
4729
#if MIN_CACHE_BITS < 19
4730
                LAST_SKIP_BITS(re, &s->gb, 1);
4731
                UPDATE_CACHE(re, &s->gb);
4732
#else
4733
                SKIP_BITS(re, &s->gb, 1);
4734
#endif
4735
                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
4736
                i+= run;
4737
                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
4738
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
4739
                LAST_SKIP_BITS(re, &s->gb, 1);
4740
            }
4741
          }
4742
        } else {
4743
            i+= run;
4744
            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
4745
            LAST_SKIP_BITS(re, &s->gb, 1);
4746
        }
4747
        if (i > 62){
4748
            i-= 192;
4749
            if(i&(~63)){
4750
                av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
4751
                return -1;
4752
            }
4753

    
4754
            block[scan_table[i]] = level;
4755
            break;
4756
        }
4757

    
4758
        block[scan_table[i]] = level;
4759
    }
4760
    CLOSE_READER(re, &s->gb);
4761
  }
4762
 not_coded:
4763
    if (intra) {
4764
        if(s->qscale >= s->intra_dc_threshold){
4765
            uint16_t *dc_val;
4766
            block[0] += ff_mpeg4_pred_dc(s, n, &dc_val, &dc_pred_dir);
4767
            if (n < 4) {
4768
                *dc_val = block[0] * s->y_dc_scale;
4769
            } else {
4770
                *dc_val = block[0] * s->c_dc_scale;
4771
            }
4772

    
4773
            if(i == -1) i=0;
4774
        }
4775

    
4776
        mpeg4_pred_ac(s, block, n, dc_pred_dir);
4777
        if (s->ac_pred) {
4778
            i = 63; /* XXX: not optimal */
4779
        }
4780
    }
4781
    s->block_last_index[n] = i;
4782
    return 0;
4783
}
4784

    
4785
/* most is hardcoded. should extend to handle all h263 streams */
4786
int h263_decode_picture_header(MpegEncContext *s)
4787
{
4788
    int format, width, height, i;
4789
    uint32_t startcode;
4790