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

34 35 36 37
//#undef NDEBUG
//#include <assert.h>

#if 1
Felix Bünemann's avatar
Felix Bünemann committed
38
#define PRINT_MB_TYPE(a) {}
39 40 41
#else
#define PRINT_MB_TYPE(a) printf(a)
#endif
Michael Niedermayer's avatar
Michael Niedermayer committed
42

43 44 45 46 47 48 49 50 51
#define INTRA_MCBPC_VLC_BITS 6
#define INTER_MCBPC_VLC_BITS 6
#define CBPY_VLC_BITS 6
#define MV_VLC_BITS 9
#define DC_VLC_BITS 9
#define SPRITE_TRAJ_VLC_BITS 6
#define MB_TYPE_B_VLC_BITS 4
#define TEX_VLC_BITS 9

52
#ifdef CONFIG_ENCODERS
Fabrice Bellard's avatar
Fabrice Bellard committed
53 54
static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
			      int n);
55
static void h263_encode_motion(MpegEncContext * s, int val, int fcode);
56
static void h263p_encode_umotion(MpegEncContext * s, int val);
57
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
58 59
			       int n, int dc, UINT8 *scan_table, 
                               PutBitContext *dc_pb, PutBitContext *ac_pb);
60 61
#endif

Michael Niedermayer's avatar
Michael Niedermayer committed
62
static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
63
static int h263p_decode_umotion(MpegEncContext * s, int pred);
Fabrice Bellard's avatar
Fabrice Bellard committed
64 65
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
                             int n, int coded);
66 67
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr);
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
Michael Niedermayer's avatar
Michael Niedermayer committed
68
                              int n, int coded, int intra);
69
static int h263_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr);
70 71
static void mpeg4_inv_pred_ac(MpegEncContext * s, INT16 *block, int n,
                              int dir);
72
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s);
73 74
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr, int *dir_ptr);

75
extern UINT32 inverse[256];
Fabrice Bellard's avatar
Fabrice Bellard committed
76

77 78 79 80 81
static UINT16 uni_DCtab_lum  [512][2];
static UINT16 uni_DCtab_chrom[512][2];

#ifdef CONFIG_ENCODERS
static UINT16 (*mv_penalty)[MAX_MV*2+1]= NULL;
82
static UINT8 fcode_tab[MAX_MV*2+1];
83
static UINT8 umv_fcode_tab[MAX_MV*2+1];
84

Michael Niedermayer's avatar
Michael Niedermayer committed
85 86 87 88 89
static uint32_t uni_mpeg4_intra_rl_bits[64*64*2*2];
static uint8_t  uni_mpeg4_intra_rl_len [64*64*2*2];
static uint32_t uni_mpeg4_inter_rl_bits[64*64*2*2];
static uint8_t  uni_mpeg4_inter_rl_len [64*64*2*2];
//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
90
//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
Michael Niedermayer's avatar
Michael Niedermayer committed
91
#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
92 93 94 95 96 97 98 99 100 101

/* mpeg4
inter
max level: 24/6
max run: 53/63

intra
max level: 53/16
max run: 29/41
*/
102 103
#endif

104

Fabrice Bellard's avatar
Fabrice Bellard committed
105 106 107 108 109
int h263_get_picture_format(int width, int height)
{
    int format;

    if (width == 128 && height == 96)
110
        format = 1;
Fabrice Bellard's avatar
Fabrice Bellard committed
111
    else if (width == 176 && height == 144)
112
        format = 2;
Fabrice Bellard's avatar
Fabrice Bellard committed
113
    else if (width == 352 && height == 288)
114
        format = 3;
Fabrice Bellard's avatar
Fabrice Bellard committed
115
    else if (width == 704 && height == 576)
116
        format = 4;
Fabrice Bellard's avatar
Fabrice Bellard committed
117
    else if (width == 1408 && height == 1152)
118
        format = 5;
Fabrice Bellard's avatar
Fabrice Bellard committed
119 120 121 122 123
    else
        format = 7;
    return format;
}

