h263.c 213 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
 * Copyright (c) 2001 Juan J. Sierralta P.
6
 * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
Fabrice Bellard's avatar
Fabrice Bellard committed
7
 *
8 9 10
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
Fabrice Bellard's avatar
Fabrice Bellard committed
11 12
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
13
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
14
 *
15
 * FFmpeg is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Fabrice Bellard's avatar
Fabrice Bellard committed
17 18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
19
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
20
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with FFmpeg; if not, write to the Free Software
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23
 *
24
 * ac prediction encoding, b-frame support, error resilience, optimizations,
25
 * qpel decoding, gmc decoding, interlaced decoding,
26
 * by Michael Niedermayer <michaelni@gmx.at>
Fabrice Bellard's avatar
Fabrice Bellard committed
27
 */
Michael Niedermayer's avatar
Michael Niedermayer committed
28 29 30

/**
 * @file h263.c
Michael Niedermayer's avatar
Michael Niedermayer committed
31
 * h263/mpeg4 codec.
Michael Niedermayer's avatar
Michael Niedermayer committed
32
 */
33

34
//#define DEBUG
35 36
#include <limits.h>

Fabrice Bellard's avatar
Fabrice Bellard committed
37 38 39 40 41 42
#include "dsputil.h"
#include "avcodec.h"
#include "mpegvideo.h"
#include "h263data.h"
#include "mpeg4data.h"

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

46
#define INTRA_MCBPC_VLC_BITS 6
Michael Niedermayer's avatar
Michael Niedermayer committed
47
#define INTER_MCBPC_VLC_BITS 7
48 49 50 51 52 53
#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
54 55
#define H263_MBTYPE_B_VLC_BITS 6
#define CBPC_B_VLC_BITS 3
56

57
#ifdef CONFIG_ENCODERS
Fabrice Bellard's avatar
Fabrice Bellard committed
58
static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
59
                              int n);
60
static void h263p_encode_umotion(MpegEncContext * s, int val);
61
static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
62
                               int n, int dc, uint8_t *scan_table,
63
                               PutBitContext *dc_pb, PutBitContext *ac_pb);
64 65
static int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc,
                                  uint8_t *scan_table);
66 67
#endif

Michael Niedermayer's avatar
Michael Niedermayer committed
68
static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
69
static int h263p_decode_umotion(MpegEncContext * s, int pred);
Fabrice Bellard's avatar
Fabrice Bellard committed
70 71
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
                             int n, int coded);
72 73
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
74
                              int n, int coded, int intra, int rvlc);
75
#ifdef CONFIG_ENCODERS
Måns Rullgård's avatar
Måns Rullgård committed
76
static int h263_pred_dc(MpegEncContext * s, int n, int16_t **dc_val_ptr);
77 78
static void mpeg4_encode_visual_object_header(MpegEncContext * s);
static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number);
79
#endif //CONFIG_ENCODERS
Michael Niedermayer's avatar
Michael Niedermayer committed
80
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s, GetBitContext *gb);
81
static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, int level, int *dir_ptr, int encoding);
82

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

89
static uint8_t mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
90 91
static uint8_t fcode_tab[MAX_MV*2+1];
static uint8_t umv_fcode_tab[MAX_MV*2+1];
92

Michael Niedermayer's avatar
Michael Niedermayer committed
93 94 95 96
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];
97 98
static uint8_t  uni_h263_intra_aic_rl_len [64*64*2*2];
static uint8_t  uni_h263_inter_rl_len [64*64*2*2];
Michael Niedermayer's avatar
Michael Niedermayer committed
99
//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
100
//#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
Michael Niedermayer's avatar
Michael Niedermayer committed
101
#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
102 103 104 105 106 107 108 109 110 111

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

intra
max level: 53/16
max run: 29/41
*/
112 113
#endif

114 115
static uint8_t static_rl_table_store[5][2][2*MAX_RUN + MAX_LEVEL + 3];

