Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegvideo.c @ 1c2a8c7f

History | View | Annotate | Download (78 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);
42

    
43
int (*dct_quantize)(MpegEncContext *s, DCTELEM *block, int n, int qscale)= 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, UINT16 *qmat16, const UINT16 *quant_matrix, int qscale)
82
{
83
    int i;
84

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

    
108
/* init common structure for both encoder and decoder */
109
int MPV_common_init(MpegEncContext *s)
110
{
111
    int c_size, i;
112
    UINT8 *pict;
113

    
114
    s->dct_unquantize_h263 = dct_unquantize_h263_c;
115
    s->dct_unquantize_mpeg1 = dct_unquantize_mpeg1_c;
116
    s->dct_unquantize_mpeg2 = dct_unquantize_mpeg2_c;
117
        
118
#ifdef HAVE_MMX
119
    MPV_common_init_mmx(s);
120
#endif
121
    //setup default unquantizers (mpeg4 might change it later)
122
    if(s->out_format == FMT_H263)
123
        s->dct_unquantize = s->dct_unquantize_h263;
124
    else
125
        s->dct_unquantize = s->dct_unquantize_mpeg1;
126
    
127
    s->mb_width = (s->width + 15) / 16;
128
    s->mb_height = (s->height + 15) / 16;
129
    s->mb_num = s->mb_width * s->mb_height;
130
    s->linesize = s->mb_width * 16 + 2 * EDGE_WIDTH;
131

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

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

    
141
        pict = av_mallocz(c_size);
142
        if (pict == NULL)
143
            goto fail;
144
        s->last_picture_base[i] = pict;
145
        s->last_picture[i] = pict + pict_start;
146
    
147
        pict = av_mallocz(c_size);
148
        if (pict == NULL)
149
            goto fail;
150
        s->next_picture_base[i] = pict;
151
        s->next_picture[i] = pict + pict_start;
152
        
153
        if (s->has_b_frames) {
154
            pict = av_mallocz(c_size);
155
            if (pict == NULL) 
156
                goto fail;
157
            s->aux_picture_base[i] = pict;
158
            s->aux_picture[i] = pict + pict_start;
159
        }
160
    }
161
    
162
    if (s->encoding) {
163
        int j;
164
        int mv_table_size= (s->mb_width+2)*(s->mb_height+2);
165

    
166
        /* Allocate MB type table */
167
        s->mb_type = av_mallocz(s->mb_num * sizeof(char));
168
        if (s->mb_type == NULL) {
169
            perror("malloc");
170
            goto fail;
171
        }
172
        
173
        s->mb_var = av_mallocz(s->mb_num * sizeof(INT16));
174
        if (s->mb_var == NULL) {
175
            perror("malloc");
176
            goto fail;
177
        }
178

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

    
226
        s->me_scratchpad = av_mallocz( s->linesize*16*3*sizeof(uint8_t));
227
        if (s->me_scratchpad == NULL) {
228
            perror("malloc");
229
            goto fail;
230
        }
231

    
232
        if(s->max_b_frames){
233
            for(j=0; j<REORDER_BUFFER_SIZE; j++){
234
                int i;
235
                for(i=0;i<3;i++) {
236
                    int w, h, shift;
237

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

    
243
                    pict = av_mallocz(c_size);
244
                    if (pict == NULL)
245
                        goto fail;
246
                    s->picture_buffer[j][i] = pict;
247
                }
248
            }
249
        }
250
    }
251
    
252
    if (s->out_format == FMT_H263 || s->encoding) {
253
        int size;
254
        /* MV prediction */
255
        size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
256
        s->motion_val = malloc(size * 2 * sizeof(INT16));
257
        if (s->motion_val == NULL)
258
            goto fail;
259
        memset(s->motion_val, 0, size * 2 * sizeof(INT16));
260
    }
261

    
262
    if (s->h263_pred || s->h263_plus) {
263
        int y_size, c_size, i, size;
264
        
265
        /* dc values */
266

    
267
        y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
268
        c_size = (s->mb_width + 2) * (s->mb_height + 2);
269
        size = y_size + 2 * c_size;
270
        s->dc_val[0] = malloc(size * sizeof(INT16));
271
        if (s->dc_val[0] == NULL)
272
            goto fail;
273
        s->dc_val[1] = s->dc_val[0] + y_size;
274
        s->dc_val[2] = s->dc_val[1] + c_size;
275
        for(i=0;i<size;i++)
276
            s->dc_val[0][i] = 1024;
277

    
278
        /* ac values */
279
        s->ac_val[0] = av_mallocz(size * sizeof(INT16) * 16);
280
        if (s->ac_val[0] == NULL)
281
            goto fail;
282
        s->ac_val[1] = s->ac_val[0] + y_size;
283
        s->ac_val[2] = s->ac_val[1] + c_size;
284
        
285
        /* cbp values */
286
        s->coded_block = av_mallocz(y_size);
287
        if (!s->coded_block)
288
            goto fail;
289

    
290
        /* which mb is a intra block */
291
        s->mbintra_table = av_mallocz(s->mb_num);
292
        if (!s->mbintra_table)
293
            goto fail;
294
        memset(s->mbintra_table, 1, s->mb_num);
295
        
296
        /* divx501 bitstream reorder buffer */
297
        s->bitstream_buffer= av_mallocz(BITSTREAM_BUFFER_SIZE);
298
        if (!s->bitstream_buffer)
299
            goto fail;
300
    }
301
    /* default structure is frame */
302
    s->picture_structure = PICT_FRAME;
303

    
304
    /* init macroblock skip table */
305
    s->mbskip_table = av_mallocz(s->mb_num);
306
    if (!s->mbskip_table)
307
        goto fail;
308
    
309
    s->block= s->blocks[0];
310

    
311
    s->context_initialized = 1;
312
    return 0;
313
 fail:
314
    MPV_common_end(s);
315
    return -1;
316
}
317

    
318
#define CHECK_FREE(p)\
319
{\
320
    if(p) free(p);\
321
    p= NULL;\
322
}
323

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

    
329
    CHECK_FREE(s->mb_type);
330
    CHECK_FREE(s->mb_var);
331
    CHECK_FREE(s->p_mv_table);
332
    CHECK_FREE(s->last_p_mv_table);
333
    CHECK_FREE(s->b_forw_mv_table);
334
    CHECK_FREE(s->b_back_mv_table);
335
    CHECK_FREE(s->b_bidir_forw_mv_table);
336
    CHECK_FREE(s->b_bidir_back_mv_table);
337
    CHECK_FREE(s->b_direct_forw_mv_table);
338
    CHECK_FREE(s->b_direct_back_mv_table);
339
    CHECK_FREE(s->b_direct_mv_table);
340
    CHECK_FREE(s->motion_val);
341
    CHECK_FREE(s->dc_val[0]);
342
    CHECK_FREE(s->ac_val[0]);
343
    CHECK_FREE(s->coded_block);
344
    CHECK_FREE(s->mbintra_table);
345
    CHECK_FREE(s->me_scratchpad);
346

    
347
    CHECK_FREE(s->mbskip_table);
348
    CHECK_FREE(s->bitstream_buffer);
349
    for(i=0;i<3;i++) {
350
        int j;
351
        CHECK_FREE(s->last_picture_base[i]);
352
        CHECK_FREE(s->next_picture_base[i]);
353
        CHECK_FREE(s->aux_picture_base[i]);
354
        for(j=0; j<REORDER_BUFFER_SIZE; j++){
355
            CHECK_FREE(s->picture_buffer[j][i]);
356
        }
357
    }
358
    s->context_initialized = 0;
