mpegvideo.c 78.4 KB
Newer Older
F
Fabrice Bellard 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * The simplest mpeg encoder (well, it was the simplest!)
 * Copyright (c) 2000,2001 Gerard Lantau.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
M
Michael Niedermayer 已提交
18
 *
19
 * 4MV & hq & b-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
F
Fabrice Bellard 已提交
20 21 22 23 24 25 26 27 28
 */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "avcodec.h"
#include "dsputil.h"
#include "mpegvideo.h"

29 30 31 32
#ifdef USE_FASTMEMCPY
#include "fastmemcpy.h"
#endif

33 34 35
static void encode_picture(MpegEncContext *s, int picture_number);
static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
                                   DCTELEM *block, int n, int qscale);
36 37
static void dct_unquantize_mpeg2_c(MpegEncContext *s,
                                   DCTELEM *block, int n, int qscale);
38 39
static void dct_unquantize_h263_c(MpegEncContext *s, 
                                  DCTELEM *block, int n, int qscale);
M
Michael Niedermayer 已提交
40
static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w);
41
static int dct_quantize_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
M
Michael Niedermayer 已提交
42

43
int (*dct_quantize)(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow)= dct_quantize_c;
M
Michael Niedermayer 已提交
44 45
void (*draw_edges)(UINT8 *buf, int wrap, int width, int height, int w)= draw_edges_c;

F
Fabrice Bellard 已提交
46 47 48 49 50 51 52
#define EDGE_WIDTH 16

/* enable all paranoid tests for rounding, overflows, etc... */
//#define PARANOID

//#define DEBUG

53

F
Fabrice Bellard 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
/* for jpeg fast DCT */
#define CONST_BITS 14

static const unsigned short aanscales[64] = {
    /* precomputed values scaled up by 14 bits */
    16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
    22725, 31521, 29692, 26722, 22725, 17855, 12299,  6270,
    21407, 29692, 27969, 25172, 21407, 16819, 11585,  5906,
    19266, 26722, 25172, 22654, 19266, 15137, 10426,  5315,
    16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
    12873, 17855, 16819, 15137, 12873, 10114,  6967,  3552,
    8867, 12299, 11585, 10426,  8867,  6967,  4799,  2446,
    4520,  6270,  5906,  5315,  4520,  3552,  2446,  1247
};

static UINT8 h263_chroma_roundtab[16] = {
    0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
};

73
static UINT16 default_mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
74 75
static UINT8 default_fcode_tab[MAX_MV*2+1];

M
Michael Niedermayer 已提交
76 77
extern UINT8 zigzag_end[64];

78 79 80
/* default motion estimation */
int motion_estimation_method = ME_EPZS;

81 82
static void convert_matrix(int (*qmat)[64], uint16_t (*qmat16)[64], uint16_t (*qmat16_bias)[64],
                           const UINT16 *quant_matrix, int bias)
F
Fabrice Bellard 已提交
83
{
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    int qscale;

    for(qscale=1; qscale<32; qscale++){
        int i;
        if (av_fdct == jpeg_fdct_ifast) {
            for(i=0;i<64;i++) {
                const int j= block_permute_op(i);
                /* 16 <= qscale * quant_matrix[i] <= 7905 */
                /* 19952         <= aanscales[i] * qscale * quant_matrix[i]           <= 249205026 */
                /* (1<<36)/19952 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
                /* 3444240       >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= 275 */
                
                qmat[qscale][j] = (int)((UINT64_C(1) << (QMAT_SHIFT + 11)) / 
                                (aanscales[i] * qscale * quant_matrix[j]));
            }
        } else {
            for(i=0;i<64;i++) {
                /* We can safely suppose that 16 <= quant_matrix[i] <= 255
                   So 16           <= qscale * quant_matrix[i]             <= 7905
                   so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
                   so 32768        >= (1<<19) / (qscale * quant_matrix[i]) >= 67
                */
                qmat  [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
                qmat16[qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[block_permute_op(i)]);

                if(qmat16[qscale][i]==0 || qmat16[qscale][i]==128*256) qmat16[qscale][i]=128*256-1;

                qmat16_bias[qscale][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][i]);
            }
F
Fabrice Bellard 已提交
113 114 115 116 117 118 119 120 121 122
        }
    }
}

/* init common structure for both encoder and decoder */
int MPV_common_init(MpegEncContext *s)
{
    int c_size, i;
    UINT8 *pict;

123
    s->dct_unquantize_h263 = dct_unquantize_h263_c;
124 125
    s->dct_unquantize_mpeg1 = dct_unquantize_mpeg1_c;
    s->dct_unquantize_mpeg2 = dct_unquantize_mpeg2_c;
126 127 128
        
#ifdef HAVE_MMX
    MPV_common_init_mmx(s);
N
Nick Kurshev 已提交
129
#endif
130 131 132 133
    //setup default unquantizers (mpeg4 might change it later)
    if(s->out_format == FMT_H263)
        s->dct_unquantize = s->dct_unquantize_h263;
    else
134
        s->dct_unquantize = s->dct_unquantize_mpeg1;
135
    
F
Fabrice Bellard 已提交
136 137
    s->mb_width = (s->width + 15) / 16;
    s->mb_height = (s->height + 15) / 16;
138
    s->mb_num = s->mb_width * s->mb_height;
F
Fabrice Bellard 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    s->linesize = s->mb_width * 16 + 2 * EDGE_WIDTH;

    for(i=0;i<3;i++) {
        int w, h, shift, pict_start;

        w = s->linesize;
        h = s->mb_height * 16 + 2 * EDGE_WIDTH;
        shift = (i == 0) ? 0 : 1;
        c_size = (w >> shift) * (h >> shift);
        pict_start = (w >> shift) * (EDGE_WIDTH >> shift) + (EDGE_WIDTH >> shift);

        pict = av_mallocz(c_size);
        if (pict == NULL)
            goto fail;
        s->last_picture_base[i] = pict;
        s->last_picture[i] = pict + pict_start;
    
        pict = av_mallocz(c_size);
        if (pict == NULL)
            goto fail;
        s->next_picture_base[i] = pict;
        s->next_picture[i] = pict + pict_start;
161
        
F
Fabrice Bellard 已提交
162 163 164 165 166 167 168 169
        if (s->has_b_frames) {
            pict = av_mallocz(c_size);
            if (pict == NULL) 
                goto fail;
            s->aux_picture_base[i] = pict;
            s->aux_picture[i] = pict + pict_start;
        }
    }
170 171
    
    if (s->encoding) {
172 173 174
        int j;
        int mv_table_size= (s->mb_width+2)*(s->mb_height+2);

175
        /* Allocate MB type table */
J
Juanjo 已提交
176
        s->mb_type = av_mallocz(s->mb_num * sizeof(char));
177 178 179 180
        if (s->mb_type == NULL) {
            perror("malloc");
            goto fail;
        }
J
Juanjo 已提交
181 182 183 184 185 186
        
        s->mb_var = av_mallocz(s->mb_num * sizeof(INT16));
        if (s->mb_var == NULL) {
            perror("malloc");
            goto fail;
        }
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

        /* Allocate MV tables */
        s->p_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
        if (s->p_mv_table == NULL) {
            perror("malloc");
            goto fail;
        }
        s->last_p_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
        if (s->last_p_mv_table == NULL) {
            perror("malloc");
            goto fail;
        }
        s->b_forw_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
        if (s->b_forw_mv_table == NULL) {
            perror("malloc");
            goto fail;
        }
        s->b_back_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
        if (s->b_back_mv_table == NULL) {
            perror("malloc");
            goto fail;
        }
        s->b_bidir_forw_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
        if (s->b_bidir_forw_mv_table == NULL) {
            perror("malloc");
            goto fail;
        }
        s->b_bidir_back_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
        if (s->b_bidir_back_mv_table == NULL) {
            perror("malloc");
            goto fail;
        }
        s->b_direct_forw_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
        if (s->b_direct_forw_mv_table == NULL) {
221 222 223
            perror("malloc");
            goto fail;
        }
224 225 226 227 228 229 230 231 232 233 234
        s->b_direct_back_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
        if (s->b_direct_back_mv_table == NULL) {
            perror("malloc");
            goto fail;
        }
        s->b_direct_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
        if (s->b_direct_mv_table == NULL) {
            perror("malloc");
            goto fail;
        }

235 236 237 238 239 240
        s->me_scratchpad = av_mallocz( s->linesize*16*3*sizeof(uint8_t));
        if (s->me_scratchpad == NULL) {
            perror("malloc");
            goto fail;
        }

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
        if(s->max_b_frames){
            for(j=0; j<REORDER_BUFFER_SIZE; j++){
                int i;
                for(i=0;i<3;i++) {
                    int w, h, shift;

                    w = s->linesize;
                    h = s->mb_height * 16;
                    shift = (i == 0) ? 0 : 1;
                    c_size = (w >> shift) * (h >> shift);

                    pict = av_mallocz(c_size);
                    if (pict == NULL)
                        goto fail;
                    s->picture_buffer[j][i] = pict;
                }
            }
        }
259 260
    }
    
261
    if (s->out_format == FMT_H263 || s->encoding) {
F
Fabrice Bellard 已提交
262 263 264 265 266 267 268 269 270
        int size;
        /* MV prediction */
        size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
        s->motion_val = malloc(size * 2 * sizeof(INT16));
        if (s->motion_val == NULL)
            goto fail;
        memset(s->motion_val, 0, size * 2 * sizeof(INT16));
    }

271
    if (s->h263_pred || s->h263_plus) {
F
Fabrice Bellard 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
        int y_size, c_size, i, size;
        
        /* dc values */

        y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
        c_size = (s->mb_width + 2) * (s->mb_height + 2);
        size = y_size + 2 * c_size;
        s->dc_val[0] = malloc(size * sizeof(INT16));
        if (s->dc_val[0] == NULL)
            goto fail;
        s->dc_val[1] = s->dc_val[0] + y_size;
        s->dc_val[2] = s->dc_val[1] + c_size;
        for(i=0;i<size;i++)
            s->dc_val[0][i] = 1024;

        /* ac values */
        s->ac_val[0] = av_mallocz(size * sizeof(INT16) * 16);
        if (s->ac_val[0] == NULL)
            goto fail;
        s->ac_val[1] = s->ac_val[0] + y_size;
        s->ac_val[2] = s->ac_val[1] + c_size;
        
        /* cbp values */
        s->coded_block = av_mallocz(y_size);
        if (!s->coded_block)
            goto fail;
298 299

        /* which mb is a intra block */
300
        s->mbintra_table = av_mallocz(s->mb_num);
301 302
        if (!s->mbintra_table)
            goto fail;
303
        memset(s->mbintra_table, 1, s->mb_num);
M
Michael Niedermayer 已提交
304 305 306 307 308
        
        /* divx501 bitstream reorder buffer */
        s->bitstream_buffer= av_mallocz(BITSTREAM_BUFFER_SIZE);
        if (!s->bitstream_buffer)
            goto fail;
309
    }
F
Fabrice Bellard 已提交
310 311 312
    /* default structure is frame */
    s->picture_structure = PICT_FRAME;

313
    /* init macroblock skip table */
314 315 316
    s->mbskip_table = av_mallocz(s->mb_num);
    if (!s->mbskip_table)
        goto fail;
317
    
318
    s->block= s->blocks[0];
319

F
Fabrice Bellard 已提交
320 321 322
    s->context_initialized = 1;
    return 0;
 fail:
323
    MPV_common_end(s);
F
Fabrice Bellard 已提交
324 325 326
    return -1;
}

327 328 329 330 331 332
#define CHECK_FREE(p)\
{\
    if(p) free(p);\
    p= NULL;\
}