116
#if 0 //3IV1 is quite rare and it slows things down a tiny bit
117
#define IS_3IV1 s->codec_tag == ff_get_fourcc("3IV1")
118
#else
119 120
#define IS_3IV1 0
#endif
121

Fabrice Bellard's avatar
Fabrice Bellard committed
122 123 124 125 126
int h263_get_picture_format(int width, int height)
{
    int format;

    if (width == 128 && height == 96)
127
        format = 1;
Fabrice Bellard's avatar
Fabrice Bellard committed
128
    else if (width == 176 && height == 144)
129
        format = 2;
Fabrice Bellard's avatar
Fabrice Bellard committed
130
    else if (width == 352 && height == 288)
131
        format = 3;
Fabrice Bellard's avatar
Fabrice Bellard committed
132
    else if (width == 704 && height == 576)
133
        format = 4;
Fabrice Bellard's avatar
Fabrice Bellard committed
134
    else if (width == 1408 && height == 1152)
135
        format = 5;
Fabrice Bellard's avatar
Fabrice Bellard committed
136 137 138 139 140
    else
        format = 7;
    return format;
}

141 142
#ifdef CONFIG_ENCODERS

Michael Niedermayer's avatar
Michael Niedermayer committed
143
static void aspect_to_info(MpegEncContext * s, AVRational aspect){
Michael Niedermayer's avatar
Michael Niedermayer committed
144 145
    int i;

Michael Niedermayer's avatar
Michael Niedermayer committed
146
    if(aspect.num==0) aspect= (AVRational){1,1};
Michael Niedermayer's avatar
Michael Niedermayer committed
147 148

    for(i=1; i<6; i++){
Michael Niedermayer's avatar
Michael Niedermayer committed
149
        if(av_cmp_q(pixel_aspect[i], aspect) == 0){
Michael Niedermayer's avatar
Michael Niedermayer committed
150 151 152 153
            s->aspect_ratio_info=i;
            return;
        }
    }
154

Michael Niedermayer's avatar
Michael Niedermayer committed
155
    s->aspect_ratio_info= FF_ASPECT_EXTENDED;
Michael Niedermayer's avatar
Michael Niedermayer committed
156 157
}

Michael Niedermayer's avatar
Michael Niedermayer committed
158
void ff_flv_encode_picture_header(MpegEncContext * s, int picture_number)
Fabrice Bellard's avatar
Fabrice Bellard committed
159
{
Michael Niedermayer's avatar
Michael Niedermayer committed
160
      int format;
Fabrice Bellard's avatar
Fabrice Bellard committed
161

Michael Niedermayer's avatar
Michael Niedermayer committed
162
      align_put_bits(&s->pb);
163

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

      if(s->h263_aic){
196
        s->y_dc_scale_table=
Michael Niedermayer's avatar
Michael Niedermayer committed
197
          s->c_dc_scale_table= ff_aic_dc_scale_table;
198 199 200 201
      }else{
        s->y_dc_scale_table=
          s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
      }
Michael Niedermayer's avatar
Michael Niedermayer committed
202 203 204 205
}

