h263.c 212 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 43
#include "common.h"
#include "dsputil.h"
#include "avcodec.h"
#include "mpegvideo.h"
#include "h263data.h"
#include "mpeg4data.h"

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

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

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

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

84
#ifdef CONFIG_ENCODERS
85 86 87 88
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];
89

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

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

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

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

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

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

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

140 141
#ifdef CONFIG_ENCODERS

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

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

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

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

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

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

163 164
      put_bits(&s->pb, 17, 1);
      put_bits(&s->pb, 5, (s->h263_flv-1)); /* 0: h263 escape codes 1: 11-bit escape codes */
165 166
      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 */
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
      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 */
190
      put_bits(&s->pb, 1, 1); /* DeblockingFlag: on */
191 192 193 194
      put_bits(&s->pb, 5, s->qscale); /* Quantizer */
      put_bits(&s->pb, 1, 0); /* ExtraInformation */

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

void h263_encode_picture_header(MpegEncContext * s, int picture_number)
{
Michael Niedermayer's avatar
Michael Niedermayer committed
205 206 207 208
    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;
209

Michael Niedermayer's avatar
Michael Niedermayer committed
210 211 212
    if(s->h263_plus){
        for(i=0; i<2; i++){
            int div, error;
213
            div= (s->avctx->time_base.num*1800000LL + 500LL*s->avctx->time_base.den) / ((1000LL+i)*s->avctx->time_base.den);
Michael Niedermayer's avatar
Michael Niedermayer committed
214
            div= clip(1, div, 127);
Diego Biurrun's avatar
Diego Biurrun committed
215
            error= FFABS(s->avctx->time_base.num*1800000LL - (1000LL+i)*s->avctx->time_base.den*div);
Michael Niedermayer's avatar
Michael Niedermayer committed
216 217 218 219 220 221 222 223 224 225
            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
226 227

    align_put_bits(&s->pb);
228

229
    /* Update the pointer to last GOB */
230
    s->ptr_lastgob = pbBufPtr(&s->pb);
231
    put_bits(&s->pb, 22, 0x20); /* PSC */
232 233
    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
234
    put_bits(&s->pb, 8, temp_ref & 0xff); /* TemporalReference */
Fabrice Bellard's avatar
Fabrice Bellard committed
235

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

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

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

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

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

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

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

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

            put_bits(&s->pb,4,s->aspect_ratio_info);
298 299 300
            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
301 302 303
            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);
304
            }
305
        }
Michael Niedermayer's avatar
Michael Niedermayer committed
306 307 308 309 310 311 312
        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);
        }
313

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

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

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

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

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

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

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

Michael Niedermayer's avatar
Michael Niedermayer committed
345 346 347
/**
 * Encodes a group of blocks header.
 */
348
void h263_encode_gob_header(MpegEncContext * s, int mb_line)
349
{
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
    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 */
    }
369
}
370

Michael Niedermayer's avatar
Michael Niedermayer committed
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
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;
        }
    }
391

Michael Niedermayer's avatar
Michael Niedermayer committed
392 393 394 395
    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])
396
{
Michael Niedermayer's avatar
Michael Niedermayer committed
397
    int score= 0;
398
    int i, n;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
399
    int8_t * const qscale_table= s->current_picture.qscale_table;
400

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

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

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

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

        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]);
461 462
    }

Michael Niedermayer's avatar
Michael Niedermayer committed
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    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  ];
            }
        }
    }
487 488
}

489 490 491 492 493 494 495 496 497 498 499 500 501 502
/**
 * 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);
        qscale_table[ s->mb_index2xy[i] ]= clip(qp, s->avctx->qmin, s->avctx->qmax);
    }
}

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

510 511
    ff_init_qscale_tab(s);

512
    for(i=1; i<s->mb_num; i++){
513 514
        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;
515 516
    }
    for(i=s->mb_num-2; i>=0; i--){
517 518
        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;
519
    }
Michael Niedermayer's avatar
Michael Niedermayer committed
520 521 522 523

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

Michael Niedermayer's avatar
Michael Niedermayer committed
525 526 527 528 529
            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;
            }
        }
    }
530 531
}

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

539
    ff_clean_h263_qscales(s);
540

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

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

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

553
        for(i=0; i<s->mb_num; i++){
554 555 556 557 558
            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;
559 560
        }

561
        for(i=1; i<s->mb_num; i++){
562
            int mb_xy= s->mb_index2xy[i];
563 564
            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;
565 566 567 568 569
            }
        }
    }
}

570
#endif //CONFIG_ENCODERS
571

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

575
void ff_mpeg4_init_direct_mv(MpegEncContext *s){
576 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
    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;
    }
}

611 612 613
#undef tab_size
#undef tab_bias

614 615 616 617 618 619
/**
 *
 * @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;
620
    const int colocated_mb_type= s->next_picture.mb_type[mb_index];
Michael Niedermayer's avatar
Michael Niedermayer committed
621 622 623
    uint16_t time_pp= s->pp_time;
    uint16_t time_pb= s->pb_time;
    int i;
624

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

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

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

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

    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++){
691 692
                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];
693
            }
694 695 696 697
            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];
698
        }
699

700
        /* no update if 8X8 because it has been done during parsing */
701 702 703 704 705 706 707 708
        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;
709 710 711
    }

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

721
#ifdef CONFIG_ENCODERS
722

723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
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){
742
        skip_put_bits(&s->pb,
743 744 745 746 747 748 749 750
            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);
    }
}

751 752 753 754 755 756 757 758
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;
759
        int cbpc = (-1), cbpy= (-1);
760
        const int offset= (s->mv_type==MV_TYPE_16X16 ? 0 : 16) + (s->dquant ? 8 : 0);
761
        const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
762 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

        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;
814
        const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
815

816 817 818 819 820 821
        for(i=0; i<6; i++){
            if(s->coded_score[i] < 0){
                score += s->coded_score[i];
                cbp |= 1 << (5 - i);
            }
        }