mpegvideo.c 60.5 KB
Newer Older
F
Fabrice Bellard 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*
 * 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.
 */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "avcodec.h"
#include "dsputil.h"
#include "mpegvideo.h"

27 28 29 30
#ifdef USE_FASTMEMCPY
#include "fastmemcpy.h"
#endif

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

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

F
Fabrice Bellard 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#define EDGE_WIDTH 16

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

//#define DEBUG

/* 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,
};

70 71 72
static UINT16 default_mv_penalty[MAX_FCODE][MAX_MV*2+1];
static UINT8 default_fcode_tab[MAX_MV*2+1];

F
Fabrice Bellard 已提交
73 74 75
/* default motion estimation */
int motion_estimation_method = ME_LOG;

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

M
Michael Niedermayer 已提交
78
static void convert_matrix(int *qmat, UINT16 *qmat16, const UINT16 *quant_matrix, int qscale)
F
Fabrice Bellard 已提交
79 80 81 82 83 84
{
    int i;

    if (av_fdct == jpeg_fdct_ifast) {
        for(i=0;i<64;i++) {
            /* 16 <= qscale * quant_matrix[i] <= 7905 */
M
Michael Niedermayer 已提交
85 86 87
            /* 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 */
F
Fabrice Bellard 已提交
88
            
M
Michael Niedermayer 已提交
89 90
            qmat[block_permute_op(i)] = (int)((UINT64_C(1) << (QMAT_SHIFT + 11)) / 
                            (aanscales[i] * qscale * quant_matrix[block_permute_op(i)]));
F
Fabrice Bellard 已提交
91 92 93 94
        }
    } else {
        for(i=0;i<64;i++) {
            /* We can safely suppose that 16 <= quant_matrix[i] <= 255
M
Michael Niedermayer 已提交
95 96 97
               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
F
Fabrice Bellard 已提交
98
            */
M
Michael Niedermayer 已提交
99 100
            qmat[i]   = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
            qmat16[i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[block_permute_op(i)]);
F
Fabrice Bellard 已提交
101 102 103 104 105 106 107 108 109 110
        }
    }
}

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

111 112 113 114 115 116 117
    if (s->out_format == FMT_H263) 
        s->dct_unquantize = dct_unquantize_h263_c;
    else
        s->dct_unquantize = dct_unquantize_mpeg1_c;
        
#ifdef HAVE_MMX
    MPV_common_init_mmx(s);
N
Nick Kurshev 已提交
118
#endif
F
Fabrice Bellard 已提交
119 120
    s->mb_width = (s->width + 15) / 16;
    s->mb_height = (s->height + 15) / 16;
121
    s->mb_num = s->mb_width * s->mb_height;
F
Fabrice Bellard 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    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;

        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;
        }
    }
153 154 155
    
    if (s->encoding) {
        /* Allocate MB type table */
J
Juanjo 已提交
156
        s->mb_type = av_mallocz(s->mb_num * sizeof(char));
157 158 159 160
        if (s->mb_type == NULL) {
            perror("malloc");
            goto fail;
        }
J
Juanjo 已提交
161 162 163 164 165 166
        
        s->mb_var = av_mallocz(s->mb_num * sizeof(INT16));
        if (s->mb_var == NULL) {
            perror("malloc");
            goto fail;
        }
167 168
        /* Allocate MV table */
        /* By now we just have one MV per MB */
J
Juanjo 已提交
169 170
        s->mv_table[0] = av_mallocz(s->mb_num * sizeof(INT16));
        s->mv_table[1] = av_mallocz(s->mb_num * sizeof(INT16));
171 172 173 174 175 176
        if (s->mv_table[1] == NULL || s->mv_table[0] == NULL) {
            perror("malloc");
            goto fail;
        }
    }
    
177
    if (s->out_format == FMT_H263) {
F
Fabrice Bellard 已提交
178 179 180 181 182 183 184 185 186
        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));
    }

187
    if (s->h263_pred || s->h263_plus) {
F
Fabrice Bellard 已提交
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
        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;
214 215

        /* which mb is a intra block */
216
        s->mbintra_table = av_mallocz(s->mb_num);
217 218
        if (!s->mbintra_table)
            goto fail;
219
        memset(s->mbintra_table, 1, s->mb_num);
220
    }
F
Fabrice Bellard 已提交
221 222 223
    /* default structure is frame */
    s->picture_structure = PICT_FRAME;

224 225
    /* init macroblock skip table */
    if (!s->encoding) {
226
        s->mbskip_table = av_mallocz(s->mb_num);
227 228 229 230
        if (!s->mbskip_table)
            goto fail;
    }

F
Fabrice Bellard 已提交
231 232 233
    s->context_initialized = 1;
    return 0;
 fail:
234
    MPV_common_end(s);
F
Fabrice Bellard 已提交
235 236 237 238 239 240 241 242
    return -1;
}

/* init common structure for both encoder and decoder */
void MPV_common_end(MpegEncContext *s)
{
    int i;

243 244
    if (s->mb_type)
        free(s->mb_type);
J
Juanjo 已提交
245 246
    if (s->mb_var)
        free(s->mb_var);
247 248 249 250
    if (s->mv_table[0])
        free(s->mv_table[0]);
    if (s->mv_table[1])
        free(s->mv_table[1]);
F
Fabrice Bellard 已提交
251 252
    if (s->motion_val)
        free(s->motion_val);
253
    if (s->dc_val[0])
F
Fabrice Bellard 已提交
254
        free(s->dc_val[0]);
255
    if (s->ac_val[0])
F
Fabrice Bellard 已提交
256
        free(s->ac_val[0]);
257
    if (s->coded_block)
F
Fabrice Bellard 已提交
258
        free(s->coded_block);
259
    if (s->mbintra_table)
260
        free(s->mbintra_table);
261

262 263
    if (s->mbskip_table)
        free(s->mbskip_table);
F
Fabrice Bellard 已提交
264
    for(i=0;i<3;i++) {
265 266 267 268
        if (s->last_picture_base[i])
	    free(s->last_picture_base[i]);
	if (s->next_picture_base[i])
	    free(s->next_picture_base[i]);
F
Fabrice Bellard 已提交
269 270 271 272 273 274 275 276 277 278
        if (s->has_b_frames)
            free(s->aux_picture_base[i]);
    }
    s->context_initialized = 0;
}

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

    s->bit_rate = avctx->bit_rate;