void h263_encode_picture_header(MpegEncContext * s, int picture_number)
{
Michael Niedermayer's avatar
Michael Niedermayer committed
206 207 208 209
    int format, coded_frame_rate, coded_frame_rate_base, i, temp_ref;
    int best_clock_code=1;
    int best_divisor=60;
    int best_error= INT_MAX;
210

Michael Niedermayer's avatar
Michael Niedermayer committed
211 212 213
    if(s->h263_plus){
        for(i=0; i<2; i++){
            int div, error;
214
            div= (s->avctx->time_base.num*1800000LL + 500LL*s->avctx->time_base.den) / ((1000LL+i)*s->avctx->time_base.den);
215
            div= av_clip(div, 1, 127);
Diego Biurrun's avatar
Diego Biurrun committed
216
            error= FFABS(s->avctx->time_base.num*1800000LL - (1000LL+i)*s->avctx->time_base.den*div);
Michael Niedermayer's avatar
Michael Niedermayer committed
217 218 219 220 221 222 223 224 225 226
            if(error < best_error){
                best_error= error;
                best_divisor= div;
                best_clock_code= i;
            }
        }
    }
    s->custom_pcf= best_clock_code!=1 || best_divisor!=60;
    coded_frame_rate= 1800000;
    coded_frame_rate_base= (1000+best_clock_code)*best_divisor;
Michael Niedermayer's avatar
Michael Niedermayer committed
227 228

    align_put_bits(&s->pb);
229

230
    /* Update the pointer to last GOB */
231
    s->ptr_lastgob = pbBufPtr(&s->pb);
232
    put_bits(&s->pb, 22, 0x20); /* PSC */
233 234
    temp_ref= s->picture_number * (int64_t)coded_frame_rate * s->avctx->time_base.num / //FIXME use timestamp
                         (coded_frame_rate_base * (int64_t)s->avctx->time_base.den);
Michael Niedermayer's avatar
Michael Niedermayer committed
235
    put_bits(&s->pb, 8, temp_ref & 0xff); /* TemporalReference */
Fabrice Bellard's avatar
Fabrice Bellard committed
236

237 238 239 240 241
    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 */
242

243
    format = h263_get_picture_format(s->width, s->height);
Fabrice Bellard's avatar
Fabrice Bellard committed
244 245 246 247 248 249 250
    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 */
251 252 253 254
        put_bits(&s->pb, 1, 0);         /* Unrestricted Motion Vector: off */
        put_bits(&s->pb, 1, 0);         /* SAC: off */
        put_bits(&s->pb, 1, s->obmc);   /* Advanced Prediction */
        put_bits(&s->pb, 1, 0);         /* only I/P frames, no PB frame */
Fabrice Bellard's avatar
Fabrice Bellard committed
255
        put_bits(&s->pb, 5, s->qscale);
256
        put_bits(&s->pb, 1, 0);         /* Continuous Presence Multipoint mode: off */
Fabrice Bellard's avatar
Fabrice Bellard committed
257
    } else {
Michael Niedermayer's avatar
Michael Niedermayer committed
258
        int ufep=1;
Fabrice Bellard's avatar
Fabrice Bellard committed
259 260
        /* H.263v2 */
        /* H.263 Plus PTYPE */
261

Fabrice Bellard's avatar
Fabrice Bellard committed
262
        put_bits(&s->pb, 3, 7);
Michael Niedermayer's avatar
Michael Niedermayer committed
263
        put_bits(&s->pb,3,ufep); /* Update Full Extended PTYPE */
264 265 266 267
        if (format == 7)
            put_bits(&s->pb,3,6); /* Custom Source Format */
        else
            put_bits(&s->pb, 3, format);
268

Michael Niedermayer's avatar
Michael Niedermayer committed
269
        put_bits(&s->pb,1, s->custom_pcf);
270
        put_bits(&s->pb,1, s->umvplus); /* Unrestricted Motion Vector */
Fabrice Bellard's avatar
Fabrice Bellard committed
271
        put_bits(&s->pb,1,0); /* SAC: off */
Michael Niedermayer's avatar
Michael Niedermayer committed
272
        put_bits(&s->pb,1,s->obmc); /* Advanced Prediction Mode */
273
        put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
Michael Niedermayer's avatar
Michael Niedermayer committed
274
        put_bits(&s->pb,1,s->loop_filter); /* Deblocking Filter */
275
        put_bits(&s->pb,1,s->h263_slice_structured); /* Slice Structured */
Fabrice Bellard's avatar
Fabrice Bellard committed
276 277
        put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
        put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
278
        put_bits(&s->pb,1,s->alt_inter_vlc); /* Alternative Inter VLC */
Michael Niedermayer's avatar
Michael Niedermayer committed
279
        put_bits(&s->pb,1,s->modified_quant); /* Modified Quantization: */
Fabrice Bellard's avatar
Fabrice Bellard committed
280 281
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
        put_bits(&s->pb,3,0); /* Reserved */
282

Fabrice Bellard's avatar
Fabrice Bellard committed
283
        put_bits(&s->pb, 3, s->pict_type == P_TYPE);
284

Fabrice Bellard's avatar
Fabrice Bellard committed
285 286
        put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
        put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
287
        put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
Fabrice Bellard's avatar
Fabrice Bellard committed
288 289
        put_bits(&s->pb,2,0); /* Reserved */
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
290

Fabrice Bellard's avatar
Fabrice Bellard committed
291
        /* This should be here if PLUSPTYPE */
292
        put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
293

294
                if (format == 7) {
295
            /* Custom Picture Format (CPFMT) */
Michael Niedermayer's avatar
Michael Niedermayer committed
296
            aspect_to_info(s, s->avctx->sample_aspect_ratio);
Michael Niedermayer's avatar
Michael Niedermayer committed
297 298

            put_bits(&s->pb,4,s->aspect_ratio_info);
299 300 301
            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));
