Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegvideo.c @ 3bf43d42

History | View | Annotate | Download (69.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 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 rate_control_init(MpegEncContext *s);
35
static int rate_estimate_qscale(MpegEncContext *s);
36
static void dct_unquantize_mpeg1_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
/* for jpeg fast DCT */
54
#define CONST_BITS 14
55

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

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

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

    
75
/* default motion estimation */
76
int motion_estimation_method = ME_LOG;
77

    
78
extern UINT8 zigzag_end[64];
79

    
80
static void convert_matrix(int *qmat, UINT16 *qmat16, const UINT16 *quant_matrix, int qscale)
81
{
82
    int i;
83

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

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

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

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

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

    
139
        pict = av_mallocz(c_size);
140
        if (pict == NULL)
141
            goto fail;
142
        s->last_picture_base[i] = pict;
143
        s->last_picture[i] = pict + pict_start;
144
    
145
        pict = av_mallocz(c_size);
146
        if (pict == NULL)
147
            goto fail;
148
        s->next_picture_base[i] = pict;
149
        s->next_picture[i] = pict + pict_start;
150

    
151
        if (s->has_b_frames) {
152
            pict = av_mallocz(c_size);
153
            if (pict == NULL) 
154
                goto fail;
155
            s->aux_picture_base[i] = pict;
156
            s->aux_picture[i] = pict + pict_start;
157
        }
158
    }
159
    
160
    if (s->encoding) {
161
        /* Allocate MB type table */
162
        s->mb_type = av_mallocz(s->mb_num * sizeof(char));
163
        if (s->mb_type == NULL) {
164
            perror("malloc");
165
            goto fail;
166
        }
167
        
168
        s->mb_var = av_mallocz(s->mb_num * sizeof(INT16));
169
        if (s->mb_var == NULL) {
170
            perror("malloc");
171
            goto fail;
172
        }
173
        /* Allocate MV table */
174
        /* By now we just have one MV per MB */
175
        s->mv_table[0] = av_mallocz(s->mb_num * sizeof(INT16));
176
        s->mv_table[1] = av_mallocz(s->mb_num * sizeof(INT16));
177
        if (s->mv_table[1] == NULL || s->mv_table[0] == NULL) {
178
            perror("malloc");
179
            goto fail;
180
        }
181
    }
182
    
183
    if (s->out_format == FMT_H263 || s->encoding) {
184
        int size;
185
        /* MV prediction */
186
        size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
187
        s->motion_val = malloc(size * 2 * sizeof(INT16));
188
        if (s->motion_val == NULL)
189
            goto fail;
190
        memset(s->motion_val, 0, size * 2 * sizeof(INT16));
191
    }
192

    
193
    if (s->h263_pred || s->h263_plus) {
194
        int y_size, c_size, i, size;
195
        
196
        /* dc values */
197

    
198
        y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
199
        c_size = (s->mb_width + 2) * (s->mb_height + 2);
200
        size = y_size + 2 * c_size;
201
        s->dc_val[0] = malloc(size * sizeof(INT16));
202
        if (s->dc_val[0] == NULL)
203
            goto fail;
204
        s->dc_val[1] = s->dc_val[0] + y_size;
205
        s->dc_val[2] = s->dc_val[1] + c_size;
206
        for(i=0;i<size;i++)
207
            s->dc_val[0][i] = 1024;
208

    
209
        /* ac values */
210
        s->ac_val[0] = av_mallocz(size * sizeof(INT16) * 16);
211
        if (s->ac_val[0] == NULL)
212
            goto fail;
213
        s->ac_val[1] = s->ac_val[0] + y_size;
214
        s->ac_val[2] = s->ac_val[1] + c_size;
215
        
216
        /* cbp values */
217
        s->coded_block = av_mallocz(y_size);
218
        if (!s->coded_block)
219
            goto fail;
220

    
221
        /* which mb is a intra block */
222
        s->mbintra_table = av_mallocz(s->mb_num);
223
        if (!s->mbintra_table)
224
            goto fail;
225
        memset(s->mbintra_table, 1, s->mb_num);
226
    }
227
    /* default structure is frame */
228
    s->picture_structure = PICT_FRAME;
229

    
230
    /* init macroblock skip table */
231
    if (!s->encoding) {
232
        s->mbskip_table = av_mallocz(s->mb_num);
233
        if (!s->mbskip_table)
234
            goto fail;
235
    }
236
    
237
    s->block= s->intra_block;
238

    
239
    s->context_initialized = 1;
240
    return 0;
241
 fail:
242
    MPV_common_end(s);
243
    return -1;
244
}
245

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

    
251
    if (s->mb_type)
252
        free(s->mb_type);
253
    if (s->mb_var)
254
        free(s->mb_var);
255
    if (s->mv_table[0])
256
        free(s->mv_table[0]);
257
    if (s->mv_table[1])
258
        free(s->mv_table[1]);
259
    if (s->motion_val)
260
        free(s->motion_val);
261
    if (s->dc_val[0])
262
        free(s->dc_val[0]);
263
    if (s->ac_val[0])
264
        free(s->ac_val[0]);
265
    if (s->coded_block)
266
        free(s->coded_block);
267
    if (s->mbintra_table)
268
        free(s->mbintra_table);
269

    
270
    if (s->mbskip_table)
271
        free(s->mbskip_table);
272
    for(i=0;i<3;i++) {
273
        if (s->last_picture_base[i])
274
            free(s->last_picture_base[i]);
275
        if (s->next_picture_base[i])
276
            free(s->next_picture_base[i]);
277
        if (s->has_b_frames)
278
            free(s->aux_picture_base[i]);
279
    }
280
    s->context_initialized = 0;