Michael Niedermayer's avatar
Michael Niedermayer committed
124 125 126 127 128
static void float_aspect_to_info(MpegEncContext * s, float aspect){
    int i;

    aspect*= s->height/(double)s->width;
//printf("%f\n", aspect);
Michael Niedermayer's avatar
Michael Niedermayer committed
129
    
Michael Niedermayer's avatar
Michael Niedermayer committed
130 131
    if(aspect==0) aspect= 1.0;

Michael Niedermayer's avatar
Michael Niedermayer committed
132
    ff_float2fraction(&s->aspected_width, &s->aspected_height, aspect, 255);
Michael Niedermayer's avatar
Michael Niedermayer committed
133 134 135 136 137 138 139 140

//printf("%d %d\n", s->aspected_width, s->aspected_height);
    for(i=1; i<6; i++){
        if(s->aspected_width == pixel_aspect[i][0] && s->aspected_height== pixel_aspect[i][1]){
            s->aspect_ratio_info=i;
            return;
        }
    }
Michael Niedermayer's avatar
Michael Niedermayer committed
141
    
Michael Niedermayer's avatar
Michael Niedermayer committed
142
    s->aspect_ratio_info= FF_ASPECT_EXTENDED;
Michael Niedermayer's avatar
Michael Niedermayer committed
143 144
}

Fabrice Bellard's avatar
Fabrice Bellard committed
145 146
void h263_encode_picture_header(MpegEncContext * s, int picture_number)
{
147
    int format;
Fabrice Bellard's avatar
Fabrice Bellard committed
148 149

    align_put_bits(&s->pb);
150 151

    /* Update the pointer to last GOB */
152
    s->ptr_lastgob = pbBufPtr(&s->pb);
153 154 155
    s->gob_number = 0;

    put_bits(&s->pb, 22, 0x20); /* PSC */
156
    put_bits(&s->pb, 8, (((INT64)s->picture_number * 30 * FRAME_RATE_BASE) / 
Fabrice Bellard's avatar
Fabrice Bellard committed
157 158 159 160 161 162 163
                         s->frame_rate) & 0xff);

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

            put_bits(&s->pb,4,s->aspect_ratio_info);
220 221 222
            put_bits(&s->pb,9,(s->width >> 2) - 1);
            put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
            put_bits(&s->pb,9,(s->height >> 2));
223 224 225 226 227
	    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
	    {
		put_bits(&s->pb, 8, s->aspected_width);
		put_bits(&s->pb, 8, s->aspected_height);
	    }
228 229
        }
        
Fabrice Bellard's avatar
Fabrice Bellard committed
230
        /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
231
        if (s->umvplus)
Fabrice Bellard's avatar
Fabrice Bellard committed
232 233 234 235 236
            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
        put_bits(&s->pb, 5, s->qscale);
    }

    put_bits(&s->pb, 1, 0);	/* no PEI */
237 238 239 240 241 242 243 244

    if(s->h263_aic){
         s->y_dc_scale_table= 
         s->c_dc_scale_table= h263_aic_dc_scale_table;
    }else{
        s->y_dc_scale_table=
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
245 246
}

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

static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6])
{
    int score0=0, score1=0;
    int i, n;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
272
    int8_t * const qscale_table= s->current_picture.qscale_table;
273 274 275 276

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

Michael Niedermayer's avatar
Michael Niedermayer committed
277
        ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
278 279
        ac_val1= ac_val;
        if(dir[n]){
280 281
            const int xy= s->mb_x + s->mb_y*s->mb_width - s->mb_width;
            /* top prediction */
Michael Niedermayer's avatar
Michael Niedermayer committed
282
            ac_val-= s->block_wrap[n]*16;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
283
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
284 285
                /* same qscale */
                for(i=1; i<8; i++){
286
                    const int level= block[n][s->idct_permutation[i   ]];
287 288
                    score0+= ABS(level);
                    score1+= ABS(level - ac_val[i+8]);
289
                    ac_val1[i  ]=    block[n][s->idct_permutation[i<<3]];
290 291 292 293 294
                    ac_val1[i+8]= level;
                }
            }else{
                /* different qscale, we must rescale */
                for(i=1; i<8; i++){
295
                    const int level= block[n][s->idct_permutation[i   ]];
296
                    score0+= ABS(level);
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
297
                    score1+= ABS(level - ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale));
298
                    ac_val1[i  ]=    block[n][s->idct_permutation[i<<3]];
299 300
                    ac_val1[i+8]= level;
                }
301 302
            }
        }else{
303 304
            const int xy= s->mb_x-1 + s->mb_y*s->mb_width;
            /* left prediction */
305
            ac_val-= 16;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
306
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
307 308
                /* same qscale */
                for(i=1; i<8; i++){
309
                    const int level= block[n][s->idct_permutation[i<<3]];
310 311 312
                    score0+= ABS(level);
                    score1+= ABS(level - ac_val[i]);
                    ac_val1[i  ]= level;
313
                    ac_val1[i+8]=    block[n][s->idct_permutation[i   ]];
314 315 316 317
                }
            }else{
                /* different qscale, we must rescale */
                for(i=1; i<8; i++){
318
                    const int level= block[n][s->idct_permutation[i<<3]];
319
                    score0+= ABS(level);
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
320
                    score1+= ABS(level - ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale));
321
                    ac_val1[i  ]= level;
322
                    ac_val1[i+8]=    block[n][s->idct_permutation[i   ]];
323
                }
