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

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

32 33 34
//#undef NDEBUG
//#include <assert.h>

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

void (*draw_edges)(UINT8 *buf, int wrap, int width, int height, int w)= draw_edges_c;

F
Fabrice Bellard 已提交
47 48 49 50 51 52

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

//#define DEBUG

53

F
Fabrice Bellard 已提交
54 55 56
/* for jpeg fast DCT */
#define CONST_BITS 14

57
static const uint16_t aanscales[64] = {
F
Fabrice Bellard 已提交
58 59 60 61 62 63 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,
M
Michael Niedermayer 已提交
65 66
    8867 , 12299, 11585, 10426,  8867,  6967,  4799,  2446,
    4520 ,  6270,  5906,  5315,  4520,  3552,  2446,  1247
F
Fabrice Bellard 已提交
67 68
};

69
/* Input permutation for the simple_idct_mmx */
70
static const uint8_t simple_mmx_permutation[64]={
71 72 73 74 75 76 77 78 79 80
	0x00, 0x08, 0x04, 0x09, 0x01, 0x0C, 0x05, 0x0D, 
	0x10, 0x18, 0x14, 0x19, 0x11, 0x1C, 0x15, 0x1D, 
	0x20, 0x28, 0x24, 0x29, 0x21, 0x2C, 0x25, 0x2D, 
	0x12, 0x1A, 0x16, 0x1B, 0x13, 0x1E, 0x17, 0x1F, 
	0x02, 0x0A, 0x06, 0x0B, 0x03, 0x0E, 0x07, 0x0F, 
	0x30, 0x38, 0x34, 0x39, 0x31, 0x3C, 0x35, 0x3D, 
	0x22, 0x2A, 0x26, 0x2B, 0x23, 0x2E, 0x27, 0x2F, 
	0x32, 0x3A, 0x36, 0x3B, 0x33, 0x3E, 0x37, 0x3F,
};

81
static const uint8_t h263_chroma_roundtab[16] = {
F
Fabrice Bellard 已提交
82 83 84
    0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
};

85
static UINT16 (*default_mv_penalty)[MAX_MV*2+1]=NULL;
86 87
static UINT8 default_fcode_tab[MAX_MV*2+1];

88
static void convert_matrix(MpegEncContext *s, int (*qmat)[64], uint16_t (*qmat16)[64], uint16_t (*qmat16_bias)[64],
89
                           const UINT16 *quant_matrix, int bias, int qmin, int qmax)
F
Fabrice Bellard 已提交
90
{
91 92
    int qscale;

93
    for(qscale=qmin; qscale<=qmax; qscale++){
94
        int i;
95 96
        if (s->fdct == ff_jpeg_fdct_islow) {
            for(i=0;i<64;i++) {
97
                const int j= s->idct_permutation[i];
98 99 100 101 102
                /* 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 */
                
M
Michael Niedermayer 已提交
103
                qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) / 
104 105 106
                                (qscale * quant_matrix[j]));
            }
        } else if (s->fdct == fdct_ifast) {
107
            for(i=0;i<64;i++) {
108
                const int j= s->idct_permutation[i];
109 110 111 112 113
                /* 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 */
                
M
Michael Niedermayer 已提交
114
                qmat[qscale][i] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) / 
115 116 117 118
                                (aanscales[i] * qscale * quant_matrix[j]));
            }
        } else {
            for(i=0;i<64;i++) {
119
                const int j= s->idct_permutation[i];
120 121 122 123 124 125
                /* 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]);
126
                qmat16[qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[j]);
127 128 129 130

                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 已提交
131 132 133
        }
    }
}
134 135 136 137 138 139 140 141 142
// move into common.c perhaps 
#define CHECKED_ALLOCZ(p, size)\
{\
    p= av_mallocz(size);\
    if(p==NULL){\
        perror("malloc");\
        goto fail;\
    }\
}
143

144 145 146
void ff_init_scantable(MpegEncContext *s, ScanTable *st, const UINT8 *src_scantable){
    int i;
    int end;
M
Michael Niedermayer 已提交
147 148
    
    st->scantable= src_scantable;
149 150 151 152 153

    for(i=0; i<64; i++){
        int j;
        j = src_scantable[i];
        st->permutated[i] = s->idct_permutation[j];
154 155 156
#ifdef ARCH_POWERPC
        st->inverse[j] = i;
#endif
157 158 159 160 161 162 163 164 165 166 167 168
    }
    
    end=-1;
    for(i=0; i<64; i++){
        int j;
        j = st->permutated[i];
        if(j>end) end=j;
        st->raster_end[i]= end;
    }
}

/* XXX: those functions should be suppressed ASAP when all IDCTs are
169 170 171 172
 converted */
// *FIXME* this is ugly hack using local static
static void (*ff_put_pixels_clamped)(const DCTELEM *block, UINT8 *pixels, int line_size);
static void (*ff_add_pixels_clamped)(const DCTELEM *block, UINT8 *pixels, int line_size);
173 174 175
static void ff_jref_idct_put(UINT8 *dest, int line_size, DCTELEM *block)
{
    j_rev_dct (block);
176
    ff_put_pixels_clamped(block, dest, line_size);
177 178 179 180
}
static void ff_jref_idct_add(UINT8 *dest, int line_size, DCTELEM *block)
{
    j_rev_dct (block);
181
    ff_add_pixels_clamped(block, dest, line_size);
182
}
F
Fabrice Bellard 已提交
183

184 185
/* init common dct for both encoder and decoder */
int DCT_common_init(MpegEncContext *s)
F
Fabrice Bellard 已提交
186
{
187
    int i;
F
Fabrice Bellard 已提交
188

189 190 191
    ff_put_pixels_clamped = s->dsp.put_pixels_clamped;
    ff_add_pixels_clamped = s->dsp.add_pixels_clamped;

192
    s->dct_unquantize_h263 = dct_unquantize_h263_c;
193 194
    s->dct_unquantize_mpeg1 = dct_unquantize_mpeg1_c;
    s->dct_unquantize_mpeg2 = dct_unquantize_mpeg2_c;
195 196 197 198 199
    s->dct_quantize= dct_quantize_c;

    if(s->avctx->dct_algo==FF_DCT_FASTINT)
        s->fdct = fdct_ifast;
    else
200 201 202 203 204
        s->fdct = ff_jpeg_fdct_islow; //slow/accurate/default

    if(s->avctx->idct_algo==FF_IDCT_INT){
        s->idct_put= ff_jref_idct_put;
        s->idct_add= ff_jref_idct_add;
205
        s->idct_permutation_type= FF_LIBMPEG2_IDCT_PERM;
206 207 208
    }else{ //accurate/default
        s->idct_put= simple_idct_put;
        s->idct_add= simple_idct_add;
209
        s->idct_permutation_type= FF_NO_IDCT_PERM;
210
    }
211 212 213
        
#ifdef HAVE_MMX
    MPV_common_init_mmx(s);
214 215 216
#endif
#ifdef ARCH_ALPHA
    MPV_common_init_axp(s);
N
Nick Kurshev 已提交
217
#endif
218 219 220
#ifdef HAVE_MLIB
    MPV_common_init_mlib(s);
#endif
221 222 223
#ifdef HAVE_MMI
    MPV_common_init_mmi(s);
#endif
224
#ifdef ARCH_ARMV4L
225
    MPV_common_init_armv4l(s);
226
#endif
227 228 229
#ifdef ARCH_POWERPC
    MPV_common_init_ppc(s);
#endif
230

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    switch(s->idct_permutation_type){
    case FF_NO_IDCT_PERM:
        for(i=0; i<64; i++)
            s->idct_permutation[i]= i;
        break;
    case FF_LIBMPEG2_IDCT_PERM:
        for(i=0; i<64; i++)
            s->idct_permutation[i]= (i & 0x38) | ((i & 6) >> 1) | ((i & 1) << 2);
        break;
    case FF_SIMPLE_IDCT_PERM:
        for(i=0; i<64; i++)
            s->idct_permutation[i]= simple_mmx_permutation[i];
        break;
    case FF_TRANSPOSE_IDCT_PERM:
        for(i=0; i<64; i++)
            s->idct_permutation[i]= ((i&7)<<3) | (i>>3);
        break;
    default:
        fprintf(stderr, "Internal error, IDCT permutation not set\n");
        return -1;
    }

253 254 255 256 257 258 259 260

    /* load & permutate scantables
       note: only wmv uses differnt ones 
    */
    ff_init_scantable(s, &s->inter_scantable  , ff_zigzag_direct);
    ff_init_scantable(s, &s->intra_scantable  , ff_zigzag_direct);
    ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_horizontal_scan);
    ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
261

262 263 264
    return 0;
}

M
cleanup  
Michael Niedermayer 已提交
265
/**
M
Michael Niedermayer 已提交
266 267
 * allocates a Picture
 * The pixels are allocated/set by calling get_buffer() if shared=0
M
cleanup  
Michael Niedermayer 已提交
268
 */
M
Michael Niedermayer 已提交
269 270 271 272 273 274 275 276 277 278 279
static int alloc_picture(MpegEncContext *s, Picture *pic, int shared){
    
    if(shared){
        assert(pic->data[0]);
        assert(pic->type == 0 || pic->type == FF_BUFFER_TYPE_SHARED);
        pic->type= FF_BUFFER_TYPE_SHARED;
    }else{
        int r;
        
        assert(!pic->data[0]);
        
M
Michael Niedermayer 已提交
280
        r= s->avctx->get_buffer(s->avctx, (AVFrame*)pic);
M
Michael Niedermayer 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        
        if(r<0 || !pic->age || !pic->type || !pic->data[0]){
            fprintf(stderr, "get_buffer() failed (%d %d %d %X)\n", r, pic->age, pic->type, (int)pic->data[0]);
            return -1;
        }

        if(s->linesize && (s->linesize != pic->linesize[0] || s->uvlinesize != pic->linesize[1])){
            fprintf(stderr, "get_buffer() failed (stride changed)\n");
            return -1;
        }

        if(pic->linesize[1] != pic->linesize[2]){
            fprintf(stderr, "get_buffer() failed (uv stride missmatch)\n");
            return -1;
        }

        s->linesize  = pic->linesize[0];
        s->uvlinesize= pic->linesize[1];
M
cleanup  
Michael Niedermayer 已提交
299
    }
M
Michael Niedermayer 已提交
300 301 302 303 304 305 306
    
    if(pic->qscale_table==NULL){
        if (s->encoding) {        
            CHECKED_ALLOCZ(pic->mb_var   , s->mb_num * sizeof(INT16))
            CHECKED_ALLOCZ(pic->mc_mb_var, s->mb_num * sizeof(INT16))
            CHECKED_ALLOCZ(pic->mb_mean  , s->mb_num * sizeof(INT8))
        }
M
cleanup  
Michael Niedermayer 已提交
307

M
Michael Niedermayer 已提交
308 309 310 311
        CHECKED_ALLOCZ(pic->mbskip_table , s->mb_num * sizeof(UINT8)+1) //the +1 is for the slice end check
        CHECKED_ALLOCZ(pic->qscale_table , s->mb_num * sizeof(UINT8))
        pic->qstride= s->mb_width;
    }
M
cleanup  
Michael Niedermayer 已提交
312 313 314 315 316 317
    
    return 0;
fail: //for the CHECKED_ALLOCZ macro
    return -1;
}

M
Michael Niedermayer 已提交
318 319 320
/**
 * deallocates a picture
 */
M
cleanup  
Michael Niedermayer 已提交
321 322
static void free_picture(MpegEncContext *s, Picture *pic){
    int i;
M
Michael Niedermayer 已提交
323 324

    if(pic->data[0] && pic->type!=FF_BUFFER_TYPE_SHARED){
M
Michael Niedermayer 已提交
325
        s->avctx->release_buffer(s->avctx, (AVFrame*)pic);
M
Michael Niedermayer 已提交
326 327
    }

M
cleanup  
Michael Niedermayer 已提交
328 329 330 331 332 333
    av_freep(&pic->mb_var);
    av_freep(&pic->mc_mb_var);
    av_freep(&pic->mb_mean);
    av_freep(&pic->mbskip_table);
    av_freep(&pic->qscale_table);
    
M
Michael Niedermayer 已提交
334
    if(pic->type == FF_BUFFER_TYPE_INTERNAL){
M
cleanup  
Michael Niedermayer 已提交
335 336 337 338 339
        for(i=0; i<4; i++){
            av_freep(&pic->base[i]);
            pic->data[i]= NULL;
        }
        av_freep(&pic->opaque);
M
Michael Niedermayer 已提交
340 341 342 343 344 345 346
        pic->type= 0;
    }else if(pic->type == FF_BUFFER_TYPE_SHARED){
        for(i=0; i<4; i++){
            pic->base[i]=
            pic->data[i]= NULL;
        }
        pic->type= 0;        
M
cleanup  
Michael Niedermayer 已提交
347 348 349
    }
}

350 351 352
/* init common structure for both encoder and decoder */
int MPV_common_init(MpegEncContext *s)
{
353
    int y_size, c_size, yc_size, i;
354

355
    dsputil_init(&s->dsp, s->avctx->dsp_mask);
356
    DCT_common_init(s);
357

358
    s->flags= s->avctx->flags;
359

M
cleanup  
Michael Niedermayer 已提交
360
    s->mb_width  = (s->width  + 15) / 16;
F
Fabrice Bellard 已提交
361
    s->mb_height = (s->height + 15) / 16;
362

363 364 365
    /* set default edge pos, will be overriden in decode_header if needed */
    s->h_edge_pos= s->mb_width*16;
    s->v_edge_pos= s->mb_height*16;
366 367 368 369 370 371 372

    s->mb_num = s->mb_width * s->mb_height;

    y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
    c_size = (s->mb_width + 2) * (s->mb_height + 2);
    yc_size = y_size + 2 * c_size;

373 374 375 376 377
    /* convert fourcc to upper case */
    s->avctx->fourcc=   toupper( s->avctx->fourcc     &0xFF)          
                     + (toupper((s->avctx->fourcc>>8 )&0xFF)<<8 )
                     + (toupper((s->avctx->fourcc>>16)&0xFF)<<16) 
                     + (toupper((s->avctx->fourcc>>24)&0xFF)<<24);
378

379
    CHECKED_ALLOCZ(s->edge_emu_buffer, (s->width+64)*2*17*2); //(width + edge + align)*interlaced*MBsize*tolerance
M
cleanup  
Michael Niedermayer 已提交
380

M
Michael Niedermayer 已提交
381
    s->avctx->coded_frame= (AVFrame*)&s->current_picture;
M
cleanup  
Michael Niedermayer 已提交
382

383
    if (s->encoding) {
384 385 386
        int mv_table_size= (s->mb_width+2)*(s->mb_height+2);

        /* Allocate MV tables */
387 388 389 390 391 392 393
        CHECKED_ALLOCZ(s->p_mv_table            , mv_table_size * 2 * sizeof(INT16))
        CHECKED_ALLOCZ(s->b_forw_mv_table       , mv_table_size * 2 * sizeof(INT16))
        CHECKED_ALLOCZ(s->b_back_mv_table       , mv_table_size * 2 * sizeof(INT16))
        CHECKED_ALLOCZ(s->b_bidir_forw_mv_table , mv_table_size * 2 * sizeof(INT16))
        CHECKED_ALLOCZ(s->b_bidir_back_mv_table , mv_table_size * 2 * sizeof(INT16))
        CHECKED_ALLOCZ(s->b_direct_mv_table     , mv_table_size * 2 * sizeof(INT16))

M
cleanup  
Michael Niedermayer 已提交
394
        //FIXME should be linesize instead of s->width*2 but that isnt known before get_buffer()
M
Michael Niedermayer 已提交
395
        CHECKED_ALLOCZ(s->me.scratchpad,  s->width*2*16*3*sizeof(uint8_t)) 
396
        
M
Michael Niedermayer 已提交
397 398
        CHECKED_ALLOCZ(s->me.map      , ME_MAP_SIZE*sizeof(uint32_t))
        CHECKED_ALLOCZ(s->me.score_map, ME_MAP_SIZE*sizeof(uint32_t))
399

400 401 402 403
        if(s->codec_id==CODEC_ID_MPEG4){
            CHECKED_ALLOCZ(s->tex_pb_buffer, PB_BUFFER_SIZE);
            CHECKED_ALLOCZ(   s->pb2_buffer, PB_BUFFER_SIZE);
        }
M
Michael Niedermayer 已提交
404
        
405 406 407
        if(s->msmpeg4_version){
            CHECKED_ALLOCZ(s->ac_stats, 2*2*(MAX_LEVEL+1)*(MAX_RUN+1)*2*sizeof(int));
        }
M
Michael Niedermayer 已提交
408
        CHECKED_ALLOCZ(s->avctx->stats_out, 256);
409
    }
410 411
        
    CHECKED_ALLOCZ(s->error_status_table, s->mb_num*sizeof(UINT8))
412
    
413
    if (s->out_format == FMT_H263 || s->encoding) {
F
Fabrice Bellard 已提交
414
        int size;
415 416 417
        /* Allocate MB type table */
        CHECKED_ALLOCZ(s->mb_type  , s->mb_num * sizeof(UINT8))

F
Fabrice Bellard 已提交
418 419
        /* MV prediction */
        size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
420
        CHECKED_ALLOCZ(s->motion_val, size * 2 * sizeof(INT16));
421 422 423
    }

    if(s->codec_id==CODEC_ID_MPEG4){
424
        /* interlaced direct mode decoding tables */
425 426
        CHECKED_ALLOCZ(s->field_mv_table, s->mb_num*2*2 * sizeof(INT16))
        CHECKED_ALLOCZ(s->field_select_table, s->mb_num*2* sizeof(INT8))
F
Fabrice Bellard 已提交
427
    }
428 429 430
    /* 4mv b frame decoding table */
    //note this is needed for h263 without b frames too (segfault on damaged streams otherwise)
    CHECKED_ALLOCZ(s->co_located_type_table, s->mb_num * sizeof(UINT8))
M
Michael Niedermayer 已提交
431
    if (s->out_format == FMT_H263) {
F
Fabrice Bellard 已提交
432
        /* ac values */
433
        CHECKED_ALLOCZ(s->ac_val[0], yc_size * sizeof(INT16) * 16);
F
Fabrice Bellard 已提交
434 435 436 437
        s->ac_val[1] = s->ac_val[0] + y_size;
        s->ac_val[2] = s->ac_val[1] + c_size;
        
        /* cbp values */
438
        CHECKED_ALLOCZ(s->coded_block, y_size);
M
Michael Niedermayer 已提交
439 440
        
        /* divx501 bitstream reorder buffer */
441
        CHECKED_ALLOCZ(s->bitstream_buffer, BITSTREAM_BUFFER_SIZE);
M
cleanup  
Michael Niedermayer 已提交
442

443 444 445
        /* cbp, ac_pred, pred_dir */
        CHECKED_ALLOCZ(s->cbp_table  , s->mb_num * sizeof(UINT8))
        CHECKED_ALLOCZ(s->pred_dir_table, s->mb_num * sizeof(UINT8))
446
    }
447 448 449 450 451 452 453 454 455 456 457
    
    if (s->h263_pred || s->h263_plus || !s->encoding) {
        /* dc values */
        //MN: we need these for error resilience of intra-frames
        CHECKED_ALLOCZ(s->dc_val[0], yc_size * sizeof(INT16));
        s->dc_val[1] = s->dc_val[0] + y_size;
        s->dc_val[2] = s->dc_val[1] + c_size;
        for(i=0;i<yc_size;i++)
            s->dc_val[0][i] = 1024;
    }

458 459 460 461
    /* which mb is a intra block */
    CHECKED_ALLOCZ(s->mbintra_table, s->mb_num);
    memset(s->mbintra_table, 1, s->mb_num);
    
F
Fabrice Bellard 已提交
462 463
    /* default structure is frame */
    s->picture_structure = PICT_FRAME;
464
    
465
    /* init macroblock skip table */
466 467
    CHECKED_ALLOCZ(s->mbskip_table, s->mb_num+1);
    //Note the +1 is for a quicker mpeg4 slice_end detection
468
    
469
    s->block= s->blocks[0];
470

471 472
    s->parse_context.state= -1;

F
Fabrice Bellard 已提交
473 474 475
    s->context_initialized = 1;
    return 0;
 fail:
476
    MPV_common_end(s);
F
Fabrice Bellard 已提交
477 478 479
    return -1;
}

480 481 482

//extern int sads;

F
Fabrice Bellard 已提交
483 484 485 486 487
/* init common structure for both encoder and decoder */
void MPV_common_end(MpegEncContext *s)
{
    int i;

488 489 490 491 492 493 494 495 496 497 498 499
    av_freep(&s->mb_type);
    av_freep(&s->p_mv_table);
    av_freep(&s->b_forw_mv_table);
    av_freep(&s->b_back_mv_table);
    av_freep(&s->b_bidir_forw_mv_table);
    av_freep(&s->b_bidir_back_mv_table);
    av_freep(&s->b_direct_mv_table);
    av_freep(&s->motion_val);
    av_freep(&s->dc_val[0]);
    av_freep(&s->ac_val[0]);
    av_freep(&s->coded_block);
    av_freep(&s->mbintra_table);
500 501
    av_freep(&s->cbp_table);
    av_freep(&s->pred_dir_table);
M
Michael Niedermayer 已提交
502 503 504
    av_freep(&s->me.scratchpad);
    av_freep(&s->me.map);
    av_freep(&s->me.score_map);
505
    
506 507
    av_freep(&s->mbskip_table);
    av_freep(&s->bitstream_buffer);
508 509
    av_freep(&s->tex_pb_buffer);
    av_freep(&s->pb2_buffer);
510
    av_freep(&s->edge_emu_buffer);
511 512 513
    av_freep(&s->co_located_type_table);
    av_freep(&s->field_mv_table);
    av_freep(&s->field_select_table);
M
Michael Niedermayer 已提交
514
    av_freep(&s->avctx->stats_out);
515
    av_freep(&s->ac_stats);
516
    av_freep(&s->error_status_table);
M
cleanup  
Michael Niedermayer 已提交
517 518 519

    for(i=0; i<MAX_PICTURE_COUNT; i++){
        free_picture(s, &s->picture[i]);
F
Fabrice Bellard 已提交
520 521 522 523 524 525 526 527
    }
    s->context_initialized = 0;
}

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

530 531
    avctx->pix_fmt = PIX_FMT_YUV420P;

F
Fabrice Bellard 已提交
532
    s->bit_rate = avctx->bit_rate;
533
    s->bit_rate_tolerance = avctx->bit_rate_tolerance;
F
Fabrice Bellard 已提交
534 535 536
    s->frame_rate = avctx->frame_rate;
    s->width = avctx->width;
    s->height = avctx->height;
537
    if(avctx->gop_size > 600){
538
        fprintf(stderr, "Warning keyframe interval too large! reducing it ...\n");
539 540
        avctx->gop_size=600;
    }
F
Fabrice Bellard 已提交
541
    s->gop_size = avctx->gop_size;
542 543
    s->rtp_mode = avctx->rtp_mode;
    s->rtp_payload_size = avctx->rtp_payload_size;
544 545
    if (avctx->rtp_callback)
        s->rtp_callback = avctx->rtp_callback;
546 547 548 549 550
    s->qmin= avctx->qmin;
    s->qmax= avctx->qmax;
    s->max_qdiff= avctx->max_qdiff;
    s->qcompress= avctx->qcompress;
    s->qblur= avctx->qblur;
551
    s->avctx = avctx;
552
    s->flags= avctx->flags;
553
    s->max_b_frames= avctx->max_b_frames;
554
    s->b_frame_strategy= avctx->b_frame_strategy;
555
    s->codec_id= avctx->codec->id;
556 557 558 559
    s->luma_elim_threshold  = avctx->luma_elim_threshold;
    s->chroma_elim_threshold= avctx->chroma_elim_threshold;
    s->strict_std_compliance= avctx->strict_std_compliance;
    s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
M
Michael Niedermayer 已提交
560
    s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;
561
    s->mpeg_quant= avctx->mpeg_quant;
562

F
Fabrice Bellard 已提交
563 564 565 566 567 568
    if (s->gop_size <= 1) {
        s->intra_only = 1;
        s->gop_size = 12;
    } else {
        s->intra_only = 0;
    }
569

M
Michael Niedermayer 已提交
570
    s->me_method = avctx->me_method;
571

572
    /* Fixed QSCALE */
F
Fabrice Bellard 已提交
573
    s->fixed_qscale = (avctx->flags & CODEC_FLAG_QSCALE);
574
    
575
    s->adaptive_quant= (   s->avctx->lumi_masking
576
                        || s->avctx->dark_masking
577 578 579 580
                        || s->avctx->temporal_cplx_masking 
                        || s->avctx->spatial_cplx_masking
                        || s->avctx->p_masking)
                       && !s->fixed_qscale;
581 582
    
    s->progressive_sequence= !(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
583

F
Fabrice Bellard 已提交
584 585 586
    switch(avctx->codec->id) {
    case CODEC_ID_MPEG1VIDEO:
        s->out_format = FMT_MPEG1;
M
Michael Niedermayer 已提交
587
        avctx->delay=0; //FIXME not sure, should check the spec
F
Fabrice Bellard 已提交
588 589 590 591
        break;
    case CODEC_ID_MJPEG:
        s->out_format = FMT_MJPEG;
        s->intra_only = 1; /* force intra only for jpeg */
592
        s->mjpeg_write_tables = 1; /* write all tables */
593
	s->mjpeg_data_only_frames = 0; /* write all the needed headers */
594 595 596
        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; 
597
        s->mjpeg_hsample[0] = 2;
598 599
        s->mjpeg_hsample[1] = 1; 
        s->mjpeg_hsample[2] = 1; 
F
Fabrice Bellard 已提交
600 601
        if (mjpeg_init(s) < 0)
            return -1;
M
Michael Niedermayer 已提交
602
        avctx->delay=0;
M
Michael Niedermayer 已提交
603
        s->low_delay=1;
F
Fabrice Bellard 已提交
604 605
        break;
    case CODEC_ID_H263:
606 607
        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 已提交
608
            return -1;
609
        }
F
Fabrice Bellard 已提交
610
        s->out_format = FMT_H263;
M
Michael Niedermayer 已提交
611
        avctx->delay=0;
M
Michael Niedermayer 已提交
612
        s->low_delay=1;
F
Fabrice Bellard 已提交
613 614 615 616
        break;
    case CODEC_ID_H263P:
        s->out_format = FMT_H263;
        s->h263_plus = 1;
617
        s->unrestricted_mv = 1;
618
        s->h263_aic = 1;
619 620 621 622
        
        /* These are just to be sure */
        s->umvplus = 0;
        s->umvplus_dec = 0;
M
Michael Niedermayer 已提交
623
        avctx->delay=0;
M
Michael Niedermayer 已提交
624
        s->low_delay=1;
F
Fabrice Bellard 已提交
625 626 627 628
        break;
    case CODEC_ID_RV10:
        s->out_format = FMT_H263;
        s->h263_rv10 = 1;
M
Michael Niedermayer 已提交
629
        avctx->delay=0;
M
Michael Niedermayer 已提交
630
        s->low_delay=1;
F
Fabrice Bellard 已提交
631
        break;
F
Fabrice Bellard 已提交
632
    case CODEC_ID_MPEG4:
F
Fabrice Bellard 已提交
633 634 635
        s->out_format = FMT_H263;
        s->h263_pred = 1;
        s->unrestricted_mv = 1;
M
Michael Niedermayer 已提交
636
        s->low_delay= s->max_b_frames ? 0 : 1;
637
        avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
F
Fabrice Bellard 已提交
638
        break;
639
    case CODEC_ID_MSMPEG4V1:
F
Fabrice Bellard 已提交
640 641 642 643
        s->out_format = FMT_H263;
        s->h263_msmpeg4 = 1;
        s->h263_pred = 1;
        s->unrestricted_mv = 1;
644
        s->msmpeg4_version= 1;
M
Michael Niedermayer 已提交
645
        avctx->delay=0;
M
Michael Niedermayer 已提交
646
        s->low_delay=1;
647 648 649 650 651 652 653
        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 已提交
654
        avctx->delay=0;
M
Michael Niedermayer 已提交
655
        s->low_delay=1;
656 657 658 659 660 661 662
        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 已提交
663
        avctx->delay=0;
M
Michael Niedermayer 已提交
664
        s->low_delay=1;
F
Fabrice Bellard 已提交
665
        break;
M
Michael Niedermayer 已提交
666 667 668 669 670 671 672
    case CODEC_ID_WMV1:
        s->out_format = FMT_H263;
        s->h263_msmpeg4 = 1;
        s->h263_pred = 1;
        s->unrestricted_mv = 1;
        s->msmpeg4_version= 4;
        avctx->delay=0;
M
Michael Niedermayer 已提交
673
        s->low_delay=1;
M
Michael Niedermayer 已提交
674 675 676 677 678 679 680 681
        break;
    case CODEC_ID_WMV2:
        s->out_format = FMT_H263;
        s->h263_msmpeg4 = 1;
        s->h263_pred = 1;
        s->unrestricted_mv = 1;
        s->msmpeg4_version= 5;
        avctx->delay=0;
M
Michael Niedermayer 已提交
682
        s->low_delay=1;
M
Michael Niedermayer 已提交
683
        break;
F
Fabrice Bellard 已提交
684 685 686
    default:
        return -1;
    }
M
Michael Niedermayer 已提交
687
    
688 689 690 691 692
    { /* set up some save defaults, some codecs might override them later */
        static int done=0;
        if(!done){
            int i;
            done=1;
693 694

            default_mv_penalty= av_mallocz( sizeof(UINT16)*(MAX_FCODE+1)*(2*MAX_MV+1) );
695
            memset(default_mv_penalty, 0, sizeof(UINT16)*(MAX_FCODE+1)*(2*MAX_MV+1));
696 697 698 699 700 701 702
            memset(default_fcode_tab , 0, sizeof(UINT8)*(2*MAX_MV+1));

            for(i=-16; i<16; i++){
                default_fcode_tab[i + MAX_MV]= 1;
            }
        }
    }
M
Michael Niedermayer 已提交
703
    s->me.mv_penalty= default_mv_penalty;
704
    s->fcode_tab= default_fcode_tab;
705 706 707
    s->y_dc_scale_table=
    s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
 
708
    /* dont use mv_penalty table for crap MV as it would be confused */
M
Michael Niedermayer 已提交
709 710
    //FIXME remove after fixing / removing old ME
    if (s->me_method < ME_EPZS) s->me.mv_penalty = default_mv_penalty;
711

712 713
    s->encoding = 1;

F
Fabrice Bellard 已提交
714 715 716 717
    /* init */
    if (MPV_common_init(s) < 0)
        return -1;
    
M
Michael Niedermayer 已提交
718 719
    ff_init_me(s);

720
#ifdef CONFIG_ENCODERS
721 722 723 724 725 726
    if (s->out_format == FMT_H263)
        h263_encode_init(s);
    else if (s->out_format == FMT_MPEG1)
        ff_mpeg1_encode_init(s);
    if(s->msmpeg4_version)
        ff_msmpeg4_encode_init(s);
727
#endif
728

729 730
    /* init default q matrix */
    for(i=0;i<64;i++) {
731
        int j= s->idct_permutation[i];
732
        if(s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
733 734
            s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
            s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
735
        }else if(s->out_format == FMT_H263){
736 737
            s->intra_matrix[j] =
            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
738
        }else{ /* mpeg1 */
739 740
            s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
741
        }
742 743 744
    }

    /* precompute matrix */
745
    /* for mjpeg, we do include qscale in the matrix */
746
    if (s->out_format != FMT_MJPEG) {
747
        convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16, s->q_intra_matrix16_bias, 
748
                       s->intra_matrix, s->intra_quant_bias, 1, 31);
749
        convert_matrix(s, s->q_inter_matrix, s->q_inter_matrix16, s->q_inter_matrix16_bias, 
750
                       s->inter_matrix, s->inter_quant_bias, 1, 31);
751 752
    }