F
Fabrice Bellard 已提交
333 334 335 336 337
/* init common structure for both encoder and decoder */
void MPV_common_end(MpegEncContext *s)
{
    int i;

338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    CHECK_FREE(s->mb_type);
    CHECK_FREE(s->mb_var);
    CHECK_FREE(s->p_mv_table);
    CHECK_FREE(s->last_p_mv_table);
    CHECK_FREE(s->b_forw_mv_table);
    CHECK_FREE(s->b_back_mv_table);
    CHECK_FREE(s->b_bidir_forw_mv_table);
    CHECK_FREE(s->b_bidir_back_mv_table);
    CHECK_FREE(s->b_direct_forw_mv_table);
    CHECK_FREE(s->b_direct_back_mv_table);
    CHECK_FREE(s->b_direct_mv_table);
    CHECK_FREE(s->motion_val);
    CHECK_FREE(s->dc_val[0]);
    CHECK_FREE(s->ac_val[0]);
    CHECK_FREE(s->coded_block);
    CHECK_FREE(s->mbintra_table);
354
    CHECK_FREE(s->me_scratchpad);
355 356

    CHECK_FREE(s->mbskip_table);
M
Michael Niedermayer 已提交
357
    CHECK_FREE(s->bitstream_buffer);
F
Fabrice Bellard 已提交
358
    for(i=0;i<3;i++) {
359 360 361 362 363 364 365
        int j;
        CHECK_FREE(s->last_picture_base[i]);
        CHECK_FREE(s->next_picture_base[i]);
        CHECK_FREE(s->aux_picture_base[i]);
        for(j=0; j<REORDER_BUFFER_SIZE; j++){
            CHECK_FREE(s->picture_buffer[j][i]);
        }
F
Fabrice Bellard 已提交
366 367 368 369 370 371 372 373
    }
    s->context_initialized = 0;
}

/* init video encoder */
int MPV_encode_init(AVCodecContext *avctx)
{
    MpegEncContext *s = avctx->priv_data;
374
    int i;
F
Fabrice Bellard 已提交
375

376 377
    avctx->pix_fmt = PIX_FMT_YUV420P;

F
Fabrice Bellard 已提交
378
    s->bit_rate = avctx->bit_rate;
379
    s->bit_rate_tolerance = avctx->bit_rate_tolerance;
F
Fabrice Bellard 已提交
380 381 382 383
    s->frame_rate = avctx->frame_rate;
    s->width = avctx->width;
    s->height = avctx->height;
    s->gop_size = avctx->gop_size;
384 385
    s->rtp_mode = avctx->rtp_mode;
    s->rtp_payload_size = avctx->rtp_payload_size;
386 387
    if (avctx->rtp_callback)
        s->rtp_callback = avctx->rtp_callback;
388 389 390 391 392
    s->qmin= avctx->qmin;
    s->qmax= avctx->qmax;
    s->max_qdiff= avctx->max_qdiff;
    s->qcompress= avctx->qcompress;
    s->qblur= avctx->qblur;
393
    s->b_quant_factor= avctx->b_quant_factor;
394
    s->avctx = avctx;
395
    s->aspect_ratio_info= avctx->aspect_ratio_info;
396
    s->flags= avctx->flags;
397
    s->max_b_frames= avctx->max_b_frames;
398 399
    s->rc_strategy= avctx->rc_strategy;
    s->b_frame_strategy= avctx->b_frame_strategy;
400 401
    s->codec_id= avctx->codec->id;

F
Fabrice Bellard 已提交
402 403 404 405 406 407
    if (s->gop_size <= 1) {
        s->intra_only = 1;
        s->gop_size = 12;
    } else {
        s->intra_only = 0;
    }
408 409
    
    /* ME algorithm */
410 411 412 413 414 415
    if (avctx->me_method == 0)
        /* For compatibility */
        s->me_method = motion_estimation_method;
    else
        s->me_method = avctx->me_method;
        
416
    /* Fixed QSCALE */
F
Fabrice Bellard 已提交
417
    s->fixed_qscale = (avctx->flags & CODEC_FLAG_QSCALE);
418
    
F
Fabrice Bellard 已提交
419 420 421
    switch(avctx->codec->id) {
    case CODEC_ID_MPEG1VIDEO:
        s->out_format = FMT_MPEG1;
M
Michael Niedermayer 已提交
422
        avctx->delay=0; //FIXME not sure, should check the spec
F
Fabrice Bellard 已提交
423 424 425 426
        break;
    case CODEC_ID_MJPEG:
        s->out_format = FMT_MJPEG;
        s->intra_only = 1; /* force intra only for jpeg */
427 428 429 430 431 432 433
        s->mjpeg_write_tables = 1; /* write all tables */
        s->mjpeg_vsample[0] = 2; /* set up default sampling factors */
        s->mjpeg_vsample[1] = 1; /* the only currently supported values */
        s->mjpeg_vsample[2] = 1; 
        s->mjpeg_hsample[0] = 2; 
        s->mjpeg_hsample[1] = 1; 
        s->mjpeg_hsample[2] = 1; 
F
Fabrice Bellard 已提交
434 435
        if (mjpeg_init(s) < 0)
            return -1;
M
Michael Niedermayer 已提交
436
        avctx->delay=0;
F
Fabrice Bellard 已提交
437 438
        break;
    case CODEC_ID_H263:
439 440
        if (h263_get_picture_format(s->width, s->height) == 7) {
            printf("Input picture size isn't suitable for h263 codec! try h263+\n");
F
Fabrice Bellard 已提交
441
            return -1;
442
        }
F
Fabrice Bellard 已提交
443
        s->out_format = FMT_H263;
M
Michael Niedermayer 已提交
444
        avctx->delay=0;
F
Fabrice Bellard 已提交
445 446 447
        break;
    case CODEC_ID_H263P:
        s->out_format = FMT_H263;
448 449
        s->rtp_mode = 1;
        s->rtp_payload_size = 1200; 
F
Fabrice Bellard 已提交
450
        s->h263_plus = 1;
451
        s->unrestricted_mv = 1;
452 453 454 455
        
        /* These are just to be sure */
        s->umvplus = 0;
        s->umvplus_dec = 0;
M
Michael Niedermayer 已提交
456
        avctx->delay=0;
F
Fabrice Bellard 已提交
457 458 459 460
        break;
    case CODEC_ID_RV10:
        s->out_format = FMT_H263;
        s->h263_rv10 = 1;
M
Michael Niedermayer 已提交
461
        avctx->delay=0;
F
Fabrice Bellard 已提交
462
        break;
F
Fabrice Bellard 已提交
463
    case CODEC_ID_MPEG4:
F
Fabrice Bellard 已提交
464 465 466
        s->out_format = FMT_H263;
        s->h263_pred = 1;
        s->unrestricted_mv = 1;
467
        s->has_b_frames= s->max_b_frames ? 1 : 0;
M
Michael Niedermayer 已提交
468 469
        s->low_delay=0;
        avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1); 
F
Fabrice Bellard 已提交
470
        break;
471
    case CODEC_ID_MSMPEG4V1:
F
Fabrice Bellard 已提交
472 473 474 475
        s->out_format = FMT_H263;
        s->h263_msmpeg4 = 1;
        s->h263_pred = 1;
        s->unrestricted_mv = 1;
476
        s->msmpeg4_version= 1;
M
Michael Niedermayer 已提交
477
        avctx->delay=0;
478 479 480 481 482 483 484
        break;
    case CODEC_ID_MSMPEG4V2:
        s->out_format = FMT_H263;
        s->h263_msmpeg4 = 1;
        s->h263_pred = 1;
        s->unrestricted_mv = 1;
        s->msmpeg4_version= 2;
M
Michael Niedermayer 已提交
485
        avctx->delay=0;
486 487 488 489 490 491 492
        break;
    case CODEC_ID_MSMPEG4V3:
        s->out_format = FMT_H263;
        s->h263_msmpeg4 = 1;
        s->h263_pred = 1;
        s->unrestricted_mv = 1;
        s->msmpeg4_version= 3;
M
Michael Niedermayer 已提交
493
        avctx->delay=0;
F
Fabrice Bellard 已提交
494 495 496 497
        break;
    default:
        return -1;
    }
M
Michael Niedermayer 已提交
498 499 500 501 502
    
    if((s->flags&CODEC_FLAG_4MV) && !(s->flags&CODEC_FLAG_HQ)){
        printf("4MV is currently only supported in HQ mode\n");
        return -1;
    }
F
Fabrice Bellard 已提交
503

504 505 506 507 508
    { /* set up some save defaults, some codecs might override them later */
        static int done=0;
        if(!done){
            int i;
            done=1;
509
            memset(default_mv_penalty, 0, sizeof(UINT16)*(MAX_FCODE+1)*(2*MAX_MV+1));
510 511 512 513 514 515 516 517 518 519
            memset(default_fcode_tab , 0, sizeof(UINT8)*(2*MAX_MV+1));

            for(i=-16; i<16; i++){
                default_fcode_tab[i + MAX_MV]= 1;
            }
        }
    }
    s->mv_penalty= default_mv_penalty;
    s->fcode_tab= default_fcode_tab;

F
Fabrice Bellard 已提交
520
    if (s->out_format == FMT_H263)
521
        h263_encode_init(s);
522 523
    else if (s->out_format == FMT_MPEG1)
        mpeg1_encode_init(s);
F
Fabrice Bellard 已提交
524

525
    /* dont use mv_penalty table for crap MV as it would be confused */
526
    if (s->me_method < ME_EPZS) s->mv_penalty = default_mv_penalty;
527

528 529
    s->encoding = 1;

F
Fabrice Bellard 已提交
530 531 532 533
    /* init */
    if (MPV_common_init(s) < 0)
        return -1;
    
534 535
    /* init default q matrix */
    for(i=0;i<64;i++) {
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
        if(s->out_format == FMT_H263)
            s->intra_matrix[i] = default_non_intra_matrix[i];
        else
            s->intra_matrix[i] = default_intra_matrix[i];

        s->inter_matrix[i] = default_non_intra_matrix[i];
    }

    /* precompute matrix */
        /* for mjpeg, we do include qscale in the matrix */
    if (s->out_format != FMT_MJPEG) {
        convert_matrix(s->q_intra_matrix, s->q_intra_matrix16, s->q_intra_matrix16_bias, 
                       s->intra_matrix, s->intra_quant_bias);
        convert_matrix(s->q_inter_matrix, s->q_inter_matrix16, s->q_inter_matrix16_bias, 
                       s->inter_matrix, s->inter_quant_bias);
551 552
    }

553 554
    if(ff_rate_control_init(s) < 0)
        return -1;
F
Fabrice Bellard 已提交
555 556

    s->picture_number = 0;
557
    s->picture_in_gop_number = 0;
F
Fabrice Bellard 已提交
558 559 560
    s->fake_picture_number = 0;
    /* motion detector init */
    s->f_code = 1;
561
    s->b_code = 1;
F
Fabrice Bellard 已提交
562 563 564 565 566 567 568 569 570 571 572

    return 0;
}

int MPV_encode_end(AVCodecContext *avctx)
{
    MpegEncContext *s = avctx->priv_data;

#ifdef STATS
    print_stats();
#endif
573 574 575

    ff_rate_control_uninit(s);

F
Fabrice Bellard 已提交
576 577 578
    MPV_common_end(s);
    if (s->out_format == FMT_MJPEG)
        mjpeg_close(s);
579
      
F
Fabrice Bellard 已提交
580 581 582 583
    return 0;
}

/* draw the edges of width 'w' of an image of size width, height */
M
Michael Niedermayer 已提交
584
static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w)
F
Fabrice Bellard 已提交
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 612 613 614 615 616
{
    UINT8 *ptr, *last_line;
    int i;

    last_line = buf + (height - 1) * wrap;
    for(i=0;i<w;i++) {
        /* top and bottom */
        memcpy(buf - (i + 1) * wrap, buf, width);
        memcpy(last_line + (i + 1) * wrap, last_line, width);
    }
    /* left and right */
    ptr = buf;
    for(i=0;i<height;i++) {
        memset(ptr - w, ptr[0], w);
        memset(ptr + width, ptr[width-1], w);
        ptr += wrap;
    }
    /* corners */
    for(i=0;i<w;i++) {
        memset(buf - (i + 1) * wrap - w, buf[0], w); /* top left */
        memset(buf - (i + 1) * wrap + width, buf[width-1], w); /* top right */
        memset(last_line + (i + 1) * wrap - w, last_line[0], w); /* top left */
        memset(last_line + (i + 1) * wrap + width, last_line[width-1], w); /* top right */
    }
}