Michael Niedermayer's avatar
Michael Niedermayer committed
302 303 304
            if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
                put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
                put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
305
            }
306
        }
Michael Niedermayer's avatar
Michael Niedermayer committed
307 308 309 310 311 312 313
        if(s->custom_pcf){
            if(ufep){
                put_bits(&s->pb, 1, best_clock_code);
                put_bits(&s->pb, 7, best_divisor);
            }
            put_bits(&s->pb, 2, (temp_ref>>8)&3);
        }
314

Fabrice Bellard's avatar
Fabrice Bellard committed
315
        /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
316
        if (s->umvplus)
317
//            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
Michael Niedermayer's avatar
Michael Niedermayer committed
318
//FIXME check actual requested range
319
            put_bits(&s->pb,2,1); /* unlimited */
320 321
        if(s->h263_slice_structured)
            put_bits(&s->pb,2,0); /* no weird submodes */
322

Fabrice Bellard's avatar
Fabrice Bellard committed
323 324 325
        put_bits(&s->pb, 5, s->qscale);
    }

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

Michael Niedermayer's avatar
Michael Niedermayer committed
328 329
    if(s->h263_slice_structured){
        put_bits(&s->pb, 1, 1);
330

Michael Niedermayer's avatar
Michael Niedermayer committed
331 332 333 334 335 336
        assert(s->mb_x == 0 && s->mb_y == 0);
        ff_h263_encode_mba(s);

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

337
    if(s->h263_aic){
338
         s->y_dc_scale_table=
Michael Niedermayer's avatar
Michael Niedermayer committed
339
         s->c_dc_scale_table= ff_aic_dc_scale_table;
340 341 342 343
    }else{
        s->y_dc_scale_table=
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
344 345
}

Michael Niedermayer's avatar
Michael Niedermayer committed
346 347 348
/**
 * Encodes a group of blocks header.
 */
349
void h263_encode_gob_header(MpegEncContext * s, int mb_line)
350
{
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
    put_bits(&s->pb, 17, 1); /* GBSC */

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

        ff_h263_encode_mba(s);

        if(s->mb_num > 1583)
            put_bits(&s->pb, 1, 1);
        put_bits(&s->pb, 5, s->qscale); /* GQUANT */
        put_bits(&s->pb, 1, 1);
        put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
    }else{
        int gob_number= mb_line / s->gob_index;

        put_bits(&s->pb, 5, gob_number); /* GN */
        put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
        put_bits(&s->pb, 5, s->qscale); /* GQUANT */
    }
370
}
371

Michael Niedermayer's avatar
Michael Niedermayer committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
static inline int get_block_rate(MpegEncContext * s, DCTELEM block[64], int block_last_index, uint8_t scantable[64]){
    int last=0;
    int j;
    int rate=0;

    for(j=1; j<=block_last_index; j++){
        const int index= scantable[j];
        int level= block[index];
        if(level){
            level+= 64;
            if((level&(~127)) == 0){
                if(j<block_last_index) rate+= s->intra_ac_vlc_length     [UNI_AC_ENC_INDEX(j-last-1, level)];
                else                   rate+= s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j-last-1, level)];
            }else
                rate += s->ac_esc_length;
            level-= 64;

            last= j;
        }
    }