753 754
    if(ff_rate_control_init(s) < 0)
        return -1;
F
Fabrice Bellard 已提交
755 756

    s->picture_number = 0;
757
    s->picture_in_gop_number = 0;
F
Fabrice Bellard 已提交
758 759 760
    s->fake_picture_number = 0;
    /* motion detector init */
    s->f_code = 1;
761
    s->b_code = 1;
F
Fabrice Bellard 已提交
762 763 764 765 766 767 768 769 770 771 772

    return 0;
}

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

#ifdef STATS
    print_stats();
#endif
773 774 775

    ff_rate_control_uninit(s);

F
Fabrice Bellard 已提交
776 777 778
    MPV_common_end(s);
    if (s->out_format == FMT_MJPEG)
        mjpeg_close(s);
779
      
F
Fabrice Bellard 已提交
780 781 782 783
    return 0;
}

/* draw the edges of width 'w' of an image of size width, height */
784
//FIXME check that this is ok for mpeg4 interlaced
M
Michael Niedermayer 已提交
785
static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w)
F
Fabrice Bellard 已提交
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
{
    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 */
    }
}

M
Michael Niedermayer 已提交
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
static int find_unused_picture(MpegEncContext *s, int shared){
    int i;
    
    if(shared){
        for(i=0; i<MAX_PICTURE_COUNT; i++){
            if(s->picture[i].data[0]==NULL && s->picture[i].type==0) break;
        }
    }else{
        for(i=0; i<MAX_PICTURE_COUNT; i++){
            if(s->picture[i].data[0]==NULL && s->picture[i].type!=0) break;
        }
        for(i=0; i<MAX_PICTURE_COUNT; i++){
            if(s->picture[i].data[0]==NULL) break;
        }
    }

    assert(i<MAX_PICTURE_COUNT);
    return i;
}

F
Fabrice Bellard 已提交
832
/* generic function for encode/decode called before a frame is coded/decoded */
833
int MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
F
Fabrice Bellard 已提交
834
{
M
Michael Niedermayer 已提交
835
    int i;
M
Michael Niedermayer 已提交
836
    AVFrame *pic;
F
Fabrice Bellard 已提交
837

838
    s->mb_skiped = 0;
M
cleanup  
Michael Niedermayer 已提交
839 840 841 842
    
    /* mark&release old frames */
    if (s->pict_type != B_TYPE && s->last_picture.data[0]) {
        for(i=0; i<MAX_PICTURE_COUNT; i++){
M
Michael Niedermayer 已提交
843
//printf("%8X %d %d %X %X\n", s->picture[i].data[0], s->picture[i].type, i, s->next_picture.data[0], s->last_picture.data[0]);
M
cleanup  
Michael Niedermayer 已提交
844 845
            if(s->picture[i].data[0] == s->last_picture.data[0]){
//                s->picture[i].reference=0;
M
Michael Niedermayer 已提交
846
                avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);
M
cleanup  
Michael Niedermayer 已提交
847 848 849 850 851 852 853 854 855 856 857
                break;
            }    
        }
        assert(i<MAX_PICTURE_COUNT);

        /* release forgotten pictures */
        /* if(mpeg124/h263) */
        if(!s->encoding){
            for(i=0; i<MAX_PICTURE_COUNT; i++){
                if(s->picture[i].data[0] && s->picture[i].data[0] != s->next_picture.data[0] && s->picture[i].reference){
                    fprintf(stderr, "releasing zombie picture\n");
M
Michael Niedermayer 已提交
858
                    avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);                
M
cleanup  
Michael Niedermayer 已提交
859 860
                }
            }
861
        }