324 325 326 327 328 329 330
            }
        }
    }

    return score0 > score1 ? 1 : 0;    
}

331 332 333
/**
 * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
 */
334
void ff_clean_h263_qscales(MpegEncContext *s){
335
    int i;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
336
    int8_t * const qscale_table= s->current_picture.qscale_table;
337 338
    
    for(i=1; i<s->mb_num; i++){
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
339 340
        if(qscale_table[i] - qscale_table[i-1] >2)
            qscale_table[i]= qscale_table[i-1]+2;
341 342
    }
    for(i=s->mb_num-2; i>=0; i--){
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
343 344
        if(qscale_table[i] - qscale_table[i+1] >2)
            qscale_table[i]= qscale_table[i+1]+2;
345
    }
346 347
}

348 349 350
/**
 * modify mb_type & qscale so that encoding is acually possible in mpeg4
 */
351 352
void ff_clean_mpeg4_qscales(MpegEncContext *s){
    int i;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
353 354
    int8_t * const qscale_table= s->current_picture.qscale_table;

355
    ff_clean_h263_qscales(s);
356 357
    
    for(i=1; i<s->mb_num; i++){
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
358
        if(qscale_table[i] != qscale_table[i-1] && (s->mb_type[i]&MB_TYPE_INTER4V)){
359 360 361 362 363 364 365 366 367 368 369
            s->mb_type[i]&= ~MB_TYPE_INTER4V;
            s->mb_type[i]|= MB_TYPE_INTER;
        }
    }

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

Michael Niedermayer's avatar
Michael Niedermayer committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
void ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
    const int mb_index= s->mb_x + s->mb_y*s->mb_width;
    int xy= s->block_index[0];
    uint16_t time_pp= s->pp_time;
    uint16_t time_pb= s->pb_time;
    int i;
        
    //FIXME avoid divides
    switch(s->co_located_type_table[mb_index]){
    case 0:
        s->mv_type= MV_TYPE_16X16;
        s->mv[0][0][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
        s->mv[0][0][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
        s->mv[1][0][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
                            : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
        s->mv[1][0][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1] 
                            : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
        break;
    case CO_LOCATED_TYPE_4MV:
        s->mv_type = MV_TYPE_8X8;
        for(i=0; i<4; i++){
            xy= s->block_index[i];
            s->mv[0][i][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
            s->mv[0][i][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->motion_val[xy][0]
                                : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->motion_val[xy][1] 
                                : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
        }
        break;
    case CO_LOCATED_TYPE_FIELDMV:
        s->mv_type = MV_TYPE_FIELD;
        for(i=0; i<2; i++){
            if(s->top_field_first){
                time_pp= s->pp_field_time - s->field_select_table[mb_index][i] + i;
                time_pb= s->pb_field_time - s->field_select_table[mb_index][i] + i;
            }else{
                time_pp= s->pp_field_time + s->field_select_table[mb_index][i] - i;
                time_pb= s->pb_field_time + s->field_select_table[mb_index][i] - i;
            }
            s->mv[0][i][0] = s->field_mv_table[mb_index][i][0]*time_pb/time_pp + mx;
            s->mv[0][i][1] = s->field_mv_table[mb_index][i][1]*time_pb/time_pp + my;
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->field_mv_table[mb_index][i][0]
                                : s->field_mv_table[mb_index][i][0]*(time_pb - time_pp)/time_pp;
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->field_mv_table[mb_index][i][1] 
                                : s->field_mv_table[mb_index][i][1]*(time_pb - time_pp)/time_pp;
        }
        break;
    }
}

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

        if(s->pict_type==B_TYPE){
            static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
            int mb_type=  mb_type_table[s->mv_dir];
            
            if(s->mb_x==0){
                s->last_mv[0][0][0]= 
                s->last_mv[0][0][1]= 
                s->last_mv[1][0][0]= 
                s->last_mv[1][0][1]= 0;
            }
475 476 477 478
            
            assert(s->dquant>=-2 && s->dquant<=2);
            assert((s->dquant&1)==0);
            assert(mb_type>=0);
479 480

            /* nothing to do if this MB was skiped in the next P Frame */
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
481
            if(s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x]){ //FIXME avoid DCT & ...
482 483 484 485 486
                s->skip_count++;
                s->mv[0][0][0]= 
                s->mv[0][0][1]= 
                s->mv[1][0][0]= 
                s->mv[1][0][1]= 0;
487
                s->mv_dir= MV_DIR_FORWARD; //doesnt matter
488
                s->qscale -= s->dquant;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
489 490
//                s->mb_skiped=1;

491 492
                return;
            }
Michael Niedermayer's avatar
Michael Niedermayer committed
493
            
494 495
            if ((cbp | motion_x | motion_y | mb_type) ==0) {
                /* direct MB with MV={0,0} */
496 497
                assert(s->dquant==0);
                
498
                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
499 500 501 502 503

                if(interleaved_stats){
                    s->misc_bits++;
                    s->last_bits++;
                }
504 505 506
                s->skip_count++;
                return;
            }
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
507
            
508 509 510 511 512
            put_bits(&s->pb, 1, 0);	/* mb coded modb1=0 */
            put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
            put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we dont need it :)
            if(cbp) put_bits(&s->pb, 6, cbp);
            
513 514 515 516 517 518 519
            if(cbp && mb_type){
                if(s->dquant)
                    put_bits(&s->pb, 2, (s->dquant>>2)+3);
                else
                    put_bits(&s->pb, 1, 0);
            }else
                s->qscale -= s->dquant;
520 521 522 523 524 525 526
            
            if(!s->progressive_sequence){
                if(cbp)
                    put_bits(&s->pb, 1, s->interlaced_dct);
                if(mb_type) // not diect mode
                    put_bits(&s->pb, 1, 0); // no interlaced ME yet
            }
527

528 529 530 531 532
            if(interleaved_stats){
                bits= get_bit_count(&s->pb);
                s->misc_bits+= bits - s->last_bits;
                s->last_bits=bits;
            }
Michael Niedermayer's avatar
Michael Niedermayer committed
533

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

            if(interleaved_stats){
                bits= get_bit_count(&s->pb);
                s->mv_bits+= bits - s->last_bits;
                s->last_bits=bits;
            }
578

579 580
            /* encode each block */
            for (i = 0; i < 6; i++) {
581
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, &s->pb);
582 583 584 585 586 587
            }

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

                    x= s->mb_x*16;
                    y= s->mb_y*16;
                    if(x+16 > s->width)  x= s->width-16;
                    if(y+16 > s->height) y= s->height-16;

                    offset= x + y*s->linesize;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
604
                    p_pic= s->new_picture.data[0] + offset;
605
                    
Michael Niedermayer's avatar
Michael Niedermayer committed
606 607
                    s->mb_skiped=1;
                    for(i=0; i<s->max_b_frames; i++){
Michael Niedermayer's avatar
Michael Niedermayer committed
608 609
                        uint8_t *b_pic;
                        int diff;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
610
                        Picture *pic= s->reordered_input_picture[i+1];
Michael Niedermayer's avatar
Michael Niedermayer committed
611

Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
612
                        if(pic==NULL || pic->pict_type!=B_TYPE) break;
Michael Niedermayer's avatar
Michael Niedermayer committed
613

Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
614
                        b_pic= pic->data[0] + offset + 16; //FIXME +16
615
			diff= s->dsp.pix_abs16x16(p_pic, b_pic, s->linesize);
616
                        if(diff>s->qscale*70){ //FIXME check that 70 is optimal
Michael Niedermayer's avatar
Michael Niedermayer committed
617 618 619 620 621 622 623 624 625 626
                            s->mb_skiped=0;
                            break;
                        }
                    }
                }else
                    s->mb_skiped=1; 

                if(s->mb_skiped==1){
                    /* skip macroblock */
                    put_bits(&s->pb, 1, 1);
627 628 629 630 631

                    if(interleaved_stats){
                        s->misc_bits++;
                        s->last_bits++;
                    }
Michael Niedermayer's avatar
Michael Niedermayer committed
632 633 634
                    s->skip_count++;
                    return;
                }
635
            }
636

637 638 639
            put_bits(&s->pb, 1, 0);	/* mb coded */
            if(s->mv_type==MV_TYPE_16X16){
                cbpc = cbp & 3;
640
                if(s->dquant) cbpc+= 8;
641 642 643
                put_bits(&s->pb,
                        inter_MCBPC_bits[cbpc],
                        inter_MCBPC_code[cbpc]);
644

645 646
                cbpy = cbp >> 2;
                cbpy ^= 0xf;
647
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
648 649
                if(s->dquant)
                    put_bits(pb2, 2, dquant_code[s->dquant+2]);
650 651 652 653 654 655

                if(!s->progressive_sequence){
                    if(cbp)
                        put_bits(pb2, 1, s->interlaced_dct);
                    put_bits(pb2, 1, 0); // no interlaced ME yet
                }
656
                    
657 658 659 660 661
                if(interleaved_stats){
                    bits= get_bit_count(&s->pb);
                    s->misc_bits+= bits - s->last_bits;
                    s->last_bits=bits;
                }
662

663 664 665 666 667 668 669 670 671 672 673 674
                /* motion vectors: 16x16 mode */
                h263_pred_motion(s, 0, &pred_x, &pred_y);
            
                h263_encode_motion(s, motion_x - pred_x, s->f_code);
                h263_encode_motion(s, motion_y - pred_y, s->f_code);
            }else{
                cbpc = (cbp & 3)+16;
                put_bits(&s->pb,
                        inter_MCBPC_bits[cbpc],
                        inter_MCBPC_code[cbpc]);
                cbpy = cbp >> 2;
                cbpy ^= 0xf;
675
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
676

677 678 679 680 681
                if(!s->progressive_sequence){
                    if(cbp)
                        put_bits(pb2, 1, s->interlaced_dct);
                }
    
682 683 684 685 686
                if(interleaved_stats){
                    bits= get_bit_count(&s->pb);
                    s->misc_bits+= bits - s->last_bits;
                    s->last_bits=bits;
                }
687 688 689 690 691 692 693 694

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

                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x, s->f_code);
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y, s->f_code);
                }
