Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegvideo.c @ bb71e317

History | View | Annotate | Download (78.4 KB)

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

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

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

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

    
46
#define EDGE_WIDTH 16
47

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

    
51
//#define DEBUG
52

    
53

    
54
/* for jpeg fast DCT */
55
#define CONST_BITS 14
56

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

    
69
static UINT8 h263_chroma_roundtab[16] = {
70
    0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
71
};
72

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

    
76
extern UINT8 zigzag_end[64];
77

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

    
81
static void convert_matrix(int (*qmat)[64], uint16_t (*qmat16)[64], uint16_t (*qmat16_bias)[64],
82
                           const UINT16 *quant_matrix, int bias)
83
{
84
    int qscale;
85

    
86
    for(qscale=1; qscale<32; qscale++){
87
        int i;
88
        if (av_fdct == jpeg_fdct_ifast) {
89
            for(i=0;i<64;i++) {
90
                const int j= block_permute_op(i);
91
                /* 16 <= qscale * quant_matrix[i] <= 7905 */
92
                /* 19952         <= aanscales[i] * qscale * quant_matrix[i]           <= 249205026 */
93
                /* (1<<36)/19952 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
94
                /* 3444240       >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= 275 */
95
                
96
                qmat[qscale][j] = (int)((UINT64_C(1) << (QMAT_SHIFT + 11)) / 
97
                                (aanscales[i] * qscale * quant_matrix[j]));
98
            }
99
        } else {
100
            for(i=0;i<64;i++) {
101
                /* We can safely suppose that 16 <= quant_matrix[i] <= 255
102
                   So 16           <= qscale * quant_matrix[i]             <= 7905
103
                   so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
104
                   so 32768        >= (1<<19) / (qscale * quant_matrix[i]) >= 67
105
                */
106
                qmat  [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
107
                qmat16[qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[block_permute_op(i)]);
108

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

    
111
                qmat16_bias[qscale][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][i]);
112
            }
113
        }
114
    }
115
}
116

    
117
/* init common structure for both encoder and decoder */
118
int MPV_common_init(MpegEncContext *s)
119
{
120
    int c_size, i;
121
    UINT8 *pict;
122

    
123
    s->dct_unquantize_h263 = dct_unquantize_h263_c;
124
    s->dct_unquantize_mpeg1 = dct_unquantize_mpeg1_c;
125
    s->dct_unquantize_mpeg2 = dct_unquantize_mpeg2_c;
126
        
127
#ifdef HAVE_MMX
128
    MPV_common_init_mmx(s);
129
#endif
130
    //setup default unquantizers (mpeg4 might change it later)
131
    if(s->out_format == FMT_H263)
132
        s->dct_unquantize = s->dct_unquantize_h263;
133
    else
134
        s->dct_unquantize = s->dct_unquantize_mpeg1;
135
    
136
    s->mb_width = (s->width + 15) / 16;
137
    s->mb_height = (s->height + 15) / 16;
138
    s->mb_num = s->mb_width * s->mb_height;
139
    s->linesize = s->mb_width * 16 + 2 * EDGE_WIDTH;
140

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

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

    
150
        pict = av_mallocz(c_size);
151
        if (pict == NULL)
152
            goto fail;
153
        s->last_picture_base[i] = pict;
154
        s->last_picture[i] = pict + pict_start;
155
    
156
        pict = av_mallocz(c_size);
157
        if (pict == NULL)
158
            goto fail;
159
        s->next_picture_base[i] = pict;
160
        s->next_picture[i] = pict + pict_start;
161
        
162
        if (s->has_b_frames) {
163
            pict = av_mallocz(c_size);
164
            if (pict == NULL) 
165
                goto fail;
166
            s->aux_picture_base[i] = pict;
167
            s->aux_picture[i] = pict + pict_start;
168
        }
169
    }
170
    
171
    if (s->encoding) {
172
        int j;
173
        int mv_table_size= (s->mb_width+2)*(s->mb_height+2);
174

    
175
        /* Allocate MB type table */
176
        s->mb_type = av_mallocz(s->mb_num * sizeof(char));
177
        if (s->mb_type == NULL) {
178
            perror("malloc");
179
            goto fail;
180
        }
181
        
182
        s->mb_var = av_mallocz(s->mb_num * sizeof(INT16));
183
        if (s->mb_var == NULL) {
184
            perror("malloc");
185
            goto fail;
186
        }
187

    
188
        /* Allocate MV tables */
189
        s->p_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
190
        if (s->p_mv_table == NULL) {
191
            perror("malloc");
192
            goto fail;
193
        }
194
        s->last_p_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
195
        if (s->last_p_mv_table == NULL) {
196
            perror("malloc");
197
            goto fail;
198
        }
199
        s->b_forw_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
200
        if (s->b_forw_mv_table == NULL) {
201
            perror("malloc");
202
            goto fail;
203
        }
204
        s->b_back_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
205
        if (s->b_back_mv_table == NULL) {
206
            perror("malloc");
207
            goto fail;
208
        }
209
        s->b_bidir_forw_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
210
        if (s->b_bidir_forw_mv_table == NULL) {
211
            perror("malloc");
212
            goto fail;
213
        }
214
        s->b_bidir_back_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
215
        if (s->b_bidir_back_mv_table == NULL) {
216
            perror("malloc");
217
            goto fail;
218
        }
219
        s->b_direct_forw_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
220
        if (s->b_direct_forw_mv_table == NULL) {
221
            perror("malloc");
222
            goto fail;
223
        }
224
        s->b_direct_back_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
225
        if (s->b_direct_back_mv_table == NULL) {
226
            perror("malloc");
227
            goto fail;
228
        }
229
        s->b_direct_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));