282
    s->bit_rate_tolerance = avctx->bit_rate_tolerance;
F
Fabrice Bellard 已提交
283 284 285 286
    s->frame_rate = avctx->frame_rate;
    s->width = avctx->width;
    s->height = avctx->height;
    s->gop_size = avctx->gop_size;
287 288
    s->rtp_mode = avctx->rtp_mode;
    s->rtp_payload_size = avctx->rtp_payload_size;
289 290
    if (avctx->rtp_callback)
        s->rtp_callback = avctx->rtp_callback;
291 292 293 294 295
    s->qmin= avctx->qmin;
    s->qmax= avctx->qmax;
    s->max_qdiff= avctx->max_qdiff;
    s->qcompress= avctx->qcompress;
    s->qblur= avctx->qblur;
296
    s->avctx = avctx;
297
    s->aspect_ratio_info= avctx->aspect_ratio_info;
298
    
F
Fabrice Bellard 已提交
299 300 301 302 303 304 305 306 307
    if (s->gop_size <= 1) {
        s->intra_only = 1;
        s->gop_size = 12;
    } else {
        s->intra_only = 0;
    }
    s->full_search = motion_estimation_method;

    s->fixed_qscale = (avctx->flags & CODEC_FLAG_QSCALE);
308
    
F
Fabrice Bellard 已提交
309 310 311 312 313 314 315
    switch(avctx->codec->id) {
    case CODEC_ID_MPEG1VIDEO:
        s->out_format = FMT_MPEG1;
        break;
    case CODEC_ID_MJPEG:
        s->out_format = FMT_MJPEG;
        s->intra_only = 1; /* force intra only for jpeg */
316 317 318 319 320 321 322
        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 已提交
323 324 325 326
        if (mjpeg_init(s) < 0)
            return -1;
        break;
    case CODEC_ID_H263:
327 328
        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 已提交
329
            return -1;
330
        }
F
Fabrice Bellard 已提交
331 332 333 334
        s->out_format = FMT_H263;
        break;
    case CODEC_ID_H263P:
        s->out_format = FMT_H263;
335 336
        s->rtp_mode = 1;
        s->rtp_payload_size = 1200; 
F
Fabrice Bellard 已提交
337
        s->h263_plus = 1;
338
        s->unrestricted_mv = 1;
339 340 341 342
        
        /* These are just to be sure */
        s->umvplus = 0;
        s->umvplus_dec = 0;
F
Fabrice Bellard 已提交
343 344 345 346 347
        break;
    case CODEC_ID_RV10:
        s->out_format = FMT_H263;
        s->h263_rv10 = 1;
        break;
F
Fabrice Bellard 已提交
348
    case CODEC_ID_MPEG4:
F
Fabrice Bellard 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362
        s->out_format = FMT_H263;
        s->h263_pred = 1;
        s->unrestricted_mv = 1;
        break;
    case CODEC_ID_MSMPEG4:
        s->out_format = FMT_H263;
        s->h263_msmpeg4 = 1;
        s->h263_pred = 1;
        s->unrestricted_mv = 1;
        break;
    default:
        return -1;
    }

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    { /* set up some save defaults, some codecs might override them later */
        static int done=0;
        if(!done){
            int i;
            done=1;
            memset(default_mv_penalty, 0, sizeof(UINT16)*MAX_FCODE*(2*MAX_MV+1));
            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 已提交
379
    if (s->out_format == FMT_H263)
380
        h263_encode_init(s);
381 382
    else if (s->out_format == FMT_MPEG1)
        mpeg1_encode_init(s);
F
Fabrice Bellard 已提交
383

384 385
    s->encoding = 1;

F
Fabrice Bellard 已提交
386 387 388 389
    /* init */
    if (MPV_common_init(s) < 0)
        return -1;
    
390 391 392 393 394 395
    /* init default q matrix */
    for(i=0;i<64;i++) {
        s->intra_matrix[i] = default_intra_matrix[i];
        s->non_intra_matrix[i] = default_non_intra_matrix[i];
    }

F
Fabrice Bellard 已提交
396 397 398 399
    /* rate control init */
    rate_control_init(s);

    s->picture_number = 0;
400
    s->picture_in_gop_number = 0;
F
Fabrice Bellard 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    s->fake_picture_number = 0;
    /* motion detector init */
    s->f_code = 1;

    return 0;
}

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

#ifdef STATS
    print_stats();
#endif
    MPV_common_end(s);
    if (s->out_format == FMT_MJPEG)
        mjpeg_close(s);
418
      
F
Fabrice Bellard 已提交
419 420 421 422
    return 0;
}

/* draw the edges of width 'w' of an image of size width, height */
M
Michael Niedermayer 已提交
423
static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w)
F
Fabrice Bellard 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
{
    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;

456
    s->mb_skiped = 0;
F
Fabrice Bellard 已提交
457 458 459 460 461
    if (s->pict_type == B_TYPE) {
        for(i=0;i<3;i++) {
            s->current_picture[i] = s->aux_picture[i];
        }
    } else {
M
Michael Niedermayer 已提交
462
        s->last_non_b_pict_type= s->pict_type;
F
Fabrice Bellard 已提交
463 464 465 466 467 468 469 470 471
        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;
        }
    }
}
472

F
Fabrice Bellard 已提交
473 474 475 476
/* 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 已提交
477
    if (s->pict_type != B_TYPE && !s->intra_only) {
M
Michael Niedermayer 已提交
478
      if(s->avctx==NULL || s->avctx->codec->id!=CODEC_ID_MPEG4 || s->divx_version==500){
479 480 481
        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);
482
      }else{
M
Michael Niedermayer 已提交
483
        /* mpeg4? / opendivx / xvid */
F
Fabrice Bellard 已提交
484 485 486
        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);
487
      }
F
Fabrice Bellard 已提交
488
    }
M
Michael Niedermayer 已提交
489
    emms_c();