359
}
360

    
361
/* init video encoder */
362
int MPV_encode_init(AVCodecContext *avctx)
363
{
364
    MpegEncContext *s = avctx->priv_data;
365
    int i;
366

    
367
    avctx->pix_fmt = PIX_FMT_YUV420P;
368

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

    
494
    { /* set up some save defaults, some codecs might override them later */
495
        static int done=0;
496
        if(!done){
497
            int i;
498
            done=1;
499
            memset(default_mv_penalty, 0, sizeof(UINT16)*(MAX_FCODE+1)*(2*MAX_MV+1));
500
            memset(default_fcode_tab , 0, sizeof(UINT8)*(2*MAX_MV+1));
501

    
502
            for(i=-16; i<16; i++){
503
                default_fcode_tab[i + MAX_MV]= 1;
504
            }
505
        }
506
    }
507
    s->mv_penalty= default_mv_penalty;
508
    s->fcode_tab= default_fcode_tab;
509

    
510
    if (s->out_format == FMT_H263)
511
        h263_encode_init(s);
512
    else if (s->out_format == FMT_MPEG1)
513
        mpeg1_encode_init(s);
514

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

    
518
    s->encoding = 1;
519

    
520
    /* init */
521
    if (MPV_common_init(s) < 0)
522
        return -1;
523
    
524
    /* init default q matrix */
525
    for(i=0;i<64;i++) {
526
        s->intra_matrix[i] = default_intra_matrix[i];
527
        s->non_intra_matrix[i] = default_non_intra_matrix[i];
528
    }
529

    
530
    if(ff_rate_control_init(s) < 0)
531
        return -1;
532

    
533
    s->picture_number = 0;
534
    s->picture_in_gop_number = 0;
535
    s->fake_picture_number = 0;
536
    /* motion detector init */
537
    s->f_code = 1;
538
    s->b_code = 1;
539

    
540
    return 0;
541
}
542

    
543
int MPV_encode_end(AVCodecContext *avctx)
544
{
545
    MpegEncContext *s = avctx->priv_data;
546

    
547
#ifdef STATS
548
    print_stats();
549
#endif
550

    
551
    ff_rate_control_uninit(s);
552

    
553
    MPV_common_end(s);
554
    if (s->out_format == FMT_MJPEG)
555
        mjpeg_close(s);
556
      
557
    return 0;
558
}
559

    
560
/* draw the edges of width 'w' of an image of size width, height */
561
static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w)
562
{
563
    UINT8 *ptr, *last_line;
564
    int i;
565

    
566
    last_line = buf + (height - 1) * wrap;
567
    for(i=0;i<w;i++) {
568
        /* top and bottom */
569
        memcpy(buf - (i + 1) * wrap, buf, width);
570
        memcpy(last_line + (i + 1) * wrap, last_line, width);
571
    }
572
    /* left and right */
573
    ptr = buf;
574
    for(i=0;i<height;i++) {
575
        memset(ptr - w, ptr[0], w);
576
        memset(ptr + width, ptr[width-1], w);
577
        ptr += wrap;
578
    }
579
    /* corners */
580
    for(i=0;i<w;i++) {
581
        memset(buf - (i + 1) * wrap - w, buf[0], w); /* top left */
582
        memset(buf - (i + 1) * wrap + width, buf[width-1], w); /* top right */
583
        memset(last_line + (i + 1) * wrap - w, last_line[0], w); /* top left */
584
        memset(last_line + (i + 1) * wrap + width, last_line[width-1], w); /* top right */
585
    }
586
}
587

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

    
594
    s->mb_skiped = 0;
595
    if (s->pict_type == B_TYPE) {
596
        for(i=0;i<3;i++) {
597
            s->current_picture[i] = s->aux_picture[i];
598
        }
599
    } else {
600
        for(i=0;i<3;i++) {
601
            /* swap next and last */
602
            tmp = s->last_picture[i];
603
            s->last_picture[i] = s->next_picture[i];
604
            s->next_picture[i] = tmp;
605
            s->current_picture[i] = tmp;
606
        }
607
    }