230
        if (s->b_direct_mv_table == NULL) {
231
            perror("malloc");
232
            goto fail;
233
        }
234

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

    
241
        if(s->max_b_frames){
242
            for(j=0; j<REORDER_BUFFER_SIZE; j++){
243
                int i;
244
                for(i=0;i<3;i++) {
245
                    int w, h, shift;
246

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

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

    
271
    if (s->h263_pred || s->h263_plus) {
272
        int y_size, c_size, i, size;
273
        
274
        /* dc values */
275

    
276
        y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
277
        c_size = (s->mb_width + 2) * (s->mb_height + 2);
278
        size = y_size + 2 * c_size;
279
        s->dc_val[0] = malloc(size * sizeof(INT16));
280
        if (s->dc_val[0] == NULL)
281
            goto fail;
282
        s->dc_val[1] = s->dc_val[0] + y_size;
283
        s->dc_val[2] = s->dc_val[1] + c_size;
284
        for(i=0;i<size;i++)
285
            s->dc_val[0][i] = 1024;
286

    
287
        /* ac values */
288
        s->ac_val[0] = av_mallocz(size * sizeof(INT16) * 16);
289
        if (s->ac_val[0] == NULL)
290
            goto fail;
291
        s->ac_val[1] = s->ac_val[0] + y_size;
292
        s->ac_val[2] = s->ac_val[1] + c_size;
293
        
294
        /* cbp values */
295
        s->coded_block = av_mallocz(y_size);
296
        if (!s->coded_block)
297
            goto fail;
298

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

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

    
320
    s->context_initialized = 1;
321
    return 0;
322
 fail:
323
    MPV_common_end(s);
324
    return -1;
325
}
326

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

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

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

    
356
    CHECK_FREE(s->mbskip_table);
357
    CHECK_FREE(s->bitstream_buffer);
358
    for(i=0;i<3;i++) {
359
        int j;
360
        CHECK_FREE(s->last_picture_base[i]);
361
        CHECK_FREE(s->next_picture_base[i]);
362
        CHECK_FREE(s->aux_picture_base[i]);
363
        for(j=0; j<REORDER_BUFFER_SIZE; j++){
364
            CHECK_FREE(s->picture_buffer[j][i]);
365
        }
366
    }
367
    s->context_initialized = 0;
368
}
369

    
370
/* init video encoder */
371
int MPV_encode_init(AVCodecContext *avctx)
372
{
373
    MpegEncContext *s = avctx->priv_data;
374
    int i;
375

    
376
    avctx->pix_fmt = PIX_FMT_YUV420P;
377

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

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

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

    
512
            for(i=-16; i<16; i++){
513
                default_fcode_tab[i + MAX_MV]= 1;
514
            }
515
        }
516
    }
517
    s->mv_penalty= default_mv_penalty;
518
    s->fcode_tab= default_fcode_tab;
519

    
520
    if (s->out_format == FMT_H263)
521
        h263_encode_init(s);
522
    else if (s->out_format == FMT_MPEG1)
523
        mpeg1_encode_init(s);
524

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

    
528
    s->encoding = 1;
529

    
530
    /* init */
531
    if (MPV_common_init(s) < 0)
532
        return -1;
533
    
534
    /* init default q matrix */
535
    for(i=0;i<64;i++) {
536
        if(s->out_format == FMT_H263)
537
            s->intra_matrix[i] = default_non_intra_matrix[i];
538
        else
539
            s->intra_matrix[i] = default_intra_matrix[i];
540

    
541
        s->inter_matrix[i] = default_non_intra_matrix[i];
542
    }
543

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

    
553
    if(ff_rate_control_init(s) < 0)
554
        return -1;
555

    
556
    s->picture_number = 0;
557
    s->picture_in_gop_number = 0;
558
    s->fake_picture_number = 0;
559
    /* motion detector init */
560
    s->f_code = 1;
561
    s->b_code = 1;
562

    
563
    return 0;
564
}
565

    
566
int MPV_encode_end(AVCodecContext *avctx)
567
{
568
    MpegEncContext *s = avctx->priv_data;
569

    
570
#ifdef STATS
571
    print_stats();
572
#endif
573

    
574
    ff_rate_control_uninit(s);
575

    
576
    MPV_common_end(s);
577
    if (s->out_format == FMT_MJPEG)
578
        mjpeg_close(s);
579
      
580
    return 0;
581
}
582

    
583
/* draw the edges of width 'w' of an image of size width, height */
584
static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w)
585
{
586
    UINT8 *ptr, *last_line;
587
    int i;
588

    
589
    last_line = buf + (height - 1) * wrap;
590
    for(i=0;i<w;i++) {
591
        /* top and bottom */
592
        memcpy(buf - (i + 1) * wrap, buf, width);
593
        memcpy(last_line + (i + 1) * wrap, last_line, width);
594
    }
595
    /* left and right */
596
    ptr = buf;
597
    for(i=0;i<height;i++) {
598
        memset(ptr - w, ptr[0], w);
599
        memset(ptr + width, ptr[width-1], w);
600
        ptr += wrap;
601
    }
602
    /* corners */
603
    for(i=0;i<w;i++) {
604
        memset(buf - (i + 1) * wrap - w, buf[0], w); /* top left */
605
        memset(buf - (i + 1) * wrap + width, buf[width-1], w); /* top right */
606
        memset(last_line + (i + 1) * wrap - w, last_line[0], w); /* top left */
607
        memset(last_line + (i + 1) * wrap + width, last_line[width-1], w); /* top right */
608
    }
609
}
610

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

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

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

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

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

    
669
    for(j=0; j<REORDER_BUFFER_SIZE-1; j++){
670
        s->coded_order[j]= s->coded_order[j+1];
671
    }