F
Fabrice Bellard 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
}

int MPV_encode_picture(AVCodecContext *avctx,
                       unsigned char *buf, int buf_size, void *data)
{
    MpegEncContext *s = avctx->priv_data;
    AVPicture *pict = data;
    int i, j;

    if (s->fixed_qscale) 
        s->qscale = avctx->quality;

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

    if (!s->intra_only) {
        /* first picture of GOP is intra */
506 507
        if (s->picture_in_gop_number >= s->gop_size){
            s->picture_in_gop_number=0;
F
Fabrice Bellard 已提交
508
            s->pict_type = I_TYPE;
509
        }else
F
Fabrice Bellard 已提交
510 511 512 513 514 515
            s->pict_type = P_TYPE;
    } else {
        s->pict_type = I_TYPE;
    }
    
    MPV_frame_start(s);
M
Michael Niedermayer 已提交
516
    
F
Fabrice Bellard 已提交
517 518 519 520 521 522 523 524 525 526 527 528 529 530
    for(i=0;i<3;i++) {
        UINT8 *src = pict->data[i];
        UINT8 *dest = s->current_picture[i];
        int src_wrap = pict->linesize[i];
        int dest_wrap = s->linesize;
        int w = s->width;
        int h = s->height;

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

531 532 533
        if(dest_wrap==src_wrap){
            s->new_picture[i] = pict->data[i];
        } else {
M
Michael Niedermayer 已提交
534 535 536 537 538
            for(j=0;j<h;j++) {
                memcpy(dest, src, w);
                dest += dest_wrap;
                src += src_wrap;
            }
539
            s->new_picture[i] = s->current_picture[i];
540
	    }
F
Fabrice Bellard 已提交
541 542 543
    }

    encode_picture(s, s->picture_number);
M
Michael Niedermayer 已提交
544
    avctx->key_frame = (s->pict_type == I_TYPE);
545 546 547 548 549 550 551 552 553
    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;

F
Fabrice Bellard 已提交
554 555
    MPV_frame_end(s);
    s->picture_number++;
556
    s->picture_in_gop_number++;
F
Fabrice Bellard 已提交
557 558 559 560 561

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

    flush_put_bits(&s->pb);
562 563 564
    s->last_frame_bits= s->frame_bits;
    s->frame_bits  = (pbBufPtr(&s->pb) - s->pb.buf) * 8;
    s->total_bits += s->frame_bits;
565 566 567
    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);
568

F
Fabrice Bellard 已提交
569
    avctx->quality = s->qscale;
570 571 572 573 574 575
    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);
    }
576
    return pbBufPtr(&s->pb) - s->pb.buf;
F
Fabrice Bellard 已提交
577 578 579 580 581 582 583 584 585 586 587 588
}

static inline int clip(int a, int amin, int amax)
{
    if (a < amin)
        return amin;
    else if (a > amax)
        return amax;
    else
        return a;
}

M
Michael Niedermayer 已提交
589 590 591 592 593 594 595 596 597 598
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;
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
    int motion_x, motion_y;

599
    if(s->real_sprite_warping_points>1) printf("more than 1 warp point isnt supported\n");
M
Michael Niedermayer 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
    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 已提交
642 643 644 645 646 647 648 649 650 651
/* 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 已提交
652 653 654 655 656
if(s->quarter_sample)
{
    motion_x>>=1;
    motion_y>>=1;
}
F
Fabrice Bellard 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 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
    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 已提交
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 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
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 已提交
766 767 768
static inline void MPV_motion(MpegEncContext *s, 
                              UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
                              int dir, UINT8 **ref_picture, 
M
Michael Niedermayer 已提交
769
                              op_pixels_func *pix_op, qpel_mc_func *qpix_op)
F
Fabrice Bellard 已提交
770 771 772 773 774 775 776 777 778 779
{
    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 已提交
780 781 782 783 784 785 786 787 788 789 790 791 792
        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 已提交
793
        }else if(s->quarter_sample && dir==0){ //FIXME
M
Michael Niedermayer 已提交
794 795 796 797 798 799 800 801 802 803
            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 已提交
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 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 889 890
        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;
            src_y = mb_y * 16 + (motion_y >> 1) + ((i >> 1) & 1) * 8;
                    
            /* 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)
891
        s->dct_unquantize(s, block, i, s->qscale);
892
    ff_idct (block);
F
Fabrice Bellard 已提交
893 894 895 896 897 898 899 900 901
    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)
{
    if (s->block_last_index[i] >= 0) {
        if (!s->mpeg2)
M
Michael Niedermayer 已提交
902
            if(s->encoding || (!s->h263_msmpeg4))
M
Michael Niedermayer 已提交
903
                s->dct_unquantize(s, block, i, s->qscale);
904
        ff_idct (block);
F
Fabrice Bellard 已提交
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
        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])
{
921
    int mb_x, mb_y;
F
Fabrice Bellard 已提交
922 923
    int dct_linesize, dct_offset;
    op_pixels_func *op_pix;
M
Michael Niedermayer 已提交
924
    qpel_mc_func *op_qpix;
F
Fabrice Bellard 已提交
925 926 927 928

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

929 930 931 932 933
#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 已提交
934 935
    /* update DC predictors for P macroblocks */
    if (!s->mb_intra) {
936
        if (s->h263_pred || s->h263_aic) {
937 938
          if(s->mbintra_table[mb_x + mb_y*s->mb_width])
          {
939
            int wrap, xy, v;
940
            s->mbintra_table[mb_x + mb_y*s->mb_width]=0;
F
Fabrice Bellard 已提交
941
            wrap = 2 * s->mb_width + 2;
942
            xy = 2 * mb_x + 1 +  (2 * mb_y + 1) * wrap;
F
Fabrice Bellard 已提交
943
            v = 1024;
944
            
945
            s->dc_val[0][xy] = v;
946 947 948
            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 已提交
949
            /* ac pred */
950 951 952 953
            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 已提交
954
            if (s->h263_msmpeg4) {
955 956 957 958
                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 已提交
959 960 961
            }
            /* chroma */
            wrap = s->mb_width + 2;
962 963 964
            xy = mb_x + 1 + (mb_y + 1) * wrap;
            s->dc_val[1][xy] = v;
            s->dc_val[2][xy] = v;
F
Fabrice Bellard 已提交
965
            /* ac pred */
966 967
            memset(s->ac_val[1][xy], 0, 16 * sizeof(INT16));
            memset(s->ac_val[2][xy], 0, 16 * sizeof(INT16));
968
          }
F
Fabrice Bellard 已提交
969 970 971 972 973 974
        } 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;
        }
    }