Michael Niedermayer's avatar
Michael Niedermayer committed
695
            }
696 697 698 699 700 701

            if(interleaved_stats){ 
                bits= get_bit_count(&s->pb);
                s->mv_bits+= bits - s->last_bits;
                s->last_bits=bits;
            }
702

703 704
            /* encode each block */
            for (i = 0; i < 6; i++) {
705
                mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, tex_pb);
706 707 708 709 710 711
            }

            if(interleaved_stats){
                bits= get_bit_count(&s->pb);
                s->p_tex_bits+= bits - s->last_bits;
                s->last_bits=bits;
712
            }
713
            s->f_count++;
714 715
        }
    } else {
716
        int cbp;
717 718 719 720 721 722 723 724 725
        int dc_diff[6];   //dc values with the dc prediction subtracted 
        int dir[6];  //prediction direction
        int zigzag_last_index[6];
        UINT8 *scan_table[6];

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

726
            dc_diff[i]= level - ff_mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
            if (i < 4) {
                *dc_ptr = level * s->y_dc_scale;
            } else {
                *dc_ptr = level * s->c_dc_scale;
            }
        }

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

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

                mpeg4_inv_pred_ac(s, block[i], i, dir[i]);
742 743
                if (dir[i]==0) st = s->intra_v_scantable.permutated; /* left */
                else           st = s->intra_h_scantable.permutated; /* top */