672
    s->coded_order[j].picture[0]= s->coded_order[j].picture[1]= s->coded_order[j].picture[2]= NULL; //catch uninitalized buffers
673
    s->coded_order[j].pict_type=0;
674

    
675
    switch(s->input_pict_type){
676
    default: 
677
    case I_TYPE:
678
    case S_TYPE:
679
    case P_TYPE:
680
        index= s->max_b_frames - s->b_frames_since_non_b;
681
        s->b_frames_since_non_b=0;
682
        break;            
683
    case B_TYPE:
684
        index= s->max_b_frames + 1;
685
        s->b_frames_since_non_b++;
686
        break;          
687
    }
688
//printf("index:%d type:%d strides: %d %d\n", index, s->input_pict_type, pict->linesize[0], s->linesize);
689
    if(   (index==0 || (s->flags&CODEC_FLAG_INPUT_PRESERVED))
690
       && pict->linesize[0] == s->linesize
691
       && pict->linesize[1] == s->linesize>>1
692
       && pict->linesize[2] == s->linesize>>1){
693
//printf("ptr\n");
694
        for(i=0; i<3; i++){
695
            s->coded_order[index].picture[i]= pict->data[i];
696
        }
697
    }else{
698
//printf("copy\n");
699
        for(i=0; i<3; i++){
700
            uint8_t *src = pict->data[i];
701
            uint8_t *dest;
702
            int src_wrap = pict->linesize[i];
703
            int dest_wrap = s->linesize;
704
            int w = s->width;
705
            int h = s->height;
706

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

    
710
            if (i >= 1) {
711
                dest_wrap >>= 1;
712
                w >>= 1;
713
                h >>= 1;
714
            }
715

    
716
            s->coded_order[index].picture[i]= dest;
717
            for(j=0;j<h;j++) {
718
                memcpy(dest, src, w);
719
                dest += dest_wrap;
720
                src += src_wrap;
721
            }
722
        }
723
        if(index!=0){
724
            s->picture_buffer_index++;
725
            if(s->picture_buffer_index >= REORDER_BUFFER_SIZE-1) s->picture_buffer_index=0;
726
        }
727
    }
728
    s->coded_order[index].pict_type = s->input_pict_type;
729
    s->coded_order[index].qscale    = s->input_qscale;
730
    s->coded_order[index].force_type= s->force_input_type;
731
    s->coded_order[index].picture_in_gop_number= s->input_picture_in_gop_number;
732
    s->coded_order[index].picture_number= s->input_picture_number;
733

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

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

    
745
    s->input_qscale = avctx->quality;
746

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

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

    
774
    if(s->input_pict_type==I_TYPE)
775
        s->input_picture_in_gop_number=0;
776
    
777
    reorder_input(s, pict);
778
    
779
    /* output? */
780
    if(s->coded_order[0].picture[0]){
781

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

    
789
        MPV_frame_start(s);
790

    
791
        encode_picture(s, s->picture_number);
792
        avctx->key_frame = (s->pict_type == I_TYPE);
793
        avctx->header_bits = s->header_bits;
794
        avctx->mv_bits     = s->mv_bits;
795
        avctx->misc_bits   = s->misc_bits;
796
        avctx->i_tex_bits  = s->i_tex_bits;
797
        avctx->p_tex_bits  = s->p_tex_bits;
798
        avctx->i_count     = s->i_count;
799
        avctx->p_count     = s->p_count;
800
        avctx->skip_count  = s->skip_count;
801

    
802
        MPV_frame_end(s);
803

    
804
        if (s->out_format == FMT_MJPEG)
805
            mjpeg_picture_trailer(s);
806

    
807
        avctx->quality = s->qscale;
808
        
809
        if(s->flags&CODEC_FLAG_PASS1)
810
            ff_write_pass1_stats(s);
811
    }
812

    
813
    s->input_picture_number++;
814
    s->input_picture_in_gop_number++;
815

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

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

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

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

    
846
    if(s->real_sprite_warping_points>1) printf("more than 1 warp point isnt supported\n");
847
    motion_x= s->sprite_offset[0][0];
848
    motion_y= s->sprite_offset[0][1];
849
    src_x = s->mb_x * 16 + (motion_x >> (s->sprite_warping_accuracy+1));
850
    src_y = s->mb_y * 16 + (motion_y >> (s->sprite_warping_accuracy+1));
851
    motion_x<<=(3-s->sprite_warping_accuracy);
852
    motion_y<<=(3-s->sprite_warping_accuracy);
853
    src_x = clip(src_x, -16, s->width);
854
    if (src_x == s->width)
855
        motion_x =0;
856
    src_y = clip(src_y, -16, s->height);