392

Michael Niedermayer's avatar
Michael Niedermayer committed
393 394 395 396
    return rate;
}

static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
397
{
Michael Niedermayer's avatar
Michael Niedermayer committed
398
    int score= 0;
399
    int i, n;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
400
    int8_t * const qscale_table= s->current_picture.qscale_table;
401

Michael Niedermayer's avatar
Michael Niedermayer committed
402
    memcpy(zigzag_last_index, s->block_last_index, sizeof(int)*6);
403

404
    for(n=0; n<6; n++){
405
        int16_t *ac_val, *ac_val1;
406

Michael Niedermayer's avatar
Michael Niedermayer committed
407
        score -= get_block_rate(s, block[n], s->block_last_index[n], s->intra_scantable.permutated);
408

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

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

        score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
462 463
    }

Michael Niedermayer's avatar
Michael Niedermayer committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    return score < 0;
}

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

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

        st[n]= s->intra_scantable.permutated;
        if(dir[n]){
            /* top prediction */
            for(i=1; i<8; i++){
                block[n][s->dsp.idct_permutation[i   ]] = ac_val[i+8];
            }
        }else{
            /* left prediction */
            for(i=1; i<8; i++){
                block[n][s->dsp.idct_permutation[i<<3]]= ac_val[i  ];
            }
        }
    }
488 489
}

490 491 492 493 494 495 496 497 498 499
/**
 * init s->current_picture.qscale_table from s->lambda_table
 */
static void ff_init_qscale_tab(MpegEncContext *s){
    int8_t * const qscale_table= s->current_picture.qscale_table;
    int i;

    for(i=0; i<s->mb_num; i++){
        unsigned int lam= s->lambda_table[ s->mb_index2xy[i] ];
        int qp= (lam*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
500
        qscale_table[ s->mb_index2xy[i] ]= av_clip(qp, s->avctx->qmin, s->avctx->qmax);
501 502 503
    }
}

504 505 506
/**
 * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
 */
507
void ff_clean_h263_qscales(MpegEncContext *s){
508
    int i;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
509
    int8_t * const qscale_table= s->current_picture.qscale_table;
510

511 512
    ff_init_qscale_tab(s);

513
    for(i=1; i<s->mb_num; i++){
514 515
        if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i-1] ] >2)
            qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i-1] ]+2;
516 517
    }
    for(i=s->mb_num-2; i>=0; i--){
518 519
        if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i+1] ] >2)
            qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i+1] ]+2;
520
    }
Michael Niedermayer's avatar
Michael Niedermayer committed
521 522 523 524

    if(s->codec_id != CODEC_ID_H263P){
        for(i=1; i<s->mb_num; i++){
            int mb_xy= s->mb_index2xy[i];
525

Michael Niedermayer's avatar
Michael Niedermayer committed
526 527 528 529 530
            if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTER4V)){
                s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_INTER;
            }
        }
    }
531 532
}

533 534 535
/**
 * modify mb_type & qscale so that encoding is acually possible in mpeg4
 */
536 537
void ff_clean_mpeg4_qscales(MpegEncContext *s){
    int i;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
538 539
    int8_t * const qscale_table= s->current_picture.qscale_table;

540
    ff_clean_h263_qscales(s);
541

542 543
    if(s->pict_type== B_TYPE){
        int odd=0;
544
        /* ok, come on, this isn't funny anymore, there's more code for handling this mpeg4 mess than for the actual adaptive quantization */
545

546
        for(i=0; i<s->mb_num; i++){
547 548
            int mb_xy= s->mb_index2xy[i];
            odd += qscale_table[mb_xy]&1;
549
        }
550

551 552
        if(2*odd > s->mb_num) odd=1;
        else                  odd=0;
553

554
        for(i=0; i<s->mb_num; i++){
555 556 557 558 559
            int mb_xy= s->mb_index2xy[i];
            if((qscale_table[mb_xy]&1) != odd)
                qscale_table[mb_xy]++;
            if(qscale_table[mb_xy] > 31)
                qscale_table[mb_xy]= 31;
560 561
        }

562
        for(i=1; i<s->mb_num; i++){
563
            int mb_xy= s->mb_index2xy[i];
564 565
            if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_DIRECT)){
                s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_BIDIR;
566 567 568 569 570
            }
        }
    }
}