862
    }
863 864
alloc:
    if(!s->encoding){
M
Michael Niedermayer 已提交
865
        i= find_unused_picture(s, 0);
M
cleanup  
Michael Niedermayer 已提交
866
    
M
Michael Niedermayer 已提交
867
        pic= (AVFrame*)&s->picture[i];
M
cleanup  
Michael Niedermayer 已提交
868 869 870
        pic->reference= s->pict_type != B_TYPE;
        pic->coded_picture_number= s->current_picture.coded_picture_number+1;
        
M
Michael Niedermayer 已提交
871
        alloc_picture(s, (Picture*)pic, 0);
872

M
cleanup  
Michael Niedermayer 已提交
873 874
        s->current_picture= s->picture[i];
    }
875

M
cleanup  
Michael Niedermayer 已提交
876 877 878
    if (s->pict_type != B_TYPE) {
        s->last_picture= s->next_picture;
        s->next_picture= s->current_picture;
F
Fabrice Bellard 已提交
879
    }
880 881 882 883 884 885
    
    if(s->pict_type != I_TYPE && s->last_picture.data[0]==NULL){
        fprintf(stderr, "warning: first frame is no keyframe\n");
        assert(s->pict_type != B_TYPE); //these should have been dropped if we dont have a reference
        goto alloc;
    }
M
cleanup  
Michael Niedermayer 已提交
886
   
887 888 889
    s->hurry_up= s->avctx->hurry_up;
    s->error_resilience= avctx->error_resilience;

890 891 892 893 894 895 896 897 898
    /* set dequantizer, we cant do it during init as it might change for mpeg4
       and we cant do it in the header decode as init isnt called for mpeg4 there yet */
    if(s->out_format == FMT_H263){
        if(s->mpeg_quant)
            s->dct_unquantize = s->dct_unquantize_mpeg2;
        else
            s->dct_unquantize = s->dct_unquantize_h263;
    }else 
        s->dct_unquantize = s->dct_unquantize_mpeg1;
899 900

    return 0;
F
Fabrice Bellard 已提交
901
}
902

F
Fabrice Bellard 已提交
903 904 905
/* generic function for encode/decode called after a frame has been coded/decoded */
void MPV_frame_end(MpegEncContext *s)
{
M
cleanup  
Michael Niedermayer 已提交
906
    int i;
F
Fabrice Bellard 已提交
907
    /* draw edge for correct motion prediction if outside */
M
cleanup  
Michael Niedermayer 已提交
908 909 910 911 912 913
    if(s->codec_id!=CODEC_ID_SVQ1){
        if (s->pict_type != B_TYPE && !s->intra_only && !(s->flags&CODEC_FLAG_EMU_EDGE)) {
            draw_edges(s->current_picture.data[0], s->linesize  , s->h_edge_pos   , s->v_edge_pos   , EDGE_WIDTH  );
            draw_edges(s->current_picture.data[1], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
            draw_edges(s->current_picture.data[2], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
        }
F
Fabrice Bellard 已提交
914
    }
M
Michael Niedermayer 已提交
915
    emms_c();
916
    
M
Michael Niedermayer 已提交
917
    s->last_pict_type    = s->pict_type;
918 919 920
    if(s->pict_type!=B_TYPE){
        s->last_non_b_pict_type= s->pict_type;
    }
M
cleanup  
Michael Niedermayer 已提交
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
    
    s->current_picture.quality= s->qscale; //FIXME get average of qscale_table
    s->current_picture.pict_type= s->pict_type;
    s->current_picture.key_frame= s->pict_type == I_TYPE;
    
    /* copy back current_picture variables */
    for(i=0; i<MAX_PICTURE_COUNT; i++){
        if(s->picture[i].data[0] == s->current_picture.data[0]){
            s->picture[i]= s->current_picture;
            break;
        }    
    }
    assert(i<MAX_PICTURE_COUNT);

    /* release non refernce frames */
    for(i=0; i<MAX_PICTURE_COUNT; i++){
M
Michael Niedermayer 已提交
937
        if(s->picture[i].data[0] && !s->picture[i].reference /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/)
M
Michael Niedermayer 已提交
938
            s->avctx->release_buffer(s->avctx, (AVFrame*)&s->picture[i]);
M
cleanup  
Michael Niedermayer 已提交
939
    }
M
Michael Niedermayer 已提交
940 941 942 943 944 945 946 947 948 949 950 951
    if(s->avctx->debug&FF_DEBUG_SKIP){
        int x,y;        
        for(y=0; y<s->mb_height; y++){
            for(x=0; x<s->mb_width; x++){
                int count= s->mbskip_table[x + y*s->mb_width];
                if(count>9) count=9;
                printf(" %1d", count);
            }
            printf("\n");
        }
        printf("pict type: %d\n", s->pict_type);
    }
F
Fabrice Bellard 已提交
952 953
}

M
Michael Niedermayer 已提交
954 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
static int get_sae(uint8_t *src, int ref, int stride){
    int x,y;
    int acc=0;
    
    for(y=0; y<16; y++){
        for(x=0; x<16; x++){
            acc+= ABS(src[x+y*stride] - ref);
        }
    }
    
    return acc;
}

static int get_intra_count(MpegEncContext *s, uint8_t *src, uint8_t *ref, int stride){
    int x, y, w, h;
    int acc=0;
    
    w= s->width &~15;
    h= s->height&~15;
    
    for(y=0; y<h; y+=16){
        for(x=0; x<w; x+=16){
            int offset= x + y*stride;
            int sad = s->dsp.pix_abs16x16(src + offset, ref + offset, stride);
            int mean= (s->dsp.pix_sum(src + offset, stride) + 128)>>8;
            int sae = get_sae(src + offset, mean, stride);
            
            acc+= sae + 500 < sad;
        }
    }
    return acc;
}

M
Michael Niedermayer 已提交
987

M
Michael Niedermayer 已提交
988 989
static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
    AVFrame *pic;
M
Michael Niedermayer 已提交
990
    int i;
M
cleanup  
Michael Niedermayer 已提交
991
    const int encoding_delay= s->max_b_frames;
M
Michael Niedermayer 已提交
992
    int direct=1;
M
cleanup  
Michael Niedermayer 已提交
993

M
Michael Niedermayer 已提交
994 995 996 997 998 999
    if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
    if(pic_arg->linesize[0] != s->linesize) direct=0;
    if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
    if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
  
//    printf("%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);
M
cleanup  
Michael Niedermayer 已提交
1000
    
M
Michael Niedermayer 已提交
1001 1002
    if(direct){
        i= find_unused_picture(s, 1);
M
cleanup  
Michael Niedermayer 已提交
1003

M
Michael Niedermayer 已提交
1004
        pic= (AVFrame*)&s->picture[i];
M
Michael Niedermayer 已提交
1005
        pic->reference= 1;
M
cleanup  
Michael Niedermayer 已提交
1006
    
M
Michael Niedermayer 已提交
1007 1008 1009 1010 1011 1012 1013
        for(i=0; i<4; i++){
            pic->data[i]= pic_arg->data[i];
            pic->linesize[i]= pic_arg->linesize[i];
        }
        alloc_picture(s, (Picture*)pic, 1);
    }else{
        i= find_unused_picture(s, 0);
M
cleanup  
Michael Niedermayer 已提交
1014

M
Michael Niedermayer 已提交
1015
        pic= (AVFrame*)&s->picture[i];
M
Michael Niedermayer 已提交
1016
        pic->reference= 1;
M
cleanup  
Michael Niedermayer 已提交
1017

M
Michael Niedermayer 已提交
1018 1019 1020 1021 1022
        alloc_picture(s, (Picture*)pic, 0);

        if(   pic->data[0] == pic_arg->data[0] 
           && pic->data[1] == pic_arg->data[1]
           && pic->data[2] == pic_arg->data[2]){
M
cleanup  
Michael Niedermayer 已提交
1023
       // empty
M
Michael Niedermayer 已提交
1024 1025
        }else{
            int h_chroma_shift, v_chroma_shift;
M
cleanup  
Michael Niedermayer 已提交
1026
        
M
Michael Niedermayer 已提交
1027
            avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
M
cleanup  
Michael Niedermayer 已提交
1028
        
M
Michael Niedermayer 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037
            for(i=0; i<3; i++){
                int src_stride= pic_arg->linesize[i];
                int dst_stride= i ? s->uvlinesize : s->linesize;
                int h_shift= i ? h_chroma_shift : 0;
                int v_shift= i ? v_chroma_shift : 0;
                int w= s->width >>h_shift;
                int h= s->height>>v_shift;
                uint8_t *src= pic_arg->data[i];
                uint8_t *dst= pic->data[i];
M
cleanup  
Michael Niedermayer 已提交
1038
            
M
Michael Niedermayer 已提交
1039 1040 1041 1042 1043 1044 1045 1046
                if(src_stride==dst_stride)
                    memcpy(dst, src, src_stride*h);
                else{
                    while(h--){
                        memcpy(dst, src, w);
                        dst += dst_stride;
                        src += src_stride;
                    }
M
cleanup  
Michael Niedermayer 已提交
1047
                }
1048
            }
M
cleanup  
Michael Niedermayer 已提交
1049 1050
        }
    }
M
Michael Niedermayer 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    pic->quality= pic_arg->quality;
    pic->pict_type= pic_arg->pict_type;
    
    if(s->input_picture[encoding_delay])
        pic->display_picture_number= s->input_picture[encoding_delay]->display_picture_number + 1;

    /* shift buffer entries */
    for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
        s->input_picture[i-1]= s->input_picture[i];
        
    s->input_picture[encoding_delay]= (Picture*)pic;
M
cleanup  
Michael Niedermayer 已提交
1062 1063 1064

    return 0;
}
1065

M
cleanup  
Michael Niedermayer 已提交
1066 1067 1068 1069 1070 1071 1072
static void select_input_picture(MpegEncContext *s){
    int i;
    const int encoding_delay= s->max_b_frames;
    int coded_pic_num=0;    

    if(s->reordered_input_picture[0])
        coded_pic_num= s->reordered_input_picture[0]->coded_picture_number + 1;
M
Michael Niedermayer 已提交
1073

M
cleanup  
Michael Niedermayer 已提交
1074 1075 1076 1077 1078 1079
    for(i=1; i<MAX_PICTURE_COUNT; i++)
        s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
    s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;

    /* set next picture types & ordering */
    if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
M
Michael Niedermayer 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
        if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture.data[0]==NULL || s->intra_only){
            s->reordered_input_picture[0]= s->input_picture[0];
            s->reordered_input_picture[0]->pict_type= I_TYPE;
            s->reordered_input_picture[0]->coded_picture_number= coded_pic_num;
        }else{
            int b_frames;
            
            if(s->flags&CODEC_FLAG_PASS2){
                for(i=0; i<s->max_b_frames+1; i++){
                    int pict_num= s->input_picture[0]->display_picture_number + i;
                    int pict_type= s->rc_context.entry[pict_num].new_pict_type;
                    s->input_picture[i]->pict_type= pict_type;
                    
                    if(i + 1 >= s->rc_context.num_entries) break;
                }
            }
M
Michael Niedermayer 已提交
1096

M
Michael Niedermayer 已提交
1097 1098
            if(s->input_picture[0]->pict_type){
                /* user selected pict_type */
1099 1100 1101
                for(b_frames=0; b_frames<s->max_b_frames+1; b_frames++){
                    if(s->input_picture[b_frames]->pict_type!=B_TYPE) break;
                }
M
Michael Niedermayer 已提交
1102
            
1103 1104 1105 1106
                if(b_frames > s->max_b_frames){
                    fprintf(stderr, "warning, too many bframes in a row\n");
                    b_frames = s->max_b_frames;
                }
M
Michael Niedermayer 已提交
1107 1108 1109 1110 1111 1112
            }else if(s->b_frame_strategy==0){
                b_frames= s->max_b_frames;
            }else if(s->b_frame_strategy==1){
                for(i=1; i<s->max_b_frames+1; i++){
                    if(s->input_picture[i]->b_frame_score==0){
                        s->input_picture[i]->b_frame_score= 
M
Michael Niedermayer 已提交
1113 1114
                            get_intra_count(s, s->input_picture[i  ]->data[0], 
                                               s->input_picture[i-1]->data[0], s->linesize) + 1;
M
Michael Niedermayer 已提交
1115 1116 1117 1118 1119 1120 1121
                    }
                }
                for(i=0; i<s->max_b_frames; i++){
                    if(s->input_picture[i]->b_frame_score - 1 > s->mb_num/40) break;
                }
                                
                b_frames= FFMAX(0, i-1);
1122
                
M
Michael Niedermayer 已提交
1123 1124 1125 1126 1127 1128 1129
                /* reset scores */
                for(i=0; i<b_frames+1; i++){
                    s->input_picture[i]->b_frame_score=0;
                }
            }else{
                fprintf(stderr, "illegal b frame strategy\n");
                b_frames=0;
1130
            }
M
Michael Niedermayer 已提交
1131 1132 1133 1134 1135 1136 1137 1138 1139

            emms_c();
//static int b_count=0;
//b_count+= b_frames;
//printf("b_frames: %d\n", b_count);
                        
            s->reordered_input_picture[0]= s->input_picture[b_frames];
            if(   s->picture_in_gop_number + b_frames >= s->gop_size 
               || s->reordered_input_picture[0]->pict_type== I_TYPE)
M
cleanup  
Michael Niedermayer 已提交
1140
                s->reordered_input_picture[0]->pict_type= I_TYPE;
M
Michael Niedermayer 已提交
1141 1142 1143 1144 1145 1146 1147 1148
            else
                s->reordered_input_picture[0]->pict_type= P_TYPE;
            s->reordered_input_picture[0]->coded_picture_number= coded_pic_num;
            for(i=0; i<b_frames; i++){
                coded_pic_num++;
                s->reordered_input_picture[i+1]= s->input_picture[i];
                s->reordered_input_picture[i+1]->pict_type= B_TYPE;
                s->reordered_input_picture[i+1]->coded_picture_number= coded_pic_num;
1149 1150 1151
            }
        }
    }
M
cleanup  
Michael Niedermayer 已提交
1152 1153
    
    if(s->reordered_input_picture[0]){
M
Michael Niedermayer 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
       s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=B_TYPE;

        if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_SHARED){
            int i= find_unused_picture(s, 0);
            Picture *pic= &s->picture[i];

            s->new_picture= *s->reordered_input_picture[0];

            /* mark us unused / free shared pic */
            for(i=0; i<4; i++)
                s->reordered_input_picture[0]->data[i]= NULL;
            s->reordered_input_picture[0]->type= 0;
            
            pic->pict_type = s->reordered_input_picture[0]->pict_type;
            pic->quality   = s->reordered_input_picture[0]->quality;
            pic->coded_picture_number = s->reordered_input_picture[0]->coded_picture_number;
            pic->reference = s->reordered_input_picture[0]->reference;
            
            alloc_picture(s, pic, 0);

            s->current_picture= *pic;
        }else{
            assert(   s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER 
                   || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
            
            s->new_picture= *s->reordered_input_picture[0];

            for(i=0; i<4; i++){
                s->reordered_input_picture[0]->data[i]-=16; //FIXME dirty
            }
            s->current_picture= *s->reordered_input_picture[0];
M
cleanup  
Michael Niedermayer 已提交
1185 1186 1187 1188 1189 1190
        }
    
        s->picture_number= s->new_picture.display_picture_number;
//printf("dpn:%d\n", s->picture_number);
    }else{
       memset(&s->new_picture, 0, sizeof(Picture));
1191 1192 1193
    }
}

F
Fabrice Bellard 已提交
1194 1195 1196 1197
int MPV_encode_picture(AVCodecContext *avctx,
                       unsigned char *buf, int buf_size, void *data)
{
    MpegEncContext *s = avctx->priv_data;
M
Michael Niedermayer 已提交
1198
    AVFrame *pic_arg = data;
1199
    int i;
F
Fabrice Bellard 已提交
1200 1201 1202

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

M
cleanup  
Michael Niedermayer 已提交
1203
    s->picture_in_gop_number++;
F
Fabrice Bellard 已提交
1204

M
cleanup  
Michael Niedermayer 已提交
1205
    load_input_picture(s, pic_arg);
1206
    
M
cleanup  
Michael Niedermayer 已提交
1207
    select_input_picture(s);
1208 1209
    
    /* output? */
M
cleanup  
Michael Niedermayer 已提交
1210
    if(s->new_picture.data[0]){
1211

M
cleanup  
Michael Niedermayer 已提交
1212 1213 1214 1215 1216 1217 1218
        s->pict_type= s->new_picture.pict_type;
        if (s->fixed_qscale){ /* the ratecontrol needs the last qscale so we dont touch it for CBR */
            s->qscale= (int)(s->new_picture.quality+0.5);
            assert(s->qscale);
        }
//emms_c();
//printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
1219
        MPV_frame_start(s, avctx);
1220 1221

        encode_picture(s, s->picture_number);
1222
        
J
Juanjo 已提交
1223
        avctx->real_pict_num  = s->picture_number;
1224 1225 1226 1227 1228 1229
        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;
1230
        avctx->p_count     = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
1231 1232 1233 1234 1235 1236
        avctx->skip_count  = s->skip_count;

        MPV_frame_end(s);

        if (s->out_format == FMT_MJPEG)
            mjpeg_picture_trailer(s);
1237 1238 1239
        
        if(s->flags&CODEC_FLAG_PASS1)
            ff_write_pass1_stats(s);
F
Fabrice Bellard 已提交
1240 1241
    }

1242
    s->input_picture_number++;
F
Fabrice Bellard 已提交
1243 1244

    flush_put_bits(&s->pb);
1245
    s->frame_bits  = (pbBufPtr(&s->pb) - s->pb.buf) * 8;
M
Michael Niedermayer 已提交
1246
    
1247
    s->total_bits += s->frame_bits;
1248
    avctx->frame_bits  = s->frame_bits;
M
cleanup  
Michael Niedermayer 已提交
1249

1250 1251 1252 1253
    for(i=0; i<4; i++){
        avctx->error[i] += s->current_picture.error[i];
    }
    
1254
    return pbBufPtr(&s->pb) - s->pb.buf;
F
Fabrice Bellard 已提交
1255 1256
}