744 745 746 747 748 749 750 751 752

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

        /* compute cbp */
        cbp = 0;
        for (i = 0; i < 6; i++) {
            if (s->block_last_index[i] >= 1)
                cbp |= 1 << (5 - i);
        }

        cbpc = cbp & 3;
        if (s->pict_type == I_TYPE) {
765
            if(s->dquant) cbpc+=4;
766 767 768 769
            put_bits(&s->pb,
                intra_MCBPC_bits[cbpc],
                intra_MCBPC_code[cbpc]);
        } else {
770
            if(s->dquant) cbpc+=8;
771 772 773 774 775
            put_bits(&s->pb, 1, 0);	/* mb coded */
            put_bits(&s->pb,
                inter_MCBPC_bits[cbpc + 4],
                inter_MCBPC_code[cbpc + 4]);
        }
776
        put_bits(pb2, 1, s->ac_pred);
777
        cbpy = cbp >> 2;
778
        put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
779 780
        if(s->dquant)
            put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
781

782 783 784 785
        if(!s->progressive_sequence){
            put_bits(dc_pb, 1, s->interlaced_dct);
        }

786 787 788 789 790
        if(interleaved_stats){
            bits= get_bit_count(&s->pb);
            s->misc_bits+= bits - s->last_bits;
            s->last_bits=bits;
        }