571
#endif //CONFIG_ENCODERS
572

573
#define tab_size ((signed)(sizeof(s->direct_scale_mv[0])/sizeof(int16_t)))
574 575
#define tab_bias (tab_size/2)

576
void ff_mpeg4_init_direct_mv(MpegEncContext *s){
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
    int i;
    for(i=0; i<tab_size; i++){
        s->direct_scale_mv[0][i] = (i-tab_bias)*s->pb_time/s->pp_time;
        s->direct_scale_mv[1][i] = (i-tab_bias)*(s->pb_time-s->pp_time)/s->pp_time;
    }
}

static inline void ff_mpeg4_set_one_direct_mv(MpegEncContext *s, int mx, int my, int i){
    int xy= s->block_index[i];
    uint16_t time_pp= s->pp_time;
    uint16_t time_pb= s->pb_time;
    int p_mx, p_my;

    p_mx= s->next_picture.motion_val[0][xy][0];
    if((unsigned)(p_mx + tab_bias) < tab_size){
        s->mv[0][i][0] = s->direct_scale_mv[0][p_mx + tab_bias] + mx;
        s->mv[1][i][0] = mx ? s->mv[0][i][0] - p_mx
                            : s->direct_scale_mv[1][p_mx + tab_bias];
    }else{
        s->mv[0][i][0] = p_mx*time_pb/time_pp + mx;
        s->mv[1][i][0] = mx ? s->mv[0][i][0] - p_mx
                            : p_mx*(time_pb - time_pp)/time_pp;
    }
    p_my= s->next_picture.motion_val[0][xy][1];
    if((unsigned)(p_my + tab_bias) < tab_size){
        s->mv[0][i][1] = s->direct_scale_mv[0][p_my + tab_bias] + my;
        s->mv[1][i][1] = my ? s->mv[0][i][1] - p_my
                            : s->direct_scale_mv[1][p_my + tab_bias];
    }else{
        s->mv[0][i][1] = p_my*time_pb/time_pp + my;
        s->mv[1][i][1] = my ? s->mv[0][i][1] - p_my
                            : p_my*(time_pb - time_pp)/time_pp;
    }
}

612 613 614
#undef tab_size
#undef tab_bias

615 616 617 618 619 620
/**
 *
 * @return the mb_type
 */
int ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
    const int mb_index= s->mb_x + s->mb_y*s->mb_stride;
621
    const int colocated_mb_type= s->next_picture.mb_type[mb_index];
Michael Niedermayer's avatar
Michael Niedermayer committed
622 623 624
    uint16_t time_pp= s->pp_time;
    uint16_t time_pb= s->pb_time;
    int i;
625

Michael Niedermayer's avatar
Michael Niedermayer committed
626
    //FIXME avoid divides
627
    // try special case with shifts for 1 and 3 B-frames?
628