975
    else if (s->h263_pred || s->h263_aic)
976 977
        s->mbintra_table[mb_x + mb_y*s->mb_width]=1;

978 979
    /* update motion predictor, not for B-frames as they need the motion_val from the last P/S-Frame */
    if (s->out_format == FMT_H263) {
M
Michael Niedermayer 已提交
980
      if(s->pict_type!=B_TYPE){
981
        int xy, wrap, motion_x, motion_y;
F
Fabrice Bellard 已提交
982 983
        
        wrap = 2 * s->mb_width + 2;
984
        xy = 2 * mb_x + 1 + (2 * mb_y + 1) * wrap;
F
Fabrice Bellard 已提交
985 986 987 988 989 990 991 992 993
        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 */
994 995 996 997 998 999 1000 1001
            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 已提交
1002
        }
M
Michael Niedermayer 已提交
1003
      }
F
Fabrice Bellard 已提交
1004 1005 1006 1007
    }
    
    if (!s->intra_only) {
        UINT8 *dest_y, *dest_cb, *dest_cr;
1008 1009 1010
        UINT8 *mbskip_ptr;

        /* avoid copy if macroblock skipped in last frame too */
1011
        if (!s->encoding && s->pict_type != B_TYPE) {
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
            mbskip_ptr = &s->mbskip_table[s->mb_y * s->mb_width + s->mb_x];
            if (s->mb_skiped) {
                s->mb_skiped = 0;
                /* if previous was skipped too, then nothing to do ! */
                if (*mbskip_ptr != 0) 
                    goto the_end;
                *mbskip_ptr = 1; /* indicate that this time we skiped it */
            } else {
                *mbskip_ptr = 0; /* not skipped */
            }
        }
F
Fabrice Bellard 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037

        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 */
M
Michael Niedermayer 已提交
1038
            if (!s->no_rounding){
F
Fabrice Bellard 已提交
1039
                op_pix = put_pixels_tab;
M
Michael Niedermayer 已提交
1040 1041
                op_qpix= qpel_mc_rnd_tab;
            }else{
F
Fabrice Bellard 已提交
1042
                op_pix = put_no_rnd_pixels_tab;
M
Michael Niedermayer 已提交
1043 1044
                op_qpix= qpel_mc_no_rnd_tab;
            }
F
Fabrice Bellard 已提交
1045 1046

            if (s->mv_dir & MV_DIR_FORWARD) {
M
Michael Niedermayer 已提交
1047
                MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
F
Fabrice Bellard 已提交
1048 1049 1050 1051 1052 1053
                if (!s->no_rounding) 
                    op_pix = avg_pixels_tab;
                else
                    op_pix = avg_no_rnd_pixels_tab;
            }
            if (s->mv_dir & MV_DIR_BACKWARD) {
M
Michael Niedermayer 已提交
1054
                MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
F
Fabrice Bellard 已提交
1055 1056 1057 1058 1059 1060 1061 1062
            }

            /* 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 已提交
1063 1064
            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 已提交
1065 1066 1067 1068 1069 1070 1071
        } 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 已提交
1072 1073
            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 已提交
1074 1075
        }
    }
1076 1077
 the_end:
    emms_c();
F
Fabrice Bellard 已提交
1078 1079 1080 1081
}

static void encode_picture(MpegEncContext *s, int picture_number)
{
1082
    int mb_x, mb_y, wrap, last_gob, pdif = 0;
F
Fabrice Bellard 已提交
1083 1084
    UINT8 *ptr;
    int i, motion_x, motion_y;
1085
    int bits;
F
Fabrice Bellard 已提交
1086 1087

    s->picture_number = picture_number;
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

    s->last_mc_mb_var = s->mc_mb_var;
    /* Reset the average MB variance */
    s->avg_mb_var = 0;
    s->mc_mb_var = 0;
    /* Estimate motion for every MB */
    for(mb_y=0; mb_y < s->mb_height; mb_y++) {
        for(mb_x=0; mb_x < s->mb_width; mb_x++) {
            int xy= mb_y * s->mb_width + mb_x;
            s->mb_x = mb_x;
            s->mb_y = mb_y;

            /* compute motion vector and macro block type (intra or non intra) */
            motion_x = 0;
            motion_y = 0;
            if (s->pict_type == P_TYPE) {
                s->mb_intra = estimate_motion(s, mb_x, mb_y,
                                              &motion_x,
                                              &motion_y);
            } else {
                s->mb_intra = 1;
            }
            /* Store MB type and MV */
            s->mb_type[xy] = s->mb_intra;
            s->mv_table[0][xy] = motion_x;
            s->mv_table[1][xy] = motion_y;
        }
    }
1116
    emms_c();
1117

M
Michael Niedermayer 已提交
1118 1119 1120
    if(s->avg_mb_var < s->mc_mb_var && s->pict_type != B_TYPE){ //FIXME subtract MV bits
        int i;
        s->pict_type= I_TYPE;
1121 1122 1123
        s->picture_in_gop_number=0;
        for(i=0; i<s->mb_num; i++){
            s->mb_type[i] = 1;
M
Michael Niedermayer 已提交
1124 1125 1126 1127
            s->mv_table[0][i] = 0;
            s->mv_table[1][i] = 0;
        }
    }
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148

    /* find best f_code */
    if(s->pict_type==P_TYPE){
        int mv_num[8];
        int i;
        int loose=0;
        UINT8 * fcode_tab= s->fcode_tab;

        for(i=0; i<8; i++) mv_num[i]=0;

        for(i=0; i<s->mb_num; i++){
            if(s->mb_type[i] == 0){
                mv_num[ fcode_tab[s->mv_table[0][i] + MAX_MV] ]++;
                mv_num[ fcode_tab[s->mv_table[1][i] + MAX_MV] ]++;
//printf("%d %d %d\n", s->mv_table[0][i], fcode_tab[s->mv_table[0][i] + MAX_MV], i);
            }
//else printf("I");
        }

        for(i=MAX_FCODE; i>1; i--){
            loose+= mv_num[i];
1149
            if(loose > 10) break; //FIXME this is pretty ineffective
1150 1151 1152 1153 1154
        }
        s->f_code= i;
    }else{
        s->f_code= 1;
    }
1155

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
//printf("f_code %d ///\n", s->f_code);
    /* convert MBs with too long MVs to I-Blocks */
    if(s->pict_type==P_TYPE){
        int i;
        const int f_code= s->f_code;
        UINT8 * fcode_tab= s->fcode_tab;

        for(i=0; i<s->mb_num; i++){
            if(s->mb_type[i] == 0){
                if(   fcode_tab[s->mv_table[0][i] + MAX_MV] > f_code
                   || fcode_tab[s->mv_table[0][i] + MAX_MV] == 0
                   || fcode_tab[s->mv_table[1][i] + MAX_MV] > f_code
                   || fcode_tab[s->mv_table[1][i] + MAX_MV] == 0 ){
                    s->mb_type[i] = 1;
                    s->mv_table[0][i] = 0;
                    s->mv_table[1][i] = 0;
                }
            }
        }
    }

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

F
Fabrice Bellard 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187
    if (!s->fixed_qscale) 
        s->qscale = rate_estimate_qscale(s);

    /* precompute matrix */
    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;
M
Michael Niedermayer 已提交
1188
        convert_matrix(s->q_intra_matrix, s->q_intra_matrix16, s->intra_matrix, 8);
F
Fabrice Bellard 已提交
1189
    } else {
M
Michael Niedermayer 已提交
1190 1191
        convert_matrix(s->q_intra_matrix, s->q_intra_matrix16, s->intra_matrix, s->qscale);
        convert_matrix(s->q_non_intra_matrix, s->q_non_intra_matrix16, s->non_intra_matrix, s->qscale);
F
Fabrice Bellard 已提交
1192 1193
    }