/* generic function for encode/decode called before a frame is coded/decoded */
void MPV_frame_start(MpegEncContext *s)
{
    int i;
    UINT8 *tmp;

617
    s->mb_skiped = 0;
F
Fabrice Bellard 已提交
618 619 620 621 622 623 624 625 626 627 628 629 630 631
    if (s->pict_type == B_TYPE) {
        for(i=0;i<3;i++) {
            s->current_picture[i] = s->aux_picture[i];
        }
    } else {
        for(i=0;i<3;i++) {
            /* swap next and last */
            tmp = s->last_picture[i];
            s->last_picture[i] = s->next_picture[i];
            s->next_picture[i] = tmp;
            s->current_picture[i] = tmp;
        }
    }
}
632

F
Fabrice Bellard 已提交
633 634 635 636
/* generic function for encode/decode called after a frame has been coded/decoded */
void MPV_frame_end(MpegEncContext *s)
{
    /* draw edge for correct motion prediction if outside */
M
Michael Niedermayer 已提交
637
    if (s->pict_type != B_TYPE && !s->intra_only) {
M
Michael Niedermayer 已提交
638
      if(s->avctx==NULL || s->avctx->codec->id!=CODEC_ID_MPEG4 || s->divx_version==500){
639 640 641
        draw_edges(s->current_picture[0], s->linesize, s->mb_width*16, s->mb_height*16, EDGE_WIDTH);
        draw_edges(s->current_picture[1], s->linesize/2, s->mb_width*8, s->mb_height*8, EDGE_WIDTH/2);
        draw_edges(s->current_picture[2], s->linesize/2, s->mb_width*8, s->mb_height*8, EDGE_WIDTH/2);
642
      }else{
M
Michael Niedermayer 已提交
643
        /* mpeg4? / opendivx / xvid */
F
Fabrice Bellard 已提交
644 645 646
        draw_edges(s->current_picture[0], s->linesize, s->width, s->height, EDGE_WIDTH);
        draw_edges(s->current_picture[1], s->linesize/2, s->width/2, s->height/2, EDGE_WIDTH/2);
        draw_edges(s->current_picture[2], s->linesize/2, s->width/2, s->height/2, EDGE_WIDTH/2);
647
      }
F
Fabrice Bellard 已提交
648
    }
M
Michael Niedermayer 已提交
649
    emms_c();
650 651 652 653 654
    
    if(s->pict_type!=B_TYPE){
        s->last_non_b_pict_type= s->pict_type;
        s->last_non_b_qscale= s->qscale;
        s->last_non_b_mc_mb_var= s->mc_mb_var;
M
Michael Niedermayer 已提交
655 656
        s->num_available_buffers++;
        if(s->num_available_buffers>2) s->num_available_buffers= 2;
657
    }
F
Fabrice Bellard 已提交
658 659
}

660 661 662 663 664 665 666 667 668 669 670 671 672
/* reorder input for encoding */
void reorder_input(MpegEncContext *s, AVPicture *pict)
{
    int i, j, index;
            
    if(s->max_b_frames > FF_MAX_B_FRAMES) s->max_b_frames= FF_MAX_B_FRAMES;

//        delay= s->max_b_frames+1; (or 0 if no b frames cuz decoder diff)

    for(j=0; j<REORDER_BUFFER_SIZE-1; j++){
        s->coded_order[j]= s->coded_order[j+1];
    }
    s->coded_order[j].picture[0]= s->coded_order[j].picture[1]= s->coded_order[j].picture[2]= NULL; //catch uninitalized buffers
M
Michael Niedermayer 已提交
673
    s->coded_order[j].pict_type=0;
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738

    switch(s->input_pict_type){
    default: 
    case I_TYPE:
    case S_TYPE:
    case P_TYPE:
        index= s->max_b_frames - s->b_frames_since_non_b;
        s->b_frames_since_non_b=0;
        break;            
    case B_TYPE:
        index= s->max_b_frames + 1;
        s->b_frames_since_non_b++;
        break;          
    }
//printf("index:%d type:%d strides: %d %d\n", index, s->input_pict_type, pict->linesize[0], s->linesize);
    if(   (index==0 || (s->flags&CODEC_FLAG_INPUT_PRESERVED))
       && pict->linesize[0] == s->linesize
       && pict->linesize[1] == s->linesize>>1
       && pict->linesize[2] == s->linesize>>1){
//printf("ptr\n");
        for(i=0; i<3; i++){
            s->coded_order[index].picture[i]= pict->data[i];
        }
    }else{
//printf("copy\n");
        for(i=0; i<3; i++){
            uint8_t *src = pict->data[i];
            uint8_t *dest;
            int src_wrap = pict->linesize[i];
            int dest_wrap = s->linesize;
            int w = s->width;
            int h = s->height;

            if(index==0) dest= s->last_picture[i]+16; //is current_picture indeed but the switch hapens after reordering
            else         dest= s->picture_buffer[s->picture_buffer_index][i];

            if (i >= 1) {
                dest_wrap >>= 1;
                w >>= 1;
                h >>= 1;
            }

            s->coded_order[index].picture[i]= dest;
            for(j=0;j<h;j++) {
                memcpy(dest, src, w);
                dest += dest_wrap;
                src += src_wrap;
            }
        }
        if(index!=0){
            s->picture_buffer_index++;
            if(s->picture_buffer_index >= REORDER_BUFFER_SIZE-1) s->picture_buffer_index=0;
        }
    }
    s->coded_order[index].pict_type = s->input_pict_type;
    s->coded_order[index].qscale    = s->input_qscale;
    s->coded_order[index].force_type= s->force_input_type;
    s->coded_order[index].picture_in_gop_number= s->input_picture_in_gop_number;
    s->coded_order[index].picture_number= s->input_picture_number;

    for(i=0; i<3; i++){
        s->new_picture[i]= s->coded_order[0].picture[i];
    }
}

F
Fabrice Bellard 已提交
739 740 741 742 743 744
int MPV_encode_picture(AVCodecContext *avctx,
                       unsigned char *buf, int buf_size, void *data)
{
    MpegEncContext *s = avctx->priv_data;
    AVPicture *pict = data;

745
    s->input_qscale = avctx->quality;
F
Fabrice Bellard 已提交
746 747 748

    init_put_bits(&s->pb, buf, buf_size, NULL, NULL);

749 750 751 752 753 754 755 756 757 758 759 760 761
    if(avctx->flags&CODEC_FLAG_TYPE){
        s->input_pict_type=
        s->force_input_type= avctx->key_frame ? I_TYPE : P_TYPE;
    }else if(s->flags&CODEC_FLAG_PASS2){
        s->input_pict_type=
        s->force_input_type= s->rc_context.entry[s->input_picture_number].new_pict_type;
    }else{
        s->force_input_type=0;
        if (!s->intra_only) {
            /* first picture of GOP is intra */
            if (s->input_picture_in_gop_number % s->gop_size==0){
                s->input_pict_type = I_TYPE;
            }else if(s->max_b_frames==0){
762
                s->input_pict_type = P_TYPE;
763 764 765 766 767 768 769 770
            }else{
                if(s->b_frames_since_non_b < s->max_b_frames) //FIXME more IQ
                    s->input_pict_type = B_TYPE;
                else
                    s->input_pict_type = P_TYPE;
            }
        } else {
            s->input_pict_type = I_TYPE;
771
        }
F
Fabrice Bellard 已提交
772 773
    }

774 775 776
    if(s->input_pict_type==I_TYPE)
        s->input_picture_in_gop_number=0;
    
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
    reorder_input(s, pict);
    
    /* output? */
    if(s->coded_order[0].picture[0]){

        s->pict_type= s->coded_order[0].pict_type;
        if (s->fixed_qscale) /* the ratecontrol needs the last qscale so we dont touch it for CBR */
            s->qscale= s->coded_order[0].qscale;
        s->force_type= s->coded_order[0].force_type;
        s->picture_in_gop_number= s->coded_order[0].picture_in_gop_number;
        s->picture_number= s->coded_order[0].picture_number;

        MPV_frame_start(s);

        encode_picture(s, s->picture_number);
        avctx->key_frame = (s->pict_type == I_TYPE);
        avctx->header_bits = s->header_bits;
        avctx->mv_bits     = s->mv_bits;
        avctx->misc_bits   = s->misc_bits;
        avctx->i_tex_bits  = s->i_tex_bits;
        avctx->p_tex_bits  = s->p_tex_bits;
        avctx->i_count     = s->i_count;
        avctx->p_count     = s->p_count;
        avctx->skip_count  = s->skip_count;

        MPV_frame_end(s);

        if (s->out_format == FMT_MJPEG)
            mjpeg_picture_trailer(s);

        avctx->quality = s->qscale;
808 809 810
        
        if(s->flags&CODEC_FLAG_PASS1)
            ff_write_pass1_stats(s);
F
Fabrice Bellard 已提交
811 812
    }

813 814
    s->input_picture_number++;
    s->input_picture_in_gop_number++;
F
Fabrice Bellard 已提交
815 816

    flush_put_bits(&s->pb);
817
    s->frame_bits  = (pbBufPtr(&s->pb) - s->pb.buf) * 8;
818 819 820
    if(s->pict_type==B_TYPE) s->pb_frame_bits+= s->frame_bits;
    else                     s->pb_frame_bits= s->frame_bits;

821
    s->total_bits += s->frame_bits;
822 823 824
    avctx->frame_bits  = s->frame_bits;
//printf("fcode: %d, type: %d, head: %d, mv: %d, misc: %d, frame: %d, itex: %d, ptex: %d\n", 
//s->f_code, avctx->key_frame, s->header_bits, s->mv_bits, s->misc_bits, s->frame_bits, s->i_tex_bits, s->p_tex_bits);
825

826 827 828 829 830
    if (avctx->get_psnr) {
        /* At this point pict->data should have the original frame   */
        /* an s->current_picture should have the coded/decoded frame */
        get_psnr(pict->data, s->current_picture,
                 pict->linesize, s->linesize, avctx);
831
//        printf("%f\n", avctx->psnr_y);
832
    }
833
    return pbBufPtr(&s->pb) - s->pb.buf;
F
Fabrice Bellard 已提交
834 835
}