857
    if (src_y == s->height)
858
        motion_y =0;
859
    
860
    linesize = s->linesize;
861
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
862

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

    
867
    motion_x= s->sprite_offset[1][0];
868
    motion_y= s->sprite_offset[1][1];
869
    src_x = s->mb_x * 8 + (motion_x >> (s->sprite_warping_accuracy+1));
870
    src_y = s->mb_y * 8 + (motion_y >> (s->sprite_warping_accuracy+1));
871
    motion_x<<=(3-s->sprite_warping_accuracy);
872
    motion_y<<=(3-s->sprite_warping_accuracy);
873
    src_x = clip(src_x, -8, s->width>>1);
874
    if (src_x == s->width>>1)
875
        motion_x =0;
876
    src_y = clip(src_y, -8, s->height>>1);
877
    if (src_y == s->height>>1)
878
        motion_y =0;
879

    
880
    offset = (src_y * linesize>>1) + src_x + (src_offset>>1);
881
    ptr = ref_picture[1] + offset;
882
    gmc1(dest_cb + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
883
    ptr = ref_picture[2] + offset;
884
    gmc1(dest_cr + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
885
    
886
    return;
887
}
888

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

    
905
    dxy = ((motion_y & 1) << 1) | (motion_x & 1);
906
    src_x = s->mb_x * 16 + (motion_x >> 1);
907
    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 1);
908
                
909
    /* WARNING: do no forget half pels */
910
    height = s->height >> field_based;
911
    src_x = clip(src_x, -16, s->width);
912
    if (src_x == s->width)
913
        dxy &= ~1;
914
    src_y = clip(src_y, -16, height);
915
    if (src_y == height)
916
        dxy &= ~2;
917
    linesize = s->linesize << field_based;
918
    ptr = ref_picture[0] + (src_y * linesize) + (src_x) + src_offset;
919
    dest_y += dest_offset;
920
    pix_op[dxy](dest_y, ptr, linesize, h);
921
    pix_op[dxy](dest_y + 8, ptr + 8, linesize, h);
922

    
923
    if (s->out_format == FMT_H263) {
924
        dxy = 0;
925
        if ((motion_x & 3) != 0)
926
            dxy |= 1;
927
        if ((motion_y & 3) != 0)
928
            dxy |= 2;
929
        mx = motion_x >> 2;
930
        my = motion_y >> 2;
931
    } else {
932
        mx = motion_x / 2;
933
        my = motion_y / 2;
934
        dxy = ((my & 1) << 1) | (mx & 1);
935
        mx >>= 1;
936
        my >>= 1;
937
    }
938
    
939
    src_x = s->mb_x * 8 + mx;
940
    src_y = s->mb_y * (8 >> field_based) + my;
941
    src_x = clip(src_x, -8, s->width >> 1);
942
    if (src_x == (s->width >> 1))
943
        dxy &= ~1;
944
    src_y = clip(src_y, -8, height >> 1);
945
    if (src_y == (height >> 1))
946
        dxy &= ~2;
947

    
948
    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
949
    ptr = ref_picture[1] + offset;
950
    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
951
    ptr = ref_picture[2] + offset;
952
    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
953
}
954

    
955
static inline void qpel_motion(MpegEncContext *s,
956
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
957
                               int dest_offset,
958
                               UINT8 **ref_picture, int src_offset,
959
                               int field_based, op_pixels_func *pix_op,
960
                               qpel_mc_func *qpix_op,
961
                               int motion_x, int motion_y, int h)
962
{
963
    UINT8 *ptr;
964
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
965

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

    
970
    height = s->height >> field_based;
971
    src_x = clip(src_x, -16, s->width);
972
    if (src_x == s->width)
973
        dxy &= ~3;
974
    src_y = clip(src_y, -16, height);
975
    if (src_y == height)
976
        dxy &= ~12;
977
    linesize = s->linesize << field_based;
978
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
979
    dest_y += dest_offset;
980
//printf("%d %d %d\n", src_x, src_y, dxy);
981
    qpix_op[dxy](dest_y                 , ptr                 , linesize, linesize, motion_x&3, motion_y&3);
982
    qpix_op[dxy](dest_y              + 8, ptr              + 8, linesize, linesize, motion_x&3, motion_y&3);
983
    qpix_op[dxy](dest_y + linesize*8    , ptr + linesize*8    , linesize, linesize, motion_x&3, motion_y&3);
984
    qpix_op[dxy](dest_y + linesize*8 + 8, ptr + linesize*8 + 8, linesize, linesize, motion_x&3, motion_y&3);
985
    
986
    mx= (motion_x>>1) | (motion_x&1);
987
    my= (motion_y>>1) | (motion_y&1);
988

    
989
    dxy = 0;
990
    if ((mx & 3) != 0)
991
        dxy |= 1;
992
    if ((my & 3) != 0)
993
        dxy |= 2;
994
    mx = mx >> 2;
995
    my = my >> 2;
996
    
997
    src_x = s->mb_x * 8 + mx;
998
    src_y = s->mb_y * (8 >> field_based) + my;
999
    src_x = clip(src_x, -8, s->width >> 1);
1000
    if (src_x == (s->width >> 1))
1001
        dxy &= ~1;
1002
    src_y = clip(src_y, -8, height >> 1);
1003
    if (src_y == (height >> 1))
1004
        dxy &= ~2;
1005

    
1006
    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
1007
    ptr = ref_picture[1] + offset;
1008
    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
1009
    ptr = ref_picture[2] + offset;
1010
    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
1011
}
1012

    
1013

    
1014
static inline void MPV_motion(MpegEncContext *s, 
1015
                              UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
1016
                              int dir, UINT8 **ref_picture, 
1017
                              op_pixels_func *pix_op, qpel_mc_func *qpix_op)