1194
    s->last_bits= get_bit_count(&s->pb);
F
Fabrice Bellard 已提交
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    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;
    }
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
    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 已提交
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
    /* 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;
    s->mv_type = MV_TYPE_16X16;
    s->mv_dir = MV_DIR_FORWARD;

1235
    /* Get the GOB height based on picture height */
1236
    if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4) {
1237 1238 1239 1240 1241 1242 1243
        if (s->height <= 400)
            s->gob_index = 1;
        else if (s->height <= 800)
            s->gob_index = 2;
        else
            s->gob_index = 4;
    }
1244
        
1245 1246
    s->avg_mb_var = s->avg_mb_var / s->mb_num;        
    
M
Michael Niedermayer 已提交
1247 1248 1249 1250 1251 1252
    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;
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
    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 已提交
1268 1269 1270 1271 1272 1273
        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);
1274 1275 1276 1277
        for(mb_x=0; mb_x < s->mb_width; mb_x++) {

            s->mb_x = mb_x;
            s->mb_y = mb_y;
M
Michael Niedermayer 已提交
1278 1279 1280 1281 1282 1283
            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]++;
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
#if 0
            /* compute motion vector and macro block type (intra or non intra) */
            motion_x = 0;
            motion_y = 0;
            if (s->pict_type == P_TYPE) {
                s->mb_intra = estimate_motion(s, mb_x, mb_y,
                                              &motion_x,
                                              &motion_y);
            } else {
                s->mb_intra = 1;
            }
#endif
F
Fabrice Bellard 已提交
1296

1297 1298 1299 1300
            s->mb_intra = s->mb_type[mb_y * s->mb_width + mb_x];
            motion_x = s->mv_table[0][mb_y * s->mb_width + mb_x];
            motion_y = s->mv_table[1][mb_y * s->mb_width + mb_x];
            
F
Fabrice Bellard 已提交
1301 1302 1303
            /* get the pixels */
            wrap = s->linesize;
            ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
1304 1305 1306 1307
            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);
F
Fabrice Bellard 已提交
1308 1309
            wrap = s->linesize >> 1;
            ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;
1310
            get_pixels(s->block[4], ptr, wrap);
F
Fabrice Bellard 已提交
1311 1312 1313

            wrap = s->linesize >> 1;
            ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
1314
            get_pixels(s->block[5], ptr, wrap);
