Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegvideo.c @ d697b89b

History | View | Annotate | Download (77.9 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
    }
633
}
634

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

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

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

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

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

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

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

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

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

    
720
    s->input_qscale = avctx->quality;
721

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

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

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

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

    
764
        MPV_frame_start(s);
765

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

    
777
        MPV_frame_end(s);
778

    
779
        if (s->out_format == FMT_MJPEG)
780
            mjpeg_picture_trailer(s);
781

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

    
788
    s->input_picture_number++;
789
    s->input_picture_in_gop_number++;
790

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
988

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

    
998
    mb_x = s->mb_x;
999
    mb_y = s->mb_y;
1000

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

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

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

    
1103
        }
1104
        break;
1105
    }
1106
}
1107

    
1108

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

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

    
1128
        ff_idct (block);
1129
        add_pixels_clamped(block, dest, line_size);
1130
    }
1131
}
1132

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

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

    
1150
    mb_x = s->mb_x;
1151
    mb_y = s->mb_y;
1152

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

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

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

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

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

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

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

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

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

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

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

    
1308

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1470
    d->mb_skiped= s->mb_skiped;
1471
}
1472

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

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

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

    
1503

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

    
1512
    s->picture_number = picture_number;
1513

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

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

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

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

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

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

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

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

    
1597

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

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

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

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

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

    
1702
                copy_context_before_encode(&backup_s, s, -1);
1703

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

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

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

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

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

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

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

    
1919
            MPV_decode_mb(s, s->block);
1920
        }
1921

    
1922

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

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

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

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

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

    
1982
    av_fdct (block);
1983

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

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

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

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

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

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

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

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

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

    
2193

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

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

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

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

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

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

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

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

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

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

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

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