1018
{
1019
    int dxy, offset, mx, my, src_x, src_y, motion_x, motion_y;
1020
    int mb_x, mb_y, i;
1021
    UINT8 *ptr, *dest;
1022

    
1023
    mb_x = s->mb_x;
1024
    mb_y = s->mb_y;
1025

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

    
1058
            dxy = ((motion_y & 1) << 1) | (motion_x & 1);
1059
            src_x = mb_x * 16 + (motion_x >> 1) + (i & 1) * 8;
1060
            src_y = mb_y * 16 + (motion_y >> 1) + (i >>1) * 8;
1061
                    
1062
            /* WARNING: do no forget half pels */
1063
            src_x = clip(src_x, -16, s->width);
1064
            if (src_x == s->width)
1065
                dxy &= ~1;
1066
            src_y = clip(src_y, -16, s->height);
1067
            if (src_y == s->height)
1068
                dxy &= ~2;
1069
                    
1070
            ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
1071
            dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
1072
            pix_op[dxy](dest, ptr, s->linesize, 8);
1073
        }
1074
        /* In case of 8X8, we construct a single chroma motion vector
1075
           with a special rounding */
1076
        mx = 0;
1077
        my = 0;
1078
        for(i=0;i<4;i++) {
1079
            mx += s->mv[dir][i][0];
1080
            my += s->mv[dir][i][1];
1081
        }
1082
        if (mx >= 0)
1083
            mx = (h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
1084
        else {
1085
            mx = -mx;
1086
            mx = -(h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
1087
        }
1088
        if (my >= 0)
1089
            my = (h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
1090
        else {
1091
            my = -my;
1092
            my = -(h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
1093
        }
1094
        dxy = ((my & 1) << 1) | (mx & 1);
1095
        mx >>= 1;
1096
        my >>= 1;
1097

    
1098
        src_x = mb_x * 8 + mx;
1099
        src_y = mb_y * 8 + my;
1100
        src_x = clip(src_x, -8, s->width/2);
1101
        if (src_x == s->width/2)
1102
            dxy &= ~1;
1103
        src_y = clip(src_y, -8, s->height/2);
1104
        if (src_y == s->height/2)
1105
            dxy &= ~2;
1106
        
1107
        offset = (src_y * (s->linesize >> 1)) + src_x;
1108
        ptr = ref_picture[1] + offset;
1109
        pix_op[dxy](dest_cb, ptr, s->linesize >> 1, 8);
1110
        ptr = ref_picture[2] + offset;
1111
        pix_op[dxy](dest_cr, ptr, s->linesize >> 1, 8);
1112
        break;
1113
    case MV_TYPE_FIELD:
1114
        if (s->picture_structure == PICT_FRAME) {
1115
            /* top field */
1116
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
1117
                        ref_picture, s->field_select[dir][0] ? s->linesize : 0,
1118
                        1, pix_op,
1119
                        s->mv[dir][0][0], s->mv[dir][0][1], 8);
1120
            /* bottom field */
1121
            mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
1122
                        ref_picture, s->field_select[dir][1] ? s->linesize : 0,
1123
                        1, pix_op,
1124
                        s->mv[dir][1][0], s->mv[dir][1][1], 8);
1125
        } else {
1126
            
1127

    
1128
        }
1129
        break;
1130
    }
1131
}
1132

    
1133

    
1134
/* put block[] to dest[] */
1135
static inline void put_dct(MpegEncContext *s, 
1136
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
1137
{
1138
    if (!s->mpeg2)
1139
        s->dct_unquantize(s, block, i, s->qscale);
1140
    ff_idct (block);
1141
    put_pixels_clamped(block, dest, line_size);
1142
}
1143

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

    
1151
    if (s->block_last_index[i] >= 0) {
1152
        if (!s->mpeg2)
1153
            if(s->encoding || (!s->h263_msmpeg4))
1154
                s->dct_unquantize(s, block, i, s->qscale);
1155

    
1156
        ff_idct (block);
1157
        add_pixels_clamped(block, dest, line_size);
1158
    }
1159
}
1160

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

1164
   Important variables used:
1165
   s->mb_intra : true if intra macroblock
1166
   s->mv_dir   : motion vector direction
1167
   s->mv_type  : motion vector type
1168
   s->mv       : motion vector
1169
   s->interlaced_dct : true if interlaced dct used (mpeg2)
1170
 */
1171
void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
1172
{
1173
    int mb_x, mb_y;
1174
    int dct_linesize, dct_offset;
1175
    op_pixels_func *op_pix;
1176
    qpel_mc_func *op_qpix;
1177

    
1178
    mb_x = s->mb_x;
1179
    mb_y = s->mb_y;
1180

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

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

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

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

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

    
1282
        if (s->interlaced_dct) {
1283
            dct_linesize = s->linesize * 2;
1284
            dct_offset = s->linesize;
1285
        } else {
1286
            dct_linesize = s->linesize;
1287
            dct_offset = s->linesize * 8;
1288
        }
1289

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

    
1301
                if (s->mv_dir & MV_DIR_FORWARD) {
1302
                    MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
1303
                    if ((!s->no_rounding) || s->pict_type==B_TYPE)
1304
                        op_pix = avg_pixels_tab;
1305
                    else
1306
                        op_pix = avg_no_rnd_pixels_tab;
1307
                }
1308
                if (s->mv_dir & MV_DIR_BACKWARD) {
1309
                    MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
1310
                }
1311
            }