F
Fabrice Bellard 已提交
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324

            /* subtract previous frame if non intra */
            if (!s->mb_intra) {
                int dxy, offset, mx, my;

                dxy = ((motion_y & 1) << 1) | (motion_x & 1);
                ptr = s->last_picture[0] + 
                    ((mb_y * 16 + (motion_y >> 1)) * s->linesize) + 
                    (mb_x * 16 + (motion_x >> 1));

1325 1326 1327 1328
                sub_pixels_2(s->block[0], ptr, s->linesize, dxy);
                sub_pixels_2(s->block[1], ptr + 8, s->linesize, dxy);
                sub_pixels_2(s->block[2], ptr + s->linesize * 8, s->linesize, dxy);
                sub_pixels_2(s->block[3], ptr + 8 + s->linesize * 8, s->linesize ,dxy);
F
Fabrice Bellard 已提交
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

                if (s->out_format == FMT_H263) {
                    /* special rounding for 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;
                }
                offset = ((mb_y * 8 + my) * (s->linesize >> 1)) + (mb_x * 8 + mx);
                ptr = s->last_picture[1] + offset;
1348
                sub_pixels_2(s->block[4], ptr, s->linesize >> 1, dxy);
F
Fabrice Bellard 已提交
1349
                ptr = s->last_picture[2] + offset;
1350
                sub_pixels_2(s->block[5], ptr, s->linesize >> 1, dxy);
F
Fabrice Bellard 已提交
1351
            }
1352
            emms_c();
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
            
#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
F
Fabrice Bellard 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
            /* DCT & quantize */
            if (s->h263_msmpeg4) {
                msmpeg4_dc_scale(s);
            } else if (s->h263_pred) {
                h263_dc_scale(s);
            } else {
                /* default quantization values */
                s->y_dc_scale = 8;
                s->c_dc_scale = 8;
            }
            for(i=0;i<6;i++) {
M
Michael Niedermayer 已提交
1378
                s->block_last_index[i] = dct_quantize(s, s->block[i], i, s->qscale);
F
Fabrice Bellard 已提交
1379 1380 1381 1382 1383
            }

            /* huffman encode */
            switch(s->out_format) {
            case FMT_MPEG1:
1384
                mpeg1_encode_mb(s, s->block, motion_x, motion_y);
F
Fabrice Bellard 已提交
1385 1386 1387
                break;
            case FMT_H263:
                if (s->h263_msmpeg4)
1388
                    msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
1389 1390
                else if(s->h263_pred)
                    mpeg4_encode_mb(s, s->block, motion_x, motion_y);
F
Fabrice Bellard 已提交
1391
                else
1392
                    h263_encode_mb(s, s->block, motion_x, motion_y);
F
Fabrice Bellard 已提交
1393 1394
                break;
            case FMT_MJPEG:
1395
                mjpeg_encode_mb(s, s->block);
F
Fabrice Bellard 已提交
1396 1397
                break;
            }
1398
            
F
Fabrice Bellard 已提交
1399 1400 1401 1402
            /* decompress blocks so that we keep the state of the decoder */
            s->mv[0][0][0] = motion_x;
            s->mv[0][0][1] = motion_y;

1403
            MPV_decode_mb(s, s->block);
F
Fabrice Bellard 已提交
1404
        }
1405 1406


1407 1408 1409
        /* Obtain average GOB size for RTP */
        if (s->rtp_mode) {
            if (!mb_y)
1410
                s->mb_line_avgsize = pbBufPtr(&s->pb) - s->ptr_last_mb_line;
1411
            else if (!(mb_y % s->gob_index)) {    
1412 1413
                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);
1414 1415 1416 1417 1418
            }
            //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 已提交
1419
    }
1420

1421
    if (s->h263_msmpeg4 && s->pict_type == I_TYPE)
M
Michael Niedermayer 已提交
1422 1423
        msmpeg4_encode_ext_header(s);

1424 1425
    //if (s->gob_number)
    //    fprintf(stderr,"\nNumber of GOB: %d", s->gob_number);
1426 1427 1428 1429
    
    /* Send the last GOB if RTP */    
    if (s->rtp_mode) {
        flush_put_bits(&s->pb);
1430
        pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
1431 1432 1433
        /* Call the RTP callback to send the last GOB */
        if (s->rtp_callback)
            s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
1434
        s->ptr_lastgob = pbBufPtr(&s->pb);
1435 1436 1437
        //fprintf(stderr,"\nGOB: %2d size: %d (last)", s->gob_number, pdif);
    }

F
Fabrice Bellard 已提交
1438 1439
}

M
Michael Niedermayer 已提交
1440
static int dct_quantize_c(MpegEncContext *s, 
F
Fabrice Bellard 已提交
1441 1442 1443 1444 1445
                        DCTELEM *block, int n,
                        int qscale)
{
    int i, j, level, last_non_zero, q;
    const int *qmat;
M
Michael Niedermayer 已提交
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
    int minLevel, maxLevel;

    if(s->avctx!=NULL && s->avctx->codec->id==CODEC_ID_MPEG4){
	/* mpeg4 */
        minLevel= -2048;
	maxLevel= 2047;
    }else if(s->out_format==FMT_MPEG1){
	/* mpeg1 */
        minLevel= -255;
	maxLevel= 255;
A
Arpi 已提交
1456 1457 1458 1459
    }else if(s->out_format==FMT_MJPEG){
	/* (m)jpeg */
        minLevel= -1023;
	maxLevel= 1023;
M
Michael Niedermayer 已提交
1460 1461 1462 1463 1464
    }else{
	/* h263 / msmpeg4 */
        minLevel= -128;
	maxLevel= 127;
    }
F
Fabrice Bellard 已提交
1465 1466 1467

    av_fdct (block);

F
Fabrice Bellard 已提交
1468 1469 1470 1471
    /* we need this permutation so that we correct the IDCT
       permutation. will be moved into DCT code */
    block_permute(block);

F
Fabrice Bellard 已提交
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    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;
        if (s->out_format == FMT_H263) {
            qmat = s->q_non_intra_matrix;
        } else {
            qmat = s->q_intra_matrix;
        }
    } else {
        i = 0;
        last_non_zero = -1;
        qmat = s->q_non_intra_matrix;
    }

    for(;i<64;i++) {
        j = zigzag_direct[i];
        level = block[j];
        level = level * qmat[j];
#ifdef PARANOID
        {
            static int count = 0;
            int level1, level2, qmat1;
            double val;
            if (qmat == s->q_non_intra_matrix) {
                qmat1 = default_non_intra_matrix[j] * s->qscale;
            } else {
                qmat1 = default_intra_matrix[j] * s->qscale;
            }
            if (av_fdct != jpeg_fdct_ifast)
                val = ((double)block[j] * 8.0) / (double)qmat1;
            else
                val = ((double)block[j] * 8.0 * 2048.0) / 
                    ((double)qmat1 * aanscales[j]);
            level1 = (int)val;
            level2 = level / (1 << (QMAT_SHIFT - 3));
            if (level1 != level2) {
                fprintf(stderr, "%d: quant error qlevel=%d wanted=%d level=%d qmat1=%d qmat=%d wantedf=%0.6f\n", 
                        count, level2, level1, block[j], qmat1, qmat[j],
                        val);
                count++;
            }

        }
#endif
        /* XXX: slight error for the low range. Test should be equivalent to
           (level <= -(1 << (QMAT_SHIFT - 3)) || level >= (1 <<
           (QMAT_SHIFT - 3)))
        */
        if (((level << (31 - (QMAT_SHIFT - 3))) >> (31 - (QMAT_SHIFT - 3))) != 
            level) {
            level = level / (1 << (QMAT_SHIFT - 3));
            /* XXX: currently, this code is not optimal. the range should be:
               mpeg1: -255..255
               mpeg2: -2048..2047
               h263:  -128..127
               mpeg4: -2048..2047
            */
M
Michael Niedermayer 已提交
1537 1538 1539 1540
            if (level > maxLevel)
                level = maxLevel;
            else if (level < minLevel)
                level = minLevel;
F
Fabrice Bellard 已提交
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550

            block[j] = level;
            last_non_zero = i;
        } else {
            block[j] = 0;
        }
    }
    return last_non_zero;
}