281
}
282

    
283
/* init video encoder */
284
int MPV_encode_init(AVCodecContext *avctx)
285
{
286
    MpegEncContext *s = avctx->priv_data;
287
    int i;
288

    
289
    s->bit_rate = avctx->bit_rate;
290
    s->bit_rate_tolerance = avctx->bit_rate_tolerance;
291
    s->frame_rate = avctx->frame_rate;
292
    s->width = avctx->width;
293
    s->height = avctx->height;
294
    s->gop_size = avctx->gop_size;
295
    s->rtp_mode = avctx->rtp_mode;
296
    s->rtp_payload_size = avctx->rtp_payload_size;
297
    if (avctx->rtp_callback)
298
        s->rtp_callback = avctx->rtp_callback;
299
    s->qmin= avctx->qmin;
300
    s->qmax= avctx->qmax;
301
    s->max_qdiff= avctx->max_qdiff;
302
    s->qcompress= avctx->qcompress;
303
    s->qblur= avctx->qblur;
304
    s->avctx = avctx;
305
    s->aspect_ratio_info= avctx->aspect_ratio_info;
306
    s->flags= avctx->flags;
307
    
308
    if (s->gop_size <= 1) {
309
        s->intra_only = 1;
310
        s->gop_size = 12;
311
    } else {
312
        s->intra_only = 0;
313
    }
314
    s->full_search = motion_estimation_method;
315

    
316
    s->fixed_qscale = (avctx->flags & CODEC_FLAG_QSCALE);
317
    
318
    switch(avctx->codec->id) {
319
    case CODEC_ID_MPEG1VIDEO:
320
        s->out_format = FMT_MPEG1;
321
        break;
322
    case CODEC_ID_MJPEG:
323
        s->out_format = FMT_MJPEG;
324
        s->intra_only = 1; /* force intra only for jpeg */
325
        s->mjpeg_write_tables = 1; /* write all tables */
326
        s->mjpeg_vsample[0] = 2; /* set up default sampling factors */
327
        s->mjpeg_vsample[1] = 1; /* the only currently supported values */
328
        s->mjpeg_vsample[2] = 1; 
329
        s->mjpeg_hsample[0] = 2; 
330
        s->mjpeg_hsample[1] = 1; 
331
        s->mjpeg_hsample[2] = 1; 
332
        if (mjpeg_init(s) < 0)
333
            return -1;
334
        break;
335
    case CODEC_ID_H263:
336
        if (h263_get_picture_format(s->width, s->height) == 7) {
337
            printf("Input picture size isn't suitable for h263 codec! try h263+\n");
338
            return -1;
339
        }
340
        s->out_format = FMT_H263;
341
        break;
342
    case CODEC_ID_H263P:
343
        s->out_format = FMT_H263;
344
        s->rtp_mode = 1;
345
        s->rtp_payload_size = 1200; 
346
        s->h263_plus = 1;
347
        s->unrestricted_mv = 1;
348
        
349
        /* These are just to be sure */
350
        s->umvplus = 0;
351
        s->umvplus_dec = 0;
352
        break;
353
    case CODEC_ID_RV10:
354
        s->out_format = FMT_H263;
355
        s->h263_rv10 = 1;
356
        break;
357
    case CODEC_ID_MPEG4:
358
        s->out_format = FMT_H263;
359
        s->h263_pred = 1;
360
        s->unrestricted_mv = 1;
361
        break;
362
    case CODEC_ID_MSMPEG4V1:
363
        s->out_format = FMT_H263;
364
        s->h263_msmpeg4 = 1;
365
        s->h263_pred = 1;
366
        s->unrestricted_mv = 1;
367
        s->msmpeg4_version= 1;
368
        break;
369
    case CODEC_ID_MSMPEG4V2:
370
        s->out_format = FMT_H263;
371
        s->h263_msmpeg4 = 1;
372
        s->h263_pred = 1;
373
        s->unrestricted_mv = 1;
374
        s->msmpeg4_version= 2;
375
        break;
376
    case CODEC_ID_MSMPEG4V3:
377
        s->out_format = FMT_H263;
378
        s->h263_msmpeg4 = 1;
379
        s->h263_pred = 1;
380
        s->unrestricted_mv = 1;
381
        s->msmpeg4_version= 3;
382
        break;
383
    default:
384
        return -1;
385
    }
386
    
387
    if((s->flags&CODEC_FLAG_4MV) && !(s->flags&CODEC_FLAG_HQ)){
388
        printf("4MV is currently only supported in HQ mode\n");
389
        return -1;
390
    }
391

    
392
    { /* set up some save defaults, some codecs might override them later */
393
        static int done=0;
394
        if(!done){
395
            int i;
396
            done=1;
397
            memset(default_mv_penalty, 0, sizeof(UINT16)*(MAX_FCODE+1)*(2*MAX_MV+1));
398
            memset(default_fcode_tab , 0, sizeof(UINT8)*(2*MAX_MV+1));
399

    
400
            for(i=-16; i<16; i++){
401
                default_fcode_tab[i + MAX_MV]= 1;
402
            }
403
        }
404
    }
405
    s->mv_penalty= default_mv_penalty;
406
    s->fcode_tab= default_fcode_tab;
407

    
408
    if (s->out_format == FMT_H263)
409
        h263_encode_init(s);
410
    else if (s->out_format == FMT_MPEG1)
411
        mpeg1_encode_init(s);
412

    
413
    /* dont use mv_penalty table for crap MV as it would be confused */
414
    if(s->full_search<4) s->mv_penalty= default_mv_penalty;
415

    
416
    s->encoding = 1;
417

    
418
    /* init */
419
    if (MPV_common_init(s) < 0)
420
        return -1;
421
    
422
    /* init default q matrix */
423
    for(i=0;i<64;i++) {
424
        s->intra_matrix[i] = default_intra_matrix[i];
425
        s->non_intra_matrix[i] = default_non_intra_matrix[i];
426
    }
427

    
428
    /* rate control init */
429
    rate_control_init(s);
430

    
431
    s->picture_number = 0;
432
    s->picture_in_gop_number = 0;
433
    s->fake_picture_number = 0;
434
    /* motion detector init */
435
    s->f_code = 1;
436

    
437
    return 0;
438
}
439

    
440
int MPV_encode_end(AVCodecContext *avctx)
441
{
442
    MpegEncContext *s = avctx->priv_data;
443

    
444
#ifdef STATS
445
    print_stats();
446
#endif
447
    MPV_common_end(s);
448
    if (s->out_format == FMT_MJPEG)
449
        mjpeg_close(s);
450
      
451
    return 0;
452
}
453

    
454
/* draw the edges of width 'w' of an image of size width, height */
455
static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w)
456
{
457
    UINT8 *ptr, *last_line;
458
    int i;
459

    
460
    last_line = buf + (height - 1) * wrap;
461
    for(i=0;i<w;i++) {
462
        /* top and bottom */
463
        memcpy(buf - (i + 1) * wrap, buf, width);
464
        memcpy(last_line + (i + 1) * wrap, last_line, width);
465
    }
466
    /* left and right */
467
    ptr = buf;
468
    for(i=0;i<height;i++) {
469
        memset(ptr - w, ptr[0], w);
470
        memset(ptr + width, ptr[width-1], w);
471
        ptr += wrap;
472
    }
473
    /* corners */
474
    for(i=0;i<w;i++) {
475
        memset(buf - (i + 1) * wrap - w, buf[0], w); /* top left */
476
        memset(buf - (i + 1) * wrap + width, buf[width-1], w); /* top right */
477
        memset(last_line + (i + 1) * wrap - w, last_line[0], w); /* top left */
478
        memset(last_line + (i + 1) * wrap + width, last_line[width-1], w); /* top right */
479
    }
480
}
481

    
482
/* generic function for encode/decode called before a frame is coded/decoded */
483
void MPV_frame_start(MpegEncContext *s)
484
{
485
    int i;
486
    UINT8 *tmp;
487

    
488
    s->mb_skiped = 0;
489
    if (s->pict_type == B_TYPE) {
490
        for(i=0;i<3;i++) {
491
            s->current_picture[i] = s->aux_picture[i];
492
        }
493
    } else {
494
        s->last_non_b_pict_type= s->pict_type;
495
        for(i=0;i<3;i++) {
496
            /* swap next and last */
497
            tmp = s->last_picture[i];
498
            s->last_picture[i] = s->next_picture[i];
499
            s->next_picture[i] = tmp;
500
            s->current_picture[i] = tmp;
501
        }
502
    }
503
}
504

    
505
/* generic function for encode/decode called after a frame has been coded/decoded */
506
void MPV_frame_end(MpegEncContext *s)
507
{
508
    /* draw edge for correct motion prediction if outside */
509
    if (s->pict_type != B_TYPE && !s->intra_only) {
510
      if(s->avctx==NULL || s->avctx->codec->id!=CODEC_ID_MPEG4 || s->divx_version==500){
511
        draw_edges(s->current_picture[0], s->linesize, s->mb_width*16, s->mb_height*16, EDGE_WIDTH);
512
        draw_edges(s->current_picture[1], s->linesize/2, s->mb_width*8, s->mb_height*8, EDGE_WIDTH/2);
513
        draw_edges(s->current_picture[2], s->linesize/2, s->mb_width*8, s->mb_height*8, EDGE_WIDTH/2);
514
      }else{
515
        /* mpeg4? / opendivx / xvid */
516
        draw_edges(s->current_picture[0], s->linesize, s->width, s->height, EDGE_WIDTH);
517
        draw_edges(s->current_picture[1], s->linesize/2, s->width/2, s->height/2, EDGE_WIDTH/2);
518
        draw_edges(s->current_picture[2], s->linesize/2, s->width/2, s->height/2, EDGE_WIDTH/2);
519
      }
520
    }
521
    emms_c();
522
}
523

    
524
int MPV_encode_picture(AVCodecContext *avctx,
525
                       unsigned char *buf, int buf_size, void *data)
526
{
527
    MpegEncContext *s = avctx->priv_data;
528
    AVPicture *pict = data;
529
    int i, j;
530

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

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

    
536
    s->force_type= (avctx->flags&CODEC_FLAG_TYPE) ?
537
        (avctx->key_frame ? I_TYPE : P_TYPE) : 0;
538
    if (!s->intra_only) {
539
        /* first picture of GOP is intra */
540
        if (s->picture_in_gop_number % s->gop_size==0 || s->force_type==I_TYPE){
541
            s->picture_in_gop_number=0;
542
            s->pict_type = I_TYPE;
543
        }else
544
            s->pict_type = P_TYPE;
545
    } else {
546
        s->pict_type = I_TYPE;
547
    }
548
    
549
    MPV_frame_start(s);
550
    
551
    for(i=0;i<3;i++) {
552
        UINT8 *src = pict->data[i];
553
        UINT8 *dest = s->current_picture[i];
554
        int src_wrap = pict->linesize[i];
555
        int dest_wrap = s->linesize;
556
        int w = s->width;
557
        int h = s->height;
558

    
559
        if (i >= 1) {
560
            dest_wrap >>= 1;
561
            w >>= 1;
562
            h >>= 1;
563
        }
564

    
565
        if(dest_wrap==src_wrap){
566
            s->new_picture[i] = pict->data[i];
567
        } else {
568
            for(j=0;j<h;j++) {
569
                memcpy(dest, src, w);
570
                dest += dest_wrap;
571
                src += src_wrap;
572
            }
573
            s->new_picture[i] = s->current_picture[i];
574
            }
575
    }
576

    
577
    encode_picture(s, s->picture_number);
578
    avctx->key_frame = (s->pict_type == I_TYPE);
579
    avctx->header_bits = s->header_bits;
580
    avctx->mv_bits     = s->mv_bits;
581
    avctx->misc_bits   = s->misc_bits;
582
    avctx->i_tex_bits  = s->i_tex_bits;
583
    avctx->p_tex_bits  = s->p_tex_bits;
584
    avctx->i_count     = s->i_count;
585
    avctx->p_count     = s->p_count;
586
    avctx->skip_count  = s->skip_count;
587

    
588
    MPV_frame_end(s);
589
    s->picture_number++;
590
    s->picture_in_gop_number++;
591

    
592
    if (s->out_format == FMT_MJPEG)
593
        mjpeg_picture_trailer(s);
594

    
595
    flush_put_bits(&s->pb);
596
    s->last_frame_bits= s->frame_bits;
597
    s->frame_bits  = (pbBufPtr(&s->pb) - s->pb.buf) * 8;
598
    s->total_bits += s->frame_bits;
599
    avctx->frame_bits  = s->frame_bits;
600
//printf("fcode: %d, type: %d, head: %d, mv: %d, misc: %d, frame: %d, itex: %d, ptex: %d\n", 
601
//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);
602

    
603
    avctx->quality = s->qscale;
604
    if (avctx->get_psnr) {
605
        /* At this point pict->data should have the original frame   */
606
        /* an s->current_picture should have the coded/decoded frame */
607
        get_psnr(pict->data, s->current_picture,
608
                 pict->linesize, s->linesize, avctx);
609
    }
610
    return pbBufPtr(&s->pb) - s->pb.buf;
611
}
612

    
613
static inline int clip(int a, int amin, int amax)
614
{
615
    if (a < amin)
616
        return amin;
617
    else if (a > amax)
618
        return amax;
619
    else
620
        return a;
621
}
622

    
623
static inline void gmc1_motion(MpegEncContext *s,
624
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
625
                               int dest_offset,
626
                               UINT8 **ref_picture, int src_offset,
627
                               int h)