1312

    
1313
            /* add dct residue */
1314
            add_dct(s, block[0], 0, dest_y, dct_linesize);
1315
            add_dct(s, block[1], 1, dest_y + 8, dct_linesize);
1316
            add_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
1317
            add_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
1318

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

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

    
1336
static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
1337
{
1338
    int i;
1339
    const int maxlevel= s->max_qcoeff;
1340
    const int minlevel= s->min_qcoeff;
1341

    
1342
    for(i=0; i<=last_index; i++){
1343
        const int j = zigzag_direct[i];
1344
        int level = block[j];
1345
       
1346
        if     (level>maxlevel) level=maxlevel;
1347
        else if(level<minlevel) level=minlevel;
1348
        block[j]= level;
1349
    }
1350
}
1351

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

    
1367
    if (s->mb_intra) {
1368
        UINT8 *ptr;
1369
        int wrap;
1370

    
1371
        wrap = s->linesize;
1372
        ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
1373
        get_pixels(s->block[0], ptr               , wrap);
1374
        get_pixels(s->block[1], ptr            + 8, wrap);
1375
        get_pixels(s->block[2], ptr + 8 * wrap    , wrap);
1376
        get_pixels(s->block[3], ptr + 8 * wrap + 8, wrap);
1377

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

    
1382
        ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
1383
        get_pixels(s->block[5], ptr, wrap);
1384
    }else{
1385
        op_pixels_func *op_pix;
1386
        qpel_mc_func *op_qpix;
1387
        UINT8 *dest_y, *dest_cb, *dest_cr;
1388
        UINT8 *ptr;
1389
        int wrap;
1390

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

    
1395
        if ((!s->no_rounding) || s->pict_type==B_TYPE){
1396
            op_pix = put_pixels_tab;
1397
            op_qpix= qpel_mc_rnd_tab;
1398
        }else{
1399
            op_pix = put_no_rnd_pixels_tab;
1400
            op_qpix= qpel_mc_no_rnd_tab;
1401
        }
1402

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

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

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

    
1464
    /* huffman encode */
1465
    switch(s->out_format) {
1466
    case FMT_MPEG1:
1467
        mpeg1_encode_mb(s, s->block, motion_x, motion_y);
1468
        break;
1469
    case FMT_H263:
1470
        if (s->h263_msmpeg4)
1471
            msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
1472
        else if(s->h263_pred)
1473
            mpeg4_encode_mb(s, s->block, motion_x, motion_y);
1474
        else
1475
            h263_encode_mb(s, s->block, motion_x, motion_y);
1476
        break;
1477
    case FMT_MJPEG:
1478
        mjpeg_encode_mb(s, s->block);
1479
        break;
1480
    }
1481
}
1482

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

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

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

    
1502
static void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
1503
    int i;
1504

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

    
1507
    /* mpeg1 */
1508
    d->mb_incr= s->mb_incr;
1509
    for(i=0; i<3; i++)
1510
        d->last_dc[i]= s->last_dc[i];
1511
    
1512
    /* statistics */
1513
    d->mv_bits= s->mv_bits;
1514
    d->i_tex_bits= s->i_tex_bits;
1515
    d->p_tex_bits= s->p_tex_bits;
1516
    d->i_count= s->i_count;
1517
    d->p_count= s->p_count;
1518
    d->skip_count= s->skip_count;
1519
    d->misc_bits= s->misc_bits;
1520
    d->last_bits= 0;
1521

    
1522
    d->mb_skiped= s->mb_skiped;
1523
}
1524

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

    
1528
    memcpy(d->mv, s->mv, 2*4*2*sizeof(int)); 
1529
    memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
1530
    
1531
    /* mpeg1 */
1532
    d->mb_incr= s->mb_incr;
1533
    for(i=0; i<3; i++)
1534
        d->last_dc[i]= s->last_dc[i];
1535
    
1536
    /* statistics */
1537
    d->mv_bits= s->mv_bits;
1538
    d->i_tex_bits= s->i_tex_bits;
1539
    d->p_tex_bits= s->p_tex_bits;
1540
    d->i_count= s->i_count;
1541
    d->p_count= s->p_count;
1542
    d->skip_count= s->skip_count;
1543
    d->misc_bits= s->misc_bits;
1544

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

    
1555

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

    
1564
    s->picture_number = picture_number;
1565

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

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

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

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

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

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

    
1642
//    printf("%d %d\n", s->avg_mb_var, s->mc_mb_var);
1643

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

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

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

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

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

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

    
1750
                copy_context_before_encode(&backup_s, s, -1);
1751

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

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

    
1784
                    encode_mb(s, 0, 0);
1785
                    d= get_bit_count(&s->pb);
1786
                    if(d<dmin){
1787
                        flush_put_bits(&s->pb);
1788
                        dmin=d;
1789
                        copy_context_after_encode(&best_s, s, MB_TYPE_INTER4V);
1790
                        best=2;
1791
                        next_block^=1;
1792
                    }