1551 1552
static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
                                   DCTELEM *block, int n, int qscale)
F
Fabrice Bellard 已提交
1553
{
M
Michael Niedermayer 已提交
1554
    int i, level, nCoeffs;
F
Fabrice Bellard 已提交
1555 1556
    const UINT16 *quant_matrix;

M
Michael Niedermayer 已提交
1557 1558 1559
    if(s->alternate_scan) nCoeffs= 64;
    else nCoeffs= s->block_last_index[n]+1;
    
F
Fabrice Bellard 已提交
1560 1561 1562 1563 1564 1565 1566
    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 已提交
1567 1568 1569
        for(i=1;i<nCoeffs;i++) {
            int j= zigzag_direct[i];
            level = block[j];
F
Fabrice Bellard 已提交
1570 1571 1572
            if (level) {
                if (level < 0) {
                    level = -level;
M
Michael Niedermayer 已提交
1573
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
F
Fabrice Bellard 已提交
1574 1575 1576
                    level = (level - 1) | 1;
                    level = -level;
                } else {
M
Michael Niedermayer 已提交
1577
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
F
Fabrice Bellard 已提交
1578 1579 1580 1581 1582 1583
                    level = (level - 1) | 1;
                }
#ifdef PARANOID
                if (level < -2048 || level > 2047)
                    fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
M
Michael Niedermayer 已提交
1584
                block[j] = level;
F
Fabrice Bellard 已提交
1585 1586 1587 1588 1589
            }
        }
    } else {
        i = 0;
        quant_matrix = s->non_intra_matrix;
M
Michael Niedermayer 已提交
1590
        for(;i<nCoeffs;i++) {
M
Michael Niedermayer 已提交
1591 1592
            int j= zigzag_direct[i];
            level = block[j];
F
Fabrice Bellard 已提交
1593 1594 1595 1596
            if (level) {
                if (level < 0) {
                    level = -level;
                    level = (((level << 1) + 1) * qscale *
M
Michael Niedermayer 已提交
1597
                             ((int) (quant_matrix[j]))) >> 4;
F
Fabrice Bellard 已提交
1598 1599 1600 1601
                    level = (level - 1) | 1;
                    level = -level;
                } else {
                    level = (((level << 1) + 1) * qscale *
M
Michael Niedermayer 已提交
1602
                             ((int) (quant_matrix[j]))) >> 4;
F
Fabrice Bellard 已提交
1603 1604 1605 1606 1607 1608
                    level = (level - 1) | 1;
                }
#ifdef PARANOID
                if (level < -2048 || level > 2047)
                    fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
M
Michael Niedermayer 已提交
1609
                block[j] = level;
F
Fabrice Bellard 已提交
1610 1611 1612 1613
            }
        }
    }
}
1614 1615 1616 1617 1618