791

792 793
        /* encode each block */
        for (i = 0; i < 6; i++) {
794
            mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
795 796
        }

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

804 805 806 807 808 809
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
        if(s->ac_pred){
            for(i=0; i<6; i++){
                int j;    
                INT16 *ac_val;

Michael Niedermayer's avatar
Michael Niedermayer committed
810
                ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
811 812 813

                if(dir[i]){
                    for(j=1; j<8; j++) 
814
                        block[i][s->idct_permutation[j   ]]= ac_val[j+8];
815 816
                }else{
                    for(j=1; j<8; j++) 
817
                        block[i][s->idct_permutation[j<<3]]= ac_val[j  ];
818 819 820 821 822 823 824
                }
                s->block_last_index[i]= zigzag_last_index[i];
            }
        }
    }
}

Fabrice Bellard's avatar
Fabrice Bellard committed
825 826 827 828 829
void h263_encode_mb(MpegEncContext * s,
		    DCTELEM block[6][64],
		    int motion_x, int motion_y)
{
    int cbpc, cbpy, i, cbp, pred_x, pred_y;
830 831 832
    INT16 pred_dc;
    INT16 rec_intradc[6];
    UINT16 *dc_ptr[6];
833
    const int dquant_code[5]= {1,0,9,2,3};
834 835
           
    //printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
836
    if (!s->mb_intra) {
837
        /* compute cbp */
838 839 840 841 842
        cbp = 0;
        for (i = 0; i < 6; i++) {
            if (s->block_last_index[i] >= 0)
                cbp |= 1 << (5 - i);
        }
843
        if ((cbp | motion_x | motion_y | s->dquant) == 0) {
844 845 846 847
            /* skip macroblock */
            put_bits(&s->pb, 1, 1);
            return;
        }
848
        put_bits(&s->pb, 1, 0);	/* mb coded */
849
        cbpc = cbp & 3;
850
        if(s->dquant) cbpc+= 8;
851
        put_bits(&s->pb,
852 853
		    inter_MCBPC_bits[cbpc],
		    inter_MCBPC_code[cbpc]);
854 855 856
        cbpy = cbp >> 2;
        cbpy ^= 0xf;
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
857 858
        if(s->dquant)
            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
859

860
        /* motion vectors: 16x16 mode only now */
861
        h263_pred_motion(s, 0, &pred_x, &pred_y);
862
      
863 864 865 866 867 868 869 870
        if (!s->umvplus) {  
            h263_encode_motion(s, motion_x - pred_x, s->f_code);
            h263_encode_motion(s, motion_y - pred_y, s->f_code);
        }
        else {
            h263p_encode_umotion(s, motion_x - pred_x);
            h263p_encode_umotion(s, motion_y - pred_y);
            if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
871
                /* To prevent Start Code emulation */
872 873
                put_bits(&s->pb,1,1);
        }
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
    } else {
        int li = s->h263_aic ? 0 : 1;
        
        cbp = 0;
        for(i=0; i<6; i++) {
            /* Predict DC */
            if (s->h263_aic && s->mb_intra) {
                INT16 level = block[i][0];
            
                pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
                level -= pred_dc;
                /* Quant */
                if (level < 0)
                    level = (level