M
Michael Niedermayer 已提交
836 837 838 839 840 841 842
static inline void gmc1_motion(MpegEncContext *s,
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
                               int dest_offset,
                               UINT8 **ref_picture, int src_offset,
                               int h)
{
    UINT8 *ptr;
843
    int offset, src_x, src_y, linesize;
M
Michael Niedermayer 已提交
844 845
    int motion_x, motion_y;

846
    if(s->real_sprite_warping_points>1) printf("more than 1 warp point isnt supported\n");
M
Michael Niedermayer 已提交
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
    motion_x= s->sprite_offset[0][0];
    motion_y= s->sprite_offset[0][1];
    src_x = s->mb_x * 16 + (motion_x >> (s->sprite_warping_accuracy+1));
    src_y = s->mb_y * 16 + (motion_y >> (s->sprite_warping_accuracy+1));
    motion_x<<=(3-s->sprite_warping_accuracy);
    motion_y<<=(3-s->sprite_warping_accuracy);
    src_x = clip(src_x, -16, s->width);
    if (src_x == s->width)
        motion_x =0;
    src_y = clip(src_y, -16, s->height);
    if (src_y == s->height)
        motion_y =0;
    
    linesize = s->linesize;
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;

    dest_y+=dest_offset;
    gmc1(dest_y  , ptr  , linesize, h, motion_x&15, motion_y&15, s->no_rounding);
    gmc1(dest_y+8, ptr+8, linesize, h, motion_x&15, motion_y&15, s->no_rounding);

    motion_x= s->sprite_offset[1][0];
    motion_y= s->sprite_offset[1][1];
    src_x = s->mb_x * 8 + (motion_x >> (s->sprite_warping_accuracy+1));
    src_y = s->mb_y * 8 + (motion_y >> (s->sprite_warping_accuracy+1));
    motion_x<<=(3-s->sprite_warping_accuracy);
    motion_y<<=(3-s->sprite_warping_accuracy);
    src_x = clip(src_x, -8, s->width>>1);
    if (src_x == s->width>>1)
        motion_x =0;
    src_y = clip(src_y, -8, s->height>>1);
    if (src_y == s->height>>1)
        motion_y =0;

    offset = (src_y * linesize>>1) + src_x + (src_offset>>1);
    ptr = ref_picture[1] + offset;
    gmc1(dest_cb + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
    ptr = ref_picture[2] + offset;
    gmc1(dest_cr + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
    
    return;
}

F
Fabrice Bellard 已提交
889 890 891 892 893 894 895 896 897 898
/* apply one mpeg motion vector to the three components */
static inline void mpeg_motion(MpegEncContext *s,
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
                               int dest_offset,
                               UINT8 **ref_picture, int src_offset,
                               int field_based, op_pixels_func *pix_op,
                               int motion_x, int motion_y, int h)
{
    UINT8 *ptr;
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
M
Michael Niedermayer 已提交
899 900 901 902 903
if(s->quarter_sample)
{
    motion_x>>=1;
    motion_y>>=1;
}
904

F
Fabrice Bellard 已提交
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
    dxy = ((motion_y & 1) << 1) | (motion_x & 1);
    src_x = s->mb_x * 16 + (motion_x >> 1);
    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 1);
                
    /* WARNING: do no forget half pels */
    height = s->height >> field_based;
    src_x = clip(src_x, -16, s->width);
    if (src_x == s->width)
        dxy &= ~1;
    src_y = clip(src_y, -16, height);
    if (src_y == height)
        dxy &= ~2;
    linesize = s->linesize << field_based;
    ptr = ref_picture[0] + (src_y * linesize) + (src_x) + src_offset;
    dest_y += dest_offset;
    pix_op[dxy](dest_y, ptr, linesize, h);
    pix_op[dxy](dest_y + 8, ptr + 8, linesize, h);

    if (s->out_format == FMT_H263) {
        dxy = 0;
        if ((motion_x & 3) != 0)
            dxy |= 1;
        if ((motion_y & 3) != 0)
            dxy |= 2;
        mx = motion_x >> 2;
        my = motion_y >> 2;
    } else {
        mx = motion_x / 2;
        my = motion_y / 2;
        dxy = ((my & 1) << 1) | (mx & 1);
        mx >>= 1;
        my >>= 1;
    }
    
    src_x = s->mb_x * 8 + mx;
    src_y = s->mb_y * (8 >> field_based) + my;
    src_x = clip(src_x, -8, s->width >> 1);
    if (src_x == (s->width >> 1))
        dxy &= ~1;
    src_y = clip(src_y, -8, height >> 1);
    if (src_y == (height >> 1))
        dxy &= ~2;

    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
    ptr = ref_picture[1] + offset;
    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
    ptr = ref_picture[2] + offset;
    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
}

M
Michael Niedermayer 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
static inline void qpel_motion(MpegEncContext *s,
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
                               int dest_offset,
                               UINT8 **ref_picture, int src_offset,
                               int field_based, op_pixels_func *pix_op,
                               qpel_mc_func *qpix_op,
                               int motion_x, int motion_y, int h)
{
    UINT8 *ptr;
    int dxy, offset, mx, my, src_x, src_y, height, linesize;

    dxy = ((motion_y & 3) << 2) | (motion_x & 3);
    src_x = s->mb_x * 16 + (motion_x >> 2);
    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 2);

    height = s->height >> field_based;
    src_x = clip(src_x, -16, s->width);
    if (src_x == s->width)
        dxy &= ~3;
    src_y = clip(src_y, -16, height);
    if (src_y == height)
        dxy &= ~12;
    linesize = s->linesize << field_based;
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
    dest_y += dest_offset;
//printf("%d %d %d\n", src_x, src_y, dxy);
    qpix_op[dxy](dest_y                 , ptr                 , linesize, linesize, motion_x&3, motion_y&3);
    qpix_op[dxy](dest_y              + 8, ptr              + 8, linesize, linesize, motion_x&3, motion_y&3);
    qpix_op[dxy](dest_y + linesize*8    , ptr + linesize*8    , linesize, linesize, motion_x&3, motion_y&3);
    qpix_op[dxy](dest_y + linesize*8 + 8, ptr + linesize*8 + 8, linesize, linesize, motion_x&3, motion_y&3);
    
    mx= (motion_x>>1) | (motion_x&1);
    my= (motion_y>>1) | (motion_y&1);

    dxy = 0;
    if ((mx & 3) != 0)
        dxy |= 1;
    if ((my & 3) != 0)
        dxy |= 2;
    mx = mx >> 2;
    my = my >> 2;
    
    src_x = s->mb_x * 8 + mx;
    src_y = s->mb_y * (8 >> field_based) + my;
    src_x = clip(src_x, -8, s->width >> 1);
    if (src_x == (s->width >> 1))
        dxy &= ~1;
    src_y = clip(src_y, -8, height >> 1);
    if (src_y == (height >> 1))
        dxy &= ~2;

    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
    ptr = ref_picture[1] + offset;
    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
    ptr = ref_picture[2] + offset;
    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
}


F
Fabrice Bellard 已提交
1014 1015 1016
static inline void MPV_motion(MpegEncContext *s, 
                              UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
                              int dir, UINT8 **ref_picture, 
M
Michael Niedermayer 已提交
1017
                              op_pixels_func *pix_op, qpel_mc_func *qpix_op)