629
    if(IS_8X8(colocated_mb_type)){
Michael Niedermayer's avatar
Michael Niedermayer committed
630 631
        s->mv_type = MV_TYPE_8X8;
        for(i=0; i<4; i++){
632
            ff_mpeg4_set_one_direct_mv(s, mx, my, i);
Michael Niedermayer's avatar
Michael Niedermayer committed
633
        }
634 635
        return MB_TYPE_DIRECT2 | MB_TYPE_8x8 | MB_TYPE_L0L1;
    } else if(IS_INTERLACED(colocated_mb_type)){
Michael Niedermayer's avatar
Michael Niedermayer committed
636 637
        s->mv_type = MV_TYPE_FIELD;
        for(i=0; i<2; i++){
638
            int field_select= s->next_picture.ref_index[0][s->block_index[2*i]];
639 640
            s->field_select[0][i]= field_select;
            s->field_select[1][i]= i;
Michael Niedermayer's avatar
Michael Niedermayer committed
641
            if(s->top_field_first){
642 643
                time_pp= s->pp_field_time - field_select + i;
                time_pb= s->pb_field_time - field_select + i;
Michael Niedermayer's avatar
Michael Niedermayer committed
644
            }else{
645 646
                time_pp= s->pp_field_time + field_select - i;
                time_pb= s->pb_field_time + field_select - i;
Michael Niedermayer's avatar
Michael Niedermayer committed
647
            }
648 649 650 651
            s->mv[0][i][0] = s->p_field_mv_table[i][0][mb_index][0]*time_pb/time_pp + mx;
            s->mv[0][i][1] = s->p_field_mv_table[i][0][mb_index][1]*time_pb/time_pp + my;
            s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->p_field_mv_table[i][0][mb_index][0]
                                : s->p_field_mv_table[i][0][mb_index][0]*(time_pb - time_pp)/time_pp;
652
            s->mv[1][i][1] = my ? s->mv[0][i][1] - s->p_field_mv_table[i][0][mb_index][1]
653
                                : s->p_field_mv_table[i][0][mb_index][1]*(time_pb - time_pp)/time_pp;
Michael Niedermayer's avatar
Michael Niedermayer committed
654
        }
655 656
        return MB_TYPE_DIRECT2 | MB_TYPE_16x8 | MB_TYPE_L0L1 | MB_TYPE_INTERLACED;
    }else{
657 658 659 660 661
        ff_mpeg4_set_one_direct_mv(s, mx, my, 0);
        s->mv[0][1][0] = s->mv[0][2][0] = s->mv[0][3][0] = s->mv[0][0][0];
        s->mv[0][1][1] = s->mv[0][2][1] = s->mv[0][3][1] = s->mv[0][0][1];
        s->mv[1][1][0] = s->mv[1][2][0] = s->mv[1][3][0] = s->mv[1][0][0];
        s->mv[1][1][1] = s->mv[1][2][1] = s->mv[1][3][1] = s->mv[1][0][1];
662 663 664 665 666
        if((s->avctx->workaround_bugs & FF_BUG_DIRECT_BLOCKSIZE) || !s->quarter_sample)
            s->mv_type= MV_TYPE_16X16;
        else
            s->mv_type= MV_TYPE_8X8;
        return MB_TYPE_DIRECT2 | MB_TYPE_16x16 | MB_TYPE_L0L1; //Note see prev line
Michael Niedermayer's avatar
Michael Niedermayer committed
667 668 669
    }
}