608
}
609

    
610
/* generic function for encode/decode called after a frame has been coded/decoded */
611
void MPV_frame_end(MpegEncContext *s)
612
{
613
    /* draw edge for correct motion prediction if outside */
614
    if (s->pict_type != B_TYPE && !s->intra_only) {
615
      if(s->avctx==NULL || s->avctx->codec->id!=CODEC_ID_MPEG4 || s->divx_version==500){
616
        draw_edges(s->current_picture[0], s->linesize, s->mb_width*16, s->mb_height*16, EDGE_WIDTH);
617
        draw_edges(s->current_picture[1], s->linesize/2, s->mb_width*8, s->mb_height*8, EDGE_WIDTH/2);
618
        draw_edges(s->current_picture[2], s->linesize/2, s->mb_width*8, s->mb_height*8, EDGE_WIDTH/2);
619
      }else{
620
        /* mpeg4? / opendivx / xvid */
621
        draw_edges(s->current_picture[0], s->linesize, s->width, s->height, EDGE_WIDTH);
622
        draw_edges(s->current_picture[1], s->linesize/2, s->width/2, s->height/2, EDGE_WIDTH/2);
623
        draw_edges(s->current_picture[2], s->linesize/2, s->width/2, s->height/2, EDGE_WIDTH/2);
624
      }
625
    }
626
    emms_c();
627
    
628
    if(s->pict_type!=B_TYPE){
629
        s->last_non_b_pict_type= s->pict_type;
630
        s->last_non_b_qscale= s->qscale;
631
        s->last_non_b_mc_mb_var= s->mc_mb_var;
632
        s->num_available_buffers++;
633
        if(s->num_available_buffers>2) s->num_available_buffers= 2;
634
    }
635
}
636

    
637
/* reorder input for encoding */
638
void reorder_input(MpegEncContext *s, AVPicture *pict)
639
{
640
    int i, j, index;
641
            
642
    if(s->max_b_frames > FF_MAX_B_FRAMES) s->max_b_frames= FF_MAX_B_FRAMES;
643

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

    
646
    for(j=0; j<REORDER_BUFFER_SIZE-1; j++){
647
        s->coded_order[j]= s->coded_order[j+1];
648
    }
649
    s->coded_order[j].picture[0]= s->coded_order[j].picture[1]= s->coded_order[j].picture[2]= NULL; //catch uninitalized buffers
650
    s->coded_order[j].pict_type=0;
651

    
652
    switch(s->input_pict_type){
653
    default: 
654
    case I_TYPE:
655
    case S_TYPE:
656
    case P_TYPE:
657
        index= s->max_b_frames - s->b_frames_since_non_b;
658
        s->b_frames_since_non_b=0;
659
        break;            
660
    case B_TYPE:
661
        index= s->max_b_frames + 1;
662
        s->b_frames_since_non_b++;
663
        break;          
664
    }
665
//printf("index:%d type:%d strides: %d %d\n", index, s->input_pict_type, pict->linesize[0], s->linesize);
666
    if(   (index==0 || (s->flags&CODEC_FLAG_INPUT_PRESERVED))
667
       && pict->linesize[0] == s->linesize
668
       && pict->linesize[1] == s->linesize>>1
669
       && pict->linesize[2] == s->linesize>>1){
670
//printf("ptr\n");
671
        for(i=0; i<3; i++){
672
            s->coded_order[index].picture[i]= pict->data[i];
673
        }
674
    }else{
675
//printf("copy\n");
676
        for(i=0; i<3; i++){
677
            uint8_t *src = pict->data[i];
678
            uint8_t *dest;
679
            int src_wrap = pict->linesize[i];
680
            int dest_wrap = s->linesize;
681
            int w = s->width;
682
            int h = s->height;
683

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

    
687
            if (i >= 1) {
688
                dest_wrap >>= 1;
689
                w >>= 1;
690
                h >>= 1;
691
            }
692

    
693
            s->coded_order[index].picture[i]= dest;
694
            for(j=0;j<h;j++) {
695
                memcpy(dest, src, w);
696
                dest += dest_wrap;
697
                src += src_wrap;
698
            }
699
        }
700
        if(index!=0){
701
            s->picture_buffer_index++;
702
            if(s->picture_buffer_index >= REORDER_BUFFER_SIZE-1) s->picture_buffer_index=0;
703
        }
704
    }
705
    s->coded_order[index].pict_type = s->input_pict_type;
706
    s->coded_order[index].qscale    = s->input_qscale;
707
    s->coded_order[index].force_type= s->force_input_type;
708
    s->coded_order[index].picture_in_gop_number= s->input_picture_in_gop_number;
709
    s->coded_order[index].picture_number= s->input_picture_number;
710

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

    
716
int MPV_encode_picture(AVCodecContext *avctx,
717
                       unsigned char *buf, int buf_size, void *data)
718
{
719
    MpegEncContext *s = avctx->priv_data;
720
    AVPicture *pict = data;
721

    
722
    s->input_qscale = avctx->quality;
723

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

    
726
    if(avctx->flags&CODEC_FLAG_TYPE){
727
        s->input_pict_type=
728
        s->force_input_type= avctx->key_frame ? I_TYPE : P_TYPE;
729
    }else if(s->flags&CODEC_FLAG_PASS2){
730
        s->input_pict_type=
731
        s->force_input_type= s->rc_context.entry[s->input_picture_number].new_pict_type;
732
    }else{
733
        s->force_input_type=0;
734
        if (!s->intra_only) {
735
            /* first picture of GOP is intra */
736
            if (s->input_picture_in_gop_number % s->gop_size==0){
737
                s->input_pict_type = I_TYPE;
738
            }else if(s->max_b_frames==0){
739
                s->input_pict_type = P_TYPE;
740
            }else{
741
                if(s->b_frames_since_non_b < s->max_b_frames) //FIXME more IQ
742
                    s->input_pict_type = B_TYPE;
743
                else
744
                    s->input_pict_type = P_TYPE;
745
            }
746
        } else {
747
            s->input_pict_type = I_TYPE;
748
        }
749
    }
750

    
751
    if(s->input_pict_type==I_TYPE)
752
        s->input_picture_in_gop_number=0;
753
    
754
    reorder_input(s, pict);
755
    
756
    /* output? */
757
    if(s->coded_order[0].picture[0]){
758

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

    
766
        MPV_frame_start(s);
767

    
768
        encode_picture(s, s->picture_number);
769
        avctx->key_frame = (s->pict_type == I_TYPE);
770
        avctx->header_bits = s->header_bits;
771
        avctx->mv_bits     = s->mv_bits;
772
        avctx->misc_bits   = s->misc_bits;
773
        avctx->i_tex_bits  = s->i_tex_bits;
774
        avctx->p_tex_bits  = s->p_tex_bits;
775
        avctx->i_count     = s->i_count;
776
        avctx->p_count     = s->p_count;
777
        avctx->skip_count  = s->skip_count;
778

    
779
        MPV_frame_end(s);
780

    
781
        if (s->out_format == FMT_MJPEG)
782
            mjpeg_picture_trailer(s);
783

    
784
        avctx->quality = s->qscale;
785
        
786
        if(s->flags&CODEC_FLAG_PASS1)
787
            ff_write_pass1_stats(s);
788
    }
789

    
790
    s->input_picture_number++;
791
    s->input_picture_in_gop_number++;
792

    
793
    flush_put_bits(&s->pb);
794
    s->frame_bits  = (pbBufPtr(&s->pb) - s->pb.buf) * 8;
795
    if(s->pict_type==B_TYPE) s->pb_frame_bits+= s->frame_bits;
796
    else                     s->pb_frame_bits= s->frame_bits;
797

    
798
    s->total_bits += s->frame_bits;
799
    avctx->frame_bits  = s->frame_bits;
800
//printf("fcode: %d, type: %d, head: %d, mv: %d, misc: %d, frame: %d, itex: %d, ptex: %d\n", 
801
//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);
802

    
803
    if (avctx->get_psnr) {
804
        /* At this point pict->data should have the original frame   */
805
        /* an s->current_picture should have the coded/decoded frame */
806
        get_psnr(pict->data, s->current_picture,
807
                 pict->linesize, s->linesize, avctx);
808
//        printf("%f\n", avctx->psnr_y);
809
    }
810
    return pbBufPtr(&s->pb) - s->pb.buf;
811
}
812

    
813
static inline void gmc1_motion(MpegEncContext *s,
814
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
815
                               int dest_offset,
816
                               UINT8 **ref_picture, int src_offset,
817
                               int h)
818
{
819
    UINT8 *ptr;
820
    int offset, src_x, src_y, linesize;
821
    int motion_x, motion_y;
822

    
823
    if(s->real_sprite_warping_points>1) printf("more than 1 warp point isnt supported\n");
824
    motion_x= s->sprite_offset[0][0];
825
    motion_y= s->sprite_offset[0][1];
826
    src_x = s->mb_x * 16 + (motion_x >> (s->sprite_warping_accuracy+1));
827
    src_y = s->mb_y * 16 + (motion_y >> (s->sprite_warping_accuracy+1));
828
    motion_x<<=(3-s->sprite_warping_accuracy);
829
    motion_y<<=(3-s->sprite_warping_accuracy);
830
    src_x = clip(src_x, -16, s->width);
831
    if (src_x == s->width)
832
        motion_x =0;
833
    src_y = clip(src_y, -16, s->height);
834
    if (src_y == s->height)
835
        motion_y =0;
836
    
837
    linesize = s->linesize;
838
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
839

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

    
844
    motion_x= s->sprite_offset[1][0];
845
    motion_y= s->sprite_offset[1][1];
846
    src_x = s->mb_x * 8 + (motion_x >> (s->sprite_warping_accuracy+1));
847
    src_y = s->mb_y * 8 + (motion_y >> (s->sprite_warping_accuracy+1));
848
    motion_x<<=(3-s->sprite_warping_accuracy);
849
    motion_y<<=(3-s->sprite_warping_accuracy);
850
    src_x = clip(src_x, -8, s->width>>1);
851
    if (src_x == s->width>>1)
852
        motion_x =0;
853
    src_y = clip(src_y, -8, s->height>>1);
854
    if (src_y == s->height>>1)
855
        motion_y =0;
856

    
857
    offset = (src_y * linesize>>1) + src_x + (src_offset>>1);
858
    ptr = ref_picture[1] + offset;
859
    gmc1(dest_cb + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
860
    ptr = ref_picture[2] + offset;
861
    gmc1(dest_cr + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
862
    
863
    return;
864
}
865

    
866
/* apply one mpeg motion vector to the three components */
867
static inline void mpeg_motion(MpegEncContext *s,
868
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
869
                               int dest_offset,
870
                               UINT8 **ref_picture, int src_offset,
871
                               int field_based, op_pixels_func *pix_op,
872
                               int motion_x, int motion_y, int h)
873
{
874
    UINT8 *ptr;
875
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
876
if(s->quarter_sample)
877
{
878
    motion_x>>=1;
879
    motion_y>>=1;
880
}
881

    
882
    dxy = ((motion_y & 1) << 1) | (motion_x & 1);
883
    src_x = s->mb_x * 16 + (motion_x >> 1);
884
    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 1);
885
                
886
    /* WARNING: do no forget half pels */
887
    height = s->height >> field_based;
888
    src_x = clip(src_x, -16, s->width);
889
    if (src_x == s->width)
890
        dxy &= ~1;
891
    src_y = clip(src_y, -16, height);
892
    if (src_y == height)
893
        dxy &= ~2;
894
    linesize = s->linesize << field_based;
895
    ptr = ref_picture[0] + (src_y * linesize) + (src_x) + src_offset;
896
    dest_y += dest_offset;
897
    pix_op[dxy](dest_y, ptr, linesize, h);
898
    pix_op[dxy](dest_y + 8, ptr + 8, linesize, h);
899

    
900
    if (s->out_format == FMT_H263) {
901
        dxy = 0;
902
        if ((motion_x & 3) != 0)
903
            dxy |= 1;
904
        if ((motion_y & 3) != 0)
905
            dxy |= 2;
906
        mx = motion_x >> 2;
907
        my = motion_y >> 2;
908
    } else {
909
        mx = motion_x / 2;
910
        my = motion_y / 2;
911
        dxy = ((my & 1) << 1) | (mx & 1);
912
        mx >>= 1;
913
        my >>= 1;
914
    }
915
    
916
    src_x = s->mb_x * 8 + mx;
917
    src_y = s->mb_y * (8 >> field_based) + my;
918
    src_x = clip(src_x, -8, s->width >> 1);
919
    if (src_x == (s->width >> 1))
920
        dxy &= ~1;
921
    src_y = clip(src_y, -8, height >> 1);
922
    if (src_y == (height >> 1))
923
        dxy &= ~2;
924

    
925
    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
926
    ptr = ref_picture[1] + offset;
927
    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
928
    ptr = ref_picture[2] + offset;
929
    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
930
}
931

    
932
static inline void qpel_motion(MpegEncContext *s,
933
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
934
                               int dest_offset,
935
                               UINT8 **ref_picture, int src_offset,
936
                               int field_based, op_pixels_func *pix_op,
937
                               qpel_mc_func *qpix_op,
938
                               int motion_x, int motion_y, int h)
939
{
940
    UINT8 *ptr;
941
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
942

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

    
947
    height = s->height >> field_based;
948
    src_x = clip(src_x, -16, s->width);
949
    if (src_x == s->width)
950
        dxy &= ~3;
951
    src_y = clip(src_y, -16, height);
952
    if (src_y == height)
953
        dxy &= ~12;
954
    linesize = s->linesize << field_based;
955
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
956
    dest_y += dest_offset;
957
//printf("%d %d %d\n", src_x, src_y, dxy);
958
    qpix_op[dxy](dest_y                 , ptr                 , linesize, linesize, motion_x&3, motion_y&3);
959
    qpix_op[dxy](dest_y              + 8, ptr              + 8, linesize, linesize, motion_x&3, motion_y&3);
960
    qpix_op[dxy](dest_y + linesize*8    , ptr + linesize*8    , linesize, linesize, motion_x&3, motion_y&3);
961
    qpix_op[dxy](dest_y + linesize*8 + 8, ptr + linesize*8 + 8, linesize, linesize, motion_x&3, motion_y&3);
962
    
963
    mx= (motion_x>>1) | (motion_x&1);
964
    my= (motion_y>>1) | (motion_y&1);
965

    
966
    dxy = 0;
967
    if ((mx & 3) != 0)
968
        dxy |= 1;
969
    if ((my & 3) != 0)
970
        dxy |= 2;
971
    mx = mx >> 2;
972
    my = my >> 2;
973
    
974
    src_x = s->mb_x * 8 + mx;
975
    src_y = s->mb_y * (8 >> field_based) + my;
976
    src_x = clip(src_x, -8, s->width >> 1);
977
    if (src_x == (s->width >> 1))
978
        dxy &= ~1;
979
    src_y = clip(src_y, -8, height >> 1);
980
    if (src_y == (height >> 1))
981
        dxy &= ~2;
982

    
983
    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
984
    ptr = ref_picture[1] + offset;
985
    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
986
    ptr = ref_picture[2] + offset;
987
    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
988
}
989

    
990

    
991
static inline void MPV_motion(MpegEncContext *s, 
992
                              UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
993
                              int dir, UINT8 **ref_picture, 
994
                              op_pixels_func *pix_op, qpel_mc_func *qpix_op)
995
{
996
    int dxy, offset, mx, my, src_x, src_y, motion_x, motion_y;
997
    int mb_x, mb_y, i;
998
    UINT8 *ptr, *dest;
999

    
1000
    mb_x = s->mb_x;
1001
    mb_y = s->mb_y;
1002

    
1003
    switch(s->mv_type) {
1004
    case MV_TYPE_16X16:
1005
        if(s->mcsel){
1006
#if 0
1007
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
1008
                        ref_picture, 0,
1009
                        0, pix_op,
1010
                        s->sprite_offset[0][0]>>3,
1011
                        s->sprite_offset[0][1]>>3,
1012
                        16);
1013
#else
1014
            gmc1_motion(s, dest_y, dest_cb, dest_cr, 0,
1015
                        ref_picture, 0,
1016
                        16);
1017
#endif
1018
        }else if(s->quarter_sample && dir==0){ //FIXME
1019
            qpel_motion(s, dest_y, dest_cb, dest_cr, 0,
1020
                        ref_picture, 0,
1021
                        0, pix_op, qpix_op,
1022
                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
1023
        }else{
1024
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
1025
                        ref_picture, 0,
1026
                        0, pix_op,
1027
                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
1028
        }           
1029
        break;
1030
    case MV_TYPE_8X8:
1031
        for(i=0;i<4;i++) {
1032
            motion_x = s->mv[dir][i][0];
1033
            motion_y = s->mv[dir][i][1];
1034

    
1035
            dxy = ((motion_y & 1) << 1) | (motion_x & 1);
1036
            src_x = mb_x * 16 + (motion_x >> 1) + (i & 1) * 8;
1037
            src_y = mb_y * 16 + (motion_y >> 1) + (i >>1) * 8;
1038
                    
1039
            /* WARNING: do no forget half pels */
1040
            src_x = clip(src_x, -16, s->width);
1041
            if (src_x == s->width)
1042
                dxy &= ~1;
1043
            src_y = clip(src_y, -16, s->height);
1044
            if (src_y == s->height)
1045
                dxy &= ~2;
1046
                    
1047
            ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
1048
            dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
1049
            pix_op[dxy](dest, ptr, s->linesize, 8);
1050
        }
1051
        /* In case of 8X8, we construct a single chroma motion vector
1052
           with a special rounding */
1053
        mx = 0;
1054
        my = 0;
1055
        for(i=0;i<4;i++) {
1056
            mx += s->mv[dir][i][0];
1057
            my += s->mv[dir][i][1];
1058
        }
1059
        if (mx >= 0)
1060
            mx = (h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
1061
        else {
1062
            mx = -mx;
1063
            mx = -(h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
1064
        }
1065
        if (my >= 0)
1066
            my = (h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
1067
        else {
1068
            my = -my;
1069
            my = -(h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
1070
        }
1071
        dxy = ((my & 1) << 1) | (mx & 1);
1072
        mx >>= 1;
1073
        my >>= 1;
1074

    
1075
        src_x = mb_x * 8 + mx;
1076
        src_y = mb_y * 8 + my;
1077
        src_x = clip(src_x, -8, s->width/2);
1078
        if (src_x == s->width/2)
1079
            dxy &= ~1;
1080
        src_y = clip(src_y, -8, s->height/2);
1081
        if (src_y == s->height/2)
1082
            dxy &= ~2;
1083
        
1084
        offset = (src_y * (s->linesize >> 1)) + src_x;
1085
        ptr = ref_picture[1] + offset;
1086
        pix_op[dxy](dest_cb, ptr, s->linesize >> 1, 8);
1087
        ptr = ref_picture[2] + offset;
1088
        pix_op[dxy](dest_cr, ptr, s->linesize >> 1, 8);
1089
        break;
1090
    case MV_TYPE_FIELD:
1091
        if (s->picture_structure == PICT_FRAME) {
1092
            /* top field */
1093
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
1094
                        ref_picture, s->field_select[dir][0] ? s->linesize : 0,
1095
                        1, pix_op,
1096
                        s->mv[dir][0][0], s->mv[dir][0][1], 8);
1097
            /* bottom field */
1098
            mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
1099
                        ref_picture, s->field_select[dir][1] ? s->linesize : 0,
1100
                        1, pix_op,
1101
                        s->mv[dir][1][0], s->mv[dir][1][1], 8);
1102
        } else {
1103
            
1104

    
1105
        }
1106
        break;
1107
    }
1108
}
1109

    
1110

    
1111
/* put block[] to dest[] */
1112
static inline void put_dct(MpegEncContext *s, 
1113
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
1114
{
1115
    if (!s->mpeg2)
1116
        s->dct_unquantize(s, block, i, s->qscale);
1117
    ff_idct (block);
1118
    put_pixels_clamped(block, dest, line_size);
1119
}
1120

    
1121
/* add block[] to dest[] */
1122
static inline void add_dct(MpegEncContext *s, 
1123
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
1124
{
1125
    if (s->block_last_index[i] >= 0) {
1126
        if (!s->mpeg2)
1127
            if(s->encoding || (!s->h263_msmpeg4))
1128
                s->dct_unquantize(s, block, i, s->qscale);
1129

    
1130
        ff_idct (block);
1131
        add_pixels_clamped(block, dest, line_size);
1132
    }
1133
}
1134

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

1138
   Important variables used:
1139
   s->mb_intra : true if intra macroblock
1140
   s->mv_dir   : motion vector direction
1141
   s->mv_type  : motion vector type
1142
   s->mv       : motion vector
1143
   s->interlaced_dct : true if interlaced dct used (mpeg2)
1144
 */
1145
void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
1146
{
1147
    int mb_x, mb_y;
1148
    int dct_linesize, dct_offset;
1149
    op_pixels_func *op_pix;
1150
    qpel_mc_func *op_qpix;
1151

    
1152
    mb_x = s->mb_x;
1153
    mb_y = s->mb_y;
1154

    
1155
#ifdef FF_POSTPROCESS
1156
    quant_store[mb_y][mb_x]=s->qscale;
1157
    //printf("[%02d][%02d] %d\n",mb_x,mb_y,s->qscale);
1158
#endif
1159

    
1160
    /* update DC predictors for P macroblocks */
1161
    if (!s->mb_intra) {
1162
        if (s->h263_pred || s->h263_aic) {
1163
          if(s->mbintra_table[mb_x + mb_y*s->mb_width])
1164
          {
1165
            int wrap, xy, v;
1166
            s->mbintra_table[mb_x + mb_y*s->mb_width]=0;
1167
            wrap = 2 * s->mb_width + 2;
1168
            xy = 2 * mb_x + 1 +  (2 * mb_y + 1) * wrap;
1169
            v = 1024;
1170
            
1171
            s->dc_val[0][xy] = v;
1172
            s->dc_val[0][xy + 1] = v;
1173
            s->dc_val[0][xy + wrap] = v;
1174
            s->dc_val[0][xy + 1 + wrap] = v;
1175
            /* ac pred */
1176
            memset(s->ac_val[0][xy], 0, 16 * sizeof(INT16));
1177
            memset(s->ac_val[0][xy + 1], 0, 16 * sizeof(INT16));
1178
            memset(s->ac_val[0][xy + wrap], 0, 16 * sizeof(INT16));
1179
            memset(s->ac_val[0][xy + 1 + wrap], 0, 16 * sizeof(INT16));
1180
            if (s->h263_msmpeg4) {
1181
                s->coded_block[xy] = 0;
1182
                s->coded_block[xy + 1] = 0;
1183
                s->coded_block[xy + wrap] = 0;
1184
                s->coded_block[xy + 1 + wrap] = 0;
1185
            }
1186
            /* chroma */
1187
            wrap = s->mb_width + 2;
1188
            xy = mb_x + 1 + (mb_y + 1) * wrap;
1189
            s->dc_val[1][xy] = v;
1190
            s->dc_val[2][xy] = v;
1191
            /* ac pred */
1192
            memset(s->ac_val[1][xy], 0, 16 * sizeof(INT16));
1193
            memset(s->ac_val[2][xy], 0, 16 * sizeof(INT16));
1194
          }
1195
        } else {
1196
            s->last_dc[0] = 128 << s->intra_dc_precision;
1197
            s->last_dc[1] = 128 << s->intra_dc_precision;
1198
            s->last_dc[2] = 128 << s->intra_dc_precision;
1199
        }
1200
    }
1201
    else if (s->h263_pred || s->h263_aic)
1202
        s->mbintra_table[mb_x + mb_y*s->mb_width]=1;
1203

    
1204
    /* update motion predictor, not for B-frames as they need the motion_val from the last P/S-Frame */
1205
    if (s->out_format == FMT_H263) { //FIXME move into h263.c if possible, format specific stuff shouldnt be here
1206
      if(s->pict_type!=B_TYPE){
1207
        int xy, wrap, motion_x, motion_y;
1208
        
1209
        wrap = 2 * s->mb_width + 2;
1210
        xy = 2 * mb_x + 1 + (2 * mb_y + 1) * wrap;
1211
        if (s->mb_intra) {
1212
            motion_x = 0;
1213
            motion_y = 0;
1214
            goto motion_init;
1215
        } else if (s->mv_type == MV_TYPE_16X16) {
1216
            motion_x = s->mv[0][0][0];
1217
            motion_y = s->mv[0][0][1];
1218
        motion_init:
1219
            /* no update if 8X8 because it has been done during parsing */
1220
            s->motion_val[xy][0] = motion_x;
1221
            s->motion_val[xy][1] = motion_y;
1222
            s->motion_val[xy + 1][0] = motion_x;
1223
            s->motion_val[xy + 1][1] = motion_y;
1224
            s->motion_val[xy + wrap][0] = motion_x;
1225
            s->motion_val[xy + wrap][1] = motion_y;
1226
            s->motion_val[xy + 1 + wrap][0] = motion_x;
1227
            s->motion_val[xy + 1 + wrap][1] = motion_y;
1228
        }
1229
      }
1230
    }
1231
    
1232
    if (!(s->encoding && (s->intra_only || s->pict_type==B_TYPE))) {
1233
        UINT8 *dest_y, *dest_cb, *dest_cr;
1234
        UINT8 *mbskip_ptr;
1235

    
1236
        /* avoid copy if macroblock skipped in last frame too 
1237
           dont touch it for B-frames as they need the skip info from the next p-frame */
1238
        if (s->pict_type != B_TYPE) {
1239
            mbskip_ptr = &s->mbskip_table[s->mb_y * s->mb_width + s->mb_x];
1240
            if (s->mb_skiped) {
1241
                s->mb_skiped = 0;
1242
                /* if previous was skipped too, then nothing to do ! 
1243
                   skip only during decoding as we might trash the buffers during encoding a bit */
1244
                if (*mbskip_ptr != 0 && !s->encoding) 
1245
                    goto the_end;
1246
                *mbskip_ptr = 1; /* indicate that this time we skiped it */
1247
            } else {
1248
                *mbskip_ptr = 0; /* not skipped */
1249
            }
1250
        }
1251

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

    
1256
        if (s->interlaced_dct) {
1257
            dct_linesize = s->linesize * 2;
1258
            dct_offset = s->linesize;
1259
        } else {
1260
            dct_linesize = s->linesize;
1261
            dct_offset = s->linesize * 8;
1262
        }
1263

    
1264
        if (!s->mb_intra) {
1265
            /* motion handling */
1266
            if((s->flags&CODEC_FLAG_HQ) || (!s->encoding)){
1267
                if ((!s->no_rounding) || s->pict_type==B_TYPE){                
1268
                    op_pix = put_pixels_tab;
1269
                    op_qpix= qpel_mc_rnd_tab;
1270
                }else{
1271
                    op_pix = put_no_rnd_pixels_tab;
1272
                    op_qpix= qpel_mc_no_rnd_tab;
1273
                }
1274

    
1275
                if (s->mv_dir & MV_DIR_FORWARD) {
1276
                    MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
1277
                    if ((!s->no_rounding) || s->pict_type==B_TYPE)
1278
                        op_pix = avg_pixels_tab;
1279
                    else
1280
                        op_pix = avg_no_rnd_pixels_tab;
1281
                }
1282
                if (s->mv_dir & MV_DIR_BACKWARD) {
1283
                    MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
1284
                }
1285
            }
1286

    
1287
            /* add dct residue */
1288
            add_dct(s, block[0], 0, dest_y, dct_linesize);
1289
            add_dct(s, block[1], 1, dest_y + 8, dct_linesize);
1290
            add_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
1291
            add_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
1292

    
1293
            add_dct(s, block[4], 4, dest_cb, s->linesize >> 1);
1294
            add_dct(s, block[5], 5, dest_cr, s->linesize >> 1);
1295
        } else {
1296
            /* dct only in intra block */
1297
            put_dct(s, block[0], 0, dest_y, dct_linesize);
1298
            put_dct(s, block[1], 1, dest_y + 8, dct_linesize);
1299
            put_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
1300
            put_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
1301

    
1302
            put_dct(s, block[4], 4, dest_cb, s->linesize >> 1);
1303
            put_dct(s, block[5], 5, dest_cr, s->linesize >> 1);
1304
        }
1305
    }
1306
 the_end:
1307
    emms_c(); //FIXME remove
1308
}
1309

    
1310

    
1311
static void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
1312
{
1313
    const int mb_x= s->mb_x;
1314
    const int mb_y= s->mb_y;
1315
    int i;
1316
#if 0
1317
        if (s->interlaced_dct) {
1318
            dct_linesize = s->linesize * 2;
1319
            dct_offset = s->linesize;
1320
        } else {
1321
            dct_linesize = s->linesize;
1322
            dct_offset = s->linesize * 8;
1323
        }
1324
#endif
1325

    
1326
    if (s->mb_intra) {
1327
        UINT8 *ptr;
1328
        int wrap;
1329

    
1330
        wrap = s->linesize;
1331
        ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
1332
        get_pixels(s->block[0], ptr               , wrap);
1333
        get_pixels(s->block[1], ptr            + 8, wrap);
1334
        get_pixels(s->block[2], ptr + 8 * wrap    , wrap);
1335
        get_pixels(s->block[3], ptr + 8 * wrap + 8, wrap);
1336

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

    
1341
        ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
1342
        get_pixels(s->block[5], ptr, wrap);
1343
    }else{
1344
        op_pixels_func *op_pix;
1345
        qpel_mc_func *op_qpix;
1346
        UINT8 *dest_y, *dest_cb, *dest_cr;
1347
        UINT8 *ptr;
1348
        int wrap;
1349

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

    
1354
        if ((!s->no_rounding) || s->pict_type==B_TYPE){
1355
            op_pix = put_pixels_tab;
1356
            op_qpix= qpel_mc_rnd_tab;
1357
        }else{
1358
            op_pix = put_no_rnd_pixels_tab;
1359
            op_qpix= qpel_mc_no_rnd_tab;
1360
        }
1361

    
1362
        if (s->mv_dir & MV_DIR_FORWARD) {
1363
            MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
1364
           if ((!s->no_rounding) || s->pict_type==B_TYPE)
1365
                op_pix = avg_pixels_tab;
1366
            else
1367
                op_pix = avg_no_rnd_pixels_tab;
1368
        }
1369
        if (s->mv_dir & MV_DIR_BACKWARD) {
1370
            MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
1371
        }
1372
        wrap = s->linesize;
1373
        ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
1374
        diff_pixels(s->block[0], ptr               , dest_y               , wrap);
1375
        diff_pixels(s->block[1], ptr            + 8, dest_y            + 8, wrap);
1376
        diff_pixels(s->block[2], ptr + 8 * wrap    , dest_y + 8 * wrap    , wrap);
1377
        diff_pixels(s->block[3], ptr + 8 * wrap + 8, dest_y + 8 * wrap + 8, wrap);
1378

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

    
1383
        ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
1384
        diff_pixels(s->block[5], ptr, dest_cr, wrap);
1385
    }
1386
            
1387
#if 0
1388
            {
1389
                float adap_parm;
1390
                
1391
                adap_parm = ((s->avg_mb_var << 1) + s->mb_var[s->mb_width*mb_y+mb_x] + 1.0) /
1392
                            ((s->mb_var[s->mb_width*mb_y+mb_x] << 1) + s->avg_mb_var + 1.0);
1393
            
1394
                printf("\ntype=%c qscale=%2d adap=%0.2f dquant=%4.2f var=%4d avgvar=%4d", 
1395
                        (s->mb_type[s->mb_width*mb_y+mb_x] > 0) ? 'I' : 'P', 
1396
                        s->qscale, adap_parm, s->qscale*adap_parm,
1397
                        s->mb_var[s->mb_width*mb_y+mb_x], s->avg_mb_var);
1398
            }
1399
#endif
1400
    /* DCT & quantize */
1401
    if (s->h263_msmpeg4) {
1402
        msmpeg4_dc_scale(s);
1403
    } else if (s->h263_pred) {
1404
        h263_dc_scale(s);
1405
    } else {
1406
        /* default quantization values */
1407
        s->y_dc_scale = 8;
1408
        s->c_dc_scale = 8;
1409
    }
1410
    for(i=0;i<6;i++) {
1411
        s->block_last_index[i] = dct_quantize(s, s->block[i], i, s->qscale);
1412
    }
1413

    
1414
    /* huffman encode */
1415
    switch(s->out_format) {
1416
    case FMT_MPEG1:
1417
        mpeg1_encode_mb(s, s->block, motion_x, motion_y);
1418
        break;
1419
    case FMT_H263:
1420
        if (s->h263_msmpeg4)
1421
            msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
1422
        else if(s->h263_pred)
1423
            mpeg4_encode_mb(s, s->block, motion_x, motion_y);
1424
        else
1425
            h263_encode_mb(s, s->block, motion_x, motion_y);
1426
        break;
1427
    case FMT_MJPEG:
1428
        mjpeg_encode_mb(s, s->block);
1429
        break;
1430
    }
1431
}
1432

    
1433
static void copy_bits(PutBitContext *pb, UINT8 *src, int length)
1434
{
1435
#if 1
1436
    int bytes= length>>4;
1437
    int bits= length&15;
1438
    int i;
1439

    
1440
    for(i=0; i<bytes; i++) put_bits(pb, 16, be2me_16(((uint16_t*)src)[i]));
1441
    put_bits(pb, bits, be2me_16(((uint16_t*)src)[i])>>(16-bits));
1442
#else
1443
    int bytes= length>>3;
1444
    int bits= length&7;
1445
    int i;
1446

    
1447
    for(i=0; i<bytes; i++) put_bits(pb, 8, src[i]);
1448
    put_bits(pb, bits, src[i]>>(8-bits));
1449
#endif
1450
}
1451

    
1452
static void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
1453
    int i;
1454

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

    
1457
    /* mpeg1 */
1458
    d->mb_incr= s->mb_incr;
1459
    for(i=0; i<3; i++)
1460
        d->last_dc[i]= s->last_dc[i];
1461
    
1462
    /* statistics */
1463
    d->mv_bits= s->mv_bits;
1464
    d->i_tex_bits= s->i_tex_bits;
1465
    d->p_tex_bits= s->p_tex_bits;
1466
    d->i_count= s->i_count;
1467
    d->p_count= s->p_count;
1468
    d->skip_count= s->skip_count;
1469
    d->misc_bits= s->misc_bits;
1470
    d->last_bits= 0;
1471

    
1472
    d->mb_skiped= s->mb_skiped;
1473
}
1474

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

    
1478
    memcpy(d->mv, s->mv, 2*4*2*sizeof(int)); 
1479
    memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
1480
    
1481
    /* mpeg1 */
1482
    d->mb_incr= s->mb_incr;
1483
    for(i=0; i<3; i++)
1484
        d->last_dc[i]= s->last_dc[i];
1485
    
1486
    /* statistics */
1487
    d->mv_bits= s->mv_bits;
1488
    d->i_tex_bits= s->i_tex_bits;
1489
    d->p_tex_bits= s->p_tex_bits;
1490
    d->i_count= s->i_count;
1491
    d->p_count= s->p_count;
1492
    d->skip_count= s->skip_count;
1493
    d->misc_bits= s->misc_bits;
1494

    
1495
    d->mb_intra= s->mb_intra;
1496
    d->mb_skiped= s->mb_skiped;
1497
    d->mv_type= s->mv_type;
1498
    d->mv_dir= s->mv_dir;
1499
    d->pb= s->pb;
1500
    d->block= s->block;
1501
    for(i=0; i<6; i++)
1502
        d->block_last_index[i]= s->block_last_index[i];
1503
}
1504

    
1505

    
1506
static void encode_picture(MpegEncContext *s, int picture_number)
1507
{
1508
    int mb_x, mb_y, last_gob, pdif = 0;
1509
    int i;
1510
    int bits;
1511
    MpegEncContext best_s, backup_s;
1512
    UINT8 bit_buf[7][3000]; //FIXME check that this is ALLWAYS large enogh for a MB
1513

    
1514
    s->picture_number = picture_number;
1515

    
1516
    s->block_wrap[0]=
1517
    s->block_wrap[1]=
1518
    s->block_wrap[2]=
1519
    s->block_wrap[3]= s->mb_width*2 + 2;
1520
    s->block_wrap[4]=
1521
    s->block_wrap[5]= s->mb_width + 2;
1522
    
1523
    /* Reset the average MB variance */
1524
    s->avg_mb_var = 0;
1525
    s->mc_mb_var = 0;
1526

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

    
1531
    /* Estimate motion for every MB */
1532
    if(s->pict_type != I_TYPE){
1533
//        int16_t (*tmp)[2]= s->p_mv_table;
1534
//        s->p_mv_table= s->last_mv_table;
1535
//        s->last_mv_table= s->mv_table;
1536
    
1537
        for(mb_y=0; mb_y < s->mb_height; mb_y++) {
1538
            s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
1539
            s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
1540
            s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
1541
            s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
1542
            for(mb_x=0; mb_x < s->mb_width; mb_x++) {
1543
                s->mb_x = mb_x;
1544
                s->mb_y = mb_y;
1545
                s->block_index[0]+=2;
1546
                s->block_index[1]+=2;
1547
                s->block_index[2]+=2;
1548
                s->block_index[3]+=2;
1549

    
1550
                /* compute motion vector & mb_type and store in context */
1551
                if(s->pict_type==B_TYPE)
1552
                    ff_estimate_b_frame_motion(s, mb_x, mb_y);
1553
                else
1554
                    ff_estimate_p_frame_motion(s, mb_x, mb_y);
1555
//                s->mb_type[mb_y*s->mb_width + mb_x]=MB_TYPE_INTER;
1556
            }
1557
        }
1558
        emms_c();
1559
    }else if(s->pict_type == I_TYPE){
1560
        /* I-Frame */
1561
        //FIXME do we need to zero them?
1562
        memset(s->motion_val[0], 0, sizeof(INT16)*(s->mb_width*2 + 2)*(s->mb_height*2 + 2)*2);
1563
        memset(s->p_mv_table   , 0, sizeof(INT16)*(s->mb_width+2)*(s->mb_height+2)*2);
1564
        memset(s->mb_type      , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
1565
    }
1566

    
1567
    if(s->avg_mb_var < s->mc_mb_var && s->pict_type == P_TYPE){ //FIXME subtract MV bits
1568
        s->pict_type= I_TYPE;
1569
        memset(s->mb_type   , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
1570
        if(s->max_b_frames==0){
1571
            s->input_pict_type= I_TYPE;
1572
            s->input_picture_in_gop_number=0;
1573
        }
1574
//printf("Scene change detected, encoding as I Frame\n");
1575
    }
1576
    
1577
    if(s->pict_type==P_TYPE || s->pict_type==S_TYPE) 
1578
        s->f_code= ff_get_best_fcode(s, s->p_mv_table, MB_TYPE_INTER);
1579
        ff_fix_long_p_mvs(s);
1580
    if(s->pict_type==B_TYPE){
1581
        s->f_code= ff_get_best_fcode(s, s->b_forw_mv_table, MB_TYPE_FORWARD);
1582
        s->b_code= ff_get_best_fcode(s, s->b_back_mv_table, MB_TYPE_BACKWARD);
1583

    
1584
        ff_fix_long_b_mvs(s, s->b_forw_mv_table, s->f_code, MB_TYPE_FORWARD);
1585
        ff_fix_long_b_mvs(s, s->b_back_mv_table, s->b_code, MB_TYPE_BACKWARD);
1586
        ff_fix_long_b_mvs(s, s->b_bidir_forw_mv_table, s->f_code, MB_TYPE_BIDIR);
1587
        ff_fix_long_b_mvs(s, s->b_bidir_back_mv_table, s->b_code, MB_TYPE_BIDIR);
1588
    }
1589
    
1590
//printf("f_code %d ///\n", s->f_code);
1591

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

    
1594
    if(s->flags&CODEC_FLAG_PASS2)
1595
        s->qscale = ff_rate_estimate_qscale_pass2(s);
1596
    else if (!s->fixed_qscale) 
1597
        s->qscale = ff_rate_estimate_qscale(s);
1598

    
1599

    
1600
    /* precompute matrix */
1601
    if (s->out_format == FMT_MJPEG) {
1602
        /* for mjpeg, we do include qscale in the matrix */
1603
        s->intra_matrix[0] = default_intra_matrix[0];
1604
        for(i=1;i<64;i++)
1605
            s->intra_matrix[i] = (default_intra_matrix[i] * s->qscale) >> 3;
1606
        convert_matrix(s->q_intra_matrix, s->q_intra_matrix16, s->intra_matrix, 8);
1607
    } else {
1608
        convert_matrix(s->q_intra_matrix, s->q_intra_matrix16, s->intra_matrix, s->qscale);
1609
        convert_matrix(s->q_non_intra_matrix, s->q_non_intra_matrix16, s->non_intra_matrix, s->qscale);
1610
    }
1611

    
1612
    s->last_bits= get_bit_count(&s->pb);
1613
    switch(s->out_format) {
1614
    case FMT_MJPEG:
1615
        mjpeg_picture_header(s);
1616
        break;
1617
    case FMT_H263:
1618
        if (s->h263_msmpeg4) 
1619
            msmpeg4_encode_picture_header(s, picture_number);
1620
        else if (s->h263_pred)
1621
            mpeg4_encode_picture_header(s, picture_number);
1622
        else if (s->h263_rv10) 
1623
            rv10_encode_picture_header(s, picture_number);
1624
        else
1625
            h263_encode_picture_header(s, picture_number);
1626
        break;
1627
    case FMT_MPEG1:
1628
        mpeg1_encode_picture_header(s, picture_number);
1629
        break;
1630
    }
1631
    bits= get_bit_count(&s->pb);
1632
    s->header_bits= bits - s->last_bits;
1633
    s->last_bits= bits;
1634
    s->mv_bits=0;
1635
    s->misc_bits=0;
1636
    s->i_tex_bits=0;
1637
    s->p_tex_bits=0;
1638
    s->i_count=0;
1639
    s->p_count=0;
1640
    s->skip_count=0;
1641

    
1642
    /* init last dc values */
1643
    /* note: quant matrix value (8) is implied here */
1644
    s->last_dc[0] = 128;
1645
    s->last_dc[1] = 128;
1646
    s->last_dc[2] = 128;
1647
    s->mb_incr = 1;
1648
    s->last_mv[0][0][0] = 0;
1649
    s->last_mv[0][0][1] = 0;
1650

    
1651
    /* Get the GOB height based on picture height */
1652
    if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4) {
1653
        if (s->height <= 400)
1654
            s->gob_index = 1;
1655
        else if (s->height <= 800)
1656
            s->gob_index = 2;
1657
        else
1658
            s->gob_index = 4;
1659
    }
1660
        
1661
    s->avg_mb_var = s->avg_mb_var / s->mb_num;        
1662
    
1663
    for(mb_y=0; mb_y < s->mb_height; mb_y++) {
1664
        /* Put GOB header based on RTP MTU */
1665
        /* TODO: Put all this stuff in a separate generic function */
1666
        if (s->rtp_mode) {
1667
            if (!mb_y) {
1668
                s->ptr_lastgob = s->pb.buf;
1669
                s->ptr_last_mb_line = s->pb.buf;
1670
            } else if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4 && !(mb_y % s->gob_index)) {
1671
                last_gob = h263_encode_gob_header(s, mb_y);
1672
                if (last_gob) {
1673
                    s->first_gob_line = 1;
1674
                }
1675
            }
1676
        }
1677
        
1678
        s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
1679
        s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
1680
        s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
1681
        s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
1682
        s->block_index[4]= s->block_wrap[4]*(mb_y + 1)                    + s->block_wrap[0]*(s->mb_height*2 + 2);
1683
        s->block_index[5]= s->block_wrap[4]*(mb_y + 1 + s->mb_height + 2) + s->block_wrap[0]*(s->mb_height*2 + 2);
1684
        for(mb_x=0; mb_x < s->mb_width; mb_x++) {
1685
            const int mb_type= s->mb_type[mb_y * s->mb_width + mb_x];
1686
            const int xy= (mb_y+1) * (s->mb_width+2) + mb_x + 1;
1687
            PutBitContext pb;
1688
            int d;
1689
            int dmin=10000000;
1690
            int best=0;
1691

    
1692
            s->mb_x = mb_x;
1693
            s->mb_y = mb_y;
1694
            s->block_index[0]+=2;
1695
            s->block_index[1]+=2;
1696
            s->block_index[2]+=2;
1697
            s->block_index[3]+=2;
1698
            s->block_index[4]++;
1699
            s->block_index[5]++;
1700
            if(mb_type & (mb_type-1)){ // more than 1 MB type possible
1701
                int next_block=0;
1702
                pb= s->pb;
1703

    
1704
                copy_context_before_encode(&backup_s, s, -1);
1705

    
1706
                if(mb_type&MB_TYPE_INTER){
1707
                    s->mv_dir = MV_DIR_FORWARD;
1708
                    s->mv_type = MV_TYPE_16X16;
1709
                    s->mb_intra= 0;
1710
                    s->mv[0][0][0] = s->p_mv_table[xy][0];
1711
                    s->mv[0][0][1] = s->p_mv_table[xy][1];
1712
                    init_put_bits(&s->pb, bit_buf[1], 3000, NULL, NULL);
1713
                    s->block= s->blocks[next_block];
1714
                    s->last_bits= 0; //done in copy_context_before_encode but we skip that here
1715

    
1716
                    encode_mb(s, s->mv[0][0][0], s->mv[0][0][1]);
1717
                    d= get_bit_count(&s->pb);
1718
                    if(d<dmin){
1719
                        flush_put_bits(&s->pb);
1720
                        dmin=d;
1721
                        copy_context_after_encode(&best_s, s, MB_TYPE_INTER);
1722
                        best=1;
1723
                        next_block^=1;
1724
                    }
1725
                }
1726
                if(mb_type&MB_TYPE_INTER4V){                 
1727
                    copy_context_before_encode(s, &backup_s, MB_TYPE_INTER4V);
1728
                    s->mv_dir = MV_DIR_FORWARD;
1729
                    s->mv_type = MV_TYPE_8X8;
1730
                    s->mb_intra= 0;
1731
                    for(i=0; i<4; i++){
1732
                        s->mv[0][i][0] = s->motion_val[s->block_index[i]][0];
1733
                        s->mv[0][i][1] = s->motion_val[s->block_index[i]][1];
1734
                    }
1735
                    init_put_bits(&s->pb, bit_buf[2], 3000, NULL, NULL);
1736
                    s->block= s->blocks[next_block];
1737

    
1738
                    encode_mb(s, 0, 0);
1739
                    d= get_bit_count(&s->pb);
1740
                    if(d<dmin){
1741
                        flush_put_bits(&s->pb);
1742
                        dmin=d;
1743
                        copy_context_after_encode(&best_s, s, MB_TYPE_INTER4V);
1744
                        best=2;
1745
                        next_block^=1;
1746
                    }
1747
                }
1748
                if(mb_type&MB_TYPE_FORWARD){
1749
                    copy_context_before_encode(s, &backup_s, MB_TYPE_FORWARD);
1750
                    s->mv_dir = MV_DIR_FORWARD;
1751
                    s->mv_type = MV_TYPE_16X16;
1752
                    s->mb_intra= 0;
1753
                    s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
1754
                    s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
1755
                    init_put_bits(&s->pb, bit_buf[3], 3000, NULL, NULL);
1756
                    s->block= s->blocks[next_block];
1757

    
1758
                    encode_mb(s, s->mv[0][0][0], s->mv[0][0][1]);
1759
                    d= get_bit_count(&s->pb);
1760
                    if(d<dmin){
1761
                        flush_put_bits(&s->pb);
1762
                        dmin=d;
1763
                        copy_context_after_encode(&best_s, s, MB_TYPE_FORWARD);
1764
                        best=3;
1765
                        next_block^=1;
1766
                    }
1767
                }
1768
                if(mb_type&MB_TYPE_BACKWARD){
1769
                    copy_context_before_encode(s, &backup_s, MB_TYPE_BACKWARD);
1770
                    s->mv_dir = MV_DIR_BACKWARD;
1771
                    s->mv_type = MV_TYPE_16X16;
1772
                    s->mb_intra= 0;
1773
                    s->mv[1][0][0] = s->b_back_mv_table[xy][0];
1774
                    s->mv[1][0][1] = s->b_back_mv_table[xy][1];
1775
                    init_put_bits(&s->pb, bit_buf[4], 3000, NULL, NULL);
1776
                    s->block= s->blocks[next_block];
1777

    
1778
                    encode_mb(s, s->mv[1][0][0], s->mv[1][0][1]);
1779
                    d= get_bit_count(&s->pb);
1780
                    if(d<dmin){
1781
                        flush_put_bits(&s->pb);
1782
                        dmin=d;
1783
                        copy_context_after_encode(&best_s, s, MB_TYPE_BACKWARD);
1784
                        best=4;
1785
                        next_block^=1;
1786
                    }
1787
                }
1788
                if(mb_type&MB_TYPE_BIDIR){
1789
                    copy_context_before_encode(s, &backup_s, MB_TYPE_BIDIR);
1790
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
1791
                    s->mv_type = MV_TYPE_16X16;
1792
                    s->mb_intra= 0;
1793
                    s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
1794
                    s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
1795
                    s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
1796
                    s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
1797
                    init_put_bits(&s->pb, bit_buf[5], 3000, NULL, NULL);
1798
                    s->block= s->blocks[next_block];
1799

    
1800
                    encode_mb(s, 0, 0);
1801
                    d= get_bit_count(&s->pb);
1802
                    if(d<dmin){
1803
                        flush_put_bits(&s->pb);
1804
                        dmin=d;
1805
                        copy_context_after_encode(&best_s, s, MB_TYPE_BIDIR);
1806
                        best=5;
1807
                        next_block^=1;
1808
                    }
1809
                }
1810
                if(mb_type&MB_TYPE_DIRECT){
1811
                    copy_context_before_encode(s, &backup_s, MB_TYPE_DIRECT);
1812
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1813
                    s->mv_type = MV_TYPE_16X16; //FIXME
1814
                    s->mb_intra= 0;
1815
                    s->mv[0][0][0] = s->b_direct_forw_mv_table[xy][0];
1816
                    s->mv[0][0][1] = s->b_direct_forw_mv_table[xy][1];
1817
                    s->mv[1][0][0] = s->b_direct_back_mv_table[xy][0];
1818
                    s->mv[1][0][1] = s->b_direct_back_mv_table[xy][1];
1819
                    init_put_bits(&s->pb, bit_buf[6], 3000, NULL, NULL);
1820
                    s->block= s->blocks[next_block];
1821

    
1822
                    encode_mb(s, s->b_direct_mv_table[xy][0], s->b_direct_mv_table[xy][1]);
1823
                    d= get_bit_count(&s->pb);
1824
                    if(d<dmin){
1825
                        flush_put_bits(&s->pb);
1826
                        dmin=d;
1827
                        copy_context_after_encode(&best_s, s, MB_TYPE_DIRECT);
1828
                        best=6;
1829
                        next_block^=1;
1830
                    }
1831
                }
1832
                if(mb_type&MB_TYPE_INTRA){
1833
                    copy_context_before_encode(s, &backup_s, MB_TYPE_INTRA);
1834
                    s->mv_dir = MV_DIR_FORWARD;
1835
                    s->mv_type = MV_TYPE_16X16;
1836
                    s->mb_intra= 1;
1837
                    s->mv[0][0][0] = 0;
1838
                    s->mv[0][0][1] = 0;
1839
                    init_put_bits(&s->pb, bit_buf[0], 3000, NULL, NULL);
1840
                    s->block= s->blocks[next_block];
1841
                   
1842
                    encode_mb(s, 0, 0);
1843
                    d= get_bit_count(&s->pb);
1844
                    if(d<dmin){
1845
                        flush_put_bits(&s->pb);
1846
                        dmin=d;
1847
                        copy_context_after_encode(&best_s, s, MB_TYPE_INTRA);
1848
                        best=0;
1849
                        next_block^=1;
1850
                    }
1851
                    /* force cleaning of ac/dc pred stuff if needed ... */
1852
                    if(s->h263_pred || s->h263_aic)
1853
                        s->mbintra_table[mb_x + mb_y*s->mb_width]=1;
1854
                }
1855
                copy_context_after_encode(s, &best_s, -1);
1856
                copy_bits(&pb, bit_buf[best], dmin);
1857
                s->pb= pb;
1858
                s->last_bits= get_bit_count(&s->pb);
1859
            } else {
1860
                int motion_x, motion_y;
1861
                s->mv_type=MV_TYPE_16X16;
1862
                // only one MB-Type possible
1863
                switch(mb_type){
1864
                case MB_TYPE_INTRA:
1865
                    s->mv_dir = MV_DIR_FORWARD;
1866
                    s->mb_intra= 1;
1867
                    motion_x= s->mv[0][0][0] = 0;
1868
                    motion_y= s->mv[0][0][1] = 0;
1869
                    break;
1870
                case MB_TYPE_INTER:
1871
                    s->mv_dir = MV_DIR_FORWARD;
1872
                    s->mb_intra= 0;
1873
                    motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
1874
                    motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
1875
                    break;
1876
                case MB_TYPE_DIRECT:
1877
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1878
                    s->mb_intra= 0;
1879
                    motion_x=s->b_direct_mv_table[xy][0];
1880
                    motion_y=s->b_direct_mv_table[xy][1];
1881
                    s->mv[0][0][0] = s->b_direct_forw_mv_table[xy][0];
1882
                    s->mv[0][0][1] = s->b_direct_forw_mv_table[xy][1];
1883
                    s->mv[1][0][0] = s->b_direct_back_mv_table[xy][0];
1884
                    s->mv[1][0][1] = s->b_direct_back_mv_table[xy][1];
1885
                    break;
1886
                case MB_TYPE_BIDIR:
1887
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
1888
                    s->mb_intra= 0;
1889
                    motion_x=0;
1890
                    motion_y=0;
1891
                    s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
1892
                    s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
1893
                    s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
1894
                    s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
1895
                    break;
1896
                case MB_TYPE_BACKWARD:
1897
                    s->mv_dir = MV_DIR_BACKWARD;
1898
                    s->mb_intra= 0;
1899
                    motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
1900
                    motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
1901
                    break;
1902
                case MB_TYPE_FORWARD:
1903
                    s->mv_dir = MV_DIR_FORWARD;
1904
                    s->mb_intra= 0;
1905
                    motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
1906
                    motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
1907
//                    printf(" %d %d ", motion_x, motion_y);
1908
                    break;
1909
                default:
1910
                    motion_x=motion_y=0; //gcc warning fix
1911
                    printf("illegal MB type\n");
1912
                }
1913
                encode_mb(s, motion_x, motion_y);
1914
            }
1915
            /* clean the MV table in IPS frames for direct mode in B frames */
1916
            if(s->mb_intra /* && I,P,S_TYPE */){
1917
                s->p_mv_table[xy][0]=0;
1918
                s->p_mv_table[xy][1]=0;
1919
            }
1920

    
1921
            MPV_decode_mb(s, s->block);
1922
        }
1923

    
1924

    
1925
        /* Obtain average GOB size for RTP */
1926
        if (s->rtp_mode) {
1927
            if (!mb_y)
1928
                s->mb_line_avgsize = pbBufPtr(&s->pb) - s->ptr_last_mb_line;
1929
            else if (!(mb_y % s->gob_index)) {    
1930
                s->mb_line_avgsize = (s->mb_line_avgsize + pbBufPtr(&s->pb) - s->ptr_last_mb_line) >> 1;
1931
                s->ptr_last_mb_line = pbBufPtr(&s->pb);
1932
            }
1933
            //fprintf(stderr, "\nMB line: %d\tSize: %u\tAvg. Size: %u", s->mb_y, 
1934
            //                    (s->pb.buf_ptr - s->ptr_last_mb_line), s->mb_line_avgsize);
1935
            s->first_gob_line = 0;
1936
        }
1937
    }
1938
    emms_c();
1939

    
1940
    if (s->h263_msmpeg4 && s->msmpeg4_version<4 && s->pict_type == I_TYPE)
1941
        msmpeg4_encode_ext_header(s);
1942

    
1943
    //if (s->gob_number)
1944
    //    fprintf(stderr,"\nNumber of GOB: %d", s->gob_number);
1945
    
1946
    /* Send the last GOB if RTP */    
1947
    if (s->rtp_mode) {
1948
        flush_put_bits(&s->pb);
1949
        pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
1950
        /* Call the RTP callback to send the last GOB */
1951
        if (s->rtp_callback)
1952
            s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
1953
        s->ptr_lastgob = pbBufPtr(&s->pb);
1954
        //fprintf(stderr,"\nGOB: %2d size: %d (last)", s->gob_number, pdif);
1955
    }
1956
}
1957

    
1958
static int dct_quantize_c(MpegEncContext *s, 
1959
                        DCTELEM *block, int n,
1960
                        int qscale)
1961
{
1962
    int i, j, level, last_non_zero, q;
1963
    const int *qmat;
1964
    int minLevel, maxLevel;
1965

    
1966
    if(s->avctx!=NULL && s->avctx->codec->id==CODEC_ID_MPEG4){
1967
        /* mpeg4 */
1968
        minLevel= -2048;
1969
        maxLevel= 2047;
1970
    }else if(s->out_format==FMT_MPEG1){
1971
        /* mpeg1 */
1972
        minLevel= -255;
1973
        maxLevel= 255;
1974
    }else if(s->out_format==FMT_MJPEG){
1975
        /* (m)jpeg */
1976
        minLevel= -1023;
1977
        maxLevel= 1023;
1978
    }else{
1979
        /* h263 / msmpeg4 */
1980
        minLevel= -128;
1981
        maxLevel= 127;
1982
    }
1983

    
1984
    av_fdct (block);
1985

    
1986
    /* we need this permutation so that we correct the IDCT
1987
       permutation. will be moved into DCT code */
1988
    block_permute(block);
1989

    
1990
    if (s->mb_intra) {
1991
        if (n < 4)
1992
            q = s->y_dc_scale;
1993
        else
1994
            q = s->c_dc_scale;
1995
        q = q << 3;
1996
        
1997
        /* note: block[0] is assumed to be positive */
1998
        block[0] = (block[0] + (q >> 1)) / q;
1999
        i = 1;
2000
        last_non_zero = 0;
2001
        if (s->out_format == FMT_H263) {
2002
            qmat = s->q_non_intra_matrix;
2003
        } else {
2004
            qmat = s->q_intra_matrix;
2005
        }
2006
    } else {
2007
        i = 0;
2008
        last_non_zero = -1;
2009
        qmat = s->q_non_intra_matrix;
2010
    }
2011

    
2012
    for(;i<64;i++) {
2013
        j = zigzag_direct[i];
2014
        level = block[j];
2015
        level = level * qmat[j];
2016
#ifdef PARANOID
2017
        {
2018
            static int count = 0;
2019
            int level1, level2, qmat1;
2020
            double val;
2021
            if (qmat == s->q_non_intra_matrix) {
2022
                qmat1 = default_non_intra_matrix[j] * s->qscale;
2023
            } else {
2024
                qmat1 = default_intra_matrix[j] * s->qscale;
2025
            }
2026
            if (av_fdct != jpeg_fdct_ifast)
2027
                val = ((double)block[j] * 8.0) / (double)qmat1;
2028
            else
2029
                val = ((double)block[j] * 8.0 * 2048.0) / 
2030
                    ((double)qmat1 * aanscales[j]);
2031
            level1 = (int)val;
2032
            level2 = level / (1 << (QMAT_SHIFT - 3));
2033
            if (level1 != level2) {
2034
                fprintf(stderr, "%d: quant error qlevel=%d wanted=%d level=%d qmat1=%d qmat=%d wantedf=%0.6f\n", 
2035
                        count, level2, level1, block[j], qmat1, qmat[j],
2036
                        val);
2037
                count++;
2038
            }
2039

    
2040
        }
2041
#endif
2042
        /* XXX: slight error for the low range. Test should be equivalent to
2043
           (level <= -(1 << (QMAT_SHIFT - 3)) || level >= (1 <<
2044
           (QMAT_SHIFT - 3)))
2045
        */
2046
        if (((level << (31 - (QMAT_SHIFT - 3))) >> (31 - (QMAT_SHIFT - 3))) != 
2047
            level) {
2048
            level = level / (1 << (QMAT_SHIFT - 3));
2049
            /* XXX: currently, this code is not optimal. the range should be:
2050
               mpeg1: -255..255
2051
               mpeg2: -2048..2047
2052
               h263:  -128..127
2053
               mpeg4: -2048..2047
2054
            */
2055
            if (level > maxLevel)
2056
                level = maxLevel;
2057
            else if (level < minLevel)
2058
                level = minLevel;
2059

    
2060
            block[j] = level;
2061
            last_non_zero = i;
2062
        } else {
2063
            block[j] = 0;
2064
        }
2065
    }
2066
    return last_non_zero;
2067
}
2068

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

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

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

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

    
2195

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

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

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

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

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

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

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

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

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

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

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

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