M
Michael Niedermayer 已提交
1257 1258 1259
static inline void gmc1_motion(MpegEncContext *s,
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
                               int dest_offset,
1260
                               UINT8 **ref_picture, int src_offset)
M
Michael Niedermayer 已提交
1261 1262
{
    UINT8 *ptr;
M
Michael Niedermayer 已提交
1263
    int offset, src_x, src_y, linesize, uvlinesize;
M
Michael Niedermayer 已提交
1264
    int motion_x, motion_y;
M
Michael Niedermayer 已提交
1265
    int emu=0;
M
Michael Niedermayer 已提交
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278

    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;
1279

M
Michael Niedermayer 已提交
1280
    linesize = s->linesize;
M
Michael Niedermayer 已提交
1281
    uvlinesize = s->uvlinesize;
1282
    
M
Michael Niedermayer 已提交
1283 1284 1285
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;

    dest_y+=dest_offset;
M
Michael Niedermayer 已提交
1286
    if(s->flags&CODEC_FLAG_EMU_EDGE){
1287
        if(src_x<0 || src_y<0 || src_x + (motion_x&15) + 16 > s->h_edge_pos
1288
                              || src_y + (motion_y&15) + 16 > s->v_edge_pos){
M
Michael Niedermayer 已提交
1289
            ff_emulated_edge_mc(s, ptr, linesize, 17, 17, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
M
Michael Niedermayer 已提交
1290 1291 1292 1293
            ptr= s->edge_emu_buffer;
            emu=1;
        }
    }
1294 1295
    
    if((motion_x|motion_y)&7){
1296 1297
        s->dsp.gmc1(dest_y  , ptr  , linesize, 16, motion_x&15, motion_y&15, 128 - s->no_rounding);
        s->dsp.gmc1(dest_y+8, ptr+8, linesize, 16, motion_x&15, motion_y&15, 128 - s->no_rounding);
1298 1299 1300 1301 1302
    }else{
        int dxy;
        
        dxy= ((motion_x>>3)&1) | ((motion_y>>2)&2);
        if (s->no_rounding){
1303
	    s->dsp.put_no_rnd_pixels_tab[0][dxy](dest_y, ptr, linesize, 16);
1304
        }else{
1305 1306
            s->dsp.put_pixels_tab       [0][dxy](dest_y, ptr, linesize, 16);
        }
1307 1308 1309
    }
    
    if(s->flags&CODEC_FLAG_GRAY) return;
M
Michael Niedermayer 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323

    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;

M
Michael Niedermayer 已提交
1324
    offset = (src_y * uvlinesize) + src_x + (src_offset>>1);
M
Michael Niedermayer 已提交
1325
    ptr = ref_picture[1] + offset;
M
Michael Niedermayer 已提交
1326
    if(emu){
M
Michael Niedermayer 已提交
1327
        ff_emulated_edge_mc(s, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
M
Michael Niedermayer 已提交
1328 1329
        ptr= s->edge_emu_buffer;
    }
1330
    s->dsp.gmc1(dest_cb + (dest_offset>>1), ptr, uvlinesize, 8, motion_x&15, motion_y&15, 128 - s->no_rounding);
M
Michael Niedermayer 已提交
1331
    
M
Michael Niedermayer 已提交
1332
    ptr = ref_picture[2] + offset;
M
Michael Niedermayer 已提交
1333
    if(emu){
M
Michael Niedermayer 已提交
1334
        ff_emulated_edge_mc(s, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
M
Michael Niedermayer 已提交
1335 1336
        ptr= s->edge_emu_buffer;
    }
1337
    s->dsp.gmc1(dest_cr + (dest_offset>>1), ptr, uvlinesize, 8, motion_x&15, motion_y&15, 128 - s->no_rounding);
M
Michael Niedermayer 已提交
1338 1339 1340 1341
    
    return;
}

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
static inline void gmc_motion(MpegEncContext *s,
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
                               int dest_offset,
                               UINT8 **ref_picture, int src_offset)
{
    UINT8 *ptr;
    int linesize, uvlinesize;
    const int a= s->sprite_warping_accuracy;
    int ox, oy;

    linesize = s->linesize;
    uvlinesize = s->uvlinesize;

    ptr = ref_picture[0] + src_offset;

    dest_y+=dest_offset;
    
    ox= s->sprite_offset[0][0] + s->sprite_delta[0][0]*s->mb_x*16 + s->sprite_delta[0][1]*s->mb_y*16;
    oy= s->sprite_offset[0][1] + s->sprite_delta[1][0]*s->mb_x*16 + s->sprite_delta[1][1]*s->mb_y*16;

1362
    s->dsp.gmc(dest_y, ptr, linesize, 16,
1363 1364 1365 1366 1367 1368
           ox, 
           oy, 
           s->sprite_delta[0][0], s->sprite_delta[0][1],
           s->sprite_delta[1][0], s->sprite_delta[1][1], 
           a+1, (1<<(2*a+1)) - s->no_rounding,
           s->h_edge_pos, s->v_edge_pos);
1369
    s->dsp.gmc(dest_y+8, ptr, linesize, 16,
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
           ox + s->sprite_delta[0][0]*8, 
           oy + s->sprite_delta[1][0]*8, 
           s->sprite_delta[0][0], s->sprite_delta[0][1],
           s->sprite_delta[1][0], s->sprite_delta[1][1], 
           a+1, (1<<(2*a+1)) - s->no_rounding,
           s->h_edge_pos, s->v_edge_pos);

    if(s->flags&CODEC_FLAG_GRAY) return;


    dest_cb+=dest_offset>>1;
    dest_cr+=dest_offset>>1;
    
    ox= s->sprite_offset[1][0] + s->sprite_delta[0][0]*s->mb_x*8 + s->sprite_delta[0][1]*s->mb_y*8;
    oy= s->sprite_offset[1][1] + s->sprite_delta[1][0]*s->mb_x*8 + s->sprite_delta[1][1]*s->mb_y*8;

    ptr = ref_picture[1] + (src_offset>>1);
1387
    s->dsp.gmc(dest_cb, ptr, uvlinesize, 8,
1388 1389 1390 1391 1392 1393 1394 1395
           ox, 
           oy, 
           s->sprite_delta[0][0], s->sprite_delta[0][1],
           s->sprite_delta[1][0], s->sprite_delta[1][1], 
           a+1, (1<<(2*a+1)) - s->no_rounding,
           s->h_edge_pos>>1, s->v_edge_pos>>1);
    
    ptr = ref_picture[2] + (src_offset>>1);
1396
    s->dsp.gmc(dest_cr, ptr, uvlinesize, 8,
1397 1398 1399 1400 1401 1402 1403 1404 1405
           ox, 
           oy, 
           s->sprite_delta[0][0], s->sprite_delta[0][1],
           s->sprite_delta[1][0], s->sprite_delta[1][1], 
           a+1, (1<<(2*a+1)) - s->no_rounding,
           s->h_edge_pos>>1, s->v_edge_pos>>1);
}


M
Michael Niedermayer 已提交
1406
void ff_emulated_edge_mc(MpegEncContext *s, UINT8 *src, int linesize, int block_w, int block_h, 
1407 1408 1409
                                    int src_x, int src_y, int w, int h){
    int x, y;
    int start_y, start_x, end_y, end_x;
M
Michael Niedermayer 已提交
1410
    UINT8 *buf= s->edge_emu_buffer;
1411

1412 1413 1414
    if(src_y>= h){
        src+= (h-1-src_y)*linesize;
        src_y=h-1;
M
Michael Niedermayer 已提交
1415 1416 1417
    }else if(src_y<=-block_h){
        src+= (1-block_h-src_y)*linesize;
        src_y=1-block_h;
1418 1419 1420 1421
    }
    if(src_x>= w){
        src+= (w-1-src_x);
        src_x=w-1;
M
Michael Niedermayer 已提交
1422 1423 1424
    }else if(src_x<=-block_w){
        src+= (1-block_w-src_x);
        src_x=1-block_w;
1425 1426
    }

M
Michael Niedermayer 已提交
1427 1428 1429 1430
    start_y= FFMAX(0, -src_y);
    start_x= FFMAX(0, -src_x);
    end_y= FFMIN(block_h, h-src_y);
    end_x= FFMIN(block_w, w-src_x);
M
Michael Niedermayer 已提交
1431

1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
    // copy existing part
    for(y=start_y; y<end_y; y++){
        for(x=start_x; x<end_x; x++){
            buf[x + y*linesize]= src[x + y*linesize];
        }
    }

    //top
    for(y=0; y<start_y; y++){
        for(x=start_x; x<end_x; x++){
            buf[x + y*linesize]= buf[x + start_y*linesize];
        }
    }

    //bottom
    for(y=end_y; y<block_h; y++){
        for(x=start_x; x<end_x; x++){
            buf[x + y*linesize]= buf[x + (end_y-1)*linesize];
        }
    }
                                    
    for(y=0; y<block_h; y++){
       //left
        for(x=0; x<start_x; x++){
            buf[x + y*linesize]= buf[start_x + y*linesize];
        }
       
       //right
        for(x=end_x; x<block_w; x++){
            buf[x + y*linesize]= buf[end_x - 1 + y*linesize];
        }
    }
}


F
Fabrice Bellard 已提交
1467 1468 1469 1470 1471
/* 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,
M
Michael Niedermayer 已提交
1472
                               int field_based, op_pixels_func (*pix_op)[4],
F
Fabrice Bellard 已提交
1473 1474 1475
                               int motion_x, int motion_y, int h)
{
    UINT8 *ptr;
1476
    int dxy, offset, mx, my, src_x, src_y, height, v_edge_pos, linesize, uvlinesize;
1477
    int emu=0;
M
Michael Niedermayer 已提交
1478
#if 0    
M
Michael Niedermayer 已提交
1479 1480 1481 1482 1483
if(s->quarter_sample)
{
    motion_x>>=1;
    motion_y>>=1;
}
M
Michael Niedermayer 已提交
1484
#endif
F
Fabrice Bellard 已提交
1485 1486 1487 1488 1489 1490
    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;
1491
    v_edge_pos = s->v_edge_pos >> field_based;
F
Fabrice Bellard 已提交
1492 1493 1494 1495 1496 1497
    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;
1498 1499
    linesize   = s->linesize << field_based;
    uvlinesize = s->uvlinesize << field_based;
F
Fabrice Bellard 已提交
1500 1501
    ptr = ref_picture[0] + (src_y * linesize) + (src_x) + src_offset;
    dest_y += dest_offset;
1502 1503

    if(s->flags&CODEC_FLAG_EMU_EDGE){
1504 1505
        if(src_x<0 || src_y<0 || src_x + (motion_x&1) + 16 > s->h_edge_pos
                              || src_y + (motion_y&1) + h  > v_edge_pos){
M
Michael Niedermayer 已提交
1506
            ff_emulated_edge_mc(s, ptr - src_offset, s->linesize, 17, 17+field_based, 
1507 1508
                             src_x, src_y<<field_based, s->h_edge_pos, s->v_edge_pos);
            ptr= s->edge_emu_buffer + src_offset;
1509 1510 1511
            emu=1;
        }
    }
M
Michael Niedermayer 已提交
1512
    pix_op[0][dxy](dest_y, ptr, linesize, h);
F
Fabrice Bellard 已提交
1513

M
Michael Niedermayer 已提交
1514 1515
    if(s->flags&CODEC_FLAG_GRAY) return;

F
Fabrice Bellard 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
    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;
1540
    offset = (src_y * uvlinesize) + src_x + (src_offset >> 1);
F
Fabrice Bellard 已提交
1541
    ptr = ref_picture[1] + offset;
1542
    if(emu){
M
Michael Niedermayer 已提交
1543
        ff_emulated_edge_mc(s, ptr - (src_offset >> 1), s->uvlinesize, 9, 9+field_based, 
1544 1545
                         src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
        ptr= s->edge_emu_buffer + (src_offset >> 1);
1546
    }
M
Michael Niedermayer 已提交
1547
    pix_op[1][dxy](dest_cb + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
1548

F
Fabrice Bellard 已提交
1549
    ptr = ref_picture[2] + offset;
1550
    if(emu){
M
Michael Niedermayer 已提交
1551
        ff_emulated_edge_mc(s, ptr - (src_offset >> 1), s->uvlinesize, 9, 9+field_based, 
1552 1553
                         src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
        ptr= s->edge_emu_buffer + (src_offset >> 1);
1554
    }
M
Michael Niedermayer 已提交
1555
    pix_op[1][dxy](dest_cr + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
F
Fabrice Bellard 已提交
1556 1557
}

M
Michael Niedermayer 已提交
1558 1559 1560 1561
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,
M
Michael Niedermayer 已提交
1562 1563
                               int field_based, op_pixels_func (*pix_op)[4],
                               qpel_mc_func (*qpix_op)[16],
M
Michael Niedermayer 已提交
1564 1565 1566
                               int motion_x, int motion_y, int h)
{
    UINT8 *ptr;
1567
    int dxy, offset, mx, my, src_x, src_y, height, v_edge_pos, linesize, uvlinesize;
M
Michael Niedermayer 已提交
1568
    int emu=0;
M
Michael Niedermayer 已提交
1569 1570 1571 1572 1573 1574

    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;
1575
    v_edge_pos = s->v_edge_pos >> field_based;
M
Michael Niedermayer 已提交
1576 1577 1578 1579 1580 1581 1582
    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;
1583
    uvlinesize = s->uvlinesize << field_based;
M
Michael Niedermayer 已提交
1584 1585 1586
    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);
M
Michael Niedermayer 已提交
1587 1588
    
    if(s->flags&CODEC_FLAG_EMU_EDGE){
1589 1590
        if(src_x<0 || src_y<0 || src_x + (motion_x&3) + 16 > s->h_edge_pos
                              || src_y + (motion_y&3) + h  > v_edge_pos){
M
Michael Niedermayer 已提交
1591
            ff_emulated_edge_mc(s, ptr - src_offset, s->linesize, 17, 17+field_based, 
1592 1593
                             src_x, src_y<<field_based, s->h_edge_pos, s->v_edge_pos);
            ptr= s->edge_emu_buffer + src_offset;
M
Michael Niedermayer 已提交
1594 1595 1596
            emu=1;
        }
    }
1597 1598 1599 1600 1601 1602 1603 1604
    if(!field_based)
        qpix_op[0][dxy](dest_y, ptr, linesize);
    else{
        //damn interlaced mode
        //FIXME boundary mirroring is not exactly correct here
        qpix_op[1][dxy](dest_y  , ptr  , linesize);
        qpix_op[1][dxy](dest_y+8, ptr+8, linesize);
    }
M
Michael Niedermayer 已提交
1605

M
Michael Niedermayer 已提交
1606 1607
    if(s->flags&CODEC_FLAG_GRAY) return;

1608 1609 1610
    if(field_based){
        mx= motion_x/2;
        my= motion_y>>1;
M
Michael Niedermayer 已提交
1611
    }else if(s->workaround_bugs&FF_BUG_QPEL_CHROMA){
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
        mx= (motion_x>>1)|(motion_x&1);
        my= (motion_y>>1)|(motion_y&1);
    }else{
        mx= motion_x/2;
        my= motion_y/2;
    }
    mx= (mx>>1)|(mx&1);
    my= (my>>1)|(my&1);
    dxy= (mx&1) | ((my&1)<<1);
    mx>>=1;
    my>>=1;
M
Michael Niedermayer 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632

    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;

1633
    offset = (src_y * uvlinesize) + src_x + (src_offset >> 1);
M
Michael Niedermayer 已提交
1634
    ptr = ref_picture[1] + offset;
M
Michael Niedermayer 已提交
1635
    if(emu){
M
Michael Niedermayer 已提交
1636
        ff_emulated_edge_mc(s, ptr - (src_offset >> 1), s->uvlinesize, 9, 9 + field_based, 
1637 1638
                         src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
        ptr= s->edge_emu_buffer + (src_offset >> 1);
M
Michael Niedermayer 已提交
1639
    }
1640
    pix_op[1][dxy](dest_cb + (dest_offset >> 1), ptr,  uvlinesize, h >> 1);
M
Michael Niedermayer 已提交
1641
    
M
Michael Niedermayer 已提交
1642
    ptr = ref_picture[2] + offset;
M
Michael Niedermayer 已提交
1643
    if(emu){
M
Michael Niedermayer 已提交
1644
        ff_emulated_edge_mc(s, ptr - (src_offset >> 1), s->uvlinesize, 9, 9 + field_based, 
1645 1646
                         src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
        ptr= s->edge_emu_buffer + (src_offset >> 1);
M
Michael Niedermayer 已提交
1647
    }
1648
    pix_op[1][dxy](dest_cr + (dest_offset >> 1), ptr,  uvlinesize, h >> 1);
M
Michael Niedermayer 已提交
1649 1650 1651
}


F
Fabrice Bellard 已提交
1652 1653 1654
static inline void MPV_motion(MpegEncContext *s, 
                              UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
                              int dir, UINT8 **ref_picture, 
M
Michael Niedermayer 已提交
1655
                              op_pixels_func (*pix_op)[4], qpel_mc_func (*qpix_op)[16])
F
Fabrice Bellard 已提交
1656 1657 1658 1659
{
    int dxy, offset, mx, my, src_x, src_y, motion_x, motion_y;
    int mb_x, mb_y, i;
    UINT8 *ptr, *dest;
M
Michael Niedermayer 已提交
1660
    int emu=0;
F
Fabrice Bellard 已提交
1661 1662 1663 1664 1665 1666

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

    switch(s->mv_type) {
    case MV_TYPE_16X16:
M
Michael Niedermayer 已提交
1667
        if(s->mcsel){
1668 1669 1670 1671 1672 1673 1674
            if(s->real_sprite_warping_points==1){
                gmc1_motion(s, dest_y, dest_cb, dest_cr, 0,
                            ref_picture, 0);
            }else{
                gmc_motion(s, dest_y, dest_cb, dest_cr, 0,
                            ref_picture, 0);
            }
M
Michael Niedermayer 已提交
1675
        }else if(s->quarter_sample){
M
Michael Niedermayer 已提交
1676 1677 1678 1679
            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);
M
Michael Niedermayer 已提交
1680 1681 1682 1683
        }else if(s->mspel){
            ff_mspel_motion(s, dest_y, dest_cb, dest_cr,
                        ref_picture, pix_op,
                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
M
Michael Niedermayer 已提交
1684 1685 1686 1687 1688 1689
        }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 已提交
1690 1691
        break;
    case MV_TYPE_8X8:
M
Michael Niedermayer 已提交
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
        mx = 0;
        my = 0;
        if(s->quarter_sample){
            for(i=0;i<4;i++) {
                motion_x = s->mv[dir][i][0];
                motion_y = s->mv[dir][i][1];

                dxy = ((motion_y & 3) << 2) | (motion_x & 3);
                src_x = mb_x * 16 + (motion_x >> 2) + (i & 1) * 8;
                src_y = mb_y * 16 + (motion_y >> 2) + (i >>1) * 8;
                    
                /* WARNING: do no forget half pels */
                src_x = clip(src_x, -16, s->width);
                if (src_x == s->width)
                    dxy &= ~3;
                src_y = clip(src_y, -16, s->height);
                if (src_y == s->height)
                    dxy &= ~12;
                    
                ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
                if(s->flags&CODEC_FLAG_EMU_EDGE){
                    if(src_x<0 || src_y<0 || src_x + (motion_x&3) + 8 > s->h_edge_pos
                                          || src_y + (motion_y&3) + 8 > s->v_edge_pos){
M
Michael Niedermayer 已提交
1715
                        ff_emulated_edge_mc(s, ptr, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
M
Michael Niedermayer 已提交
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
                        ptr= s->edge_emu_buffer;
                    }
                }
                dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
                qpix_op[1][dxy](dest, ptr, s->linesize);

                mx += s->mv[dir][i][0]/2;
                my += s->mv[dir][i][1]/2;
            }
        }else{
            for(i=0;i<4;i++) {
                motion_x = s->mv[dir][i][0];
                motion_y = s->mv[dir][i][1];
F
Fabrice Bellard 已提交
1729

M
Michael Niedermayer 已提交
1730 1731 1732
                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) * 8;
F
Fabrice Bellard 已提交
1733
                    
M
Michael Niedermayer 已提交
1734 1735 1736 1737 1738 1739 1740
                /* 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;
F
Fabrice Bellard 已提交
1741
                    
M
Michael Niedermayer 已提交
1742 1743 1744 1745
                ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
                if(s->flags&CODEC_FLAG_EMU_EDGE){
                    if(src_x<0 || src_y<0 || src_x + (motion_x&1) + 8 > s->h_edge_pos
                                          || src_y + (motion_y&1) + 8 > s->v_edge_pos){
M
Michael Niedermayer 已提交
1746
                        ff_emulated_edge_mc(s, ptr, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
M
Michael Niedermayer 已提交
1747 1748
                        ptr= s->edge_emu_buffer;
                    }
M
Michael Niedermayer 已提交
1749
                }
M
Michael Niedermayer 已提交
1750 1751 1752 1753 1754
                dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
                pix_op[1][dxy](dest, ptr, s->linesize, 8);

                mx += s->mv[dir][i][0];
                my += s->mv[dir][i][1];
M
Michael Niedermayer 已提交
1755
            }
F
Fabrice Bellard 已提交
1756
        }
M
Michael Niedermayer 已提交
1757

M
Michael Niedermayer 已提交
1758
        if(s->flags&CODEC_FLAG_GRAY) break;
F
Fabrice Bellard 已提交
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 1787
        /* In case of 8X8, we construct a single chroma motion vector
           with a special rounding */
        for(i=0;i<4;i++) {
        }
        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;
        
M
Michael Niedermayer 已提交
1788
        offset = (src_y * (s->uvlinesize)) + src_x;
F
Fabrice Bellard 已提交
1789
        ptr = ref_picture[1] + offset;
M
Michael Niedermayer 已提交
1790
        if(s->flags&CODEC_FLAG_EMU_EDGE){
1791 1792
                if(src_x<0 || src_y<0 || src_x + (dxy &1) + 8 > s->h_edge_pos>>1
                                      || src_y + (dxy>>1) + 8 > s->v_edge_pos>>1){
M
Michael Niedermayer 已提交
1793
                    ff_emulated_edge_mc(s, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
M
Michael Niedermayer 已提交
1794 1795 1796 1797
                    ptr= s->edge_emu_buffer;
                    emu=1;
                }
            }
M
Michael Niedermayer 已提交
1798
        pix_op[1][dxy](dest_cb, ptr, s->uvlinesize, 8);
M
Michael Niedermayer 已提交
1799

F
Fabrice Bellard 已提交
1800
        ptr = ref_picture[2] + offset;
M
Michael Niedermayer 已提交
1801
        if(emu){
M
Michael Niedermayer 已提交
1802
            ff_emulated_edge_mc(s, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
M
Michael Niedermayer 已提交
1803 1804
            ptr= s->edge_emu_buffer;
        }
M
Michael Niedermayer 已提交
1805
        pix_op[1][dxy](dest_cr, ptr, s->uvlinesize, 8);
F
Fabrice Bellard 已提交
1806 1807 1808
        break;
    case MV_TYPE_FIELD:
        if (s->picture_structure == PICT_FRAME) {
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
            if(s->quarter_sample){
                /* top field */
                qpel_motion(s, dest_y, dest_cb, dest_cr, 0,
                            ref_picture, s->field_select[dir][0] ? s->linesize : 0,
                            1, pix_op, qpix_op,
                            s->mv[dir][0][0], s->mv[dir][0][1], 8);
                /* bottom field */
                qpel_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
                            ref_picture, s->field_select[dir][1] ? s->linesize : 0,
                            1, pix_op, qpix_op,
                            s->mv[dir][1][0], s->mv[dir][1][1], 8);
            }else{
                /* 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);
            }
F
Fabrice Bellard 已提交
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
        } else {
            

        }
        break;
    }
}


/* put block[] to dest[] */
static inline void put_dct(MpegEncContext *s, 
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
{
1845
    s->dct_unquantize(s, block, i, s->qscale);
1846
    s->idct_put (dest, line_size, block);
F
Fabrice Bellard 已提交
1847 1848 1849 1850 1851 1852
}

/* add block[] to dest[] */
static inline void add_dct(MpegEncContext *s, 
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
{
M
Michael Niedermayer 已提交
1853
    if (s->block_last_index[i] >= 0) {
1854
        s->idct_add (dest, line_size, block);
M
Michael Niedermayer 已提交
1855 1856
    }
}
1857

M
Michael Niedermayer 已提交
1858 1859 1860
static inline void add_dequant_dct(MpegEncContext *s, 
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
{
F
Fabrice Bellard 已提交
1861
    if (s->block_last_index[i] >= 0) {
M
Michael Niedermayer 已提交
1862
        s->dct_unquantize(s, block, i, s->qscale);
1863

1864
        s->idct_add (dest, line_size, block);
F
Fabrice Bellard 已提交
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 1892 1893 1894 1895 1896 1897 1898 1899 1900
/**
 * cleans dc, ac, coded_block for the current non intra MB
 */
void ff_clean_intra_table_entries(MpegEncContext *s)
{
    int wrap = s->block_wrap[0];
    int xy = s->block_index[0];
    
    s->dc_val[0][xy           ] = 
    s->dc_val[0][xy + 1       ] = 
    s->dc_val[0][xy     + wrap] =
    s->dc_val[0][xy + 1 + wrap] = 1024;
    /* ac pred */
    memset(s->ac_val[0][xy       ], 0, 32 * sizeof(INT16));
    memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(INT16));
    if (s->msmpeg4_version>=3) {
        s->coded_block[xy           ] =
        s->coded_block[xy + 1       ] =
        s->coded_block[xy     + wrap] =
        s->coded_block[xy + 1 + wrap] = 0;
    }
    /* chroma */
    wrap = s->block_wrap[4];
    xy = s->mb_x + 1 + (s->mb_y + 1) * wrap;
    s->dc_val[1][xy] =
    s->dc_val[2][xy] = 1024;
    /* ac pred */
    memset(s->ac_val[1][xy], 0, 16 * sizeof(INT16));
    memset(s->ac_val[2][xy], 0, 16 * sizeof(INT16));
    
    s->mbintra_table[s->mb_x + s->mb_y*s->mb_width]= 0;
}

F
Fabrice Bellard 已提交
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
/* 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])
{
1913
    int mb_x, mb_y;
M
Michael Niedermayer 已提交
1914
    const int mb_xy = s->mb_y * s->mb_width + s->mb_x;
F
Fabrice Bellard 已提交
1915 1916 1917 1918

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

M
cleanup  
Michael Niedermayer 已提交
1919
    s->current_picture.qscale_table[mb_xy]= s->qscale;
1920

F
Fabrice Bellard 已提交
1921 1922
    /* update DC predictors for P macroblocks */
    if (!s->mb_intra) {
1923
        if (s->h263_pred || s->h263_aic) {
M
Michael Niedermayer 已提交
1924
            if(s->mbintra_table[mb_xy])
1925
                ff_clean_intra_table_entries(s);
F
Fabrice Bellard 已提交
1926
        } else {
1927 1928
            s->last_dc[0] =
            s->last_dc[1] =
F
Fabrice Bellard 已提交
1929 1930 1931
            s->last_dc[2] = 128 << s->intra_dc_precision;
        }
    }
1932
    else if (s->h263_pred || s->h263_aic)
M
Michael Niedermayer 已提交
1933
        s->mbintra_table[mb_xy]=1;
1934

1935
    /* update motion predictor, not for B-frames as they need the motion_val from the last P/S-Frame */
M
Michael Niedermayer 已提交
1936
    if (s->out_format == FMT_H263 && s->pict_type!=B_TYPE) { //FIXME move into h263.c if possible, format specific stuff shouldnt be here
M
Michael Niedermayer 已提交
1937
        //FIXME a lot of thet is only needed for !low_delay
M
Michael Niedermayer 已提交
1938 1939
        const int wrap = s->block_wrap[0];
        const int xy = s->block_index[0];
1940
        const int mb_index= s->mb_x + s->mb_y*s->mb_width;
1941
        if(s->mv_type == MV_TYPE_8X8){
1942
            s->co_located_type_table[mb_index]= CO_LOCATED_TYPE_4MV;
1943 1944 1945 1946 1947
        } else {
            int motion_x, motion_y;
            if (s->mb_intra) {
                motion_x = 0;
                motion_y = 0;
1948 1949
                if(s->co_located_type_table)
                    s->co_located_type_table[mb_index]= 0;
1950 1951 1952
            } else if (s->mv_type == MV_TYPE_16X16) {
                motion_x = s->mv[0][0][0];
                motion_y = s->mv[0][0][1];
1953 1954
                if(s->co_located_type_table)
                    s->co_located_type_table[mb_index]= 0;
1955
            } else /*if (s->mv_type == MV_TYPE_FIELD)*/ {
1956
                int i;
1957 1958 1959
                motion_x = s->mv[0][0][0] + s->mv[0][1][0];
                motion_y = s->mv[0][0][1] + s->mv[0][1][1];
                motion_x = (motion_x>>1) | (motion_x&1);
1960 1961 1962 1963 1964 1965
                for(i=0; i<2; i++){
                    s->field_mv_table[mb_index][i][0]= s->mv[0][i][0];
                    s->field_mv_table[mb_index][i][1]= s->mv[0][i][1];
                    s->field_select_table[mb_index][i]= s->field_select[0][i];
                }
                s->co_located_type_table[mb_index]= CO_LOCATED_TYPE_FIELDMV;
1966
            }
F
Fabrice Bellard 已提交
1967
            /* no update if 8X8 because it has been done during parsing */
1968 1969 1970 1971 1972 1973 1974 1975
            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 已提交
1976 1977 1978
        }
    }
    
1979
    if ((s->flags&CODEC_FLAG_PSNR) || !(s->encoding && (s->intra_only || s->pict_type==B_TYPE))) { //FIXME precalc
F
Fabrice Bellard 已提交
1980
        UINT8 *dest_y, *dest_cb, *dest_cr;
M
Michael Niedermayer 已提交
1981
        int dct_linesize, dct_offset;
M
Michael Niedermayer 已提交
1982 1983
        op_pixels_func (*op_pix)[4];
        qpel_mc_func (*op_qpix)[16];
1984

M
cleanup  
Michael Niedermayer 已提交
1985
        /* avoid copy if macroblock skipped in last frame too */
1986
        if (s->pict_type != B_TYPE) {
M
cleanup  
Michael Niedermayer 已提交
1987 1988 1989 1990 1991
            s->current_picture.mbskip_table[mb_xy]= s->mb_skiped;
        }

        /* skip only during decoding as we might trash the buffers during encoding a bit */
        if(!s->encoding){
M
Michael Niedermayer 已提交
1992
            UINT8 *mbskip_ptr = &s->mbskip_table[mb_xy];
M
cleanup  
Michael Niedermayer 已提交
1993
            const int age= s->current_picture.age;
M
Michael Niedermayer 已提交
1994

M
cleanup  
Michael Niedermayer 已提交
1995 1996 1997 1998 1999 2000
            assert(age);

            if (s->mb_skiped) {
                s->mb_skiped= 0;
                assert(s->pict_type!=I_TYPE);
 
M
Michael Niedermayer 已提交
2001 2002 2003
                (*mbskip_ptr) ++; /* indicate that this time we skiped it */
                if(*mbskip_ptr >99) *mbskip_ptr= 99;

M
cleanup  
Michael Niedermayer 已提交
2004 2005 2006 2007 2008 2009 2010 2011
                /* if previous was skipped too, then nothing to do !  */
                if (*mbskip_ptr >= age){
//if(s->pict_type!=B_TYPE && s->mb_x==0) printf("\n");
//if(s->pict_type!=B_TYPE) printf("%d%d ", *mbskip_ptr, age);
                    if(s->pict_type!=B_TYPE) return;
                    if(s->avctx->draw_horiz_band==NULL && *mbskip_ptr > age) return; 
                    /* we dont draw complete frames here so we cant skip */
                }
2012 2013 2014
            } else {
                *mbskip_ptr = 0; /* not skipped */
            }
M
cleanup  
Michael Niedermayer 已提交
2015 2016
        }else
            s->mb_skiped= 0;
F
Fabrice Bellard 已提交
2017

M
Michael Niedermayer 已提交
2018
        if(s->pict_type==B_TYPE && s->avctx->draw_horiz_band){
M
cleanup  
Michael Niedermayer 已提交
2019 2020 2021
            dest_y  = s->current_picture.data[0] + mb_x * 16;
            dest_cb = s->current_picture.data[1] + mb_x * 8;
            dest_cr = s->current_picture.data[2] + mb_x * 8;
M
Michael Niedermayer 已提交
2022
        }else{
M
cleanup  
Michael Niedermayer 已提交
2023 2024 2025
            dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
            dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
            dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
M
Michael Niedermayer 已提交
2026
        }
F
Fabrice Bellard 已提交
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037

        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 */
2038
            /* decoding or more than one mb_type (MC was allready done otherwise) */
M
Michael Niedermayer 已提交
2039
            if((!s->encoding) || (s->mb_type[mb_xy]&(s->mb_type[mb_xy]-1))){
2040
                if ((!s->no_rounding) || s->pict_type==B_TYPE){                
2041 2042
		    op_pix = s->dsp.put_pixels_tab;
                    op_qpix= s->dsp.put_qpel_pixels_tab;
2043
                }else{
2044 2045
                    op_pix = s->dsp.put_no_rnd_pixels_tab;
                    op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
2046
                }
F
Fabrice Bellard 已提交
2047

2048
                if (s->mv_dir & MV_DIR_FORWARD) {
M
cleanup  
Michael Niedermayer 已提交
2049
                    MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
2050 2051
		    op_pix = s->dsp.avg_pixels_tab;
                    op_qpix= s->dsp.avg_qpel_pixels_tab;
2052 2053
                }
                if (s->mv_dir & MV_DIR_BACKWARD) {
M
cleanup  
Michael Niedermayer 已提交
2054
                    MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
2055
                }
F
Fabrice Bellard 已提交
2056 2057
            }

M
Michael Niedermayer 已提交
2058
            /* skip dequant / idct if we are really late ;) */
2059
            if(s->hurry_up>1) return;
M
Michael Niedermayer 已提交
2060

F
Fabrice Bellard 已提交
2061
            /* add dct residue */
2062 2063
            if(s->encoding || !(   s->mpeg2 || s->h263_msmpeg4 || s->codec_id==CODEC_ID_MPEG1VIDEO 
                                || (s->codec_id==CODEC_ID_MPEG4 && !s->mpeg_quant))){
M
Michael Niedermayer 已提交
2064 2065 2066 2067 2068
                add_dequant_dct(s, block[0], 0, dest_y, dct_linesize);
                add_dequant_dct(s, block[1], 1, dest_y + 8, dct_linesize);
                add_dequant_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
                add_dequant_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);

M
Michael Niedermayer 已提交
2069
                if(!(s->flags&CODEC_FLAG_GRAY)){
M
Michael Niedermayer 已提交
2070 2071
                    add_dequant_dct(s, block[4], 4, dest_cb, s->uvlinesize);
                    add_dequant_dct(s, block[5], 5, dest_cr, s->uvlinesize);
M
Michael Niedermayer 已提交
2072
                }
M
Michael Niedermayer 已提交
2073
            } else if(s->codec_id != CODEC_ID_WMV2){
M
Michael Niedermayer 已提交
2074 2075 2076 2077
                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 已提交
2078

M
Michael Niedermayer 已提交
2079
                if(!(s->flags&CODEC_FLAG_GRAY)){
M
Michael Niedermayer 已提交
2080 2081
                    add_dct(s, block[4], 4, dest_cb, s->uvlinesize);
                    add_dct(s, block[5], 5, dest_cr, s->uvlinesize);
M
Michael Niedermayer 已提交
2082
                }
M
Michael Niedermayer 已提交
2083 2084
            } else{
                ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);
M
Michael Niedermayer 已提交
2085
            }
F
Fabrice Bellard 已提交
2086 2087
        } else {
            /* dct only in intra block */
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
            if(s->encoding || !(s->mpeg2 || s->codec_id==CODEC_ID_MPEG1VIDEO)){
                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);

                if(!(s->flags&CODEC_FLAG_GRAY)){
                    put_dct(s, block[4], 4, dest_cb, s->uvlinesize);
                    put_dct(s, block[5], 5, dest_cr, s->uvlinesize);
                }
            }else{
                s->idct_put(dest_y                 , dct_linesize, block[0]);
                s->idct_put(dest_y              + 8, dct_linesize, block[1]);
                s->idct_put(dest_y + dct_offset    , dct_linesize, block[2]);
                s->idct_put(dest_y + dct_offset + 8, dct_linesize, block[3]);

                if(!(s->flags&CODEC_FLAG_GRAY)){
                    s->idct_put(dest_cb, s->uvlinesize, block[4]);
                    s->idct_put(dest_cr, s->uvlinesize, block[5]);
                }
M
Michael Niedermayer 已提交
2108
            }
F
Fabrice Bellard 已提交
2109 2110 2111 2112
        }
    }
}

2113
static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
{
    static const char tab[64]=
        {3,2,2,1,1,1,1,1,
         1,1,1,1,1,1,1,1,
         1,1,1,1,1,1,1,1,
         0,0,0,0,0,0,0,0,
         0,0,0,0,0,0,0,0,
         0,0,0,0,0,0,0,0,
         0,0,0,0,0,0,0,0,
         0,0,0,0,0,0,0,0};
    int score=0;
    int run=0;
    int i;
    DCTELEM *block= s->block[n];
    const int last_index= s->block_last_index[n];
2129
    int skip_dc;
2130

2131 2132 2133
    if(threshold<0){
        skip_dc=0;
        threshold= -threshold;
2134 2135
    }else
        skip_dc=1;
2136

2137 2138 2139 2140
    /* are all which we could set to zero are allready zero? */
    if(last_index<=skip_dc - 1) return;

    for(i=0; i<=last_index; i++){
2141
        const int j = s->intra_scantable.permutated[i];
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
        const int level = ABS(block[j]);
        if(level==1){
            if(skip_dc && i==0) continue;
            score+= tab[run];
            run=0;
        }else if(level>1){
            return;
        }else{
            run++;
        }
    }
    if(score >= threshold) return;
    for(i=skip_dc; i<=last_index; i++){
2155
        const int j = s->intra_scantable.permutated[i];
2156 2157 2158 2159 2160 2161
        block[j]=0;
    }
    if(block[0]) s->block_last_index[n]= 0;
    else         s->block_last_index[n]= -1;
}

2162 2163 2164 2165 2166
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;
2167 2168 2169 2170 2171 2172 2173 2174
    
    if(s->mb_intra){
        i=1; //skip clipping of intra dc
    }else
        i=0;
    
    for(;i<=last_index; i++){
        const int j= s->intra_scantable.permutated[i];
2175 2176 2177 2178 2179 2180 2181
        int level = block[j];
       
        if     (level>maxlevel) level=maxlevel;
        else if(level<minlevel) level=minlevel;
        block[j]= level;
    }
}
2182

2183 2184 2185
static inline void requantize_coeffs(MpegEncContext *s, DCTELEM block[64], int oldq, int newq, int n)
{
    int i;
2186 2187 2188 2189

    if(s->mb_intra){
        i=1; //skip clipping of intra dc
         //FIXME requantize, note (mpeg1/h263/h263p-aic dont need it,...)
2190 2191 2192 2193
    }else
        i=0;
    
    for(;i<=s->block_last_index[n]; i++){
2194
        const int j = s->intra_scantable.permutated[i];
2195 2196 2197 2198 2199 2200
        int level = block[j];
        
        block[j]= ROUNDED_DIV(level*oldq, newq);
    }

    for(i=s->block_last_index[n]; i>=0; i--){
2201
        const int j = s->intra_scantable.permutated[i];
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
        if(block[j]) break;
    }
    s->block_last_index[n]= i;
}

static inline void auto_requantize_coeffs(MpegEncContext *s, DCTELEM block[6][64])
{
    int i,n, newq;
    const int maxlevel= s->max_qcoeff;
    const int minlevel= s->min_qcoeff;
    int largest=0, smallest=0;

    assert(s->adaptive_quant);
    
    for(n=0; n<6; n++){
2217 2218 2219 2220 2221
        if(s->mb_intra){
            i=1; //skip clipping of intra dc
             //FIXME requantize, note (mpeg1/h263/h263p-aic dont need it,...)
        }else
            i=0;
2222 2223

        for(;i<=s->block_last_index[n]; i++){
2224
            const int j = s->intra_scantable.permutated[i];
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 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 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
            int level = block[n][j];
            if(largest  < level) largest = level;
            if(smallest > level) smallest= level;
        }
    }
    
    for(newq=s->qscale+1; newq<32; newq++){
        if(   ROUNDED_DIV(smallest*s->qscale, newq) >= minlevel
           && ROUNDED_DIV(largest *s->qscale, newq) <= maxlevel) 
            break;
    }
        
    if(s->out_format==FMT_H263){
        /* h263 like formats cannot change qscale by more than 2 easiely */
        if(s->avctx->qmin + 2 < newq)
            newq= s->avctx->qmin + 2;
    }

    for(n=0; n<6; n++){
        requantize_coeffs(s, block[n], s->qscale, newq, n);
        clip_coeffs(s, block[n], s->block_last_index[n]);
    }
     
    s->dquant+= newq - s->qscale;
    s->qscale= newq;
}
#if 0
static int pix_vcmp16x8(UINT8 *s, int stride){ //FIXME move to dsputil & optimize
    int score=0;
    int x,y;
    
    for(y=0; y<7; y++){
        for(x=0; x<16; x+=4){
            score+= ABS(s[x  ] - s[x  +stride]) + ABS(s[x+1] - s[x+1+stride]) 
                   +ABS(s[x+2] - s[x+2+stride]) + ABS(s[x+3] - s[x+3+stride]);
        }
        s+= stride;
    }
    
    return score;
}

static int pix_diff_vcmp16x8(UINT8 *s1, UINT8*s2, int stride){ //FIXME move to dsputil & optimize
    int score=0;
    int x,y;
    
    for(y=0; y<7; y++){
        for(x=0; x<16; x++){
            score+= ABS(s1[x  ] - s2[x ] - s1[x  +stride] + s2[x +stride]);
        }
        s1+= stride;
        s2+= stride;
    }
    
    return score;
}
#else
#define SQ(a) ((a)*(a))

static int pix_vcmp16x8(UINT8 *s, int stride){ //FIXME move to dsputil & optimize
    int score=0;
    int x,y;
    
    for(y=0; y<7; y++){
        for(x=0; x<16; x+=4){
            score+= SQ(s[x  ] - s[x  +stride]) + SQ(s[x+1] - s[x+1+stride]) 
                   +SQ(s[x+2] - s[x+2+stride]) + SQ(s[x+3] - s[x+3+stride]);
        }
        s+= stride;
    }
    
    return score;
}

static int pix_diff_vcmp16x8(UINT8 *s1, UINT8*s2, int stride){ //FIXME move to dsputil & optimize
    int score=0;
    int x,y;
    
    for(y=0; y<7; y++){
        for(x=0; x<16; x++){
            score+= SQ(s1[x  ] - s2[x ] - s1[x  +stride] + s2[x +stride]);
        }
        s1+= stride;
        s2+= stride;
    }
    
    return score;
}

#endif
2315 2316 2317

void ff_draw_horiz_band(MpegEncContext *s){
    if (    s->avctx->draw_horiz_band 
M
Michael Niedermayer 已提交
2318
        && (s->last_picture.data[0] || s->low_delay) ) {
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
        UINT8 *src_ptr[3];
        int y, h, offset;
        y = s->mb_y * 16;
        h = s->height - y;
        if (h > 16)
            h = 16;

        if(s->pict_type==B_TYPE)
            offset = 0;
        else
            offset = y * s->linesize;

M
Michael Niedermayer 已提交
2331
        if(s->pict_type==B_TYPE || s->low_delay){
M
cleanup  
Michael Niedermayer 已提交
2332 2333 2334
            src_ptr[0] = s->current_picture.data[0] + offset;
            src_ptr[1] = s->current_picture.data[1] + (offset >> 2);
            src_ptr[2] = s->current_picture.data[2] + (offset >> 2);
2335
        } else {
M
cleanup  
Michael Niedermayer 已提交
2336 2337 2338
            src_ptr[0] = s->last_picture.data[0] + offset;
            src_ptr[1] = s->last_picture.data[1] + (offset >> 2);
            src_ptr[2] = s->last_picture.data[2] + (offset >> 2);
2339
        }
M
cleanup  
Michael Niedermayer 已提交
2340 2341
        emms_c();

2342 2343 2344 2345 2346
        s->avctx->draw_horiz_band(s->avctx, src_ptr, s->linesize,
                               y, s->width, h);
    }
}

2347
static void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
F
Fabrice Bellard 已提交
2348
{
2349 2350 2351
    const int mb_x= s->mb_x;
    const int mb_y= s->mb_y;
    int i;
2352
    int skip_dct[6];
2353 2354
    int dct_offset   = s->linesize*8; //default for progressive frames
    
2355
    for(i=0; i<6; i++) skip_dct[i]=0;
2356 2357
    
    if(s->adaptive_quant){
M
cleanup  
Michael Niedermayer 已提交
2358
        s->dquant= s->current_picture.qscale_table[mb_x + mb_y*s->mb_width] - s->qscale;
2359 2360

        if(s->out_format==FMT_H263){
2361 2362
            if     (s->dquant> 2) s->dquant= 2;
            else if(s->dquant<-2) s->dquant=-2;
2363 2364 2365
        }
            
        if(s->codec_id==CODEC_ID_MPEG4){        
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
            if(!s->mb_intra){
                assert(s->dquant==0 || s->mv_type!=MV_TYPE_8X8);

                if(s->mv_dir&MV_DIRECT)
                    s->dquant=0;
            }
        }
        s->qscale+= s->dquant;
        s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
        s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
    }
2377

2378 2379
    if (s->mb_intra) {
        UINT8 *ptr;
2380
        int wrap_y;
2381
        int emu=0;
2382

2383
        wrap_y = s->linesize;
M
cleanup  
Michael Niedermayer 已提交
2384
        ptr = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
2385

2386
        if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
M
Michael Niedermayer 已提交
2387
            ff_emulated_edge_mc(s, ptr, wrap_y, 16, 16, mb_x*16, mb_y*16, s->width, s->height);
2388 2389 2390
            ptr= s->edge_emu_buffer;
            emu=1;
        }
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
        
        if(s->flags&CODEC_FLAG_INTERLACED_DCT){
            int progressive_score, interlaced_score;
            
            progressive_score= pix_vcmp16x8(ptr, wrap_y  ) + pix_vcmp16x8(ptr + wrap_y*8, wrap_y );
            interlaced_score = pix_vcmp16x8(ptr, wrap_y*2) + pix_vcmp16x8(ptr + wrap_y  , wrap_y*2);
            
            if(progressive_score > interlaced_score + 100){
                s->interlaced_dct=1;
            
                dct_offset= wrap_y;
                wrap_y<<=1;
            }else
                s->interlaced_dct=0;
        }
        
2407 2408 2409 2410
	s->dsp.get_pixels(s->block[0], ptr                 , wrap_y);
        s->dsp.get_pixels(s->block[1], ptr              + 8, wrap_y);
        s->dsp.get_pixels(s->block[2], ptr + dct_offset    , wrap_y);
        s->dsp.get_pixels(s->block[3], ptr + dct_offset + 8, wrap_y);
2411

M
Michael Niedermayer 已提交
2412 2413 2414 2415
        if(s->flags&CODEC_FLAG_GRAY){
            skip_dct[4]= 1;
            skip_dct[5]= 1;
        }else{
2416
            int wrap_c = s->uvlinesize;
M
cleanup  
Michael Niedermayer 已提交
2417
            ptr = s->new_picture.data[1] + (mb_y * 8 * wrap_c) + mb_x * 8;
2418
            if(emu){
M
Michael Niedermayer 已提交
2419
                ff_emulated_edge_mc(s, ptr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
2420 2421
                ptr= s->edge_emu_buffer;
            }
2422
	    s->dsp.get_pixels(s->block[4], ptr, wrap_c);
2423

M
cleanup  
Michael Niedermayer 已提交
2424
            ptr = s->new_picture.data[2] + (mb_y * 8 * wrap_c) + mb_x * 8;
2425
            if(emu){
M
Michael Niedermayer 已提交
2426
                ff_emulated_edge_mc(s, ptr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
2427 2428
                ptr= s->edge_emu_buffer;
            }
2429
            s->dsp.get_pixels(s->block[5], ptr, wrap_c);
M
Michael Niedermayer 已提交
2430
        }
2431
    }else{
M
Michael Niedermayer 已提交
2432 2433
        op_pixels_func (*op_pix)[4];
        qpel_mc_func (*op_qpix)[16];
2434
        UINT8 *dest_y, *dest_cb, *dest_cr;
2435 2436
        UINT8 *ptr_y, *ptr_cb, *ptr_cr;
        int wrap_y, wrap_c;
2437
        int emu=0;
2438

M
cleanup  
Michael Niedermayer 已提交
2439 2440 2441
        dest_y  = s->current_picture.data[0] + (mb_y * 16 * s->linesize    ) + mb_x * 16;
        dest_cb = s->current_picture.data[1] + (mb_y * 8  * (s->uvlinesize)) + mb_x * 8;
        dest_cr = s->current_picture.data[2] + (mb_y * 8  * (s->uvlinesize)) + mb_x * 8;
2442
        wrap_y = s->linesize;
2443
        wrap_c = s->uvlinesize;
M
cleanup  
Michael Niedermayer 已提交
2444 2445 2446
        ptr_y  = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
        ptr_cb = s->new_picture.data[1] + (mb_y * 8 * wrap_c) + mb_x * 8;
        ptr_cr = s->new_picture.data[2] + (mb_y * 8 * wrap_c) + mb_x * 8;
2447

2448
        if ((!s->no_rounding) || s->pict_type==B_TYPE){
2449 2450
	    op_pix = s->dsp.put_pixels_tab;
            op_qpix= s->dsp.put_qpel_pixels_tab;
M
Michael Niedermayer 已提交
2451
        }else{
2452 2453
            op_pix = s->dsp.put_no_rnd_pixels_tab;
            op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
2454 2455 2456
        }

        if (s->mv_dir & MV_DIR_FORWARD) {
M
cleanup  
Michael Niedermayer 已提交
2457
            MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
2458 2459
            op_pix = s->dsp.avg_pixels_tab;
            op_qpix= s->dsp.avg_qpel_pixels_tab;
2460 2461
        }
        if (s->mv_dir & MV_DIR_BACKWARD) {
M
cleanup  
Michael Niedermayer 已提交
2462
            MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
2463
        }
2464

2465
        if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
M
Michael Niedermayer 已提交
2466
            ff_emulated_edge_mc(s, ptr_y, wrap_y, 16, 16, mb_x*16, mb_y*16, s->width, s->height);
2467 2468 2469
            ptr_y= s->edge_emu_buffer;
            emu=1;
        }
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
        
        if(s->flags&CODEC_FLAG_INTERLACED_DCT){
            int progressive_score, interlaced_score;
            
            progressive_score= pix_diff_vcmp16x8(ptr_y           , dest_y           , wrap_y  ) 
                             + pix_diff_vcmp16x8(ptr_y + wrap_y*8, dest_y + wrap_y*8, wrap_y  );
            interlaced_score = pix_diff_vcmp16x8(ptr_y           , dest_y           , wrap_y*2)
                             + pix_diff_vcmp16x8(ptr_y + wrap_y  , dest_y + wrap_y  , wrap_y*2);
            
            if(progressive_score > interlaced_score + 600){
                s->interlaced_dct=1;
            
                dct_offset= wrap_y;
                wrap_y<<=1;
            }else
                s->interlaced_dct=0;
        }
        
2488 2489 2490 2491
	s->dsp.diff_pixels(s->block[0], ptr_y                 , dest_y                 , wrap_y);
        s->dsp.diff_pixels(s->block[1], ptr_y              + 8, dest_y              + 8, wrap_y);
        s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset    , dest_y + dct_offset    , wrap_y);
        s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
M
Michael Niedermayer 已提交
2492 2493 2494 2495 2496
        
        if(s->flags&CODEC_FLAG_GRAY){
            skip_dct[4]= 1;
            skip_dct[5]= 1;
        }else{
2497
            if(emu){
M
Michael Niedermayer 已提交
2498
                ff_emulated_edge_mc(s, ptr_cb, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
2499 2500
                ptr_cb= s->edge_emu_buffer;
            }
2501
            s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
2502
            if(emu){
M
Michael Niedermayer 已提交
2503
                ff_emulated_edge_mc(s, ptr_cr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
2504 2505
                ptr_cr= s->edge_emu_buffer;
            }
2506
            s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
M
Michael Niedermayer 已提交
2507
        }
2508
        /* pre quantization */         
M
cleanup  
Michael Niedermayer 已提交
2509
        if(s->current_picture.mc_mb_var[s->mb_width*mb_y+ mb_x]<2*s->qscale*s->qscale){
2510
            //FIXME optimize
2511 2512 2513 2514
	    if(s->dsp.pix_abs8x8(ptr_y               , dest_y               , wrap_y) < 20*s->qscale) skip_dct[0]= 1;
            if(s->dsp.pix_abs8x8(ptr_y            + 8, dest_y            + 8, wrap_y) < 20*s->qscale) skip_dct[1]= 1;
            if(s->dsp.pix_abs8x8(ptr_y +dct_offset   , dest_y +dct_offset   , wrap_y) < 20*s->qscale) skip_dct[2]= 1;
            if(s->dsp.pix_abs8x8(ptr_y +dct_offset+ 8, dest_y +dct_offset+ 8, wrap_y) < 20*s->qscale) skip_dct[3]= 1;
2515 2516
            if(s->dsp.pix_abs8x8(ptr_cb              , dest_cb              , wrap_c) < 20*s->qscale) skip_dct[4]= 1;
            if(s->dsp.pix_abs8x8(ptr_cr              , dest_cr              , wrap_c) < 20*s->qscale) skip_dct[5]= 1;
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
#if 0
{
 static int stat[7];
 int num=0;
 for(i=0; i<6; i++)
  if(skip_dct[i]) num++;
 stat[num]++;
 
 if(s->mb_x==0 && s->mb_y==0){
  for(i=0; i<7; i++){
   printf("%6d %1d\n", stat[i], i);
  }
 }
}
#endif
        }
2533

2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
    }
            
#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 */
2550 2551 2552
    if(s->out_format==FMT_MJPEG){
        for(i=0;i<6;i++) {
            int overflow;
2553
            s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, 8, &overflow);
2554
            if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
2555 2556 2557
        }
    }else{
        for(i=0;i<6;i++) {
2558 2559
            if(!skip_dct[i]){
                int overflow;
2560
                s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
2561
            // FIXME we could decide to change to quantizer instead of clipping
2562 2563
            // JS: I don't think that would be a good idea it could lower quality instead
            //     of improve it. Just INTRADC clipping deserves changes in quantizer
2564 2565 2566
                if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
            }else
                s->block_last_index[i]= -1;
2567
        }
2568 2569
        if(s->luma_elim_threshold && !s->mb_intra)
            for(i=0; i<4; i++)
2570
                dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
2571 2572
        if(s->chroma_elim_threshold && !s->mb_intra)
            for(i=4; i<6; i++)
2573
                dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
2574 2575
    }

M
Michael Niedermayer 已提交
2576 2577 2578 2579 2580 2581 2582
    if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
        s->block_last_index[4]=
        s->block_last_index[5]= 0;
        s->block[4][0]=
        s->block[5][0]= 128;
    }

2583
#ifdef CONFIG_ENCODERS
2584
    /* huffman encode */
M
Michael Niedermayer 已提交
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603
    switch(s->codec_id){ //FIXME funct ptr could be slightly faster
    case CODEC_ID_MPEG1VIDEO:
        mpeg1_encode_mb(s, s->block, motion_x, motion_y); break;
    case CODEC_ID_MPEG4:
        mpeg4_encode_mb(s, s->block, motion_x, motion_y); break;
    case CODEC_ID_MSMPEG4V2:
    case CODEC_ID_MSMPEG4V3:
    case CODEC_ID_WMV1:
        msmpeg4_encode_mb(s, s->block, motion_x, motion_y); break;
    case CODEC_ID_WMV2:
         ff_wmv2_encode_mb(s, s->block, motion_x, motion_y); break;
    case CODEC_ID_MJPEG:
        mjpeg_encode_mb(s, s->block); break;
    case CODEC_ID_H263:
    case CODEC_ID_H263P:
    case CODEC_ID_RV10:
        h263_encode_mb(s, s->block, motion_x, motion_y); break;
    default:
        assert(0);
2604
    }
2605
#endif
2606 2607
}

2608
void ff_copy_bits(PutBitContext *pb, UINT8 *src, int length)
2609
{
2610 2611 2612 2613
    int bytes= length>>4;
    int bits= length&15;
    int i;

2614 2615
    if(length==0) return;

2616 2617
    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));
2618 2619
}

2620
static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
    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;
2635 2636
    d->f_count= s->f_count;
    d->b_count= s->b_count;
2637 2638
    d->skip_count= s->skip_count;
    d->misc_bits= s->misc_bits;
2639
    d->last_bits= 0;
2640 2641

    d->mb_skiped= s->mb_skiped;
M
Michael Niedermayer 已提交
2642
    d->qscale= s->qscale;
2643 2644
}