628
{
629
    UINT8 *ptr;
630
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
631
    int motion_x, motion_y;
632

    
633
    if(s->real_sprite_warping_points>1) printf("more than 1 warp point isnt supported\n");
634
    motion_x= s->sprite_offset[0][0];
635
    motion_y= s->sprite_offset[0][1];
636
    src_x = s->mb_x * 16 + (motion_x >> (s->sprite_warping_accuracy+1));
637
    src_y = s->mb_y * 16 + (motion_y >> (s->sprite_warping_accuracy+1));
638
    motion_x<<=(3-s->sprite_warping_accuracy);
639
    motion_y<<=(3-s->sprite_warping_accuracy);
640
    src_x = clip(src_x, -16, s->width);
641
    if (src_x == s->width)
642
        motion_x =0;
643
    src_y = clip(src_y, -16, s->height);
644
    if (src_y == s->height)
645
        motion_y =0;
646
    
647
    linesize = s->linesize;
648
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
649

    
650
    dest_y+=dest_offset;
651
    gmc1(dest_y  , ptr  , linesize, h, motion_x&15, motion_y&15, s->no_rounding);
652
    gmc1(dest_y+8, ptr+8, linesize, h, motion_x&15, motion_y&15, s->no_rounding);
653

    
654
    motion_x= s->sprite_offset[1][0];
655
    motion_y= s->sprite_offset[1][1];
656
    src_x = s->mb_x * 8 + (motion_x >> (s->sprite_warping_accuracy+1));
657
    src_y = s->mb_y * 8 + (motion_y >> (s->sprite_warping_accuracy+1));
658
    motion_x<<=(3-s->sprite_warping_accuracy);
659
    motion_y<<=(3-s->sprite_warping_accuracy);
660
    src_x = clip(src_x, -8, s->width>>1);
661
    if (src_x == s->width>>1)
662
        motion_x =0;
663
    src_y = clip(src_y, -8, s->height>>1);
664
    if (src_y == s->height>>1)
665
        motion_y =0;
666

    
667
    offset = (src_y * linesize>>1) + src_x + (src_offset>>1);
668
    ptr = ref_picture[1] + offset;
669
    gmc1(dest_cb + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
670
    ptr = ref_picture[2] + offset;
671
    gmc1(dest_cr + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
672
    
673
    return;
674
}
675

    
676
/* apply one mpeg motion vector to the three components */
677
static inline void mpeg_motion(MpegEncContext *s,
678
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
679
                               int dest_offset,
680
                               UINT8 **ref_picture, int src_offset,
681
                               int field_based, op_pixels_func *pix_op,
682
                               int motion_x, int motion_y, int h)
683
{
684
    UINT8 *ptr;
685
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
686
if(s->quarter_sample)
687
{
688
    motion_x>>=1;
689
    motion_y>>=1;
690
}
691
    dxy = ((motion_y & 1) << 1) | (motion_x & 1);
692
    src_x = s->mb_x * 16 + (motion_x >> 1);
693
    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 1);
694
                
695
    /* WARNING: do no forget half pels */
696
    height = s->height >> field_based;
697
    src_x = clip(src_x, -16, s->width);
698
    if (src_x == s->width)
699
        dxy &= ~1;
700
    src_y = clip(src_y, -16, height);
701
    if (src_y == height)
702
        dxy &= ~2;
703
    linesize = s->linesize << field_based;
704
    ptr = ref_picture[0] + (src_y * linesize) + (src_x) + src_offset;
705
    dest_y += dest_offset;
706
    pix_op[dxy](dest_y, ptr, linesize, h);
707
    pix_op[dxy](dest_y + 8, ptr + 8, linesize, h);
708

    
709
    if (s->out_format == FMT_H263) {
710
        dxy = 0;
711
        if ((motion_x & 3) != 0)
712
            dxy |= 1;
713
        if ((motion_y & 3) != 0)
714
            dxy |= 2;
715
        mx = motion_x >> 2;
716
        my = motion_y >> 2;
717
    } else {
718
        mx = motion_x / 2;
719
        my = motion_y / 2;
720
        dxy = ((my & 1) << 1) | (mx & 1);
721
        mx >>= 1;
722
        my >>= 1;
723
    }
724
    
725
    src_x = s->mb_x * 8 + mx;
726
    src_y = s->mb_y * (8 >> field_based) + my;
727
    src_x = clip(src_x, -8, s->width >> 1);
728
    if (src_x == (s->width >> 1))
729
        dxy &= ~1;
730
    src_y = clip(src_y, -8, height >> 1);
731
    if (src_y == (height >> 1))
732
        dxy &= ~2;
733

    
734
    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
735
    ptr = ref_picture[1] + offset;
736
    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
737
    ptr = ref_picture[2] + offset;
738
    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
739
}
740

    
741
static inline void qpel_motion(MpegEncContext *s,
742
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
743
                               int dest_offset,
744
                               UINT8 **ref_picture, int src_offset,
745
                               int field_based, op_pixels_func *pix_op,
746
                               qpel_mc_func *qpix_op,
747
                               int motion_x, int motion_y, int h)
748
{
749
    UINT8 *ptr;
750
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
751

    
752
    dxy = ((motion_y & 3) << 2) | (motion_x & 3);
753
    src_x = s->mb_x * 16 + (motion_x >> 2);
754
    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 2);
755

    
756
    height = s->height >> field_based;
757
    src_x = clip(src_x, -16, s->width);
758
    if (src_x == s->width)
759
        dxy &= ~3;
760
    src_y = clip(src_y, -16, height);
761
    if (src_y == height)
762
        dxy &= ~12;
763
    linesize = s->linesize << field_based;
764
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
765
    dest_y += dest_offset;
766
//printf("%d %d %d\n", src_x, src_y, dxy);
767
    qpix_op[dxy](dest_y                 , ptr                 , linesize, linesize, motion_x&3, motion_y&3);
768
    qpix_op[dxy](dest_y              + 8, ptr              + 8, linesize, linesize, motion_x&3, motion_y&3);
769
    qpix_op[dxy](dest_y + linesize*8    , ptr + linesize*8    , linesize, linesize, motion_x&3, motion_y&3);
770
    qpix_op[dxy](dest_y + linesize*8 + 8, ptr + linesize*8 + 8, linesize, linesize, motion_x&3, motion_y&3);
771
    
772
    mx= (motion_x>>1) | (motion_x&1);
773
    my= (motion_y>>1) | (motion_y&1);
774

    
775
    dxy = 0;
776
    if ((mx & 3) != 0)
777
        dxy |= 1;
778
    if ((my & 3) != 0)
779
        dxy |= 2;
780
    mx = mx >> 2;
781
    my = my >> 2;
782
    
783
    src_x = s->mb_x * 8 + mx;
784
    src_y = s->mb_y * (8 >> field_based) + my;
785
    src_x = clip(src_x, -8, s->width >> 1);
786
    if (src_x == (s->width >> 1))
787
        dxy &= ~1;
788
    src_y = clip(src_y, -8, height >> 1);
789
    if (src_y == (height >> 1))
790
        dxy &= ~2;
791

    
792
    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
793
    ptr = ref_picture[1] + offset;
794
    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
795
    ptr = ref_picture[2] + offset;
796
    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
797
}
798

    
799

    
800
static inline void MPV_motion(MpegEncContext *s, 
801
                              UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
802
                              int dir, UINT8 **ref_picture, 
803
                              op_pixels_func *pix_op, qpel_mc_func *qpix_op)