static void dct_unquantize_h263_c(MpegEncContext *s, 
                                  DCTELEM *block, int n, int qscale)
{
    int i, level, qmul, qadd;
M
Michael Niedermayer 已提交
1619
    int nCoeffs;
1620
    
1621
    if (s->mb_intra) {
1622 1623 1624 1625 1626 1627
        if (!s->h263_aic) {
            if (n < 4) 
                block[0] = block[0] * s->y_dc_scale;
            else
                block[0] = block[0] * s->c_dc_scale;
        }
1628
        i = 1;
M
Michael Niedermayer 已提交
1629
        nCoeffs= 64; //does not allways use zigzag table 
1630 1631
    } else {
        i = 0;
M
Michael Niedermayer 已提交
1632
        nCoeffs= zigzag_end[ s->block_last_index[n] ];
1633 1634 1635
    }

    qmul = s->qscale << 1;
1636 1637 1638 1639
    if (s->h263_aic && s->mb_intra)
        qadd = 0;
    else
        qadd = (s->qscale - 1) | 1;
1640

M
Michael Niedermayer 已提交
1641
    for(;i<nCoeffs;i++) {
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
        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 已提交
1657 1658 1659 1660 1661 1662 1663 1664 1665

/* rate control */

/* an I frame is I_FRAME_SIZE_RATIO bigger than a P frame */
#define I_FRAME_SIZE_RATIO 3.0
#define QSCALE_K           20

static void rate_control_init(MpegEncContext *s)
{
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
#if 1
    emms_c();

    //initial values, they dont really matter as they will be totally different within a few frames
    s->i_pred.coeff= s->p_pred.coeff= 7.0;
    s->i_pred.count= s->p_pred.count= 1.0;
    
    s->i_pred.decay= s->p_pred.decay= 0.4;
    
    // use more bits at the beginning, otherwise high motion at the begin will look like shit
    s->qsum=100;
    s->qcount=100;

    s->short_term_qsum=0.001;
    s->short_term_qcount=0.001;
#else
F
Fabrice Bellard 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
    s->wanted_bits = 0;

    if (s->intra_only) {
        s->I_frame_bits = ((INT64)s->bit_rate * FRAME_RATE_BASE) / s->frame_rate;
        s->P_frame_bits = s->I_frame_bits;
    } else {
        s->P_frame_bits = (int) ((float)(s->gop_size * s->bit_rate) / 
                                 (float)((float)s->frame_rate / FRAME_RATE_BASE * (I_FRAME_SIZE_RATIO + s->gop_size - 1)));
        s->I_frame_bits = (int)(s->P_frame_bits * I_FRAME_SIZE_RATIO);
    }
1692

F
Fabrice Bellard 已提交
1693 1694 1695 1696
#if defined(DEBUG)
    printf("I_frame_size=%d P_frame_size=%d\n",
           s->I_frame_bits, s->P_frame_bits);
#endif
1697
#endif
F
Fabrice Bellard 已提交
1698 1699
}

1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
static double predict(Predictor *p, double q, double var)
{
    return p->coeff*var / (q*p->count);
}

static void update_predictor(Predictor *p, double q, double var, double size)
{
    double new_coeff= size*q / (var + 1);
    if(var<1000) return;
/*{
int pred= predict(p, q, var);
int error= abs(pred-size);
static double sum=0;
static int count=0;
if(count>5) sum+=error;
count++;
if(256*256*256*64%count==0){
    printf("%d %f %f\n", count, sum/count, p->coeff);
}
}*/
    p->count*= p->decay;
    p->coeff*= p->decay;
    p->count++;
    p->coeff+= new_coeff;
}
F
Fabrice Bellard 已提交
1725 1726 1727

static int rate_estimate_qscale(MpegEncContext *s)
{
1728 1729 1730 1731
#if 1
    int qmin= s->qmin;
    int qmax= s->qmax;
    int rate_q=5;
F
Fabrice Bellard 已提交
1732
    float q;
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
    int qscale;
    float br_compensation;
    double diff;
    double short_term_q;
    double long_term_q;
    int last_qscale= s->qscale;
    double fps;
    INT64 wanted_bits;
    emms_c();
    
    fps= (double)s->frame_rate / FRAME_RATE_BASE;
    wanted_bits= s->bit_rate*(double)s->picture_number/fps;

    
    if(s->picture_number>2){
        /* update predictors */
        if(s->last_pict_type == I_TYPE){
        //FIXME
        }else{ //P Frame
//printf("%d %d %d %f\n", s->qscale, s->last_mc_mb_var, s->frame_bits, s->p_pred.coeff);
            update_predictor(&s->p_pred, s->qscale, s->last_mc_mb_var, s->frame_bits);
        }
    }

    if(s->pict_type == I_TYPE){
        //FIXME
        rate_q= s->qsum/s->qcount;
    }else{ //P Frame
        int i;
        int diff, best_diff=1000000000;
        for(i=1; i<=31; i++){
            diff= predict(&s->p_pred, i, s->mc_mb_var) - (double)s->bit_rate/fps;
            if(diff<0) diff= -diff;
            if(diff<best_diff){
                best_diff= diff;
                rate_q= i;
            }
        }
    }

    s->short_term_qsum*=s->qblur;
    s->short_term_qcount*=s->qblur;

    s->short_term_qsum+= rate_q;
    s->short_term_qcount++;
    short_term_q= s->short_term_qsum/s->short_term_qcount;
    
    long_term_q= s->qsum/s->qcount*s->total_bits/wanted_bits;

//    q= (long_term_q - short_term_q)*s->qcompress + short_term_q;
    q= 1/((1/long_term_q - 1/short_term_q)*s->qcompress + 1/short_term_q);

    diff= s->total_bits - wanted_bits;
    br_compensation= (s->bit_rate_tolerance - diff)/s->bit_rate_tolerance;
M
10l  
Michael Niedermayer 已提交
1787
    if(br_compensation<=0.0) br_compensation=0.001;
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
    q/=br_compensation;

    qscale= (int)(q + 0.5);
    if     (qscale<qmin) qscale=qmin;
    else if(qscale>qmax) qscale=qmax;
    
    if     (qscale<last_qscale-s->max_qdiff) qscale=last_qscale-s->max_qdiff;
    else if(qscale>last_qscale+s->max_qdiff) qscale=last_qscale+s->max_qdiff;

    s->qsum+= qscale;
    s->qcount++;
F
Fabrice Bellard 已提交
1799

1800 1801 1802 1803 1804 1805 1806 1807 1808
    s->last_pict_type= s->pict_type;
//printf("q:%d diff:%d comp:%f rate_q:%d st_q:%d fvar:%d last_size:%d\n", qscale, (int)diff, br_compensation, 
//       rate_q, (int)short_term_q, s->mc_mb_var, s->frame_bits);
//printf("%d %d\n", s->bit_rate, (int)fps);
    return qscale;
#else
    INT64 diff, total_bits = s->total_bits;
    float q;
    int qscale;
F
Fabrice Bellard 已提交
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
    if (s->pict_type == I_TYPE) {
        s->wanted_bits += s->I_frame_bits;
    } else {
        s->wanted_bits += s->P_frame_bits;
    }
    diff = s->wanted_bits - total_bits;
    q = 31.0 - (float)diff / (QSCALE_K * s->mb_height * s->mb_width);
    /* adjust for I frame */
    if (s->pict_type == I_TYPE && !s->intra_only) {
        q /= I_FRAME_SIZE_RATIO;
    }

    /* using a too small Q scale leeds to problems in mpeg1 and h263
       because AC coefficients are clamped to 255 or 127 */
    qmin = 3;
    if (q < qmin)
        q = qmin;
    else if (q > 31)
        q = 31;
    qscale = (int)(q + 0.5);
#if defined(DEBUG)
1830
    printf("\n%d: total=%0.0f wanted=%0.0f br=%0.1f diff=%d qest=%2.1f\n", 
F
Fabrice Bellard 已提交
1831
           s->picture_number, 
F
Fabrice Bellard 已提交
1832
           (double)total_bits, 
1833
           (double)s->wanted_bits,
F
Fabrice Bellard 已提交
1834 1835
           (float)s->frame_rate / FRAME_RATE_BASE * 
           total_bits / s->picture_number, 
1836
           (int)diff, q);
F
Fabrice Bellard 已提交
1837 1838
#endif
    return qscale;
1839
#endif
F
Fabrice Bellard 已提交
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 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
}

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 已提交
1892 1893
AVCodec mpeg4_encoder = {
    "mpeg4",
F
Fabrice Bellard 已提交
1894
    CODEC_TYPE_VIDEO,
F
Fabrice Bellard 已提交
1895
    CODEC_ID_MPEG4,
F
Fabrice Bellard 已提交
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};

AVCodec msmpeg4_encoder = {
    "msmpeg4",
    CODEC_TYPE_VIDEO,
    CODEC_ID_MSMPEG4,
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};