2645
static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
    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;
2661 2662
    d->f_count= s->f_count;
    d->b_count= s->b_count;
2663 2664 2665 2666
    d->skip_count= s->skip_count;
    d->misc_bits= s->misc_bits;

    d->mb_intra= s->mb_intra;
2667
    d->mb_skiped= s->mb_skiped;
2668 2669 2670
    d->mv_type= s->mv_type;
    d->mv_dir= s->mv_dir;
    d->pb= s->pb;
2671 2672 2673 2674
    if(s->data_partitioning){
        d->pb2= s->pb2;
        d->tex_pb= s->tex_pb;
    }
2675 2676 2677
    d->block= s->block;
    for(i=0; i<6; i++)
        d->block_last_index[i]= s->block_last_index[i];
2678
    d->interlaced_dct= s->interlaced_dct;
M
Michael Niedermayer 已提交
2679
    d->qscale= s->qscale;
2680 2681
}

2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type, 
                           PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
                           int *dmin, int *next_block, int motion_x, int motion_y)
{
    int bits_count;
    
    copy_context_before_encode(s, backup, type);

    s->block= s->blocks[*next_block];
    s->pb= pb[*next_block];
    if(s->data_partitioning){
        s->pb2   = pb2   [*next_block];
        s->tex_pb= tex_pb[*next_block];
    }

    encode_mb(s, motion_x, motion_y);

    bits_count= get_bit_count(&s->pb);
    if(s->data_partitioning){
        bits_count+= get_bit_count(&s->pb2);
        bits_count+= get_bit_count(&s->tex_pb);
    }

    if(bits_count<*dmin){
        *dmin= bits_count;
        *next_block^=1;

        copy_context_after_encode(best, s, type);
    }
}
2712 2713 2714 2715 2716 2717 2718
                