1793
                }
1794
                if(mb_type&MB_TYPE_FORWARD){
1795
                    copy_context_before_encode(s, &backup_s, MB_TYPE_FORWARD);
1796
                    s->mv_dir = MV_DIR_FORWARD;
1797
                    s->mv_type = MV_TYPE_16X16;
1798
                    s->mb_intra= 0;
1799
                    s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
1800
                    s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
1801
                    init_put_bits(&s->pb, bit_buf[3], 3000, NULL, NULL);
1802
                    s->block= s->blocks[next_block];
1803

    
1804
                    encode_mb(s, s->mv[0][0][0], s->mv[0][0][1]);
1805
                    d= get_bit_count(&s->pb);
1806
                    if(d<dmin){
1807
                        flush_put_bits(&s->pb);
1808
                        dmin=d;
1809
                        copy_context_after_encode(&best_s, s, MB_TYPE_FORWARD);
1810
                        best=3;
1811
                        next_block^=1;
1812
                    }
1813
                }
1814
                if(mb_type&MB_TYPE_BACKWARD){
1815
                    copy_context_before_encode(s, &backup_s, MB_TYPE_BACKWARD);
1816
                    s->mv_dir = MV_DIR_BACKWARD;
1817
                    s->mv_type = MV_TYPE_16X16;
1818
                    s->mb_intra= 0;
1819
                    s->mv[1][0][0] = s->b_back_mv_table[xy][0];
1820
                    s->mv[1][0][1] = s->b_back_mv_table[xy][1];
1821
                    init_put_bits(&s->pb, bit_buf[4], 3000, NULL, NULL);
1822
                    s->block= s->blocks[next_block];
1823

    
1824
                    encode_mb(s, s->mv[1][0][0], s->mv[1][0][1]);
1825
                    d= get_bit_count(&s->pb);
1826
                    if(d<dmin){
1827
                        flush_put_bits(&s->pb);
1828
                        dmin=d;
1829
                        copy_context_after_encode(&best_s, s, MB_TYPE_BACKWARD);
1830
                        best=4;
1831
                        next_block^=1;
1832
                    }
1833
                }
1834
                if(mb_type&MB_TYPE_BIDIR){
1835
                    copy_context_before_encode(s, &backup_s, MB_TYPE_BIDIR);
1836
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
1837
                    s->mv_type = MV_TYPE_16X16;
1838
                    s->mb_intra= 0;
1839
                    s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
1840
                    s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
1841
                    s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
1842
                    s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
1843
                    init_put_bits(&s->pb, bit_buf[5], 3000, NULL, NULL);
1844
                    s->block= s->blocks[next_block];
1845

    
1846
                    encode_mb(s, 0, 0);
1847
                    d= get_bit_count(&s->pb);
1848
                    if(d<dmin){
1849
                        flush_put_bits(&s->pb);
1850
                        dmin=d;
1851
                        copy_context_after_encode(&best_s, s, MB_TYPE_BIDIR);
1852
                        best=5;
1853
                        next_block^=1;
1854
                    }
1855
                }
1856
                if(mb_type&MB_TYPE_DIRECT){
1857
                    copy_context_before_encode(s, &backup_s, MB_TYPE_DIRECT);
1858
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1859
                    s->mv_type = MV_TYPE_16X16; //FIXME
1860
                    s->mb_intra= 0;
1861
                    s->mv[0][0][0] = s->b_direct_forw_mv_table[xy][0];
1862
                    s->mv[0][0][1] = s->b_direct_forw_mv_table[xy][1];
1863
                    s->mv[1][0][0] = s->b_direct_back_mv_table[xy][0];
1864
                    s->mv[1][0][1] = s->b_direct_back_mv_table[xy][1];
1865
                    init_put_bits(&s->pb, bit_buf[6], 3000, NULL, NULL);
1866
                    s->block= s->blocks[next_block];
1867

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

    
1967
            MPV_decode_mb(s, s->block);
1968
        }
1969

    
1970

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

    
1986
    if (s->h263_msmpeg4 && s->msmpeg4_version<4 && s->pict_type == I_TYPE)
1987
        msmpeg4_encode_ext_header(s);
1988

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

    
2004
static int dct_quantize_c(MpegEncContext *s, 
2005
                        DCTELEM *block, int n,
2006
                        int qscale, int *overflow)