F
Fabrice Bellard 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
{
    int dxy, offset, mx, my, src_x, src_y, motion_x, motion_y;
    int mb_x, mb_y, i;
    UINT8 *ptr, *dest;

    mb_x = s->mb_x;
    mb_y = s->mb_y;

    switch(s->mv_type) {
    case MV_TYPE_16X16:
M
Michael Niedermayer 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
        if(s->mcsel){
#if 0
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
                        ref_picture, 0,
                        0, pix_op,
                        s->sprite_offset[0][0]>>3,
                        s->sprite_offset[0][1]>>3,
                        16);
#else
            gmc1_motion(s, dest_y, dest_cb, dest_cr, 0,
                        ref_picture, 0,
                        16);
#endif
M
Michael Niedermayer 已提交
1041
        }else if(s->quarter_sample && dir==0){ //FIXME
M
Michael Niedermayer 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
            qpel_motion(s, dest_y, dest_cb, dest_cr, 0,
                        ref_picture, 0,
                        0, pix_op, qpix_op,
                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
        }else{
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
                        ref_picture, 0,
                        0, pix_op,
                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
        }           
F
Fabrice Bellard 已提交
1052 1053 1054 1055 1056 1057 1058 1059
        break;
    case MV_TYPE_8X8:
        for(i=0;i<4;i++) {
            motion_x = s->mv[dir][i][0];
            motion_y = s->mv[dir][i][1];

            dxy = ((motion_y & 1) << 1) | (motion_x & 1);
            src_x = mb_x * 16 + (motion_x >> 1) + (i & 1) * 8;
M
Michael Niedermayer 已提交
1060
            src_y = mb_y * 16 + (motion_y >> 1) + (i >>1) * 8;
F
Fabrice Bellard 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
                    
            /* WARNING: do no forget half pels */
            src_x = clip(src_x, -16, s->width);
            if (src_x == s->width)
                dxy &= ~1;
            src_y = clip(src_y, -16, s->height);
            if (src_y == s->height)
                dxy &= ~2;
                    
            ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
            dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
            pix_op[dxy](dest, ptr, s->linesize, 8);
        }
        /* In case of 8X8, we construct a single chroma motion vector
           with a special rounding */
        mx = 0;
        my = 0;
        for(i=0;i<4;i++) {
            mx += s->mv[dir][i][0];
            my += s->mv[dir][i][1];
        }
        if (mx >= 0)
            mx = (h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
        else {
            mx = -mx;
            mx = -(h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
        }
        if (my >= 0)
            my = (h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
        else {
            my = -my;
            my = -(h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
        }
        dxy = ((my & 1) << 1) | (mx & 1);
        mx >>= 1;
        my >>= 1;

        src_x = mb_x * 8 + mx;
        src_y = mb_y * 8 + my;
        src_x = clip(src_x, -8, s->width/2);
        if (src_x == s->width/2)
            dxy &= ~1;
        src_y = clip(src_y, -8, s->height/2);
        if (src_y == s->height/2)
            dxy &= ~2;
        
        offset = (src_y * (s->linesize >> 1)) + src_x;
        ptr = ref_picture[1] + offset;
        pix_op[dxy](dest_cb, ptr, s->linesize >> 1, 8);
        ptr = ref_picture[2] + offset;
        pix_op[dxy](dest_cr, ptr, s->linesize >> 1, 8);
        break;
    case MV_TYPE_FIELD:
        if (s->picture_structure == PICT_FRAME) {
            /* top field */
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
                        ref_picture, s->field_select[dir][0] ? s->linesize : 0,
                        1, pix_op,
                        s->mv[dir][0][0], s->mv[dir][0][1], 8);
            /* bottom field */
            mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
                        ref_picture, s->field_select[dir][1] ? s->linesize : 0,
                        1, pix_op,
                        s->mv[dir][1][0], s->mv[dir][1][1], 8);
        } else {
            

        }
        break;
    }
}


/* put block[] to dest[] */
static inline void put_dct(MpegEncContext *s, 
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
{
    if (!s->mpeg2)
1139
        s->dct_unquantize(s, block, i, s->qscale);
1140
    ff_idct (block);
F
Fabrice Bellard 已提交
1141 1142 1143 1144 1145 1146 1147
    put_pixels_clamped(block, dest, line_size);
}

/* add block[] to dest[] */
static inline void add_dct(MpegEncContext *s, 
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
{
1148 1149 1150
    /* skip dequant / idct if we are really late ;) */
    if(s->hurry_up>1) return;

F
Fabrice Bellard 已提交
1151 1152
    if (s->block_last_index[i] >= 0) {
        if (!s->mpeg2)
M
Michael Niedermayer 已提交
1153
            if(s->encoding || (!s->h263_msmpeg4))
M
Michael Niedermayer 已提交
1154
                s->dct_unquantize(s, block, i, s->qscale);
1155

1156
        ff_idct (block);
F
Fabrice Bellard 已提交
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
        add_pixels_clamped(block, dest, line_size);
    }
}

/* generic function called after a macroblock has been parsed by the
   decoder or after it has been encoded by the encoder.

   Important variables used:
   s->mb_intra : true if intra macroblock
   s->mv_dir   : motion vector direction
   s->mv_type  : motion vector type
   s->mv       : motion vector
   s->interlaced_dct : true if interlaced dct used (mpeg2)
 */
void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
{
1173
    int mb_x, mb_y;
F
Fabrice Bellard 已提交
1174 1175
    int dct_linesize, dct_offset;
    op_pixels_func *op_pix;
M
Michael Niedermayer 已提交
1176
    qpel_mc_func *op_qpix;
F
Fabrice Bellard 已提交
1177 1178 1179 1180

    mb_x = s->mb_x;
    mb_y = s->mb_y;

1181 1182 1183 1184 1185
#ifdef FF_POSTPROCESS
    quant_store[mb_y][mb_x]=s->qscale;
    //printf("[%02d][%02d] %d\n",mb_x,mb_y,s->qscale);
#endif

F
Fabrice Bellard 已提交
1186 1187
    /* update DC predictors for P macroblocks */
    if (!s->mb_intra) {
1188
        if (s->h263_pred || s->h263_aic) {
1189 1190
          if(s->mbintra_table[mb_x + mb_y*s->mb_width])
          {
1191
            int wrap, xy, v;
1192
            s->mbintra_table[mb_x + mb_y*s->mb_width]=0;
F
Fabrice Bellard 已提交
1193
            wrap = 2 * s->mb_width + 2;
1194
            xy = 2 * mb_x + 1 +  (2 * mb_y + 1) * wrap;
F
Fabrice Bellard 已提交
1195
            v = 1024;
1196
            
1197
            s->dc_val[0][xy] = v;
1198 1199 1200
            s->dc_val[0][xy + 1] = v;
            s->dc_val[0][xy + wrap] = v;
            s->dc_val[0][xy + 1 + wrap] = v;
F
Fabrice Bellard 已提交
1201
            /* ac pred */
1202 1203 1204 1205
            memset(s->ac_val[0][xy], 0, 16 * sizeof(INT16));
            memset(s->ac_val[0][xy + 1], 0, 16 * sizeof(INT16));
            memset(s->ac_val[0][xy + wrap], 0, 16 * sizeof(INT16));
            memset(s->ac_val[0][xy + 1 + wrap], 0, 16 * sizeof(INT16));
F
Fabrice Bellard 已提交
1206
            if (s->h263_msmpeg4) {
1207 1208 1209 1210
                s->coded_block[xy] = 0;
                s->coded_block[xy + 1] = 0;
                s->coded_block[xy + wrap] = 0;
                s->coded_block[xy + 1 + wrap] = 0;
F
Fabrice Bellard 已提交
1211 1212 1213
            }
            /* chroma */
            wrap = s->mb_width + 2;
1214 1215 1216
            xy = mb_x + 1 + (mb_y + 1) * wrap;
            s->dc_val[1][xy] = v;
            s->dc_val[2][xy] = v;
F
Fabrice Bellard 已提交
1217
            /* ac pred */
1218 1219
            memset(s->ac_val[1][xy], 0, 16 * sizeof(INT16));
            memset(s->ac_val[2][xy], 0, 16 * sizeof(INT16));
1220
          }
F
Fabrice Bellard 已提交
1221 1222 1223 1224 1225 1226
        } else {
            s->last_dc[0] = 128 << s->intra_dc_precision;
            s->last_dc[1] = 128 << s->intra_dc_precision;
            s->last_dc[2] = 128 << s->intra_dc_precision;
        }
    }
1227
    else if (s->h263_pred || s->h263_aic)
1228 1229
        s->mbintra_table[mb_x + mb_y*s->mb_width]=1;

1230
    /* update motion predictor, not for B-frames as they need the motion_val from the last P/S-Frame */
1231
    if (s->out_format == FMT_H263) { //FIXME move into h263.c if possible, format specific stuff shouldnt be here
M
Michael Niedermayer 已提交
1232
      if(s->pict_type!=B_TYPE){
1233
        int xy, wrap, motion_x, motion_y;
F
Fabrice Bellard 已提交
1234 1235
        
        wrap = 2 * s->mb_width + 2;
1236
        xy = 2 * mb_x + 1 + (2 * mb_y + 1) * wrap;
F
Fabrice Bellard 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245
        if (s->mb_intra) {
            motion_x = 0;
            motion_y = 0;
            goto motion_init;
        } else if (s->mv_type == MV_TYPE_16X16) {
            motion_x = s->mv[0][0][0];
            motion_y = s->mv[0][0][1];
        motion_init:
            /* no update if 8X8 because it has been done during parsing */
1246 1247 1248 1249 1250 1251 1252 1253
            s->motion_val[xy][0] = motion_x;
            s->motion_val[xy][1] = motion_y;
            s->motion_val[xy + 1][0] = motion_x;
            s->motion_val[xy + 1][1] = motion_y;
            s->motion_val[xy + wrap][0] = motion_x;
            s->motion_val[xy + wrap][1] = motion_y;
            s->motion_val[xy + 1 + wrap][0] = motion_x;
            s->motion_val[xy + 1 + wrap][1] = motion_y;
F
Fabrice Bellard 已提交
1254
        }
M
Michael Niedermayer 已提交
1255
      }
F
Fabrice Bellard 已提交
1256 1257
    }
    
1258
    if (!(s->encoding && (s->intra_only || s->pict_type==B_TYPE))) {
F
Fabrice Bellard 已提交
1259
        UINT8 *dest_y, *dest_cb, *dest_cr;
1260 1261
        UINT8 *mbskip_ptr;

1262 1263 1264
        /* avoid copy if macroblock skipped in last frame too 
           dont touch it for B-frames as they need the skip info from the next p-frame */
        if (s->pict_type != B_TYPE) {
1265 1266 1267
            mbskip_ptr = &s->mbskip_table[s->mb_y * s->mb_width + s->mb_x];
            if (s->mb_skiped) {
                s->mb_skiped = 0;
1268 1269 1270
                /* if previous was skipped too, then nothing to do ! 
                   skip only during decoding as we might trash the buffers during encoding a bit */
                if (*mbskip_ptr != 0 && !s->encoding) 
1271 1272 1273 1274 1275 1276
                    goto the_end;
                *mbskip_ptr = 1; /* indicate that this time we skiped it */
            } else {
                *mbskip_ptr = 0; /* not skipped */
            }
        }
F
Fabrice Bellard 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291

        dest_y = s->current_picture[0] + (mb_y * 16 * s->linesize) + mb_x * 16;
        dest_cb = s->current_picture[1] + (mb_y * 8 * (s->linesize >> 1)) + mb_x * 8;
        dest_cr = s->current_picture[2] + (mb_y * 8 * (s->linesize >> 1)) + mb_x * 8;

        if (s->interlaced_dct) {
            dct_linesize = s->linesize * 2;
            dct_offset = s->linesize;
        } else {
            dct_linesize = s->linesize;
            dct_offset = s->linesize * 8;
        }

        if (!s->mb_intra) {
            /* motion handling */
1292
            if((s->flags&CODEC_FLAG_HQ) || (!s->encoding)){
1293
                if ((!s->no_rounding) || s->pict_type==B_TYPE){                
1294 1295 1296 1297 1298 1299
                    op_pix = put_pixels_tab;
                    op_qpix= qpel_mc_rnd_tab;
                }else{
                    op_pix = put_no_rnd_pixels_tab;
                    op_qpix= qpel_mc_no_rnd_tab;
                }
F
Fabrice Bellard 已提交
1300

1301 1302
                if (s->mv_dir & MV_DIR_FORWARD) {
                    MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
1303
                    if ((!s->no_rounding) || s->pict_type==B_TYPE)
1304 1305 1306 1307 1308 1309 1310
                        op_pix = avg_pixels_tab;
                    else
                        op_pix = avg_no_rnd_pixels_tab;
                }
                if (s->mv_dir & MV_DIR_BACKWARD) {
                    MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
                }
F
Fabrice Bellard 已提交
1311 1312 1313 1314 1315 1316 1317 1318
            }

            /* add dct residue */
            add_dct(s, block[0], 0, dest_y, dct_linesize);
            add_dct(s, block[1], 1, dest_y + 8, dct_linesize);
            add_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
            add_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);

F
Fabrice Bellard 已提交
1319 1320
            add_dct(s, block[4], 4, dest_cb, s->linesize >> 1);
            add_dct(s, block[5], 5, dest_cr, s->linesize >> 1);
F
Fabrice Bellard 已提交
1321 1322 1323 1324 1325 1326 1327
        } else {
            /* dct only in intra block */
            put_dct(s, block[0], 0, dest_y, dct_linesize);
            put_dct(s, block[1], 1, dest_y + 8, dct_linesize);
            put_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
            put_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);

F
Fabrice Bellard 已提交
1328 1329
            put_dct(s, block[4], 4, dest_cb, s->linesize >> 1);
            put_dct(s, block[5], 5, dest_cr, s->linesize >> 1);
F
Fabrice Bellard 已提交
1330 1331
        }
    }
1332
 the_end:
1333
    emms_c(); //FIXME remove
F
Fabrice Bellard 已提交
1334 1335
}

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
{
    int i;
    const int maxlevel= s->max_qcoeff;
    const int minlevel= s->min_qcoeff;

    for(i=0; i<=last_index; i++){
        const int j = zigzag_direct[i];
        int level = block[j];
       
        if     (level>maxlevel) level=maxlevel;
        else if(level<minlevel) level=minlevel;
        block[j]= level;
    }
}
1351 1352

static void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
F
Fabrice Bellard 已提交
1353
{
1354 1355 1356
    const int mb_x= s->mb_x;
    const int mb_y= s->mb_y;
    int i;
1357 1358 1359 1360 1361 1362 1363 1364 1365
#if 0
        if (s->interlaced_dct) {
            dct_linesize = s->linesize * 2;
            dct_offset = s->linesize;
        } else {
            dct_linesize = s->linesize;
            dct_offset = s->linesize * 8;
        }
#endif
1366

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
    if (s->mb_intra) {
        UINT8 *ptr;
        int wrap;

        wrap = s->linesize;
        ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
        get_pixels(s->block[0], ptr               , wrap);
        get_pixels(s->block[1], ptr            + 8, wrap);
        get_pixels(s->block[2], ptr + 8 * wrap    , wrap);
        get_pixels(s->block[3], ptr + 8 * wrap + 8, wrap);

        wrap >>=1;
        ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;
        get_pixels(s->block[4], ptr, wrap);

        ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
        get_pixels(s->block[5], ptr, wrap);
    }else{
        op_pixels_func *op_pix;
        qpel_mc_func *op_qpix;
        UINT8 *dest_y, *dest_cb, *dest_cr;
        UINT8 *ptr;
        int wrap;

        dest_y  = s->current_picture[0] + (mb_y * 16 * s->linesize       ) + mb_x * 16;
        dest_cb = s->current_picture[1] + (mb_y * 8  * (s->linesize >> 1)) + mb_x * 8;
        dest_cr = s->current_picture[2] + (mb_y * 8  * (s->linesize >> 1)) + mb_x * 8;

1395
        if ((!s->no_rounding) || s->pict_type==B_TYPE){
1396 1397
            op_pix = put_pixels_tab;
            op_qpix= qpel_mc_rnd_tab;
M
Michael Niedermayer 已提交
1398
        }else{
1399 1400 1401 1402 1403 1404
            op_pix = put_no_rnd_pixels_tab;
            op_qpix= qpel_mc_no_rnd_tab;
        }

        if (s->mv_dir & MV_DIR_FORWARD) {
            MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
1405
           if ((!s->no_rounding) || s->pict_type==B_TYPE)
1406 1407 1408 1409 1410 1411
                op_pix = avg_pixels_tab;
            else
                op_pix = avg_no_rnd_pixels_tab;
        }
        if (s->mv_dir & MV_DIR_BACKWARD) {
            MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
1412
        }
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
        wrap = s->linesize;
        ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
        diff_pixels(s->block[0], ptr               , dest_y               , wrap);
        diff_pixels(s->block[1], ptr            + 8, dest_y            + 8, wrap);
        diff_pixels(s->block[2], ptr + 8 * wrap    , dest_y + 8 * wrap    , wrap);
        diff_pixels(s->block[3], ptr + 8 * wrap + 8, dest_y + 8 * wrap + 8, wrap);

        wrap >>=1;
        ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;
        diff_pixels(s->block[4], ptr, dest_cb, wrap);

        ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
        diff_pixels(s->block[5], ptr, dest_cr, wrap);
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
    }
            
#if 0
            {
                float adap_parm;
                
                adap_parm = ((s->avg_mb_var << 1) + s->mb_var[s->mb_width*mb_y+mb_x] + 1.0) /
                            ((s->mb_var[s->mb_width*mb_y+mb_x] << 1) + s->avg_mb_var + 1.0);
            
                printf("\ntype=%c qscale=%2d adap=%0.2f dquant=%4.2f var=%4d avgvar=%4d", 
                        (s->mb_type[s->mb_width*mb_y+mb_x] > 0) ? 'I' : 'P', 
                        s->qscale, adap_parm, s->qscale*adap_parm,
                        s->mb_var[s->mb_width*mb_y+mb_x], s->avg_mb_var);
            }
#endif
    /* DCT & quantize */
1442
    if (s->h263_pred && s->msmpeg4_version!=2) {
1443 1444 1445 1446 1447 1448
        h263_dc_scale(s);
    } else {
        /* default quantization values */
        s->y_dc_scale = 8;
        s->c_dc_scale = 8;
    }
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
    if(s->out_format==FMT_MJPEG){
        for(i=0;i<6;i++) {
            int overflow;
            s->block_last_index[i] = dct_quantize(s, s->block[i], i, 8, &overflow);
            if(overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
        }
    }else{
        for(i=0;i<6;i++) {
            int overflow;
            s->block_last_index[i] = dct_quantize(s, s->block[i], i, s->qscale, &overflow);
            // FIXME we could decide to change to quantizer instead of clipping
            if(overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
        }
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
    }

    /* huffman encode */
    switch(s->out_format) {
    case FMT_MPEG1:
        mpeg1_encode_mb(s, s->block, motion_x, motion_y);
        break;
    case FMT_H263:
        if (s->h263_msmpeg4)
            msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
        else if(s->h263_pred)
            mpeg4_encode_mb(s, s->block, motion_x, motion_y);
        else
            h263_encode_mb(s, s->block, motion_x, motion_y);
        break;
    case FMT_MJPEG:
        mjpeg_encode_mb(s, s->block);
        break;
    }
}

static void copy_bits(PutBitContext *pb, UINT8 *src, int length)
{
1485 1486 1487 1488 1489 1490 1491 1492
#if 1
    int bytes= length>>4;
    int bits= length&15;
    int i;

    for(i=0; i<bytes; i++) put_bits(pb, 16, be2me_16(((uint16_t*)src)[i]));
    put_bits(pb, bits, be2me_16(((uint16_t*)src)[i])>>(16-bits));
#else
1493 1494 1495 1496 1497 1498
    int bytes= length>>3;
    int bits= length&7;
    int i;

    for(i=0; i<bytes; i++) put_bits(pb, 8, src[i]);
    put_bits(pb, bits, src[i]>>(8-bits));
1499
#endif
1500 1501
}

1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
static void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
    int i;

    memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?

    /* mpeg1 */
    d->mb_incr= s->mb_incr;
    for(i=0; i<3; i++)
        d->last_dc[i]= s->last_dc[i];
    
    /* statistics */
    d->mv_bits= s->mv_bits;
    d->i_tex_bits= s->i_tex_bits;
    d->p_tex_bits= s->p_tex_bits;
    d->i_count= s->i_count;
    d->p_count= s->p_count;
    d->skip_count= s->skip_count;
    d->misc_bits= s->misc_bits;
1520
    d->last_bits= 0;
1521 1522

    d->mb_skiped= s->mb_skiped;
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
}

static void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
    int i;

    memcpy(d->mv, s->mv, 2*4*2*sizeof(int)); 
    memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
    
    /* mpeg1 */
    d->mb_incr= s->mb_incr;
    for(i=0; i<3; i++)
        d->last_dc[i]= s->last_dc[i];
    
    /* statistics */
    d->mv_bits= s->mv_bits;
    d->i_tex_bits= s->i_tex_bits;
    d->p_tex_bits= s->p_tex_bits;
    d->i_count= s->i_count;
    d->p_count= s->p_count;
    d->skip_count= s->skip_count;
    d->misc_bits= s->misc_bits;

    d->mb_intra= s->mb_intra;
1546
    d->mb_skiped= s->mb_skiped;
1547 1548 1549 1550 1551 1552 1553 1554 1555
    d->mv_type= s->mv_type;
    d->mv_dir= s->mv_dir;
    d->pb= s->pb;
    d->block= s->block;
    for(i=0; i<6; i++)
        d->block_last_index[i]= s->block_last_index[i];
}


1556 1557 1558 1559
static void encode_picture(MpegEncContext *s, int picture_number)
{
    int mb_x, mb_y, last_gob, pdif = 0;
    int i;
1560
    int bits;
1561
    MpegEncContext best_s, backup_s;
1562
    UINT8 bit_buf[7][3000]; //FIXME check that this is ALLWAYS large enogh for a MB
F
Fabrice Bellard 已提交
1563 1564

    s->picture_number = picture_number;
1565

1566 1567 1568 1569 1570 1571 1572
    s->block_wrap[0]=
    s->block_wrap[1]=
    s->block_wrap[2]=
    s->block_wrap[3]= s->mb_width*2 + 2;
    s->block_wrap[4]=
    s->block_wrap[5]= s->mb_width + 2;
    
1573 1574 1575
    /* Reset the average MB variance */
    s->avg_mb_var = 0;
    s->mc_mb_var = 0;
1576 1577 1578 1579 1580

    /* we need to initialize some time vars before we can encode b-frames */
    if (s->h263_pred && !s->h263_msmpeg4)
        ff_set_mpeg4_time(s, s->picture_number); 

1581
    /* Estimate motion for every MB */
1582 1583 1584 1585 1586
    if(s->pict_type != I_TYPE){
//        int16_t (*tmp)[2]= s->p_mv_table;
//        s->p_mv_table= s->last_mv_table;
//        s->last_mv_table= s->mv_table;
    
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
        for(mb_y=0; mb_y < s->mb_height; mb_y++) {
            s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
            s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
            s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
            s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
            for(mb_x=0; mb_x < s->mb_width; mb_x++) {
                s->mb_x = mb_x;
                s->mb_y = mb_y;
                s->block_index[0]+=2;
                s->block_index[1]+=2;
                s->block_index[2]+=2;
                s->block_index[3]+=2;

                /* compute motion vector & mb_type and store in context */
1601 1602 1603 1604
                if(s->pict_type==B_TYPE)
                    ff_estimate_b_frame_motion(s, mb_x, mb_y);
                else
                    ff_estimate_p_frame_motion(s, mb_x, mb_y);
1605
//                s->mb_type[mb_y*s->mb_width + mb_x]=MB_TYPE_INTER;
1606 1607
            }
        }
1608
        emms_c();
1609
    }else if(s->pict_type == I_TYPE){
1610 1611 1612
        /* I-Frame */
        //FIXME do we need to zero them?
        memset(s->motion_val[0], 0, sizeof(INT16)*(s->mb_width*2 + 2)*(s->mb_height*2 + 2)*2);
1613
        memset(s->p_mv_table   , 0, sizeof(INT16)*(s->mb_width+2)*(s->mb_height+2)*2);
1614
        memset(s->mb_type      , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
1615 1616
    }

1617
    if(s->avg_mb_var < s->mc_mb_var && s->pict_type == P_TYPE){ //FIXME subtract MV bits
M
Michael Niedermayer 已提交
1618
        s->pict_type= I_TYPE;
1619
        memset(s->mb_type   , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
1620 1621 1622 1623
        if(s->max_b_frames==0){
            s->input_pict_type= I_TYPE;
            s->input_picture_in_gop_number=0;
        }
1624
//printf("Scene change detected, encoding as I Frame\n");
M
Michael Niedermayer 已提交
1625
    }
1626 1627 1628 1629 1630 1631 1632
    
    if(s->pict_type==P_TYPE || s->pict_type==S_TYPE) 
        s->f_code= ff_get_best_fcode(s, s->p_mv_table, MB_TYPE_INTER);
        ff_fix_long_p_mvs(s);
    if(s->pict_type==B_TYPE){
        s->f_code= ff_get_best_fcode(s, s->b_forw_mv_table, MB_TYPE_FORWARD);
        s->b_code= ff_get_best_fcode(s, s->b_back_mv_table, MB_TYPE_BACKWARD);
1633 1634 1635 1636 1637

        ff_fix_long_b_mvs(s, s->b_forw_mv_table, s->f_code, MB_TYPE_FORWARD);
        ff_fix_long_b_mvs(s, s->b_back_mv_table, s->b_code, MB_TYPE_BACKWARD);
        ff_fix_long_b_mvs(s, s->b_bidir_forw_mv_table, s->f_code, MB_TYPE_BIDIR);
        ff_fix_long_b_mvs(s, s->b_bidir_back_mv_table, s->b_code, MB_TYPE_BIDIR);
1638
    }
1639
    
1640 1641
//printf("f_code %d ///\n", s->f_code);

M
Michael Niedermayer 已提交
1642 1643
//    printf("%d %d\n", s->avg_mb_var, s->mc_mb_var);

1644 1645 1646 1647 1648
    if(s->flags&CODEC_FLAG_PASS2)
        s->qscale = ff_rate_estimate_qscale_pass2(s);
    else if (!s->fixed_qscale) 
        s->qscale = ff_rate_estimate_qscale(s);

F
Fabrice Bellard 已提交
1649 1650 1651 1652 1653
    if (s->out_format == FMT_MJPEG) {
        /* for mjpeg, we do include qscale in the matrix */
        s->intra_matrix[0] = default_intra_matrix[0];
        for(i=1;i<64;i++)
            s->intra_matrix[i] = (default_intra_matrix[i] * s->qscale) >> 3;
1654 1655
        convert_matrix(s->q_intra_matrix, s->q_intra_matrix16, 
                       s->q_intra_matrix16_bias, s->intra_matrix, s->intra_quant_bias);
F
Fabrice Bellard 已提交
1656 1657
    }

1658
    s->last_bits= get_bit_count(&s->pb);
F
Fabrice Bellard 已提交
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
    switch(s->out_format) {
    case FMT_MJPEG:
        mjpeg_picture_header(s);
        break;
    case FMT_H263:
        if (s->h263_msmpeg4) 
            msmpeg4_encode_picture_header(s, picture_number);
        else if (s->h263_pred)
            mpeg4_encode_picture_header(s, picture_number);
        else if (s->h263_rv10) 
            rv10_encode_picture_header(s, picture_number);
        else
            h263_encode_picture_header(s, picture_number);
        break;
    case FMT_MPEG1:
        mpeg1_encode_picture_header(s, picture_number);
        break;
    }
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
    bits= get_bit_count(&s->pb);
    s->header_bits= bits - s->last_bits;
    s->last_bits= bits;
    s->mv_bits=0;
    s->misc_bits=0;
    s->i_tex_bits=0;
    s->p_tex_bits=0;
    s->i_count=0;
    s->p_count=0;
    s->skip_count=0;

F
Fabrice Bellard 已提交
1688 1689 1690 1691 1692 1693 1694 1695 1696
    /* init last dc values */
    /* note: quant matrix value (8) is implied here */
    s->last_dc[0] = 128;
    s->last_dc[1] = 128;
    s->last_dc[2] = 128;
    s->mb_incr = 1;
    s->last_mv[0][0][0] = 0;
    s->last_mv[0][0][1] = 0;

1697
    /* Get the GOB height based on picture height */
1698
    if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4) {
1699 1700 1701 1702 1703 1704 1705
        if (s->height <= 400)
            s->gob_index = 1;
        else if (s->height <= 800)
            s->gob_index = 2;
        else
            s->gob_index = 4;
    }
1706
        
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
    s->avg_mb_var = s->avg_mb_var / s->mb_num;        
    
    for(mb_y=0; mb_y < s->mb_height; mb_y++) {
        /* Put GOB header based on RTP MTU */
        /* TODO: Put all this stuff in a separate generic function */
        if (s->rtp_mode) {
            if (!mb_y) {
                s->ptr_lastgob = s->pb.buf;
                s->ptr_last_mb_line = s->pb.buf;
            } else if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4 && !(mb_y % s->gob_index)) {
                last_gob = h263_encode_gob_header(s, mb_y);
                if (last_gob) {
                    s->first_gob_line = 1;
                }
            }
        }
        
M
Michael Niedermayer 已提交
1724 1725 1726 1727 1728 1729
        s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
        s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
        s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
        s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
        s->block_index[4]= s->block_wrap[4]*(mb_y + 1)                    + s->block_wrap[0]*(s->mb_height*2 + 2);
        s->block_index[5]= s->block_wrap[4]*(mb_y + 1 + s->mb_height + 2) + s->block_wrap[0]*(s->mb_height*2 + 2);
1730
        for(mb_x=0; mb_x < s->mb_width; mb_x++) {
1731 1732
            const int mb_type= s->mb_type[mb_y * s->mb_width + mb_x];
            const int xy= (mb_y+1) * (s->mb_width+2) + mb_x + 1;
1733 1734 1735 1736
            PutBitContext pb;
            int d;
            int dmin=10000000;
            int best=0;
1737 1738 1739

            s->mb_x = mb_x;
            s->mb_y = mb_y;
M
Michael Niedermayer 已提交
1740 1741 1742 1743 1744 1745
            s->block_index[0]+=2;
            s->block_index[1]+=2;
            s->block_index[2]+=2;
            s->block_index[3]+=2;
            s->block_index[4]++;
            s->block_index[5]++;
1746
            if(mb_type & (mb_type-1)){ // more than 1 MB type possible
1747
                int next_block=0;
1748
                pb= s->pb;
1749 1750 1751

                copy_context_before_encode(&backup_s, s, -1);

1752
                if(mb_type&MB_TYPE_INTER){
1753
                    s->mv_dir = MV_DIR_FORWARD;
M
Michael Niedermayer 已提交
1754
                    s->mv_type = MV_TYPE_16X16;
1755
                    s->mb_intra= 0;
1756 1757
                    s->mv[0][0][0] = s->p_mv_table[xy][0];
                    s->mv[0][0][1] = s->p_mv_table[xy][1];
1758
                    init_put_bits(&s->pb, bit_buf[1], 3000, NULL, NULL);
1759
                    s->block= s->blocks[next_block];
1760
                    s->last_bits= 0; //done in copy_context_before_encode but we skip that here
1761

1762
                    encode_mb(s, s->mv[0][0][0], s->mv[0][0][1]);
1763 1764 1765 1766
                    d= get_bit_count(&s->pb);
                    if(d<dmin){
                        flush_put_bits(&s->pb);
                        dmin=d;
1767
                        copy_context_after_encode(&best_s, s, MB_TYPE_INTER);
1768
                        best=1;
1769
                        next_block^=1;
1770
                    }
F
Fabrice Bellard 已提交
1771
                }
1772 1773
                if(mb_type&MB_TYPE_INTER4V){                 
                    copy_context_before_encode(s, &backup_s, MB_TYPE_INTER4V);
1774
                    s->mv_dir = MV_DIR_FORWARD;
M
Michael Niedermayer 已提交
1775 1776 1777 1778 1779 1780 1781
                    s->mv_type = MV_TYPE_8X8;
                    s->mb_intra= 0;
                    for(i=0; i<4; i++){
                        s->mv[0][i][0] = s->motion_val[s->block_index[i]][0];
                        s->mv[0][i][1] = s->motion_val[s->block_index[i]][1];
                    }
                    init_put_bits(&s->pb, bit_buf[2], 3000, NULL, NULL);
1782
                    s->block= s->blocks[next_block];
M
Michael Niedermayer 已提交
1783

1784
                    encode_mb(s, 0, 0);
M
Michael Niedermayer 已提交
1785
                    d= get_bit_count(&s->pb);
1786
                    if(d<dmin){
M
Michael Niedermayer 已提交
1787 1788
                        flush_put_bits(&s->pb);
                        dmin=d;
1789
                        copy_context_after_encode(&best_s, s, MB_TYPE_INTER4V);
M
Michael Niedermayer 已提交
1790
                        best=2;
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
                        next_block^=1;
                    }
                }
                if(mb_type&MB_TYPE_FORWARD){
                    copy_context_before_encode(s, &backup_s, MB_TYPE_FORWARD);
                    s->mv_dir = MV_DIR_FORWARD;
                    s->mv_type = MV_TYPE_16X16;
                    s->mb_intra= 0;
                    s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
                    s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
                    init_put_bits(&s->pb, bit_buf[3], 3000, NULL, NULL);
                    s->block= s->blocks[next_block];

                    encode_mb(s, s->mv[0][0][0], s->mv[0][0][1]);
                    d= get_bit_count(&s->pb);
                    if(d<dmin){
                        flush_put_bits(&s->pb);
                        dmin=d;
                        copy_context_after_encode(&best_s, s, MB_TYPE_FORWARD);
                        best=3;
                        next_block^=1;
                    }
                }
                if(mb_type&MB_TYPE_BACKWARD){
                    copy_context_before_encode(s, &backup_s, MB_TYPE_BACKWARD);
                    s->mv_dir = MV_DIR_BACKWARD;
                    s->mv_type = MV_TYPE_16X16;
                    s->mb_intra= 0;
                    s->mv[1][0][0] = s->b_back_mv_table[xy][0];
                    s->mv[1][0][1] = s->b_back_mv_table[xy][1];
                    init_put_bits(&s->pb, bit_buf[4], 3000, NULL, NULL);
                    s->block= s->blocks[next_block];

                    encode_mb(s, s->mv[1][0][0], s->mv[1][0][1]);
                    d= get_bit_count(&s->pb);
                    if(d<dmin){
                        flush_put_bits(&s->pb);
                        dmin=d;
                        copy_context_after_encode(&best_s, s, MB_TYPE_BACKWARD);
                        best=4;
                        next_block^=1;
                    }
                }
                if(mb_type&MB_TYPE_BIDIR){
                    copy_context_before_encode(s, &backup_s, MB_TYPE_BIDIR);
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
                    s->mv_type = MV_TYPE_16X16;
                    s->mb_intra= 0;
                    s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
                    s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
                    s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
                    s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
                    init_put_bits(&s->pb, bit_buf[5], 3000, NULL, NULL);
                    s->block= s->blocks[next_block];

                    encode_mb(s, 0, 0);
                    d= get_bit_count(&s->pb);
                    if(d<dmin){
                        flush_put_bits(&s->pb);
                        dmin=d;
                        copy_context_after_encode(&best_s, s, MB_TYPE_BIDIR);
                        best=5;
                        next_block^=1;
                    }
                }
                if(mb_type&MB_TYPE_DIRECT){
                    copy_context_before_encode(s, &backup_s, MB_TYPE_DIRECT);
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
                    s->mv_type = MV_TYPE_16X16; //FIXME
                    s->mb_intra= 0;
                    s->mv[0][0][0] = s->b_direct_forw_mv_table[xy][0];
                    s->mv[0][0][1] = s->b_direct_forw_mv_table[xy][1];
                    s->mv[1][0][0] = s->b_direct_back_mv_table[xy][0];
                    s->mv[1][0][1] = s->b_direct_back_mv_table[xy][1];
                    init_put_bits(&s->pb, bit_buf[6], 3000, NULL, NULL);
                    s->block= s->blocks[next_block];

                    encode_mb(s, s->b_direct_mv_table[xy][0], s->b_direct_mv_table[xy][1]);
                    d= get_bit_count(&s->pb);
                    if(d<dmin){
                        flush_put_bits(&s->pb);
                        dmin=d;
                        copy_context_after_encode(&best_s, s, MB_TYPE_DIRECT);
                        best=6;
                        next_block^=1;
M
Michael Niedermayer 已提交
1876 1877
                    }
                }
1878
                if(mb_type&MB_TYPE_INTRA){
1879
                    copy_context_before_encode(s, &backup_s, MB_TYPE_INTRA);
1880
                    s->mv_dir = MV_DIR_FORWARD;
M
Michael Niedermayer 已提交
1881
                    s->mv_type = MV_TYPE_16X16;
1882 1883 1884 1885
                    s->mb_intra= 1;
                    s->mv[0][0][0] = 0;
                    s->mv[0][0][1] = 0;
                    init_put_bits(&s->pb, bit_buf[0], 3000, NULL, NULL);
1886
                    s->block= s->blocks[next_block];
1887
                   
1888
                    encode_mb(s, 0, 0);
1889 1890 1891 1892
                    d= get_bit_count(&s->pb);
                    if(d<dmin){
                        flush_put_bits(&s->pb);
                        dmin=d;
1893
                        copy_context_after_encode(&best_s, s, MB_TYPE_INTRA);
1894
                        best=0;
1895
                        next_block^=1;
1896
                    }
1897 1898 1899
                    /* force cleaning of ac/dc pred stuff if needed ... */
                    if(s->h263_pred || s->h263_aic)
                        s->mbintra_table[mb_x + mb_y*s->mb_width]=1;
M
Michael Niedermayer 已提交
1900
                }
1901
                copy_context_after_encode(s, &best_s, -1);
1902 1903
                copy_bits(&pb, bit_buf[best], dmin);
                s->pb= pb;
1904
                s->last_bits= get_bit_count(&s->pb);
F
Fabrice Bellard 已提交
1905
            } else {
1906 1907
                int motion_x, motion_y;
                s->mv_type=MV_TYPE_16X16;
1908
                // only one MB-Type possible
1909 1910
                switch(mb_type){
                case MB_TYPE_INTRA:
1911
                    s->mv_dir = MV_DIR_FORWARD;
1912
                    s->mb_intra= 1;
1913 1914
                    motion_x= s->mv[0][0][0] = 0;
                    motion_y= s->mv[0][0][1] = 0;
1915 1916
                    break;
                case MB_TYPE_INTER:
1917 1918 1919 1920
                    s->mv_dir = MV_DIR_FORWARD;
                    s->mb_intra= 0;
                    motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
                    motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
1921 1922
                    break;
                case MB_TYPE_DIRECT:
1923 1924
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
                    s->mb_intra= 0;
1925 1926 1927 1928 1929 1930 1931 1932
                    motion_x=s->b_direct_mv_table[xy][0];
                    motion_y=s->b_direct_mv_table[xy][1];
                    s->mv[0][0][0] = s->b_direct_forw_mv_table[xy][0];
                    s->mv[0][0][1] = s->b_direct_forw_mv_table[xy][1];
                    s->mv[1][0][0] = s->b_direct_back_mv_table[xy][0];
                    s->mv[1][0][1] = s->b_direct_back_mv_table[xy][1];
                    break;
                case MB_TYPE_BIDIR:
1933
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
1934
                    s->mb_intra= 0;
1935 1936 1937 1938 1939 1940
                    motion_x=0;
                    motion_y=0;
                    s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
                    s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
                    s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
                    s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
1941 1942
                    break;
                case MB_TYPE_BACKWARD:
1943 1944 1945 1946
                    s->mv_dir = MV_DIR_BACKWARD;
                    s->mb_intra= 0;
                    motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
                    motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
1947 1948
                    break;
                case MB_TYPE_FORWARD:
1949 1950 1951 1952 1953
                    s->mv_dir = MV_DIR_FORWARD;
                    s->mb_intra= 0;
                    motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
                    motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
//                    printf(" %d %d ", motion_x, motion_y);
1954 1955
                    break;
                default:
1956 1957
                    motion_x=motion_y=0; //gcc warning fix
                    printf("illegal MB type\n");
1958
                }
1959
                encode_mb(s, motion_x, motion_y);
F
Fabrice Bellard 已提交
1960
            }
1961 1962 1963 1964 1965
            /* clean the MV table in IPS frames for direct mode in B frames */
            if(s->mb_intra /* && I,P,S_TYPE */){
                s->p_mv_table[xy][0]=0;
                s->p_mv_table[xy][1]=0;
            }
F
Fabrice Bellard 已提交
1966

1967
            MPV_decode_mb(s, s->block);
F
Fabrice Bellard 已提交
1968
        }
1969 1970


1971 1972 1973
        /* Obtain average GOB size for RTP */
        if (s->rtp_mode) {
            if (!mb_y)
1974
                s->mb_line_avgsize = pbBufPtr(&s->pb) - s->ptr_last_mb_line;
1975
            else if (!(mb_y % s->gob_index)) {    
1976 1977
                s->mb_line_avgsize = (s->mb_line_avgsize + pbBufPtr(&s->pb) - s->ptr_last_mb_line) >> 1;
                s->ptr_last_mb_line = pbBufPtr(&s->pb);
1978 1979 1980 1981 1982
            }
            //fprintf(stderr, "\nMB line: %d\tSize: %u\tAvg. Size: %u", s->mb_y, 
            //                    (s->pb.buf_ptr - s->ptr_last_mb_line), s->mb_line_avgsize);
            s->first_gob_line = 0;
        }
F
Fabrice Bellard 已提交
1983
    }
1984
    emms_c();
1985

1986
    if (s->h263_msmpeg4 && s->msmpeg4_version<4 && s->pict_type == I_TYPE)
M
Michael Niedermayer 已提交
1987 1988
        msmpeg4_encode_ext_header(s);

1989 1990
    //if (s->gob_number)
    //    fprintf(stderr,"\nNumber of GOB: %d", s->gob_number);
1991 1992 1993 1994
    
    /* Send the last GOB if RTP */    
    if (s->rtp_mode) {
        flush_put_bits(&s->pb);
1995
        pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
1996 1997 1998
        /* Call the RTP callback to send the last GOB */
        if (s->rtp_callback)
            s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
1999
        s->ptr_lastgob = pbBufPtr(&s->pb);
2000 2001
        //fprintf(stderr,"\nGOB: %2d size: %d (last)", s->gob_number, pdif);
    }
F
Fabrice Bellard 已提交
2002 2003
}

M
Michael Niedermayer 已提交
2004
static int dct_quantize_c(MpegEncContext *s, 
F
Fabrice Bellard 已提交
2005
                        DCTELEM *block, int n,
2006
                        int qscale, int *overflow)
F
Fabrice Bellard 已提交
2007 2008 2009
{
    int i, j, level, last_non_zero, q;
    const int *qmat;
2010 2011 2012
    int bias;
    int max=0;
    unsigned int threshold1, threshold2;
F
Fabrice Bellard 已提交
2013 2014 2015

    av_fdct (block);

F
Fabrice Bellard 已提交
2016 2017 2018 2019
    /* we need this permutation so that we correct the IDCT
       permutation. will be moved into DCT code */
    block_permute(block);

F
Fabrice Bellard 已提交
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
    if (s->mb_intra) {
        if (n < 4)
            q = s->y_dc_scale;
        else
            q = s->c_dc_scale;
        q = q << 3;
        
        /* note: block[0] is assumed to be positive */
        block[0] = (block[0] + (q >> 1)) / q;
        i = 1;
        last_non_zero = 0;
2031 2032
        qmat = s->q_intra_matrix[qscale];
        bias= s->intra_quant_bias<<(QMAT_SHIFT - 3 - QUANT_BIAS_SHIFT);
F
Fabrice Bellard 已提交
2033 2034 2035
    } else {
        i = 0;
        last_non_zero = -1;
2036 2037
        qmat = s->q_inter_matrix[qscale];
        bias= s->inter_quant_bias<<(QMAT_SHIFT - 3 - QUANT_BIAS_SHIFT);
F
Fabrice Bellard 已提交
2038
    }
2039 2040
    threshold1= (1<<(QMAT_SHIFT - 3)) - bias - 1;
    threshold2= threshold1<<1;
F
Fabrice Bellard 已提交
2041 2042 2043 2044 2045 2046

    for(;i<64;i++) {
        j = zigzag_direct[i];
        level = block[j];
        level = level * qmat[j];

2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
//        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
//           || bias-level >= (1<<(QMAT_SHIFT - 3))){
        if(((unsigned)(level+threshold1))>threshold2){
            if(level>0){
                level= (bias + level)>>(QMAT_SHIFT - 3);
                block[j]= level;
            }else{
                level= (bias - level)>>(QMAT_SHIFT - 3);
                block[j]= -level;
            }
            max |=level;
F
Fabrice Bellard 已提交
2058
            last_non_zero = i;
2059 2060
        }else{
            block[j]=0;
F
Fabrice Bellard 已提交
2061 2062
        }
    }
2063 2064
    *overflow= s->max_qcoeff < max; //overflow might have happend
    
F
Fabrice Bellard 已提交
2065 2066 2067
    return last_non_zero;
}

2068 2069
static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
                                   DCTELEM *block, int n, int qscale)
F
Fabrice Bellard 已提交
2070
{
M
Michael Niedermayer 已提交
2071
    int i, level, nCoeffs;
F
Fabrice Bellard 已提交
2072 2073
    const UINT16 *quant_matrix;

M
Michael Niedermayer 已提交
2074 2075 2076
    if(s->alternate_scan) nCoeffs= 64;
    else nCoeffs= s->block_last_index[n]+1;
    
F
Fabrice Bellard 已提交
2077 2078 2079 2080 2081 2082 2083
    if (s->mb_intra) {
        if (n < 4) 
            block[0] = block[0] * s->y_dc_scale;
        else
            block[0] = block[0] * s->c_dc_scale;
        /* XXX: only mpeg1 */
        quant_matrix = s->intra_matrix;
M
Michael Niedermayer 已提交
2084 2085 2086
        for(i=1;i<nCoeffs;i++) {
            int j= zigzag_direct[i];
            level = block[j];
F
Fabrice Bellard 已提交
2087 2088 2089
            if (level) {
                if (level < 0) {
                    level = -level;
M
Michael Niedermayer 已提交
2090
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
F
Fabrice Bellard 已提交
2091 2092 2093
                    level = (level - 1) | 1;
                    level = -level;
                } else {
M
Michael Niedermayer 已提交
2094
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
F
Fabrice Bellard 已提交
2095 2096 2097 2098 2099 2100
                    level = (level - 1) | 1;
                }
#ifdef PARANOID
                if (level < -2048 || level > 2047)
                    fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
M
Michael Niedermayer 已提交
2101
                block[j] = level;
F
Fabrice Bellard 已提交
2102 2103 2104 2105
            }
        }
    } else {
        i = 0;
2106
        quant_matrix = s->inter_matrix;
M
Michael Niedermayer 已提交
2107
        for(;i<nCoeffs;i++) {
M
Michael Niedermayer 已提交
2108 2109
            int j= zigzag_direct[i];
            level = block[j];
F
Fabrice Bellard 已提交
2110 2111 2112 2113
            if (level) {
                if (level < 0) {
                    level = -level;
                    level = (((level << 1) + 1) * qscale *
M
Michael Niedermayer 已提交
2114
                             ((int) (quant_matrix[j]))) >> 4;
F
Fabrice Bellard 已提交
2115 2116 2117 2118
                    level = (level - 1) | 1;
                    level = -level;
                } else {
                    level = (((level << 1) + 1) * qscale *
M
Michael Niedermayer 已提交
2119
                             ((int) (quant_matrix[j]))) >> 4;
F
Fabrice Bellard 已提交
2120 2121 2122 2123 2124 2125
                    level = (level - 1) | 1;
                }
#ifdef PARANOID
                if (level < -2048 || level > 2047)
                    fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
M
Michael Niedermayer 已提交
2126
                block[j] = level;
F
Fabrice Bellard 已提交
2127 2128 2129 2130
            }
        }
    }
}
2131

2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
static void dct_unquantize_mpeg2_c(MpegEncContext *s, 
                                   DCTELEM *block, int n, int qscale)
{
    int i, level, nCoeffs;
    const UINT16 *quant_matrix;

    if(s->alternate_scan) nCoeffs= 64;
    else nCoeffs= s->block_last_index[n]+1;
    
    if (s->mb_intra) {
        if (n < 4) 
            block[0] = block[0] * s->y_dc_scale;
        else
            block[0] = block[0] * s->c_dc_scale;
        quant_matrix = s->intra_matrix;
        for(i=1;i<nCoeffs;i++) {
            int j= zigzag_direct[i];
            level = block[j];
            if (level) {
                if (level < 0) {
                    level = -level;
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
                    level = -level;
                } else {
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
                }
#ifdef PARANOID
                if (level < -2048 || level > 2047)
                    fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
                block[j] = level;
            }
        }
    } else {
        int sum=-1;
        i = 0;
2168
        quant_matrix = s->inter_matrix;
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
        for(;i<nCoeffs;i++) {
            int j= zigzag_direct[i];
            level = block[j];
            if (level) {
                if (level < 0) {
                    level = -level;
                    level = (((level << 1) + 1) * qscale *
                             ((int) (quant_matrix[j]))) >> 4;
                    level = -level;
                } else {
                    level = (((level << 1) + 1) * qscale *
                             ((int) (quant_matrix[j]))) >> 4;
                }
#ifdef PARANOID
                if (level < -2048 || level > 2047)
                    fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
                block[j] = level;
                sum+=level;
            }
        }
        block[63]^=sum&1;
    }
}


2195 2196 2197 2198
static void dct_unquantize_h263_c(MpegEncContext *s, 
                                  DCTELEM *block, int n, int qscale)
{
    int i, level, qmul, qadd;
M
Michael Niedermayer 已提交
2199
    int nCoeffs;
2200
    
2201
    if (s->mb_intra) {
2202 2203 2204 2205 2206 2207
        if (!s->h263_aic) {
            if (n < 4) 
                block[0] = block[0] * s->y_dc_scale;
            else
                block[0] = block[0] * s->c_dc_scale;
        }
2208
        i = 1;
M
Michael Niedermayer 已提交
2209
        nCoeffs= 64; //does not allways use zigzag table 
2210 2211
    } else {
        i = 0;
M
Michael Niedermayer 已提交
2212
        nCoeffs= zigzag_end[ s->block_last_index[n] ];
2213 2214 2215
    }

    qmul = s->qscale << 1;
2216 2217 2218 2219
    if (s->h263_aic && s->mb_intra)
        qadd = 0;
    else
        qadd = (s->qscale - 1) | 1;
2220

M
Michael Niedermayer 已提交
2221
    for(;i<nCoeffs;i++) {
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
        level = block[i];
        if (level) {
            if (level < 0) {
                level = level * qmul - qadd;
            } else {
                level = level * qmul + qadd;
            }
#ifdef PARANOID
                if (level < -2048 || level > 2047)
                    fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
            block[i] = level;
        }
    }
}
F
Fabrice Bellard 已提交
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287

AVCodec mpeg1video_encoder = {
    "mpeg1video",
    CODEC_TYPE_VIDEO,
    CODEC_ID_MPEG1VIDEO,
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};

AVCodec h263_encoder = {
    "h263",
    CODEC_TYPE_VIDEO,
    CODEC_ID_H263,
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};

AVCodec h263p_encoder = {
    "h263p",
    CODEC_TYPE_VIDEO,
    CODEC_ID_H263P,
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};

AVCodec rv10_encoder = {
    "rv10",
    CODEC_TYPE_VIDEO,
    CODEC_ID_RV10,
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};

AVCodec mjpeg_encoder = {
    "mjpeg",
    CODEC_TYPE_VIDEO,
    CODEC_ID_MJPEG,
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};

F
Fabrice Bellard 已提交
2288 2289
AVCodec mpeg4_encoder = {
    "mpeg4",
F
Fabrice Bellard 已提交
2290
    CODEC_TYPE_VIDEO,
F
Fabrice Bellard 已提交
2291
    CODEC_ID_MPEG4,
F
Fabrice Bellard 已提交
2292 2293 2294 2295 2296 2297
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};

2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
AVCodec msmpeg4v1_encoder = {
    "msmpeg4v1",
    CODEC_TYPE_VIDEO,
    CODEC_ID_MSMPEG4V1,
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};

AVCodec msmpeg4v2_encoder = {
    "msmpeg4v2",
    CODEC_TYPE_VIDEO,
    CODEC_ID_MSMPEG4V2,
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};

AVCodec msmpeg4v3_encoder = {
F
Fabrice Bellard 已提交
2319 2320
    "msmpeg4",
    CODEC_TYPE_VIDEO,
2321
    CODEC_ID_MSMPEG4V3,
F
Fabrice Bellard 已提交
2322 2323 2324 2325 2326
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};