static inline int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
    uint32_t *sq = squareTbl + 256;
    int acc=0;
    int x,y;
    
    if(w==16 && h==16) 
M
Michael Niedermayer 已提交
2719 2720 2721
        return s->dsp.sse[0](NULL, src1, src2, stride);
    else if(w==8 && h==8)
        return s->dsp.sse[1](NULL, src1, src2, stride);
2722 2723 2724 2725 2726 2727
    
    for(y=0; y<h; y++){
        for(x=0; x<w; x++){
            acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
        } 
    }
M
Michael Niedermayer 已提交
2728 2729 2730
    
    assert(acc>=0);
    
2731 2732
    return acc;
}
2733

2734 2735
static void encode_picture(MpegEncContext *s, int picture_number)
{
M
Michael Niedermayer 已提交
2736
    int mb_x, mb_y, pdif = 0;
2737
    int i;
2738
    int bits;
2739
    MpegEncContext best_s, backup_s;
2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
    UINT8 bit_buf[2][3000];
    UINT8 bit_buf2[2][3000];
    UINT8 bit_buf_tex[2][3000];
    PutBitContext pb[2], pb2[2], tex_pb[2];

    for(i=0; i<2; i++){
        init_put_bits(&pb    [i], bit_buf    [i], 3000, NULL, NULL);
        init_put_bits(&pb2   [i], bit_buf2   [i], 3000, NULL, NULL);
        init_put_bits(&tex_pb[i], bit_buf_tex[i], 3000, NULL, NULL);
    }
F
Fabrice Bellard 已提交
2750 2751

    s->picture_number = picture_number;
2752

2753 2754 2755 2756 2757 2758 2759
    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;
    
2760
    /* Reset the average MB variance */
M
cleanup  
Michael Niedermayer 已提交
2761 2762
    s->current_picture.mb_var_sum = 0;
    s->current_picture.mc_mb_var_sum = 0;
2763 2764 2765 2766 2767

    /* 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); 

2768
    s->scene_change_score=0;
2769 2770
    
    s->qscale= (int)(s->frame_qscale + 0.5); //FIXME qscale / ... stuff for ME ratedistoration
M
Michael Niedermayer 已提交
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
    
    if(s->msmpeg4_version){
        if(s->pict_type==I_TYPE)
            s->no_rounding=1;
        else if(s->flipflop_rounding)
            s->no_rounding ^= 1;          
    }else{
        if(s->pict_type==I_TYPE)
            s->no_rounding=0;
        else if(s->pict_type!=B_TYPE)
            s->no_rounding ^= 1;          
    }
2783

2784
    /* Estimate motion for every MB */
2785
    if(s->pict_type != I_TYPE){
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
        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 */
2800 2801 2802 2803
                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);
2804 2805
            }
        }