2007
{
2008
    int i, j, level, last_non_zero, q;
2009
    const int *qmat;
2010
    int bias;
2011
    int max=0;
2012
    unsigned int threshold1, threshold2;
2013

    
2014
    av_fdct (block);
2015

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

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

    
2042
    for(;i<64;i++) {
2043
        j = zigzag_direct[i];
2044
        level = block[j];
2045
        level = level * qmat[j];
2046

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

    
2068
static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
2069
                                   DCTELEM *block, int n, int qscale)
2070
{
2071
    int i, level, nCoeffs;
2072
    const UINT16 *quant_matrix;
2073

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

    
2132
static void dct_unquantize_mpeg2_c(MpegEncContext *s, 
2133
                                   DCTELEM *block, int n, int qscale)
2134
{
2135
    int i, level, nCoeffs;
2136
    const UINT16 *quant_matrix;
2137

    
2138
    if(s->alternate_scan) nCoeffs= 64;
2139
    else nCoeffs= s->block_last_index[n]+1;
2140
    
2141
    if (s->mb_intra) {
2142
        if (n < 4) 
2143
            block[0] = block[0] * s->y_dc_scale;
2144
        else
2145
            block[0] = block[0] * s->c_dc_scale;
2146
        quant_matrix = s->intra_matrix;
2147
        for(i=1;i<nCoeffs;i++) {
2148
            int j= zigzag_direct[i];
2149
            level = block[j];
2150
            if (level) {
2151
                if (level < 0) {
2152
                    level = -level;
2153
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
2154
                    level = -level;
2155
                } else {
2156
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
2157
                }
2158
#ifdef PARANOID
2159
                if (level < -2048 || level > 2047)
2160
                    fprintf(stderr, "unquant error %d %d\n", i, level);
2161
#endif
2162
                block[j] = level;
2163
            }
2164
        }
2165
    } else {
2166
        int sum=-1;
2167
        i = 0;
2168
        quant_matrix = s->inter_matrix;
2169
        for(;i<nCoeffs;i++) {
2170
            int j= zigzag_direct[i];
2171
            level = block[j];
2172
            if (level) {
2173
                if (level < 0) {
2174
                    level = -level;
2175
                    level = (((level << 1) + 1) * qscale *
2176
                             ((int) (quant_matrix[j]))) >> 4;
2177
                    level = -level;
2178
                } else {
2179
                    level = (((level << 1) + 1) * qscale *
2180
                             ((int) (quant_matrix[j]))) >> 4;
2181
                }
2182
#ifdef PARANOID
2183
                if (level < -2048 || level > 2047)
2184
                    fprintf(stderr, "unquant error %d %d\n", i, level);
2185
#endif
2186
                block[j] = level;
2187
                sum+=level;
2188
            }
2189
        }
2190
        block[63]^=sum&1;
2191
    }
2192
}
2193

    
2194

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

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

    
2221
    for(;i<nCoeffs;i++) {
2222
        level = block[i];
2223
        if (level) {
2224
            if (level < 0) {
2225
                level = level * qmul - qadd;
2226
            } else {
2227
                level = level * qmul + qadd;
2228
            }
2229
#ifdef PARANOID
2230
                if (level < -2048 || level > 2047)
2231
                    fprintf(stderr, "unquant error %d %d\n", i, level);
2232
#endif
2233
            block[i] = level;
2234
        }
2235
    }
2236
}
2237

    
2238
AVCodec mpeg1video_encoder = {
2239
    "mpeg1video",
2240
    CODEC_TYPE_VIDEO,
2241
    CODEC_ID_MPEG1VIDEO,
2242
    sizeof(MpegEncContext),
2243
    MPV_encode_init,
2244
    MPV_encode_picture,
2245
    MPV_encode_end,
2246
};
2247

    
2248
AVCodec h263_encoder = {
2249
    "h263",
2250
    CODEC_TYPE_VIDEO,
2251
    CODEC_ID_H263,
2252
    sizeof(MpegEncContext),
2253
    MPV_encode_init,
2254
    MPV_encode_picture,
2255
    MPV_encode_end,
2256
};
2257

    
2258
AVCodec h263p_encoder = {
2259
    "h263p",
2260
    CODEC_TYPE_VIDEO,
2261
    CODEC_ID_H263P,
2262
    sizeof(MpegEncContext),
2263
    MPV_encode_init,
2264
    MPV_encode_picture,
2265
    MPV_encode_end,
2266
};
2267

    
2268
AVCodec rv10_encoder = {
2269
    "rv10",
2270
    CODEC_TYPE_VIDEO,
2271
    CODEC_ID_RV10,
2272
    sizeof(MpegEncContext),
2273
    MPV_encode_init,
2274
    MPV_encode_picture,
2275
    MPV_encode_end,
2276
};
2277

    
2278
AVCodec mjpeg_encoder = {
2279
    "mjpeg",
2280
    CODEC_TYPE_VIDEO,
2281
    CODEC_ID_MJPEG,
2282
    sizeof(MpegEncContext),
2283
    MPV_encode_init,
2284
    MPV_encode_picture,
2285
    MPV_encode_end,
2286
};
2287

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

    
2298
AVCodec msmpeg4v1_encoder = {
2299
    "msmpeg4v1",
2300
    CODEC_TYPE_VIDEO,
2301
    CODEC_ID_MSMPEG4V1,
2302
    sizeof(MpegEncContext),
2303
    MPV_encode_init,
2304
    MPV_encode_picture,
2305
    MPV_encode_end,
2306
};
2307

    
2308
AVCodec msmpeg4v2_encoder = {
2309
    "msmpeg4v2",
2310
    CODEC_TYPE_VIDEO,
2311
    CODEC_ID_MSMPEG4V2,
2312
    sizeof(MpegEncContext),
2313
    MPV_encode_init,
2314
    MPV_encode_picture,
2315
    MPV_encode_end,
2316
};
2317

    
2318
AVCodec msmpeg4v3_encoder = {
2319
    "msmpeg4",
2320
    CODEC_TYPE_VIDEO,
2321
    CODEC_ID_MSMPEG4V3,
2322
    sizeof(MpegEncContext),
2323
    MPV_encode_init,
2324
    MPV_encode_picture,
2325
    MPV_encode_end,
2326
};