670 671
void ff_h263_update_motion_val(MpegEncContext * s){
    const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
672
               //FIXME a lot of that is only needed for !low_delay
673
    const int wrap = s->b8_stride;
674
    const int xy = s->block_index[0];
675 676

    s->current_picture.mbskip_table[mb_xy]= s->mb_skipped;
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691

    if(s->mv_type != MV_TYPE_8X8){
        int motion_x, motion_y;
        if (s->mb_intra) {
            motion_x = 0;
            motion_y = 0;
        } else if (s->mv_type == MV_TYPE_16X16) {
            motion_x = s->mv[0][0][0];
            motion_y = s->mv[0][0][1];
        } else /*if (s->mv_type == MV_TYPE_FIELD)*/ {
            int i;
            motion_x = s->mv[0][0][0] + s->mv[0][1][0];
            motion_y = s->mv[0][0][1] + s->mv[0][1][1];
            motion_x = (motion_x>>1) | (motion_x&1);
            for(i=0; i<2; i++){
692 693
                s->p_field_mv_table[i][0][mb_xy][0]= s->mv[0][i][0];
                s->p_field_mv_table[i][0][mb_xy][1]= s->mv[0][i][1];
694
            }
695 696 697 698
            s->current_picture.ref_index[0][xy           ]=
            s->current_picture.ref_index[0][xy        + 1]= s->field_select[0][0];
            s->current_picture.ref_index[0][xy + wrap    ]=
            s->current_picture.ref_index[0][xy + wrap + 1]= s->field_select[0][1];
699
        }
700

701
        /* no update if 8X8 because it has been done during parsing */
702 703 704 705 706 707 708 709
        s->current_picture.motion_val[0][xy][0] = motion_x;
        s->current_picture.motion_val[0][xy][1] = motion_y;
        s->current_picture.motion_val[0][xy + 1][0] = motion_x;
        s->current_picture.motion_val[0][xy + 1][1] = motion_y;
        s->current_picture.motion_val[0][xy + wrap][0] = motion_x;
        s->current_picture.motion_val[0][xy + wrap][1] = motion_y;
        s->current_picture.motion_val[0][xy + 1 + wrap][0] = motion_x;
        s->current_picture.motion_val[0][xy + 1 + wrap][1] = motion_y;
710 711 712
    }

    if(s->encoding){ //FIXME encoding MUST be cleaned up
713
        if (s->mv_type == MV_TYPE_8X8)
714
            s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_8x8;
Michael Niedermayer's avatar
Michael Niedermayer committed
715 716
        else if(s->mb_intra)
            s->current_picture.mb_type[mb_xy]= MB_TYPE_INTRA;
717 718 719 720 721
        else
            s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_16x16;
    }
}

722
#ifdef CONFIG_ENCODERS
723

724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
static inline int h263_get_motion_length(MpegEncContext * s, int val, int f_code){
    int l, bit_size, code;

    if (val == 0) {
        return mvtab[0][1];
    } else {
        bit_size = f_code - 1;
        /* modulo encoding */
        l= INT_BIT - 6 - bit_size;
        val = (val<<l)>>l;
        val--;
        code = (val >> bit_size) + 1;

        return mvtab[code][1] + 1 + bit_size;
    }
}

static inline void ff_h263_encode_motion_vector(MpegEncContext * s, int x, int y, int f_code){
    if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
743
        skip_put_bits(&s->pb,
744 745 746 747 748 749 750 751
            h263_get_motion_length(s, x, f_code)
           +h263_get_motion_length(s, y, f_code));
    }else{
        ff_h263_encode_motion(s, x, f_code);
        ff_h263_encode_motion(s, y, f_code);
    }
}

752 753 754 755 756 757 758 759
static inline int get_p_cbp(MpegEncContext * s,
                      DCTELEM block[6][64],
                      int motion_x, int motion_y){
    int cbp, i;

    if(s->flags & CODEC_FLAG_CBP_RD){
        int best_cbpy_score= INT_MAX;
        int best_cbpc_score= INT_MAX;
760
        int cbpc = (-1), cbpy= (-1);
761
        const int offset= (s->mv_type==MV_TYPE_16X16 ? 0 : 16) + (s->dquant ? 8 : 0);
762
        const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814

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

            if(score < best_cbpc_score){
                best_cbpc_score= score;
                cbpc= i;
            }
        }

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

            if(score < best_cbpy_score){
                best_cbpy_score= score;
                cbpy= i;
            }
        }
        cbp= cbpc + 4*cbpy;
        if ((motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16){
            if(best_cbpy_score + best_cbpc_score + 2*lambda >= 0)
                cbp= 0;
        }

        for (i = 0; i < 6; i++) {
            if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
                s->block_last_index[i]= -1;
                memset(s->block[i], 0, sizeof(DCTELEM)*64);
            }
        }
    }else{
        cbp= 0;
        for (i = 0; i < 6; i++) {
            if (s->block_last_index[i] >= 0)
                cbp |= 1 << (5 - i);
        }
    }
    return cbp;
}

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

    if(s->flags & CODEC_FLAG_CBP_RD){
        int score=0;
815
        const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);