2806
    }else /* if(s->pict_type == I_TYPE) */{
2807 2808 2809
        /* 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);
2810
        memset(s->p_mv_table   , 0, sizeof(INT16)*(s->mb_width+2)*(s->mb_height+2)*2);
2811
        memset(s->mb_type      , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
M
Michael Niedermayer 已提交
2812 2813 2814 2815 2816 2817 2818
        
        if(!s->fixed_qscale){
            /* finding spatial complexity for I-frame rate control */
            for(mb_y=0; mb_y < s->mb_height; mb_y++) {
                for(mb_x=0; mb_x < s->mb_width; mb_x++) {
                    int xx = mb_x * 16;
                    int yy = mb_y * 16;
M
cleanup  
Michael Niedermayer 已提交
2819
                    uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
M
Michael Niedermayer 已提交
2820
                    int varc;
2821
		    int sum = s->dsp.pix_sum(pix, s->linesize);
M
Michael Niedermayer 已提交
2822
    
2823
		    varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
M
Michael Niedermayer 已提交
2824

M
cleanup  
Michael Niedermayer 已提交
2825 2826 2827
                    s->current_picture.mb_var [s->mb_width * mb_y + mb_x] = varc;
                    s->current_picture.mb_mean[s->mb_width * mb_y + mb_x] = (sum+128)>>8;
                    s->current_picture.mb_var_sum    += varc;
M
Michael Niedermayer 已提交
2828 2829 2830
                }
            }
        }
2831
    }
2832 2833
    emms_c();

2834
    if(s->scene_change_score > 0 && s->pict_type == P_TYPE){
M
Michael Niedermayer 已提交
2835
        s->pict_type= I_TYPE;
2836
        memset(s->mb_type   , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
M
cleanup  
Michael Niedermayer 已提交
2837
//printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
M
Michael Niedermayer 已提交
2838
    }
M
cleanup  
Michael Niedermayer 已提交
2839

2840 2841 2842 2843 2844 2845
    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);
2846 2847 2848 2849 2850

        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);
2851
    }
2852
    
2853
    if (s->fixed_qscale) 
M
cleanup  
Michael Niedermayer 已提交
2854
        s->frame_qscale = s->current_picture.quality;
2855 2856
    else
        s->frame_qscale = ff_rate_estimate_qscale(s);
2857

2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868
    if(s->adaptive_quant){
        switch(s->codec_id){
        case CODEC_ID_MPEG4:
            ff_clean_mpeg4_qscales(s);
            break;
        case CODEC_ID_H263:
        case CODEC_ID_H263P:
            ff_clean_h263_qscales(s);
            break;
        }

M
cleanup  
Michael Niedermayer 已提交
2869
        s->qscale= s->current_picture.qscale_table[0];
2870
    }else
2871 2872
        s->qscale= (int)(s->frame_qscale + 0.5);
        
F
Fabrice Bellard 已提交
2873 2874
    if (s->out_format == FMT_MJPEG) {
        /* for mjpeg, we do include qscale in the matrix */
2875
        s->intra_matrix[0] = ff_mpeg1_default_intra_matrix[0];
2876 2877 2878 2879 2880
        for(i=1;i<64;i++){
            int j= s->idct_permutation[i];

            s->intra_matrix[j] = CLAMP_TO_8BIT((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
        }
2881
        convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16, 
2882
                       s->q_intra_matrix16_bias, s->intra_matrix, s->intra_quant_bias, 8, 8);
F
Fabrice Bellard 已提交
2883
    }
M
cleanup  
Michael Niedermayer 已提交
2884 2885 2886 2887 2888 2889 2890
    
    //FIXME var duplication
    s->current_picture.key_frame= s->pict_type == I_TYPE;
    s->current_picture.pict_type= s->pict_type;

    if(s->current_picture.key_frame)
        s->picture_in_gop_number=0;
F
Fabrice Bellard 已提交
2891

2892
    s->last_bits= get_bit_count(&s->pb);
F
Fabrice Bellard 已提交
2893 2894 2895 2896 2897
    switch(s->out_format) {
    case FMT_MJPEG:
        mjpeg_picture_header(s);
        break;
    case FMT_H263:
M
Michael Niedermayer 已提交
2898 2899 2900
        if (s->codec_id == CODEC_ID_WMV2) 
            ff_wmv2_encode_picture_header(s, picture_number);
        else if (s->h263_msmpeg4) 
F
Fabrice Bellard 已提交
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912
            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;
    }
2913 2914 2915 2916 2917 2918 2919 2920
    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;
2921 2922
    s->f_count=0;
    s->b_count=0;
2923 2924
    s->skip_count=0;

2925 2926 2927 2928 2929 2930 2931
    for(i=0; i<3; i++){
        /* init last dc values */
        /* note: quant matrix value (8) is implied here */
        s->last_dc[i] = 128;
        
        s->current_picture.error[i] = 0;
    }
F
Fabrice Bellard 已提交
2932 2933 2934 2935
    s->mb_incr = 1;
    s->last_mv[0][0][0] = 0;
    s->last_mv[0][0][1] = 0;

M
Michael Niedermayer 已提交
2936
    if (s->codec_id==CODEC_ID_H263 || s->codec_id==CODEC_ID_H263P)
2937
        s->gob_index = ff_h263_get_gob_height(s);
2938

2939
    if(s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame)
2940 2941 2942 2943
        ff_mpeg4_init_partitions(s);

    s->resync_mb_x=0;
    s->resync_mb_y=0;
2944
    s->first_slice_line = 1;
M
Michael Niedermayer 已提交
2945 2946
    s->ptr_lastgob = s->pb.buf;
    s->ptr_last_mb_line = s->pb.buf;
2947
    for(mb_y=0; mb_y < s->mb_height; mb_y++) {
M
Michael Niedermayer 已提交
2948 2949
        s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
        s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
2950
        
M
Michael Niedermayer 已提交
2951 2952 2953 2954 2955 2956
        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);
2957
        for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2958 2959
            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;
2960
//            int d;
2961
            int dmin=10000000;
2962 2963 2964

            s->mb_x = mb_x;
            s->mb_y = mb_y;
M
Michael Niedermayer 已提交
2965 2966 2967 2968 2969 2970
            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]++;
M
Michael Niedermayer 已提交
2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982

            /* write gob / video packet header  */
            if(s->rtp_mode){
                int current_packet_size, is_gob_start;
                
                current_packet_size= pbBufPtr(&s->pb) - s->ptr_lastgob;
                is_gob_start=0;
                
                if(s->codec_id==CODEC_ID_MPEG4){
                    if(current_packet_size + s->mb_line_avgsize/s->mb_width >= s->rtp_payload_size
                       && s->mb_y + s->mb_x>0){

2983
                        if(s->partitioned_frame){
2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994
                            ff_mpeg4_merge_partitions(s);
                            ff_mpeg4_init_partitions(s);
                        }
                        ff_mpeg4_encode_video_packet_header(s);

                        if(s->flags&CODEC_FLAG_PASS1){
                            int bits= get_bit_count(&s->pb);
                            s->misc_bits+= bits - s->last_bits;
                            s->last_bits= bits;
                        }
                        ff_mpeg4_clean_buffers(s);
M
Michael Niedermayer 已提交
2995
                        is_gob_start=1;
2996
                    }
M
Michael Niedermayer 已提交
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
                }else{
                    if(current_packet_size + s->mb_line_avgsize*s->gob_index >= s->rtp_payload_size
                       && s->mb_x==0 && s->mb_y>0 && s->mb_y%s->gob_index==0){
                       
                        h263_encode_gob_header(s, mb_y);                       
                        is_gob_start=1;
                    }
                }

                if(is_gob_start){
3007 3008 3009 3010 3011
                    s->ptr_lastgob = pbBufPtr(&s->pb);
                    s->first_slice_line=1;
                    s->resync_mb_x=mb_x;
                    s->resync_mb_y=mb_y;
                }
3012
            }
3013