804
{
805
    int dxy, offset, mx, my, src_x, src_y, motion_x, motion_y;
806
    int mb_x, mb_y, i;
807
    UINT8 *ptr, *dest;
808

    
809
    mb_x = s->mb_x;
810
    mb_y = s->mb_y;
811

    
812
    switch(s->mv_type) {
813
    case MV_TYPE_16X16:
814
        if(s->mcsel){
815
#if 0
816
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
817
                        ref_picture, 0,
818
                        0, pix_op,
819
                        s->sprite_offset[0][0]>>3,
820
                        s->sprite_offset[0][1]>>3,
821
                        16);
822
#else
823
            gmc1_motion(s, dest_y, dest_cb, dest_cr, 0,
824
                        ref_picture, 0,
825
                        16);
826
#endif
827
        }else if(s->quarter_sample && dir==0){ //FIXME
828
            qpel_motion(s, dest_y, dest_cb, dest_cr, 0,
829
                        ref_picture, 0,
830
                        0, pix_op, qpix_op,
831
                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
832
        }else{
833
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
834
                        ref_picture, 0,
835
                        0, pix_op,
836
                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
837
        }           
838
        break;
839
    case MV_TYPE_8X8:
840
        for(i=0;i<4;i++) {
841
            motion_x = s->mv[dir][i][0];
842
            motion_y = s->mv[dir][i][1];
843

    
844
            dxy = ((motion_y & 1) << 1) | (motion_x & 1);
845
            src_x = mb_x * 16 + (motion_x >> 1) + (i & 1) * 8;
846
            src_y = mb_y * 16 + (motion_y >> 1) + (i >>1) * 8;
847
                    
848
            /* WARNING: do no forget half pels */
849
            src_x = clip(src_x, -16, s->width);
850
            if (src_x == s->width)
851
                dxy &= ~1;
852
            src_y = clip(src_y, -16, s->height);
853
            if (src_y == s->height)
854
                dxy &= ~2;
855
                    
856
            ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
857
            dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
858
            pix_op[dxy](dest, ptr, s->linesize, 8);
859
        }
860
        /* In case of 8X8, we construct a single chroma motion vector
861
           with a special rounding */
862
        mx = 0;
863
        my = 0;
864
        for(i=0;i<4;i++) {
865
            mx += s->mv[dir][i][0];
866
            my += s->mv[dir][i][1];
867
        }
868
        if (mx >= 0)
869
            mx = (h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
870
        else {
871
            mx = -mx;
872
            mx = -(h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
873
        }
874
        if (my >= 0)
875
            my = (h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
876
        else {
877
            my = -my;
878
            my = -(h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
879
        }
880
        dxy = ((my & 1) << 1) | (mx & 1);
881
        mx >>= 1;
882
        my >>= 1;
883

    
884
        src_x = mb_x * 8 + mx;
885
        src_y = mb_y * 8 + my;
886
        src_x = clip(src_x, -8, s->width/2);
887
        if (src_x == s->width/2)
888
            dxy &= ~1;
889
        src_y = clip(src_y, -8, s->height/2);
890
        if (src_y == s->height/2)
891
            dxy &= ~2;
892
        
893
        offset = (src_y * (s->linesize >> 1)) + src_x;
894
        ptr = ref_picture[1] + offset;
895
        pix_op[dxy](dest_cb, ptr, s->linesize >> 1, 8);
896
        ptr = ref_picture[2] + offset;
897
        pix_op[dxy](dest_cr, ptr, s->linesize >> 1, 8);
898
        break;
899
    case MV_TYPE_FIELD:
900
        if (s->picture_structure == PICT_FRAME) {
901
            /* top field */
902
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
903
                        ref_picture, s->field_select[dir][0] ? s->linesize : 0,
904
                        1, pix_op,
905
                        s->mv[dir][0][0], s->mv[dir][0][1], 8);
906
            /* bottom field */
907
            mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
908
                        ref_picture, s->field_select[dir][1] ? s->linesize : 0,
909
                        1, pix_op,
910
                        s->mv[dir][1][0], s->mv[dir][1][1], 8);
911
        } else {
912
            
913

    
914
        }
915
        break;
916
    }
917
}
918

    
919

    
920
/* put block[] to dest[] */
921
static inline void put_dct(MpegEncContext *s, 
922
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
923
{
924
    if (!s->mpeg2)
925
        s->dct_unquantize(s, block, i, s->qscale);
926
    ff_idct (block);
927
    put_pixels_clamped(block, dest, line_size);
928
}
929

    
930
/* add block[] to dest[] */
931
static inline void add_dct(MpegEncContext *s, 
932
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
933
{
934
    if (s->block_last_index[i] >= 0) {
935
        if (!s->mpeg2)
936
            if(s->encoding || (!s->h263_msmpeg4))
937
                s->dct_unquantize(s, block, i, s->qscale);
938
        ff_idct (block);
939
        add_pixels_clamped(block, dest, line_size);
940
    }
941
}
942

    
943
/* generic function called after a macroblock has been parsed by the
944
   decoder or after it has been encoded by the encoder.
945

946
   Important variables used:
947
   s->mb_intra : true if intra macroblock
948
   s->mv_dir   : motion vector direction
949
   s->mv_type  : motion vector type
950
   s->mv       : motion vector
951
   s->interlaced_dct : true if interlaced dct used (mpeg2)
952
 */
953
void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
954
{
955
    int mb_x, mb_y;
956
    int dct_linesize, dct_offset;
957
    op_pixels_func *op_pix;
958
    qpel_mc_func *op_qpix;
959

    
960
    mb_x = s->mb_x;
961
    mb_y = s->mb_y;
962

    
963
#ifdef FF_POSTPROCESS
964
    quant_store[mb_y][mb_x]=s->qscale;
965
    //printf("[%02d][%02d] %d\n",mb_x,mb_y,s->qscale);
966
#endif
967

    
968
    /* update DC predictors for P macroblocks */
969
    if (!s->mb_intra) {
970
        if (s->h263_pred || s->h263_aic) {
971
          if(s->mbintra_table[mb_x + mb_y*s->mb_width])
972
          {
973
            int wrap, xy, v;
974
            s->mbintra_table[mb_x + mb_y*s->mb_width]=0;
975
            wrap = 2 * s->mb_width + 2;
976
            xy = 2 * mb_x + 1 +  (2 * mb_y + 1) * wrap;
977
            v = 1024;
978
            
979
            s->dc_val[0][xy] = v;
980
            s->dc_val[0][xy + 1] = v;
981
            s->dc_val[0][xy + wrap] = v;
982
            s->dc_val[0][xy + 1 + wrap] = v;
983
            /* ac pred */
984
            memset(s->ac_val[0][xy], 0, 16 * sizeof(INT16));
985
            memset(s->ac_val[0][xy + 1], 0, 16 * sizeof(INT16));
986
            memset(s->ac_val[0][xy + wrap], 0, 16 * sizeof(INT16));
987
            memset(s->ac_val[0][xy + 1 + wrap], 0, 16 * sizeof(INT16));
988
            if (s->h263_msmpeg4) {
989
                s->coded_block[xy] = 0;
990
                s->coded_block[xy + 1] = 0;
991
                s->coded_block[xy + wrap] = 0;
992
                s->coded_block[xy + 1 + wrap] = 0;
993
            }
994
            /* chroma */
995
            wrap = s->mb_width + 2;
996
            xy = mb_x + 1 + (mb_y + 1) * wrap;
997
            s->dc_val[1][xy] = v;
998
            s->dc_val[2][xy] = v;
999
            /* ac pred */
1000
            memset(s->ac_val[1][xy], 0, 16 * sizeof(INT16));
1001
            memset(s->ac_val[2][xy], 0, 16 * sizeof(INT16));
1002
          }
1003
        } else {
1004
            s->last_dc[0] = 128 << s->intra_dc_precision;
1005
            s->last_dc[1] = 128 << s->intra_dc_precision;
1006
            s->last_dc[2] = 128 << s->intra_dc_precision;
1007
        }
1008
    }
1009
    else if (s->h263_pred || s->h263_aic)
1010
        s->mbintra_table[mb_x + mb_y*s->mb_width]=1;
1011

    
1012
    /* update motion predictor, not for B-frames as they need the motion_val from the last P/S-Frame */
1013
    if (s->out_format == FMT_H263) {
1014
      if(s->pict_type!=B_TYPE){
1015
        int xy, wrap, motion_x, motion_y;
1016
        
1017
        wrap = 2 * s->mb_width + 2;
1018
        xy = 2 * mb_x + 1 + (2 * mb_y + 1) * wrap;
1019
        if (s->mb_intra) {
1020
            motion_x = 0;
1021
            motion_y = 0;
1022
            goto motion_init;
1023
        } else if (s->mv_type == MV_TYPE_16X16) {
1024
            motion_x = s->mv[0][0][0];
1025
            motion_y = s->mv[0][0][1];
1026
        motion_init:
1027
            /* no update if 8X8 because it has been done during parsing */
1028
            s->motion_val[xy][0] = motion_x;
1029
            s->motion_val[xy][1] = motion_y;
1030
            s->motion_val[xy + 1][0] = motion_x;
1031
            s->motion_val[xy + 1][1] = motion_y;
1032
            s->motion_val[xy + wrap][0] = motion_x;
1033
            s->motion_val[xy + wrap][1] = motion_y;
1034
            s->motion_val[xy + 1 + wrap][0] = motion_x;
1035
            s->motion_val[xy + 1 + wrap][1] = motion_y;
1036
        }
1037
      }
1038
    }
1039
    
1040
    if (!s->intra_only) {
1041
        UINT8 *dest_y, *dest_cb, *dest_cr;
1042
        UINT8 *mbskip_ptr;
1043

    
1044
        /* avoid copy if macroblock skipped in last frame too */
1045
        if (!s->encoding && s->pict_type != B_TYPE) {
1046
            mbskip_ptr = &s->mbskip_table[s->mb_y * s->mb_width + s->mb_x];
1047
            if (s->mb_skiped) {
1048
                s->mb_skiped = 0;
1049
                /* if previous was skipped too, then nothing to do ! */
1050
                if (*mbskip_ptr != 0) 
1051
                    goto the_end;
1052
                *mbskip_ptr = 1; /* indicate that this time we skiped it */
1053
            } else {
1054
                *mbskip_ptr = 0; /* not skipped */
1055
            }
1056
        }
1057

    
1058
        dest_y = s->current_picture[0] + (mb_y * 16 * s->linesize) + mb_x * 16;
1059
        dest_cb = s->current_picture[1] + (mb_y * 8 * (s->linesize >> 1)) + mb_x * 8;
1060
        dest_cr = s->current_picture[2] + (mb_y * 8 * (s->linesize >> 1)) + mb_x * 8;
1061

    
1062
        if (s->interlaced_dct) {
1063
            dct_linesize = s->linesize * 2;
1064
            dct_offset = s->linesize;
1065
        } else {
1066
            dct_linesize = s->linesize;
1067
            dct_offset = s->linesize * 8;
1068
        }
1069

    
1070
        if (!s->mb_intra) {
1071
            /* motion handling */
1072
            if (!s->no_rounding){
1073
                op_pix = put_pixels_tab;
1074
                op_qpix= qpel_mc_rnd_tab;
1075
            }else{
1076
                op_pix = put_no_rnd_pixels_tab;
1077
                op_qpix= qpel_mc_no_rnd_tab;
1078
            }
1079

    
1080
            if (s->mv_dir & MV_DIR_FORWARD) {
1081
                MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
1082
                if (!s->no_rounding) 
1083
                    op_pix = avg_pixels_tab;
1084
                else
1085
                    op_pix = avg_no_rnd_pixels_tab;
1086
            }
1087
            if (s->mv_dir & MV_DIR_BACKWARD) {
1088
                MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
1089
            }
1090

    
1091
            /* add dct residue */
1092
            add_dct(s, block[0], 0, dest_y, dct_linesize);
1093
            add_dct(s, block[1], 1, dest_y + 8, dct_linesize);
1094
            add_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
1095
            add_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
1096

    
1097
            add_dct(s, block[4], 4, dest_cb, s->linesize >> 1);
1098
            add_dct(s, block[5], 5, dest_cr, s->linesize >> 1);
1099
        } else {
1100
            /* dct only in intra block */
1101
            put_dct(s, block[0], 0, dest_y, dct_linesize);
1102
            put_dct(s, block[1], 1, dest_y + 8, dct_linesize);
1103
            put_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
1104
            put_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
1105

    
1106
            put_dct(s, block[4], 4, dest_cb, s->linesize >> 1);
1107
            put_dct(s, block[5], 5, dest_cr, s->linesize >> 1);
1108
        }
1109
    }
1110
 the_end:
1111
    emms_c(); //FIXME remove
1112
}
1113

    
1114
static void encode_mb(MpegEncContext *s)
1115
{
1116
    int wrap;
1117
    const int mb_x= s->mb_x;
1118
    const int mb_y= s->mb_y;
1119
    UINT8 *ptr;
1120
    const int motion_x= s->mv[0][0][0];
1121
    const int motion_y= s->mv[0][0][1];
1122
    int i;
1123

    
1124
    /* get the pixels */
1125
    wrap = s->linesize;
1126
    ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
1127
    get_pixels(s->block[0], ptr, wrap);
1128
    get_pixels(s->block[1], ptr + 8, wrap);
1129
    get_pixels(s->block[2], ptr + 8 * wrap, wrap);
1130
    get_pixels(s->block[3], ptr + 8 * wrap + 8, wrap);
1131
    wrap = s->linesize >> 1;
1132
    ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;
1133
    get_pixels(s->block[4], ptr, wrap);
1134

    
1135
    wrap = s->linesize >> 1;
1136
    ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
1137
    get_pixels(s->block[5], ptr, wrap);
1138

    
1139
    /* subtract previous frame if non intra */
1140
    if (!s->mb_intra) {
1141
        int dxy, offset, mx, my;
1142
        
1143
        if(s->mv_type==MV_TYPE_16X16){
1144
            dxy = ((motion_y & 1) << 1) | (motion_x & 1);
1145
            ptr = s->last_picture[0] + 
1146
                ((mb_y * 16 + (motion_y >> 1)) * s->linesize) + 
1147
                (mb_x * 16 + (motion_x >> 1));
1148

    
1149
            sub_pixels_2(s->block[0], ptr, s->linesize, dxy);
1150
            sub_pixels_2(s->block[1], ptr + 8, s->linesize, dxy);
1151
            sub_pixels_2(s->block[2], ptr + s->linesize * 8, s->linesize, dxy);
1152
            sub_pixels_2(s->block[3], ptr + 8 + s->linesize * 8, s->linesize ,dxy);
1153

    
1154
            if (s->out_format == FMT_H263) {
1155
                /* special rounding for h263 */
1156
                dxy = 0;
1157
                if ((motion_x & 3) != 0)
1158
                    dxy |= 1;
1159
                if ((motion_y & 3) != 0)
1160
                    dxy |= 2;
1161
                mx = motion_x >> 2;
1162
                my = motion_y >> 2;
1163
            } else {
1164
                mx = motion_x / 2;
1165
                my = motion_y / 2;
1166
                dxy = ((my & 1) << 1) | (mx & 1);
1167
                mx >>= 1;
1168
                my >>= 1;
1169
            }
1170
            offset = ((mb_y * 8 + my) * (s->linesize >> 1)) + (mb_x * 8 + mx);
1171
            ptr = s->last_picture[1] + offset;
1172
            sub_pixels_2(s->block[4], ptr, s->linesize >> 1, dxy);
1173
            ptr = s->last_picture[2] + offset;
1174
            sub_pixels_2(s->block[5], ptr, s->linesize >> 1, dxy);
1175
        }else{
1176
            int src_x, src_y;
1177

    
1178
            for(i=0;i<4;i++) {
1179
                int motion_x = s->mv[0][i][0];
1180
                int motion_y = s->mv[0][i][1];
1181

    
1182
                dxy = ((motion_y & 1) << 1) | (motion_x & 1);
1183
                src_x = mb_x * 16 + (motion_x >> 1) + (i & 1) * 8;
1184
                src_y = mb_y * 16 + (motion_y >> 1) + (i >>1) * 8;
1185
                        
1186
                ptr = s->last_picture[0] + (src_y * s->linesize) + (src_x);
1187
                sub_pixels_2(s->block[i], ptr, s->linesize, dxy);
1188
            }
1189
            /* In case of 8X8, we construct a single chroma motion vector
1190
               with a special rounding */
1191
            mx = 0;
1192
            my = 0;
1193
            for(i=0;i<4;i++) {
1194
                mx += s->mv[0][i][0];
1195
                my += s->mv[0][i][1];
1196
            }
1197
            if (mx >= 0)
1198
                mx = (h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
1199
            else {
1200
                mx = -mx;
1201
                mx = -(h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
1202
            }
1203
            if (my >= 0)
1204
                my = (h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
1205
            else {
1206
                my = -my;
1207
                my = -(h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
1208
            }
1209
            dxy = ((my & 1) << 1) | (mx & 1);
1210
            mx >>= 1;
1211
            my >>= 1;
1212

    
1213
            src_x = mb_x * 8 + mx;
1214
            src_y = mb_y * 8 + my;
1215
            src_x = clip(src_x, -8, s->width/2);
1216
            if (src_x == s->width/2)
1217
                dxy &= ~1;
1218
            src_y = clip(src_y, -8, s->height/2);
1219
            if (src_y == s->height/2)
1220
                dxy &= ~2;
1221
            
1222
            offset = (src_y * (s->linesize >> 1)) + src_x;
1223
            ptr = s->last_picture[1] + offset;
1224
            sub_pixels_2(s->block[4], ptr, s->linesize >> 1, dxy);
1225
            ptr = s->last_picture[2] + offset;
1226
            sub_pixels_2(s->block[5], ptr, s->linesize >> 1, dxy);
1227
        }
1228
    }
1229
            
1230
#if 0
1231
            {
1232
                float adap_parm;
1233
                
1234
                adap_parm = ((s->avg_mb_var << 1) + s->mb_var[s->mb_width*mb_y+mb_x] + 1.0) /
1235
                            ((s->mb_var[s->mb_width*mb_y+mb_x] << 1) + s->avg_mb_var + 1.0);
1236
            
1237
                printf("\ntype=%c qscale=%2d adap=%0.2f dquant=%4.2f var=%4d avgvar=%4d", 
1238
                        (s->mb_type[s->mb_width*mb_y+mb_x] > 0) ? 'I' : 'P', 
1239
                        s->qscale, adap_parm, s->qscale*adap_parm,
1240
                        s->mb_var[s->mb_width*mb_y+mb_x], s->avg_mb_var);
1241
            }
1242
#endif
1243
    /* DCT & quantize */
1244
    if (s->h263_msmpeg4) {
1245
        msmpeg4_dc_scale(s);
1246
    } else if (s->h263_pred) {
1247
        h263_dc_scale(s);
1248
    } else {
1249
        /* default quantization values */
1250
        s->y_dc_scale = 8;
1251
        s->c_dc_scale = 8;
1252
    }
1253
    for(i=0;i<6;i++) {
1254
        s->block_last_index[i] = dct_quantize(s, s->block[i], i, s->qscale);
1255
    }
1256

    
1257
    /* huffman encode */
1258
    switch(s->out_format) {
1259
    case FMT_MPEG1:
1260
        mpeg1_encode_mb(s, s->block, motion_x, motion_y);
1261
        break;
1262
    case FMT_H263:
1263
        if (s->h263_msmpeg4)
1264
            msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
1265
        else if(s->h263_pred)
1266
            mpeg4_encode_mb(s, s->block, motion_x, motion_y);
1267
        else
1268
            h263_encode_mb(s, s->block, motion_x, motion_y);
1269
        break;
1270
    case FMT_MJPEG:
1271
        mjpeg_encode_mb(s, s->block);
1272
        break;
1273
    }
1274
}
1275

    
1276
static void copy_bits(PutBitContext *pb, UINT8 *src, int length)
1277
{
1278
    int bytes= length>>3;
1279
    int bits= length&7;
1280
    int i;
1281

    
1282
    for(i=0; i<bytes; i++) put_bits(pb, 8, src[i]);
1283
    put_bits(pb, bits, src[i]>>(8-bits));
1284
}
1285

    
1286
static void encode_picture(MpegEncContext *s, int picture_number)
1287
{
1288
    int mb_x, mb_y, last_gob, pdif = 0;
1289
    int i;
1290
    int bits;
1291
    MpegEncContext best_s;
1292
    UINT8 bit_buf[4][3000]; //FIXME check that this is ALLWAYS large enogh for a MB
1293

    
1294
    s->picture_number = picture_number;
1295

    
1296
    s->block_wrap[0]=
1297
    s->block_wrap[1]=
1298
    s->block_wrap[2]=
1299
    s->block_wrap[3]= s->mb_width*2 + 2;
1300
    s->block_wrap[4]=
1301
    s->block_wrap[5]= s->mb_width + 2;
1302
    
1303
    s->last_mc_mb_var = s->mc_mb_var;
1304
    /* Reset the average MB variance */
1305
    s->avg_mb_var = 0;
1306
    s->mc_mb_var = 0;
1307
    /* Estimate motion for every MB */
1308
    if(s->pict_type == P_TYPE){
1309
        for(mb_y=0; mb_y < s->mb_height; mb_y++) {
1310
            s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
1311
            s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
1312
            s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
1313
            s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
1314
            for(mb_x=0; mb_x < s->mb_width; mb_x++) {
1315
                s->mb_x = mb_x;
1316
                s->mb_y = mb_y;
1317
                s->block_index[0]+=2;
1318
                s->block_index[1]+=2;
1319
                s->block_index[2]+=2;
1320
                s->block_index[3]+=2;
1321

    
1322
                /* compute motion vector & mb_type and store in context */
1323
                estimate_motion(s, mb_x, mb_y);
1324
//                s->mb_type[mb_y*s->mb_width + mb_x]=MB_TYPE_INTER;
1325
            }
1326
        }
1327
        emms_c();
1328
    }else{
1329
        /* I-Frame */
1330
        //FIXME do we need to zero them?
1331
        memset(s->motion_val[0], 0, sizeof(INT16)*(s->mb_width*2 + 2)*(s->mb_height*2 + 2)*2);
1332
        memset(s->mv_table[0]  , 0, sizeof(INT16)*s->mb_width*s->mb_height);
1333
        memset(s->mv_table[1]  , 0, sizeof(INT16)*s->mb_width*s->mb_height);
1334
        memset(s->mb_type      , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
1335
    }
1336

    
1337
    if(s->avg_mb_var < s->mc_mb_var && s->pict_type != B_TYPE && (!s->force_type)){ //FIXME subtract MV bits
1338
        s->pict_type= I_TYPE;
1339
        s->picture_in_gop_number=0;
1340
        memset(s->mb_type   , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
1341
//printf("Scene change detected, encoding as I Frame\n");
1342
    }
1343

    
1344
    /* find best f_code for ME which do unlimited searches */
1345
    if(s->pict_type==P_TYPE && s->full_search>3){
1346
        int mv_num[8];
1347
        int i;
1348
        int loose=0;
1349
        UINT8 * fcode_tab= s->fcode_tab;
1350

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

    
1353
        for(i=0; i<s->mb_num; i++){
1354
            if(s->mb_type[i] & MB_TYPE_INTER){
1355
                mv_num[ fcode_tab[s->mv_table[0][i] + MAX_MV] ]++;
1356
                mv_num[ fcode_tab[s->mv_table[1][i] + MAX_MV] ]++;
1357
//printf("%d %d %d\n", s->mv_table[0][i], fcode_tab[s->mv_table[0][i] + MAX_MV], i);
1358
            }
1359
//else printf("I");
1360
        }
1361

    
1362
        for(i=MAX_FCODE; i>1; i--){
1363
            loose+= mv_num[i];
1364
            if(loose > 10) break; //FIXME this is pretty ineffective
1365
        }
1366
        s->f_code= i;
1367
/*        for(i=0; i<=MAX_FCODE; i++){
1368
            printf("%d ", mv_num[i]);
1369
        }
1370
        printf("\n");*/
1371
    }else{
1372
        s->f_code= 1;
1373
    }
1374

    
1375
//printf("f_code %d ///\n", s->f_code);
1376
    /* convert MBs with too long MVs to I-Blocks */
1377
    if(s->pict_type==P_TYPE){
1378
        int i, x, y;
1379
        const int f_code= s->f_code;
1380
        UINT8 * fcode_tab= s->fcode_tab;
1381
//FIXME try to clip instead of intra izing ;)
1382
        /* clip / convert to intra 16x16 type MVs */
1383
        for(i=0; i<s->mb_num; i++){
1384
            if(s->mb_type[i]&MB_TYPE_INTER){
1385
                if(   fcode_tab[s->mv_table[0][i] + MAX_MV] > f_code
1386
                   || fcode_tab[s->mv_table[0][i] + MAX_MV] == 0
1387
                   || fcode_tab[s->mv_table[1][i] + MAX_MV] > f_code
1388
                   || fcode_tab[s->mv_table[1][i] + MAX_MV] == 0 ){
1389
                    s->mb_type[i] &= ~MB_TYPE_INTER;
1390
                    s->mb_type[i] |= MB_TYPE_INTRA;
1391
                    s->mv_table[0][i] = 0;
1392
                    s->mv_table[1][i] = 0;
1393
                }
1394
            }
1395
        }
1396

    
1397
        if(s->flags&CODEC_FLAG_4MV){
1398
            int wrap= 2+ s->mb_width*2;
1399

    
1400
            /* clip / convert to intra 8x8 type MVs */
1401
            for(y=0; y<s->mb_height; y++){
1402
                int xy= (y*2 + 1)*wrap + 1;
1403
                i= y*s->mb_width;
1404

    
1405
                for(x=0; x<s->mb_width; x++){
1406
                    if(s->mb_type[i]&MB_TYPE_INTER4V){
1407
                        int block;
1408
                        for(block=0; block<4; block++){
1409
                            int off= (block& 1) + (block>>1)*wrap;
1410
                            int mx= s->motion_val[ xy + off ][0];
1411
                            int my= s->motion_val[ xy + off ][1];
1412

    
1413
                            if(   fcode_tab[mx + MAX_MV] > f_code
1414
                               || fcode_tab[mx + MAX_MV] == 0
1415
                               || fcode_tab[my + MAX_MV] > f_code
1416
                               || fcode_tab[my + MAX_MV] == 0 ){
1417
                                s->mb_type[i] &= ~MB_TYPE_INTER4V;
1418
                                s->mb_type[i] |= MB_TYPE_INTRA;
1419
                            }
1420
                        }
1421
                        xy+=2;
1422
                        i++;
1423
                    }
1424
                }
1425
            }
1426
        }
1427
    }
1428

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

    
1431
    if (!s->fixed_qscale) 
1432
        s->qscale = rate_estimate_qscale(s);
1433

    
1434
    /* precompute matrix */
1435
    if (s->out_format == FMT_MJPEG) {
1436
        /* for mjpeg, we do include qscale in the matrix */
1437
        s->intra_matrix[0] = default_intra_matrix[0];
1438
        for(i=1;i<64;i++)
1439
            s->intra_matrix[i] = (default_intra_matrix[i] * s->qscale) >> 3;
1440
        convert_matrix(s->q_intra_matrix, s->q_intra_matrix16, s->intra_matrix, 8);
1441
    } else {
1442
        convert_matrix(s->q_intra_matrix, s->q_intra_matrix16, s->intra_matrix, s->qscale);
1443
        convert_matrix(s->q_non_intra_matrix, s->q_non_intra_matrix16, s->non_intra_matrix, s->qscale);
1444
    }
1445

    
1446
    s->last_bits= get_bit_count(&s->pb);
1447
    switch(s->out_format) {
1448
    case FMT_MJPEG:
1449
        mjpeg_picture_header(s);
1450
        break;
1451
    case FMT_H263:
1452
        if (s->h263_msmpeg4) 
1453
            msmpeg4_encode_picture_header(s, picture_number);
1454
        else if (s->h263_pred)
1455
            mpeg4_encode_picture_header(s, picture_number);
1456
        else if (s->h263_rv10) 
1457
            rv10_encode_picture_header(s, picture_number);
1458
        else
1459
            h263_encode_picture_header(s, picture_number);
1460
        break;
1461
    case FMT_MPEG1:
1462
        mpeg1_encode_picture_header(s, picture_number);
1463
        break;
1464
    }
1465
    bits= get_bit_count(&s->pb);
1466
    s->header_bits= bits - s->last_bits;
1467
    s->last_bits= bits;
1468
    s->mv_bits=0;
1469
    s->misc_bits=0;
1470
    s->i_tex_bits=0;
1471
    s->p_tex_bits=0;
1472
    s->i_count=0;
1473
    s->p_count=0;
1474
    s->skip_count=0;
1475

    
1476
    /* init last dc values */
1477
    /* note: quant matrix value (8) is implied here */
1478
    s->last_dc[0] = 128;
1479
    s->last_dc[1] = 128;
1480
    s->last_dc[2] = 128;
1481
    s->mb_incr = 1;
1482
    s->last_mv[0][0][0] = 0;
1483
    s->last_mv[0][0][1] = 0;
1484

    
1485
    /* Get the GOB height based on picture height */
1486
    if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4) {
1487
        if (s->height <= 400)
1488
            s->gob_index = 1;
1489
        else if (s->height <= 800)
1490
            s->gob_index = 2;
1491
        else
1492
            s->gob_index = 4;
1493
    }
1494
        
1495
    s->avg_mb_var = s->avg_mb_var / s->mb_num;        
1496
    
1497
    for(mb_y=0; mb_y < s->mb_height; mb_y++) {
1498
        /* Put GOB header based on RTP MTU */
1499
        /* TODO: Put all this stuff in a separate generic function */
1500
        if (s->rtp_mode) {
1501
            if (!mb_y) {
1502
                s->ptr_lastgob = s->pb.buf;
1503
                s->ptr_last_mb_line = s->pb.buf;
1504
            } else if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4 && !(mb_y % s->gob_index)) {
1505
                last_gob = h263_encode_gob_header(s, mb_y);
1506
                if (last_gob) {
1507
                    s->first_gob_line = 1;
1508
                }
1509
            }
1510
        }
1511
        
1512
        s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
1513
        s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
1514
        s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
1515
        s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
1516
        s->block_index[4]= s->block_wrap[4]*(mb_y + 1)                    + s->block_wrap[0]*(s->mb_height*2 + 2);
1517
        s->block_index[5]= s->block_wrap[4]*(mb_y + 1 + s->mb_height + 2) + s->block_wrap[0]*(s->mb_height*2 + 2);
1518
        for(mb_x=0; mb_x < s->mb_width; mb_x++) {
1519
            const int mb_type= s->mb_type[mb_y * s->mb_width + mb_x];
1520
            PutBitContext pb;
1521
            int d;
1522
            int dmin=10000000;
1523
            int best=0;
1524

    
1525
            s->mb_x = mb_x;
1526
            s->mb_y = mb_y;
1527
            s->block_index[0]+=2;
1528
            s->block_index[1]+=2;
1529
            s->block_index[2]+=2;
1530
            s->block_index[3]+=2;
1531
            s->block_index[4]++;
1532
            s->block_index[5]++;
1533

    
1534
            s->mv_dir = MV_DIR_FORWARD;
1535
            if(mb_type & (mb_type-1)){ // more than 1 MB type possible
1536
                pb= s->pb;
1537
                if(mb_type&MB_TYPE_INTER){
1538
                    s->mv_type = MV_TYPE_16X16;
1539
                    s->mb_intra= 0;
1540
                    s->mv[0][0][0] = s->mv_table[0][mb_y * s->mb_width + mb_x];
1541
                    s->mv[0][0][1] = s->mv_table[1][mb_y * s->mb_width + mb_x];
1542
                    init_put_bits(&s->pb, bit_buf[1], 3000, NULL, NULL);
1543
                    s->block= s->inter_block;
1544

    
1545
                    encode_mb(s);
1546
                    d= get_bit_count(&s->pb);
1547
                    if(d<dmin){
1548
                        flush_put_bits(&s->pb);
1549
                        dmin=d;
1550
                        best_s.mv[0][0][0]= s->mv[0][0][0];
1551
                        best_s.mv[0][0][1]= s->mv[0][0][1];
1552
                        best_s.mb_intra= 0;
1553
                        best_s.mv_type = MV_TYPE_16X16;
1554
                        best_s.pb=s->pb;
1555
                        best_s.block= s->block;
1556
                        best=1;
1557
                        for(i=0; i<6; i++)
1558
                            best_s.block_last_index[i]= s->block_last_index[i];
1559
                    }
1560
                }
1561
                if(mb_type&MB_TYPE_INTER4V){
1562
                    s->mv_type = MV_TYPE_8X8;
1563
                    s->mb_intra= 0;
1564
                    for(i=0; i<4; i++){
1565
                        s->mv[0][i][0] = s->motion_val[s->block_index[i]][0];
1566
                        s->mv[0][i][1] = s->motion_val[s->block_index[i]][1];
1567
                    }
1568
                    init_put_bits(&s->pb, bit_buf[2], 3000, NULL, NULL);
1569
                    s->block= s->inter4v_block;
1570

    
1571
                    encode_mb(s);
1572
                    d= get_bit_count(&s->pb);
1573
                    if(d<dmin){
1574
                        flush_put_bits(&s->pb);
1575
                        dmin=d;
1576
                        for(i=0; i<4; i++){
1577
                            best_s.mv[0][i][0] = s->mv[0][i][0];
1578
                            best_s.mv[0][i][1] = s->mv[0][i][1];
1579
                        }
1580
                        best_s.mb_intra= 0;
1581
                        best_s.mv_type = MV_TYPE_8X8;
1582
                        best_s.pb=s->pb;
1583
                        best_s.block= s->block;
1584
                        best=2;
1585
                        for(i=0; i<6; i++)
1586
                            best_s.block_last_index[i]= s->block_last_index[i];
1587
                    }
1588
                }
1589
                if(mb_type&MB_TYPE_INTRA){
1590
                    s->mv_type = MV_TYPE_16X16;
1591
                    s->mb_intra= 1;
1592
                    s->mv[0][0][0] = 0;
1593
                    s->mv[0][0][1] = 0;
1594
                    init_put_bits(&s->pb, bit_buf[0], 3000, NULL, NULL);
1595
                    s->block= s->intra_block;
1596
                   
1597
                    encode_mb(s);
1598
                    d= get_bit_count(&s->pb);
1599
                    if(d<dmin){
1600
                        flush_put_bits(&s->pb);
1601
                        dmin=d;
1602
                        best_s.mv[0][0][0]= 0;
1603
                        best_s.mv[0][0][1]= 0;
1604
                        best_s.mb_intra= 1;
1605
                        best_s.mv_type = MV_TYPE_16X16;
1606
                        best_s.pb=s->pb;
1607
                        best_s.block= s->block;
1608
                        for(i=0; i<6; i++)
1609
                            best_s.block_last_index[i]= s->block_last_index[i];
1610
                        best=0;
1611
                    }
1612
                    /* force cleaning of ac/dc if needed ... */
1613
                    s->mbintra_table[mb_x + mb_y*s->mb_width]=1;
1614
                }
1615
                for(i=0; i<4; i++){
1616
                   s->mv[0][i][0] =  best_s.mv[0][i][0];
1617
                   s->mv[0][i][1] =  best_s.mv[0][i][1];
1618
                }
1619
                s->mb_intra= best_s.mb_intra;
1620
                s->mv_type= best_s.mv_type;
1621
                for(i=0; i<6; i++)
1622
                   s->block_last_index[i]= best_s.block_last_index[i];
1623
                copy_bits(&pb, bit_buf[best], dmin);
1624
                s->block= best_s.block;
1625
                s->pb= pb;
1626
            } else {
1627
                // only one MB-Type possible
1628
                if(mb_type&MB_TYPE_INTRA){
1629
                    s->mb_intra= 1;
1630
                    s->mv[0][0][0] = 0;
1631
                    s->mv[0][0][1] = 0;
1632
                }else{
1633
                    s->mb_intra= 0;
1634
                    s->mv[0][0][0] = s->mv_table[0][mb_y * s->mb_width + mb_x];
1635
                    s->mv[0][0][1] = s->mv_table[1][mb_y * s->mb_width + mb_x];
1636
                }
1637
                encode_mb(s);
1638
            }
1639

    
1640
            MPV_decode_mb(s, s->block);
1641
        }
1642

    
1643

    
1644
        /* Obtain average GOB size for RTP */
1645
        if (s->rtp_mode) {
1646
            if (!mb_y)
1647
                s->mb_line_avgsize = pbBufPtr(&s->pb) - s->ptr_last_mb_line;
1648
            else if (!(mb_y % s->gob_index)) {    
1649
                s->mb_line_avgsize = (s->mb_line_avgsize + pbBufPtr(&s->pb) - s->ptr_last_mb_line) >> 1;
1650
                s->ptr_last_mb_line = pbBufPtr(&s->pb);
1651
            }
1652
            //fprintf(stderr, "\nMB line: %d\tSize: %u\tAvg. Size: %u", s->mb_y, 
1653
            //                    (s->pb.buf_ptr - s->ptr_last_mb_line), s->mb_line_avgsize);
1654
            s->first_gob_line = 0;
1655
        }
1656
    }
1657
    emms_c();
1658

    
1659
    if (s->h263_msmpeg4 && s->msmpeg4_version<4 && s->pict_type == I_TYPE)
1660
        msmpeg4_encode_ext_header(s);
1661

    
1662
    //if (s->gob_number)
1663
    //    fprintf(stderr,"\nNumber of GOB: %d", s->gob_number);
1664
    
1665
    /* Send the last GOB if RTP */    
1666
    if (s->rtp_mode) {
1667
        flush_put_bits(&s->pb);
1668
        pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
1669
        /* Call the RTP callback to send the last GOB */
1670
        if (s->rtp_callback)
1671
            s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
1672
        s->ptr_lastgob = pbBufPtr(&s->pb);
1673
        //fprintf(stderr,"\nGOB: %2d size: %d (last)", s->gob_number, pdif);
1674
    }
1675
}
1676

    
1677
static int dct_quantize_c(MpegEncContext *s, 
1678
                        DCTELEM *block, int n,
1679
                        int qscale)
1680
{
1681
    int i, j, level, last_non_zero, q;
1682
    const int *qmat;
1683
    int minLevel, maxLevel;
1684

    
1685
    if(s->avctx!=NULL && s->avctx->codec->id==CODEC_ID_MPEG4){
1686
        /* mpeg4 */
1687
        minLevel= -2048;
1688
        maxLevel= 2047;
1689
    }else if(s->out_format==FMT_MPEG1){
1690
        /* mpeg1 */
1691
        minLevel= -255;
1692
        maxLevel= 255;
1693
    }else if(s->out_format==FMT_MJPEG){
1694
        /* (m)jpeg */
1695
        minLevel= -1023;
1696
        maxLevel= 1023;
1697
    }else{
1698
        /* h263 / msmpeg4 */
1699
        minLevel= -128;
1700
        maxLevel= 127;
1701
    }
1702

    
1703
    av_fdct (block);
1704

    
1705
    /* we need this permutation so that we correct the IDCT
1706
       permutation. will be moved into DCT code */
1707
    block_permute(block);
1708

    
1709
    if (s->mb_intra) {
1710
        if (n < 4)
1711
            q = s->y_dc_scale;
1712
        else
1713
            q = s->c_dc_scale;
1714
        q = q << 3;
1715
        
1716
        /* note: block[0] is assumed to be positive */
1717
        block[0] = (block[0] + (q >> 1)) / q;
1718
        i = 1;
1719
        last_non_zero = 0;
1720
        if (s->out_format == FMT_H263) {
1721
            qmat = s->q_non_intra_matrix;
1722
        } else {
1723
            qmat = s->q_intra_matrix;
1724
        }
1725
    } else {
1726
        i = 0;
1727
        last_non_zero = -1;
1728
        qmat = s->q_non_intra_matrix;
1729
    }
1730

    
1731
    for(;i<64;i++) {
1732
        j = zigzag_direct[i];
1733
        level = block[j];
1734
        level = level * qmat[j];
1735
#ifdef PARANOID
1736
        {
1737
            static int count = 0;
1738
            int level1, level2, qmat1;
1739
            double val;
1740
            if (qmat == s->q_non_intra_matrix) {
1741
                qmat1 = default_non_intra_matrix[j] * s->qscale;
1742
            } else {
1743
                qmat1 = default_intra_matrix[j] * s->qscale;
1744
            }
1745
            if (av_fdct != jpeg_fdct_ifast)
1746
                val = ((double)block[j] * 8.0) / (double)qmat1;
1747
            else
1748
                val = ((double)block[j] * 8.0 * 2048.0) / 
1749
                    ((double)qmat1 * aanscales[j]);
1750
            level1 = (int)val;
1751
            level2 = level / (1 << (QMAT_SHIFT - 3));
1752
            if (level1 != level2) {
1753
                fprintf(stderr, "%d: quant error qlevel=%d wanted=%d level=%d qmat1=%d qmat=%d wantedf=%0.6f\n", 
1754
                        count, level2, level1, block[j], qmat1, qmat[j],
1755
                        val);
1756
                count++;
1757
            }
1758

    
1759
        }
1760
#endif
1761
        /* XXX: slight error for the low range. Test should be equivalent to
1762
           (level <= -(1 << (QMAT_SHIFT - 3)) || level >= (1 <<
1763
           (QMAT_SHIFT - 3)))
1764
        */
1765
        if (((level << (31 - (QMAT_SHIFT - 3))) >> (31 - (QMAT_SHIFT - 3))) != 
1766
            level) {
1767
            level = level / (1 << (QMAT_SHIFT - 3));
1768
            /* XXX: currently, this code is not optimal. the range should be:
1769
               mpeg1: -255..255
1770
               mpeg2: -2048..2047
1771
               h263:  -128..127
1772
               mpeg4: -2048..2047
1773
            */
1774
            if (level > maxLevel)
1775
                level = maxLevel;
1776
            else if (level < minLevel)
1777
                level = minLevel;
1778

    
1779
            block[j] = level;
1780
            last_non_zero = i;
1781
        } else {
1782
            block[j] = 0;
1783
        }
1784
    }
1785
    return last_non_zero;
1786
}
1787

    
1788
static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
1789
                                   DCTELEM *block, int n, int qscale)
1790
{
1791
    int i, level, nCoeffs;
1792
    const UINT16 *quant_matrix;
1793

    
1794
    if(s->alternate_scan) nCoeffs= 64;
1795
    else nCoeffs= s->block_last_index[n]+1;
1796
    
1797
    if (s->mb_intra) {
1798
        if (n < 4) 
1799
            block[0] = block[0] * s->y_dc_scale;
1800
        else
1801
            block[0] = block[0] * s->c_dc_scale;
1802
        /* XXX: only mpeg1 */
1803
        quant_matrix = s->intra_matrix;
1804
        for(i=1;i<nCoeffs;i++) {
1805
            int j= zigzag_direct[i];
1806
            level = block[j];
1807
            if (level) {
1808
                if (level < 0) {
1809
                    level = -level;
1810
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
1811
                    level = (level - 1) | 1;
1812
                    level = -level;
1813
                } else {
1814
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
1815
                    level = (level - 1) | 1;
1816
                }
1817
#ifdef PARANOID
1818
                if (level < -2048 || level > 2047)
1819
                    fprintf(stderr, "unquant error %d %d\n", i, level);
1820
#endif
1821
                block[j] = level;
1822
            }
1823
        }
1824
    } else {
1825
        i = 0;
1826
        quant_matrix = s->non_intra_matrix;
1827
        for(;i<nCoeffs;i++) {
1828
            int j= zigzag_direct[i];
1829
            level = block[j];
1830
            if (level) {
1831
                if (level < 0) {
1832
                    level = -level;
1833
                    level = (((level << 1) + 1) * qscale *
1834
                             ((int) (quant_matrix[j]))) >> 4;
1835
                    level = (level - 1) | 1;
1836
                    level = -level;
1837
                } else {
1838
                    level = (((level << 1) + 1) * qscale *
1839
                             ((int) (quant_matrix[j]))) >> 4;
1840
                    level = (level - 1) | 1;
1841
                }
1842
#ifdef PARANOID
1843
                if (level < -2048 || level > 2047)
1844
                    fprintf(stderr, "unquant error %d %d\n", i, level);
1845
#endif
1846
                block[j] = level;
1847
            }
1848
        }
1849
    }
1850
}
1851

    
1852
static void dct_unquantize_h263_c(MpegEncContext *s, 
1853
                                  DCTELEM *block, int n, int qscale)
1854
{
1855
    int i, level, qmul, qadd;
1856
    int nCoeffs;
1857
    
1858
    if (s->mb_intra) {
1859
        if (!s->h263_aic) {
1860
            if (n < 4) 
1861
                block[0] = block[0] * s->y_dc_scale;
1862
            else
1863
                block[0] = block[0] * s->c_dc_scale;
1864
        }
1865
        i = 1;
1866
        nCoeffs= 64; //does not allways use zigzag table 
1867
    } else {
1868
        i = 0;
1869
        nCoeffs= zigzag_end[ s->block_last_index[n] ];
1870
    }
1871

    
1872
    qmul = s->qscale << 1;
1873
    if (s->h263_aic && s->mb_intra)
1874
        qadd = 0;
1875
    else
1876
        qadd = (s->qscale - 1) | 1;
1877

    
1878
    for(;i<nCoeffs;i++) {
1879
        level = block[i];
1880
        if (level) {
1881
            if (level < 0) {
1882
                level = level * qmul - qadd;
1883
            } else {
1884
                level = level * qmul + qadd;
1885
            }
1886
#ifdef PARANOID
1887
                if (level < -2048 || level > 2047)
1888
                    fprintf(stderr, "unquant error %d %d\n", i, level);
1889
#endif
1890
            block[i] = level;
1891
        }
1892
    }
1893
}
1894

    
1895
/* rate control */
1896

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

    
1901
static void rate_control_init(MpegEncContext *s)
1902
{
1903
#if 1
1904
    emms_c();
1905

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

    
1916
    s->short_term_qsum=0.001;
1917
    s->short_term_qcount=0.001;
1918
#else
1919
    s->wanted_bits = 0;
1920

    
1921
    if (s->intra_only) {
1922
        s->I_frame_bits = ((INT64)s->bit_rate * FRAME_RATE_BASE) / s->frame_rate;
1923
        s->P_frame_bits = s->I_frame_bits;
1924
    } else {
1925
        s->P_frame_bits = (int) ((float)(s->gop_size * s->bit_rate) / 
1926
                                 (float)((float)s->frame_rate / FRAME_RATE_BASE * (I_FRAME_SIZE_RATIO + s->gop_size - 1)));
1927
        s->I_frame_bits = (int)(s->P_frame_bits * I_FRAME_SIZE_RATIO);
1928
    }
1929

    
1930
#if defined(DEBUG)
1931
    printf("I_frame_size=%d P_frame_size=%d\n",
1932
           s->I_frame_bits, s->P_frame_bits);
1933
#endif
1934
#endif
1935
}
1936

    
1937
static double predict(Predictor *p, double q, double var)
1938
{
1939
    return p->coeff*var / (q*p->count);
1940
}
1941

    
1942
static void update_predictor(Predictor *p, double q, double var, double size)
1943
{
1944
    double new_coeff= size*q / (var + 1);
1945
    if(var<1000) return;
1946
/*{
1947
int pred= predict(p, q, var);
1948
int error= abs(pred-size);
1949
static double sum=0;
1950
static int count=0;
1951
if(count>5) sum+=error;
1952
count++;
1953
if(256*256*256*64%count==0){
1954
    printf("%d %f %f\n", count, sum/count, p->coeff);
1955
}
1956
}*/
1957
    p->count*= p->decay;
1958
    p->coeff*= p->decay;
1959
    p->count++;
1960
    p->coeff+= new_coeff;
1961
}
1962

    
1963
static int rate_estimate_qscale(MpegEncContext *s)
1964
{
1965
#if 1
1966
    int qmin= s->qmin;
1967
    int qmax= s->qmax;
1968
    int rate_q=5;
1969
    float q;
1970
    int qscale;
1971
    float br_compensation;
1972
    double diff;
1973
    double short_term_q;
1974
    double long_term_q;
1975
    int last_qscale= s->qscale;
1976
    double fps;
1977
    INT64 wanted_bits;
1978
    emms_c();
1979

    
1980
    fps= (double)s->frame_rate / FRAME_RATE_BASE;
1981
    wanted_bits= s->bit_rate*(double)s->picture_number/fps;
1982

    
1983
    
1984
    if(s->picture_number>2){
1985
        /* update predictors */
1986
        if(s->last_pict_type == I_TYPE){
1987
        //FIXME
1988
        }else{ //P Frame
1989
//printf("%d %d %d %f\n", s->qscale, s->last_mc_mb_var, s->frame_bits, s->p_pred.coeff);
1990
            update_predictor(&s->p_pred, s->qscale, s->last_mc_mb_var, s->frame_bits);
1991
        }
1992
    }
1993

    
1994
    if(s->pict_type == I_TYPE){
1995
        //FIXME
1996
        rate_q= s->qsum/s->qcount;
1997
    }else{ //P Frame
1998
        int i;
1999
        int diff, best_diff=1000000000;
2000
        for(i=1; i<=31; i++){
2001
            diff= predict(&s->p_pred, i, s->mc_mb_var) - (double)s->bit_rate/fps;
2002
            if(diff<0) diff= -diff;
2003
            if(diff<best_diff){
2004
                best_diff= diff;
2005
                rate_q= i;
2006
            }
2007
        }
2008
    }
2009

    
2010
    s->short_term_qsum*=s->qblur;
2011
    s->short_term_qcount*=s->qblur;
2012

    
2013
    s->short_term_qsum+= rate_q;
2014
    s->short_term_qcount++;
2015
    short_term_q= s->short_term_qsum/s->short_term_qcount;
2016
    
2017
    long_term_q= s->qsum/s->qcount*(s->total_bits+1)/(wanted_bits+1); //+1 to avoid nan & 0
2018

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

    
2022
    diff= s->total_bits - wanted_bits;
2023
    br_compensation= (s->bit_rate_tolerance - diff)/s->bit_rate_tolerance;
2024
    if(br_compensation<=0.0) br_compensation=0.001;
2025
    q/=br_compensation;
2026

    
2027
    qscale= (int)(q + 0.5);
2028
    if     (qscale<qmin) qscale=qmin;
2029
    else if(qscale>qmax) qscale=qmax;
2030
    
2031
    if     (qscale<last_qscale-s->max_qdiff) qscale=last_qscale-s->max_qdiff;
2032
    else if(qscale>last_qscale+s->max_qdiff) qscale=last_qscale+s->max_qdiff;
2033

    
2034
    s->qsum+= qscale;
2035
    s->qcount++;
2036

    
2037
    s->last_pict_type= s->pict_type;
2038
//printf("q:%d diff:%d comp:%f rate_q:%d st_q:%f fvar:%d last_size:%d\n", qscale, (int)diff, br_compensation, 
2039
//       rate_q, short_term_q, s->mc_mb_var, s->frame_bits);
2040
//printf("%d %d\n", s->bit_rate, (int)fps);
2041
    return qscale;
2042
#else
2043
    INT64 diff, total_bits = s->total_bits;
2044
    float q;
2045
    int qscale;
2046
    if (s->pict_type == I_TYPE) {
2047
        s->wanted_bits += s->I_frame_bits;
2048
    } else {
2049
        s->wanted_bits += s->P_frame_bits;
2050
    }
2051
    diff = s->wanted_bits - total_bits;
2052
    q = 31.0 - (float)diff / (QSCALE_K * s->mb_height * s->mb_width);
2053
    /* adjust for I frame */
2054
    if (s->pict_type == I_TYPE && !s->intra_only) {
2055
        q /= I_FRAME_SIZE_RATIO;
2056
    }
2057

    
2058
    /* using a too small Q scale leeds to problems in mpeg1 and h263
2059
       because AC coefficients are clamped to 255 or 127 */
2060
    qmin = 3;
2061
    if (q < qmin)
2062
        q = qmin;
2063
    else if (q > 31)
2064
        q = 31;
2065
    qscale = (int)(q + 0.5);
2066
#if defined(DEBUG)
2067
    printf("\n%d: total=%0.0f wanted=%0.0f br=%0.1f diff=%d qest=%2.1f\n", 
2068
           s->picture_number, 
2069
           (double)total_bits, 
2070
           (double)s->wanted_bits,
2071
           (float)s->frame_rate / FRAME_RATE_BASE * 
2072
           total_bits / s->picture_number, 
2073
           (int)diff, q);
2074
#endif
2075
    return qscale;
2076
#endif
2077
}
2078

    
2079
AVCodec mpeg1video_encoder = {
2080
    "mpeg1video",
2081
    CODEC_TYPE_VIDEO,
2082
    CODEC_ID_MPEG1VIDEO,
2083
    sizeof(MpegEncContext),
2084
    MPV_encode_init,
2085
    MPV_encode_picture,
2086
    MPV_encode_end,
2087
};
2088

    
2089
AVCodec h263_encoder = {
2090
    "h263",
2091
    CODEC_TYPE_VIDEO,
2092
    CODEC_ID_H263,
2093
    sizeof(MpegEncContext),
2094
    MPV_encode_init,
2095
    MPV_encode_picture,
2096
    MPV_encode_end,
2097
};
2098

    
2099
AVCodec h263p_encoder = {
2100
    "h263p",
2101
    CODEC_TYPE_VIDEO,
2102
    CODEC_ID_H263P,
2103
    sizeof(MpegEncContext),
2104
    MPV_encode_init,
2105
    MPV_encode_picture,
2106
    MPV_encode_end,
2107
};
2108

    
2109
AVCodec rv10_encoder = {
2110
    "rv10",
2111
    CODEC_TYPE_VIDEO,
2112
    CODEC_ID_RV10,
2113
    sizeof(MpegEncContext),
2114
    MPV_encode_init,
2115
    MPV_encode_picture,
2116
    MPV_encode_end,
2117
};
2118

    
2119
AVCodec mjpeg_encoder = {
2120
    "mjpeg",
2121
    CODEC_TYPE_VIDEO,
2122
    CODEC_ID_MJPEG,
2123
    sizeof(MpegEncContext),
2124
    MPV_encode_init,
2125
    MPV_encode_picture,
2126
    MPV_encode_end,
2127
};
2128

    
2129
AVCodec mpeg4_encoder = {
2130
    "mpeg4",
2131
    CODEC_TYPE_VIDEO,
2132
    CODEC_ID_MPEG4,
2133
    sizeof(MpegEncContext),
2134
    MPV_encode_init,
2135
    MPV_encode_picture,
2136
    MPV_encode_end,
2137
};
2138

    
2139
AVCodec msmpeg4v1_encoder = {
2140
    "msmpeg4v1",
2141
    CODEC_TYPE_VIDEO,
2142
    CODEC_ID_MSMPEG4V1,
2143
    sizeof(MpegEncContext),
2144
    MPV_encode_init,
2145
    MPV_encode_picture,
2146
    MPV_encode_end,
2147
};
2148

    
2149
AVCodec msmpeg4v2_encoder = {
2150
    "msmpeg4v2",
2151
    CODEC_TYPE_VIDEO,
2152
    CODEC_ID_MSMPEG4V2,
2153
    sizeof(MpegEncContext),
2154
    MPV_encode_init,
2155
    MPV_encode_picture,
2156
    MPV_encode_end,
2157
};
2158

    
2159
AVCodec msmpeg4v3_encoder = {
2160
    "msmpeg4",
2161
    CODEC_TYPE_VIDEO,
2162
    CODEC_ID_MSMPEG4V3,
2163
    sizeof(MpegEncContext),
2164
    MPV_encode_init,
2165
    MPV_encode_picture,
2166
    MPV_encode_end,
2167
};