3014 3015 3016
            if(  (s->resync_mb_x   == s->mb_x)
               && s->resync_mb_y+1 == s->mb_y){
                s->first_slice_line=0; 
3017 3018
            }

3019
            if(mb_type & (mb_type-1)){ // more than 1 MB type possible
3020
                int next_block=0;
3021
                int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
3022 3023

                copy_context_before_encode(&backup_s, s, -1);
3024 3025
                backup_s.pb= s->pb;
                best_s.data_partitioning= s->data_partitioning;
3026
                best_s.partitioned_frame= s->partitioned_frame;
3027 3028 3029 3030
                if(s->data_partitioning){
                    backup_s.pb2= s->pb2;
                    backup_s.tex_pb= s->tex_pb;
                }
3031

3032
                if(mb_type&MB_TYPE_INTER){
3033
                    s->mv_dir = MV_DIR_FORWARD;
M
Michael Niedermayer 已提交
3034
                    s->mv_type = MV_TYPE_16X16;
3035
                    s->mb_intra= 0;
3036 3037
                    s->mv[0][0][0] = s->p_mv_table[xy][0];
                    s->mv[0][0][1] = s->p_mv_table[xy][1];
3038 3039
                    encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_INTER, pb, pb2, tex_pb, 
                                 &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
F
Fabrice Bellard 已提交
3040
                }
3041
                if(mb_type&MB_TYPE_INTER4V){                 
3042
                    s->mv_dir = MV_DIR_FORWARD;
M
Michael Niedermayer 已提交
3043 3044 3045 3046 3047 3048
                    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];
                    }
3049 3050
                    encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_INTER4V, pb, pb2, tex_pb, 
                                 &dmin, &next_block, 0, 0);
3051 3052 3053 3054 3055 3056 3057
                }
                if(mb_type&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];
3058 3059
                    encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_FORWARD, pb, pb2, tex_pb, 
                                 &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
3060 3061 3062 3063 3064 3065 3066
                }
                if(mb_type&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];
3067 3068
                    encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_BACKWARD, pb, pb2, tex_pb, 
                                 &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
3069 3070 3071 3072 3073 3074 3075 3076 3077
                }
                if(mb_type&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];
3078 3079
                    encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_BIDIR, pb, pb2, tex_pb, 
                                 &dmin, &next_block, 0, 0);
3080 3081
                }
                if(mb_type&MB_TYPE_DIRECT){
M
Michael Niedermayer 已提交
3082 3083 3084
                    int mx= s->b_direct_mv_table[xy][0];
                    int my= s->b_direct_mv_table[xy][1];
                    
3085 3086
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
                    s->mb_intra= 0;
M
Michael Niedermayer 已提交
3087
                    ff_mpeg4_set_direct_mv(s, mx, my);
3088
                    encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_DIRECT, pb, pb2, tex_pb, 
M
Michael Niedermayer 已提交
3089
                                 &dmin, &next_block, mx, my);
M
Michael Niedermayer 已提交
3090
                }
3091
                if(mb_type&MB_TYPE_INTRA){
3092
                    s->mv_dir = MV_DIR_FORWARD;
M
Michael Niedermayer 已提交
3093
                    s->mv_type = MV_TYPE_16X16;
3094 3095 3096
                    s->mb_intra= 1;
                    s->mv[0][0][0] = 0;
                    s->mv[0][0][1] = 0;
3097 3098
                    encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_INTRA, pb, pb2, tex_pb, 
                                 &dmin, &next_block, 0, 0);
3099 3100 3101
                    /* 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 已提交
3102
                }
3103
                copy_context_after_encode(s, &best_s, -1);
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120
                
                pb_bits_count= get_bit_count(&s->pb);
                flush_put_bits(&s->pb);
                ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
                s->pb= backup_s.pb;
                
                if(s->data_partitioning){
                    pb2_bits_count= get_bit_count(&s->pb2);
                    flush_put_bits(&s->pb2);
                    ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
                    s->pb2= backup_s.pb2;
                    
                    tex_pb_bits_count= get_bit_count(&s->tex_pb);
                    flush_put_bits(&s->tex_pb);
                    ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
                    s->tex_pb= backup_s.tex_pb;
                }
3121
                s->last_bits= get_bit_count(&s->pb);
F
Fabrice Bellard 已提交
3122
            } else {
3123 3124
                int motion_x, motion_y;
                s->mv_type=MV_TYPE_16X16;
3125
                // only one MB-Type possible
3126 3127
                switch(mb_type){
                case MB_TYPE_INTRA:
3128
                    s->mv_dir = MV_DIR_FORWARD;
3129
                    s->mb_intra= 1;
3130 3131
                    motion_x= s->mv[0][0][0] = 0;
                    motion_y= s->mv[0][0][1] = 0;
3132 3133
                    break;
                case MB_TYPE_INTER:
3134 3135 3136 3137
                    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];
3138
                    break;
3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
                case MB_TYPE_INTER4V:
                    s->mv_dir = MV_DIR_FORWARD;
                    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];
                    }
                    motion_x= motion_y= 0;
                    break;
3149
                case MB_TYPE_DIRECT:
3150 3151
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
                    s->mb_intra= 0;
3152 3153
                    motion_x=s->b_direct_mv_table[xy][0];
                    motion_y=s->b_direct_mv_table[xy][1];
M
Michael Niedermayer 已提交
3154
                    ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
3155 3156
                    break;
                case MB_TYPE_BIDIR:
3157
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
3158
                    s->mb_intra= 0;
3159 3160 3161 3162 3163 3164
                    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];
3165 3166
                    break;
                case MB_TYPE_BACKWARD:
3167 3168 3169 3170
                    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];
3171 3172
                    break;
                case MB_TYPE_FORWARD:
3173 3174 3175 3176 3177
                    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);
3178 3179
                    break;
                default:
3180 3181
                    motion_x=motion_y=0; //gcc warning fix
                    printf("illegal MB type\n");
3182
                }
3183
                encode_mb(s, motion_x, motion_y);
F
Fabrice Bellard 已提交
3184
            }
3185 3186 3187 3188 3189
            /* 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 已提交
3190

3191
            MPV_decode_mb(s, s->block);
3192 3193 3194 3195 3196 3197 3198
            
            if(s->flags&CODEC_FLAG_PSNR){
                int w= 16;
                int h= 16;

                if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
                if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
M
Michael Niedermayer 已提交
3199

3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215
                s->current_picture.error[0] += sse(
                    s,
                    s->new_picture    .data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
                    s->current_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
                    w, h, s->linesize);
                s->current_picture.error[1] += sse(
                    s,
                    s->new_picture    .data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,
                    s->current_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,
                    w>>1, h>>1, s->uvlinesize);
                s->current_picture.error[2] += sse(
                    s,
                    s->new_picture    .data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,
                    s->current_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,
                    w>>1, h>>1, s->uvlinesize);
            }
3216
//printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_width, get_bit_count(&s->pb));
F
Fabrice Bellard 已提交
3217
        }
3218 3219


M
Michael Niedermayer 已提交
3220
        /* Obtain average mb_row size for RTP */
3221
        if (s->rtp_mode) {
M
Michael Niedermayer 已提交
3222
            if (mb_y==0)
3223
                s->mb_line_avgsize = pbBufPtr(&s->pb) - s->ptr_last_mb_line;
M
Michael Niedermayer 已提交
3224
            else {    
3225
                s->mb_line_avgsize = (s->mb_line_avgsize + pbBufPtr(&s->pb) - s->ptr_last_mb_line) >> 1;
3226
            }
M
Michael Niedermayer 已提交
3227
            s->ptr_last_mb_line = pbBufPtr(&s->pb);
3228
        }
F
Fabrice Bellard 已提交
3229
    }
3230
    emms_c();
3231

3232
    if(s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame)
3233 3234 3235
        ff_mpeg4_merge_partitions(s);

    if (s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == I_TYPE)
M
Michael Niedermayer 已提交
3236 3237
        msmpeg4_encode_ext_header(s);

3238 3239 3240
    if(s->codec_id==CODEC_ID_MPEG4) 
        ff_mpeg4_stuffing(&s->pb);

3241 3242
    //if (s->gob_number)
    //    fprintf(stderr,"\nNumber of GOB: %d", s->gob_number);
3243 3244 3245 3246
    
    /* Send the last GOB if RTP */    
    if (s->rtp_mode) {
        flush_put_bits(&s->pb);
3247
        pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
3248 3249 3250
        /* Call the RTP callback to send the last GOB */
        if (s->rtp_callback)
            s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
3251
        s->ptr_lastgob = pbBufPtr(&s->pb);
3252 3253
        //fprintf(stderr,"\nGOB: %2d size: %d (last)", s->gob_number, pdif);
    }
F
Fabrice Bellard 已提交
3254 3255
}

M
Michael Niedermayer 已提交
3256
static int dct_quantize_c(MpegEncContext *s, 
F
Fabrice Bellard 已提交
3257
                        DCTELEM *block, int n,
3258
                        int qscale, int *overflow)
F
Fabrice Bellard 已提交
3259 3260 3261
{
    int i, j, level, last_non_zero, q;
    const int *qmat;
M
Michael Niedermayer 已提交
3262
    const UINT8 *scantable= s->intra_scantable.scantable;
3263 3264 3265
    int bias;
    int max=0;
    unsigned int threshold1, threshold2;
3266

3267
    s->fdct (block);
F
Fabrice Bellard 已提交
3268 3269

    if (s->mb_intra) {
3270 3271 3272 3273 3274 3275 3276 3277 3278 3279
        if (!s->h263_aic) {
            if (n < 4)
                q = s->y_dc_scale;
            else
                q = s->c_dc_scale;
            q = q << 3;
        } else
            /* For AIC we skip quant/dequant of INTRADC */
            q = 1 << 3;
            
F
Fabrice Bellard 已提交
3280 3281 3282 3283
        /* note: block[0] is assumed to be positive */
        block[0] = (block[0] + (q >> 1)) / q;
        i = 1;
        last_non_zero = 0;
3284
        qmat = s->q_intra_matrix[qscale];
M
Michael Niedermayer 已提交
3285
        bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
F
Fabrice Bellard 已提交
3286 3287 3288
    } else {
        i = 0;
        last_non_zero = -1;
3289
        qmat = s->q_inter_matrix[qscale];
M
Michael Niedermayer 已提交
3290
        bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
F
Fabrice Bellard 已提交
3291
    }
M
Michael Niedermayer 已提交
3292 3293
    threshold1= (1<<QMAT_SHIFT) - bias - 1;
    threshold2= (threshold1<<1);
F
Fabrice Bellard 已提交
3294 3295

    for(;i<64;i++) {
M
Michael Niedermayer 已提交
3296
        j = scantable[i];
F
Fabrice Bellard 已提交
3297 3298 3299
        level = block[j];
        level = level * qmat[j];

3300 3301 3302 3303
//        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
//           || bias-level >= (1<<(QMAT_SHIFT - 3))){
        if(((unsigned)(level+threshold1))>threshold2){
            if(level>0){
M
Michael Niedermayer 已提交
3304
                level= (bias + level)>>QMAT_SHIFT;
3305 3306
                block[j]= level;
            }else{
M
Michael Niedermayer 已提交
3307
                level= (bias - level)>>QMAT_SHIFT;
3308 3309 3310
                block[j]= -level;
            }
            max |=level;
F
Fabrice Bellard 已提交
3311
            last_non_zero = i;
3312 3313
        }else{
            block[j]=0;
F
Fabrice Bellard 已提交
3314 3315
        }
    }
3316 3317
    *overflow= s->max_qcoeff < max; //overflow might have happend
    
M
Michael Niedermayer 已提交
3318
    /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
3319 3320
    if (s->idct_permutation_type != FF_NO_IDCT_PERM)
	ff_block_permute(block, s->idct_permutation, scantable, last_non_zero);
M
Michael Niedermayer 已提交
3321

F
Fabrice Bellard 已提交
3322 3323 3324
    return last_non_zero;
}

3325 3326
static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
                                   DCTELEM *block, int n, int qscale)
F
Fabrice Bellard 已提交
3327
{
M
Michael Niedermayer 已提交
3328
    int i, level, nCoeffs;
F
Fabrice Bellard 已提交
3329 3330
    const UINT16 *quant_matrix;

3331
    nCoeffs= s->block_last_index[n];
M
Michael Niedermayer 已提交
3332
    
F
Fabrice Bellard 已提交
3333 3334 3335 3336 3337 3338 3339
    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;
3340 3341
        for(i=1;i<=nCoeffs;i++) {
            int j= s->intra_scantable.permutated[i];
M
Michael Niedermayer 已提交
3342
            level = block[j];
F
Fabrice Bellard 已提交
3343 3344 3345
            if (level) {
                if (level < 0) {
                    level = -level;
M
Michael Niedermayer 已提交
3346
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
F
Fabrice Bellard 已提交
3347 3348 3349
                    level = (level - 1) | 1;
                    level = -level;
                } else {
M
Michael Niedermayer 已提交
3350
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
F
Fabrice Bellard 已提交
3351 3352 3353 3354 3355 3356
                    level = (level - 1) | 1;
                }
#ifdef PARANOID
                if (level < -2048 || level > 2047)
                    fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
M
Michael Niedermayer 已提交
3357
                block[j] = level;
F
Fabrice Bellard 已提交
3358 3359 3360 3361
            }
        }
    } else {
        i = 0;
3362
        quant_matrix = s->inter_matrix;
3363 3364
        for(;i<=nCoeffs;i++) {
            int j= s->intra_scantable.permutated[i];
M
Michael Niedermayer 已提交
3365
            level = block[j];
F
Fabrice Bellard 已提交
3366 3367 3368 3369
            if (level) {
                if (level < 0) {
                    level = -level;
                    level = (((level << 1) + 1) * qscale *
M
Michael Niedermayer 已提交
3370
                             ((int) (quant_matrix[j]))) >> 4;
F
Fabrice Bellard 已提交
3371 3372 3373 3374
                    level = (level - 1) | 1;
                    level = -level;
                } else {
                    level = (((level << 1) + 1) * qscale *
M
Michael Niedermayer 已提交
3375
                             ((int) (quant_matrix[j]))) >> 4;
F
Fabrice Bellard 已提交
3376 3377 3378 3379 3380 3381
                    level = (level - 1) | 1;
                }
#ifdef PARANOID
                if (level < -2048 || level > 2047)
                    fprintf(stderr, "unquant error %d %d\n", i, level);
#endif
M
Michael Niedermayer 已提交
3382
                block[j] = level;
F
Fabrice Bellard 已提交
3383 3384 3385 3386
            }
        }
    }
}
3387

3388 3389 3390 3391 3392 3393
static void dct_unquantize_mpeg2_c(MpegEncContext *s, 
                                   DCTELEM *block, int n, int qscale)
{
    int i, level, nCoeffs;
    const UINT16 *quant_matrix;

3394 3395
    if(s->alternate_scan) nCoeffs= 63;
    else nCoeffs= s->block_last_index[n];
3396 3397 3398 3399 3400 3401 3402
    
    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;
3403 3404
        for(i=1;i<=nCoeffs;i++) {
            int j= s->intra_scantable.permutated[i];
3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423
            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;
3424
        quant_matrix = s->inter_matrix;
3425 3426
        for(;i<=nCoeffs;i++) {
            int j= s->intra_scantable.permutated[i];
3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450
            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;
    }
}


3451 3452 3453 3454
static void dct_unquantize_h263_c(MpegEncContext *s, 
                                  DCTELEM *block, int n, int qscale)
{
    int i, level, qmul, qadd;
M
Michael Niedermayer 已提交
3455
    int nCoeffs;
3456
    
3457 3458 3459 3460 3461
    assert(s->block_last_index[n]>=0);
    
    qadd = (qscale - 1) | 1;
    qmul = qscale << 1;
    
3462
    if (s->mb_intra) {
3463 3464 3465 3466 3467
        if (!s->h263_aic) {
            if (n < 4) 
                block[0] = block[0] * s->y_dc_scale;
            else
                block[0] = block[0] * s->c_dc_scale;
3468 3469
        }else
            qadd = 0;
3470
        i = 1;
3471
        nCoeffs= 63; //does not allways use zigzag table 
3472 3473
    } else {
        i = 0;
3474
        nCoeffs= s->intra_scantable.raster_end[ s->block_last_index[n] ];
3475 3476
    }

3477
    for(;i<=nCoeffs;i++) {
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
        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 已提交
3493

M
Michael Niedermayer 已提交
3494 3495 3496 3497 3498 3499
char ff_get_pict_type_char(int pict_type){
    switch(pict_type){
    case I_TYPE: return 'I'; 
    case P_TYPE: return 'P'; 
    case B_TYPE: return 'B'; 
    case S_TYPE: return 'S'; 
M
Michael Niedermayer 已提交
3500
    default:     return '?';
M
Michael Niedermayer 已提交
3501 3502 3503
    }
}

F
Fabrice Bellard 已提交
3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553
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 已提交
3554 3555
AVCodec mpeg4_encoder = {
    "mpeg4",
F
Fabrice Bellard 已提交
3556
    CODEC_TYPE_VIDEO,
F
Fabrice Bellard 已提交
3557
    CODEC_ID_MPEG4,
F
Fabrice Bellard 已提交
3558 3559 3560 3561 3562 3563
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};

3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584
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 已提交
3585 3586
    "msmpeg4",
    CODEC_TYPE_VIDEO,
3587
    CODEC_ID_MSMPEG4V3,
F
Fabrice Bellard 已提交
3588 3589 3590 3591 3592
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};
M
Michael Niedermayer 已提交
3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603

AVCodec wmv1_encoder = {
    "wmv1",
    CODEC_TYPE_VIDEO,
    CODEC_ID_WMV1,
    sizeof(MpegEncContext),
    MPV_encode_init,
    MPV_encode_picture,
    MPV_encode_end,
};