Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegvideo.c @ 11ce8834

History | View | Annotate | Download (59.7 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
#include <stdlib.h>
20
#include <stdio.h>
21
#include <math.h>
22
#include <string.h>
23
#include "avcodec.h"
24
#include "dsputil.h"
25
#include "mpegvideo.h"
26

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

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

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

    
44
#define EDGE_WIDTH 16
45

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

    
49
//#define DEBUG
50

    
51
/* for jpeg fast DCT */
52
#define CONST_BITS 14
53

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

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

    
70
static UINT16 default_mv_penalty[MAX_FCODE][MAX_MV*2+1];
71
static UINT8 default_fcode_tab[MAX_MV*2+1];
72

    
73
/* default motion estimation */
74
int motion_estimation_method = ME_LOG;
75

    
76
extern UINT8 zigzag_end[64];
77

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

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

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

    
111
    if (s->out_format == FMT_H263) 
112
        s->dct_unquantize = dct_unquantize_h263_c;
113
    else
114
        s->dct_unquantize = dct_unquantize_mpeg1_c;
115
        
116
#ifdef HAVE_MMX
117
    MPV_common_init_mmx(s);
118
#endif
119
    s->mb_width = (s->width + 15) / 16;
120
    s->mb_height = (s->height + 15) / 16;
121
    s->mb_num = s->mb_width * s->mb_height;
122
    s->linesize = s->mb_width * 16 + 2 * EDGE_WIDTH;
123

    
124
    for(i=0;i<3;i++) {
125
        int w, h, shift, pict_start;
126

    
127
        w = s->linesize;
128
        h = s->mb_height * 16 + 2 * EDGE_WIDTH;
129
        shift = (i == 0) ? 0 : 1;
130
        c_size = (w >> shift) * (h >> shift);
131
        pict_start = (w >> shift) * (EDGE_WIDTH >> shift) + (EDGE_WIDTH >> shift);
132

    
133
        pict = av_mallocz(c_size);
134
        if (pict == NULL)
135
            goto fail;
136
        s->last_picture_base[i] = pict;
137
        s->last_picture[i] = pict + pict_start;
138
    
139
        pict = av_mallocz(c_size);
140
        if (pict == NULL)
141
            goto fail;
142
        s->next_picture_base[i] = pict;
143
        s->next_picture[i] = pict + pict_start;
144

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

    
187
    if (s->h263_pred || s->h263_plus) {
188
        int y_size, c_size, i, size;
189
        
190
        /* dc values */
191

    
192
        y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
193
        c_size = (s->mb_width + 2) * (s->mb_height + 2);
194
        size = y_size + 2 * c_size;
195
        s->dc_val[0] = malloc(size * sizeof(INT16));
196
        if (s->dc_val[0] == NULL)
197
            goto fail;
198
        s->dc_val[1] = s->dc_val[0] + y_size;
199
        s->dc_val[2] = s->dc_val[1] + c_size;
200
        for(i=0;i<size;i++)
201
            s->dc_val[0][i] = 1024;
202

    
203
        /* ac values */
204
        s->ac_val[0] = av_mallocz(size * sizeof(INT16) * 16);
205
        if (s->ac_val[0] == NULL)
206
            goto fail;
207
        s->ac_val[1] = s->ac_val[0] + y_size;
208
        s->ac_val[2] = s->ac_val[1] + c_size;
209
        
210
        /* cbp values */
211
        s->coded_block = av_mallocz(y_size);
212
        if (!s->coded_block)
213
            goto fail;
214

    
215
        /* which mb is a intra block */
216
        s->mbintra_table = av_mallocz(s->mb_num);
217
        if (!s->mbintra_table)
218
            goto fail;
219
        memset(s->mbintra_table, 1, s->mb_num);
220
    }
221
    /* default structure is frame */
222
    s->picture_structure = PICT_FRAME;
223

    
224
    /* init macroblock skip table */
225
    if (!s->encoding) {
226
        s->mbskip_table = av_mallocz(s->mb_num);
227
        if (!s->mbskip_table)
228
            goto fail;
229
    }
230

    
231
    s->context_initialized = 1;
232
    return 0;
233
 fail:
234
    MPV_common_end(s);
235
    return -1;
236
}
237

    
238
/* init common structure for both encoder and decoder */
239
void MPV_common_end(MpegEncContext *s)
240
{
241
    int i;
242

    
243
    if (s->mb_type)
244
        free(s->mb_type);
245
    if (s->mb_var)
246
        free(s->mb_var);
247
    if (s->mv_table[0])
248
        free(s->mv_table[0]);
249
    if (s->mv_table[1])
250
        free(s->mv_table[1]);
251
    if (s->motion_val)
252
        free(s->motion_val);
253
    if (s->dc_val[0])
254
        free(s->dc_val[0]);
255
    if (s->ac_val[0])
256
        free(s->ac_val[0]);
257
    if (s->coded_block)
258
        free(s->coded_block);
259
    if (s->mbintra_table)
260
        free(s->mbintra_table);
261

    
262
    if (s->mbskip_table)
263
        free(s->mbskip_table);
264
    for(i=0;i<3;i++) {
265
        if (s->last_picture_base[i])
266
            free(s->last_picture_base[i]);
267
        if (s->next_picture_base[i])
268
            free(s->next_picture_base[i]);
269
        if (s->has_b_frames)
270
            free(s->aux_picture_base[i]);
271
    }
272
    s->context_initialized = 0;
273
}
274

    
275
/* init video encoder */
276
int MPV_encode_init(AVCodecContext *avctx)
277
{
278
    MpegEncContext *s = avctx->priv_data;
279
    int i;
280

    
281
    s->bit_rate = avctx->bit_rate;
282
    s->bit_rate_tolerance = avctx->bit_rate_tolerance;
283
    s->frame_rate = avctx->frame_rate;
284
    s->width = avctx->width;
285
    s->height = avctx->height;
286
    s->gop_size = avctx->gop_size;
287
    s->rtp_mode = avctx->rtp_mode;
288
    s->rtp_payload_size = avctx->rtp_payload_size;
289
    if (avctx->rtp_callback)
290
        s->rtp_callback = avctx->rtp_callback;
291
    s->qmin= avctx->qmin;
292
    s->qmax= avctx->qmax;
293
    s->max_qdiff= avctx->max_qdiff;
294
    s->qcompress= avctx->qcompress;
295
    s->qblur= avctx->qblur;
296
    s->avctx = avctx;
297
    s->aspect_ratio_info= avctx->aspect_ratio_info;
298
    
299
    if (s->gop_size <= 1) {
300
        s->intra_only = 1;
301
        s->gop_size = 12;
302
    } else {
303
        s->intra_only = 0;
304
    }
305
    s->full_search = motion_estimation_method;
306

    
307
    s->fixed_qscale = (avctx->flags & CODEC_FLAG_QSCALE);
308
    
309
    switch(avctx->codec->id) {
310
    case CODEC_ID_MPEG1VIDEO:
311
        s->out_format = FMT_MPEG1;
312
        break;
313
    case CODEC_ID_MJPEG:
314
        s->out_format = FMT_MJPEG;
315
        s->intra_only = 1; /* force intra only for jpeg */
316
        s->mjpeg_write_tables = 1; /* write all tables */
317
        s->mjpeg_vsample[0] = 2; /* set up default sampling factors */
318
        s->mjpeg_vsample[1] = 1; /* the only currently supported values */
319
        s->mjpeg_vsample[2] = 1; 
320
        s->mjpeg_hsample[0] = 2; 
321
        s->mjpeg_hsample[1] = 1; 
322
        s->mjpeg_hsample[2] = 1; 
323
        if (mjpeg_init(s) < 0)
324
            return -1;
325
        break;
326
    case CODEC_ID_H263:
327
        if (h263_get_picture_format(s->width, s->height) == 7) {
328
            printf("Input picture size isn't suitable for h263 codec! try h263+\n");
329
            return -1;
330
        }
331
        s->out_format = FMT_H263;
332
        break;
333
    case CODEC_ID_H263P:
334
        s->out_format = FMT_H263;
335
        s->rtp_mode = 1;
336
        s->rtp_payload_size = 1200; 
337
        s->h263_plus = 1;
338
        s->unrestricted_mv = 1;
339
        
340
        /* These are just to be sure */
341
        s->umvplus = 0;
342
        s->umvplus_dec = 0;
343
        break;
344
    case CODEC_ID_RV10:
345
        s->out_format = FMT_H263;
346
        s->h263_rv10 = 1;
347
        break;
348
    case CODEC_ID_MPEG4:
349
        s->out_format = FMT_H263;
350
        s->h263_pred = 1;
351
        s->unrestricted_mv = 1;
352
        break;
353
    case CODEC_ID_MSMPEG4:
354
        s->out_format = FMT_H263;
355
        s->h263_msmpeg4 = 1;
356
        s->h263_pred = 1;
357
        s->unrestricted_mv = 1;
358
        break;
359
    default:
360
        return -1;
361
    }
362

    
363
    { /* set up some save defaults, some codecs might override them later */
364
        static int done=0;
365
        if(!done){
366
            int i;
367
            done=1;
368
            memset(default_mv_penalty, 0, sizeof(UINT16)*MAX_FCODE*(2*MAX_MV+1));
369
            memset(default_fcode_tab , 0, sizeof(UINT8)*(2*MAX_MV+1));
370

    
371
            for(i=-16; i<16; i++){
372
                default_fcode_tab[i + MAX_MV]= 1;
373
            }
374
        }
375
    }
376
    s->mv_penalty= default_mv_penalty;
377
    s->fcode_tab= default_fcode_tab;
378

    
379
    if (s->out_format == FMT_H263)
380
        h263_encode_init(s);
381
    else if (s->out_format == FMT_MPEG1)
382
        mpeg1_encode_init(s);
383

    
384
    s->encoding = 1;
385

    
386
    /* init */
387
    if (MPV_common_init(s) < 0)
388
        return -1;
389
    
390
    /* init default q matrix */
391
    for(i=0;i<64;i++) {
392
        s->intra_matrix[i] = default_intra_matrix[i];
393
        s->non_intra_matrix[i] = default_non_intra_matrix[i];
394
    }
395

    
396
    /* rate control init */
397
    rate_control_init(s);
398

    
399
    s->picture_number = 0;
400
    s->picture_in_gop_number = 0;
401
    s->fake_picture_number = 0;
402
    /* motion detector init */
403
    s->f_code = 1;
404

    
405
    return 0;
406
}
407

    
408
int MPV_encode_end(AVCodecContext *avctx)
409
{
410
    MpegEncContext *s = avctx->priv_data;
411

    
412
#ifdef STATS
413
    print_stats();
414
#endif
415
    MPV_common_end(s);
416
    if (s->out_format == FMT_MJPEG)
417
        mjpeg_close(s);
418
      
419
    return 0;
420
}
421

    
422
/* draw the edges of width 'w' of an image of size width, height */
423
static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w)
424
{
425
    UINT8 *ptr, *last_line;
426
    int i;
427

    
428
    last_line = buf + (height - 1) * wrap;
429
    for(i=0;i<w;i++) {
430
        /* top and bottom */
431
        memcpy(buf - (i + 1) * wrap, buf, width);
432
        memcpy(last_line + (i + 1) * wrap, last_line, width);
433
    }
434
    /* left and right */
435
    ptr = buf;
436
    for(i=0;i<height;i++) {
437
        memset(ptr - w, ptr[0], w);
438
        memset(ptr + width, ptr[width-1], w);
439
        ptr += wrap;
440
    }
441
    /* corners */
442
    for(i=0;i<w;i++) {
443
        memset(buf - (i + 1) * wrap - w, buf[0], w); /* top left */
444
        memset(buf - (i + 1) * wrap + width, buf[width-1], w); /* top right */
445
        memset(last_line + (i + 1) * wrap - w, last_line[0], w); /* top left */
446
        memset(last_line + (i + 1) * wrap + width, last_line[width-1], w); /* top right */
447
    }
448
}
449

    
450
/* generic function for encode/decode called before a frame is coded/decoded */
451
void MPV_frame_start(MpegEncContext *s)
452
{
453
    int i;
454
    UINT8 *tmp;
455

    
456
    s->mb_skiped = 0;
457
    if (s->pict_type == B_TYPE) {
458
        for(i=0;i<3;i++) {
459
            s->current_picture[i] = s->aux_picture[i];
460
        }
461
    } else {
462
        s->last_non_b_pict_type= s->pict_type;
463
        for(i=0;i<3;i++) {
464
            /* swap next and last */
465
            tmp = s->last_picture[i];
466
            s->last_picture[i] = s->next_picture[i];
467
            s->next_picture[i] = tmp;
468
            s->current_picture[i] = tmp;
469
        }
470
    }
471
}
472

    
473
/* generic function for encode/decode called after a frame has been coded/decoded */
474
void MPV_frame_end(MpegEncContext *s)
475
{
476
    /* draw edge for correct motion prediction if outside */
477
    if (s->pict_type != B_TYPE && !s->intra_only) {
478
      if(s->avctx==NULL || s->avctx->codec->id!=CODEC_ID_MPEG4 || s->divx_version==500){
479
        draw_edges(s->current_picture[0], s->linesize, s->mb_width*16, s->mb_height*16, EDGE_WIDTH);
480
        draw_edges(s->current_picture[1], s->linesize/2, s->mb_width*8, s->mb_height*8, EDGE_WIDTH/2);
481
        draw_edges(s->current_picture[2], s->linesize/2, s->mb_width*8, s->mb_height*8, EDGE_WIDTH/2);
482
      }else{
483
        /* mpeg4? / opendivx / xvid */
484
        draw_edges(s->current_picture[0], s->linesize, s->width, s->height, EDGE_WIDTH);
485
        draw_edges(s->current_picture[1], s->linesize/2, s->width/2, s->height/2, EDGE_WIDTH/2);
486
        draw_edges(s->current_picture[2], s->linesize/2, s->width/2, s->height/2, EDGE_WIDTH/2);
487
      }
488
    }
489
    emms_c();
490
}
491

    
492
int MPV_encode_picture(AVCodecContext *avctx,
493
                       unsigned char *buf, int buf_size, void *data)
494
{
495
    MpegEncContext *s = avctx->priv_data;
496
    AVPicture *pict = data;
497
    int i, j;
498

    
499
    if (s->fixed_qscale) 
500
        s->qscale = avctx->quality;
501

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

    
504
    if (!s->intra_only) {
505
        /* first picture of GOP is intra */
506
        if (s->picture_in_gop_number >= s->gop_size){
507
            s->picture_in_gop_number=0;
508
            s->pict_type = I_TYPE;
509
        }else
510
            s->pict_type = P_TYPE;
511
    } else {
512
        s->pict_type = I_TYPE;
513
    }
514
    
515
    MPV_frame_start(s);
516
    
517
    for(i=0;i<3;i++) {
518
        UINT8 *src = pict->data[i];
519
        UINT8 *dest = s->current_picture[i];
520
        int src_wrap = pict->linesize[i];
521
        int dest_wrap = s->linesize;
522
        int w = s->width;
523
        int h = s->height;
524

    
525
        if (i >= 1) {
526
            dest_wrap >>= 1;
527
            w >>= 1;
528
            h >>= 1;
529
        }
530

    
531
        if(dest_wrap==src_wrap){
532
            s->new_picture[i] = pict->data[i];
533
        } else {
534
            for(j=0;j<h;j++) {
535
                memcpy(dest, src, w);
536
                dest += dest_wrap;
537
                src += src_wrap;
538
            }
539
            s->new_picture[i] = s->current_picture[i];
540
            }
541
    }
542

    
543
    encode_picture(s, s->picture_number);
544
    avctx->key_frame = (s->pict_type == I_TYPE);
545
    
546
    MPV_frame_end(s);
547
    s->picture_number++;
548
    s->picture_in_gop_number++;
549

    
550
    if (s->out_format == FMT_MJPEG)
551
        mjpeg_picture_trailer(s);
552

    
553
    flush_put_bits(&s->pb);
554
    s->last_frame_bits= s->frame_bits;
555
    s->frame_bits  = (pbBufPtr(&s->pb) - s->pb.buf) * 8;
556
    s->total_bits += s->frame_bits;
557

    
558
    avctx->quality = s->qscale;
559
    if (avctx->get_psnr) {
560
        /* At this point pict->data should have the original frame   */
561
        /* an s->current_picture should have the coded/decoded frame */
562
        get_psnr(pict->data, s->current_picture,
563
                 pict->linesize, s->linesize, avctx);
564
    }
565
    return pbBufPtr(&s->pb) - s->pb.buf;
566
}
567

    
568
static inline int clip(int a, int amin, int amax)
569
{
570
    if (a < amin)
571
        return amin;
572
    else if (a > amax)
573
        return amax;
574
    else
575
        return a;
576
}
577

    
578
static inline void gmc1_motion(MpegEncContext *s,
579
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
580
                               int dest_offset,
581
                               UINT8 **ref_picture, int src_offset,
582
                               int h)
583
{
584
    UINT8 *ptr;
585
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
586
    int motion_x, motion_y;
587

    
588
    if(s->real_sprite_warping_points>1) printf("more than 1 warp point isnt supported\n");
589
    motion_x= s->sprite_offset[0][0];
590
    motion_y= s->sprite_offset[0][1];
591
    src_x = s->mb_x * 16 + (motion_x >> (s->sprite_warping_accuracy+1));
592
    src_y = s->mb_y * 16 + (motion_y >> (s->sprite_warping_accuracy+1));
593
    motion_x<<=(3-s->sprite_warping_accuracy);
594
    motion_y<<=(3-s->sprite_warping_accuracy);
595
    src_x = clip(src_x, -16, s->width);
596
    if (src_x == s->width)
597
        motion_x =0;
598
    src_y = clip(src_y, -16, s->height);
599
    if (src_y == s->height)
600
        motion_y =0;
601
    
602
    linesize = s->linesize;
603
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
604

    
605
    dest_y+=dest_offset;
606
    gmc1(dest_y  , ptr  , linesize, h, motion_x&15, motion_y&15, s->no_rounding);
607
    gmc1(dest_y+8, ptr+8, linesize, h, motion_x&15, motion_y&15, s->no_rounding);
608

    
609
    motion_x= s->sprite_offset[1][0];
610
    motion_y= s->sprite_offset[1][1];
611
    src_x = s->mb_x * 8 + (motion_x >> (s->sprite_warping_accuracy+1));
612
    src_y = s->mb_y * 8 + (motion_y >> (s->sprite_warping_accuracy+1));
613
    motion_x<<=(3-s->sprite_warping_accuracy);
614
    motion_y<<=(3-s->sprite_warping_accuracy);
615
    src_x = clip(src_x, -8, s->width>>1);
616
    if (src_x == s->width>>1)
617
        motion_x =0;
618
    src_y = clip(src_y, -8, s->height>>1);
619
    if (src_y == s->height>>1)
620
        motion_y =0;
621

    
622
    offset = (src_y * linesize>>1) + src_x + (src_offset>>1);
623
    ptr = ref_picture[1] + offset;
624
    gmc1(dest_cb + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
625
    ptr = ref_picture[2] + offset;
626
    gmc1(dest_cr + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
627
    
628
    return;
629
}
630

    
631
/* apply one mpeg motion vector to the three components */
632
static inline void mpeg_motion(MpegEncContext *s,
633
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
634
                               int dest_offset,
635
                               UINT8 **ref_picture, int src_offset,
636
                               int field_based, op_pixels_func *pix_op,
637
                               int motion_x, int motion_y, int h)
638
{
639
    UINT8 *ptr;
640
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
641
if(s->quarter_sample)
642
{
643
    motion_x>>=1;
644
    motion_y>>=1;
645
}
646
    dxy = ((motion_y & 1) << 1) | (motion_x & 1);
647
    src_x = s->mb_x * 16 + (motion_x >> 1);
648
    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 1);
649
                
650
    /* WARNING: do no forget half pels */
651
    height = s->height >> field_based;
652
    src_x = clip(src_x, -16, s->width);
653
    if (src_x == s->width)
654
        dxy &= ~1;
655
    src_y = clip(src_y, -16, height);
656
    if (src_y == height)
657
        dxy &= ~2;
658
    linesize = s->linesize << field_based;
659
    ptr = ref_picture[0] + (src_y * linesize) + (src_x) + src_offset;
660
    dest_y += dest_offset;
661
    pix_op[dxy](dest_y, ptr, linesize, h);
662
    pix_op[dxy](dest_y + 8, ptr + 8, linesize, h);
663

    
664
    if (s->out_format == FMT_H263) {
665
        dxy = 0;
666
        if ((motion_x & 3) != 0)
667
            dxy |= 1;
668
        if ((motion_y & 3) != 0)
669
            dxy |= 2;
670
        mx = motion_x >> 2;
671
        my = motion_y >> 2;
672
    } else {
673
        mx = motion_x / 2;
674
        my = motion_y / 2;
675
        dxy = ((my & 1) << 1) | (mx & 1);
676
        mx >>= 1;
677
        my >>= 1;
678
    }
679
    
680
    src_x = s->mb_x * 8 + mx;
681
    src_y = s->mb_y * (8 >> field_based) + my;
682
    src_x = clip(src_x, -8, s->width >> 1);
683
    if (src_x == (s->width >> 1))
684
        dxy &= ~1;
685
    src_y = clip(src_y, -8, height >> 1);
686
    if (src_y == (height >> 1))
687
        dxy &= ~2;
688

    
689
    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
690
    ptr = ref_picture[1] + offset;
691
    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
692
    ptr = ref_picture[2] + offset;
693
    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
694
}
695

    
696
static inline void qpel_motion(MpegEncContext *s,
697
                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
698
                               int dest_offset,
699
                               UINT8 **ref_picture, int src_offset,
700
                               int field_based, op_pixels_func *pix_op,
701
                               qpel_mc_func *qpix_op,
702
                               int motion_x, int motion_y, int h)
703
{
704
    UINT8 *ptr;
705
    int dxy, offset, mx, my, src_x, src_y, height, linesize;
706

    
707
    dxy = ((motion_y & 3) << 2) | (motion_x & 3);
708
    src_x = s->mb_x * 16 + (motion_x >> 2);
709
    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 2);
710

    
711
    height = s->height >> field_based;
712
    src_x = clip(src_x, -16, s->width);
713
    if (src_x == s->width)
714
        dxy &= ~3;
715
    src_y = clip(src_y, -16, height);
716
    if (src_y == height)
717
        dxy &= ~12;
718
    linesize = s->linesize << field_based;
719
    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
720
    dest_y += dest_offset;
721
//printf("%d %d %d\n", src_x, src_y, dxy);
722
    qpix_op[dxy](dest_y                 , ptr                 , linesize, linesize, motion_x&3, motion_y&3);
723
    qpix_op[dxy](dest_y              + 8, ptr              + 8, linesize, linesize, motion_x&3, motion_y&3);
724
    qpix_op[dxy](dest_y + linesize*8    , ptr + linesize*8    , linesize, linesize, motion_x&3, motion_y&3);
725
    qpix_op[dxy](dest_y + linesize*8 + 8, ptr + linesize*8 + 8, linesize, linesize, motion_x&3, motion_y&3);
726
    
727
    mx= (motion_x>>1) | (motion_x&1);
728
    my= (motion_y>>1) | (motion_y&1);
729

    
730
    dxy = 0;
731
    if ((mx & 3) != 0)
732
        dxy |= 1;
733
    if ((my & 3) != 0)
734
        dxy |= 2;
735
    mx = mx >> 2;
736
    my = my >> 2;
737
    
738
    src_x = s->mb_x * 8 + mx;
739
    src_y = s->mb_y * (8 >> field_based) + my;
740
    src_x = clip(src_x, -8, s->width >> 1);
741
    if (src_x == (s->width >> 1))
742
        dxy &= ~1;
743
    src_y = clip(src_y, -8, height >> 1);
744
    if (src_y == (height >> 1))
745
        dxy &= ~2;
746

    
747
    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
748
    ptr = ref_picture[1] + offset;
749
    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
750
    ptr = ref_picture[2] + offset;
751
    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
752
}
753

    
754

    
755
static inline void MPV_motion(MpegEncContext *s, 
756
                              UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
757
                              int dir, UINT8 **ref_picture, 
758
                              op_pixels_func *pix_op, qpel_mc_func *qpix_op)
759
{
760
    int dxy, offset, mx, my, src_x, src_y, motion_x, motion_y;
761
    int mb_x, mb_y, i;
762
    UINT8 *ptr, *dest;
763

    
764
    mb_x = s->mb_x;
765
    mb_y = s->mb_y;
766

    
767
    switch(s->mv_type) {
768
    case MV_TYPE_16X16:
769
        if(s->mcsel){
770
#if 0
771
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
772
                        ref_picture, 0,
773
                        0, pix_op,
774
                        s->sprite_offset[0][0]>>3,
775
                        s->sprite_offset[0][1]>>3,
776
                        16);
777
#else
778
            gmc1_motion(s, dest_y, dest_cb, dest_cr, 0,
779
                        ref_picture, 0,
780
                        16);
781
#endif
782
        }else if(s->quarter_sample && dir==0){ //FIXME
783
            qpel_motion(s, dest_y, dest_cb, dest_cr, 0,
784
                        ref_picture, 0,
785
                        0, pix_op, qpix_op,
786
                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
787
        }else{
788
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
789
                        ref_picture, 0,
790
                        0, pix_op,
791
                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
792
        }           
793
        break;
794
    case MV_TYPE_8X8:
795
        for(i=0;i<4;i++) {
796
            motion_x = s->mv[dir][i][0];
797
            motion_y = s->mv[dir][i][1];
798

    
799
            dxy = ((motion_y & 1) << 1) | (motion_x & 1);
800
            src_x = mb_x * 16 + (motion_x >> 1) + (i & 1) * 8;
801
            src_y = mb_y * 16 + (motion_y >> 1) + ((i >> 1) & 1) * 8;
802
                    
803
            /* WARNING: do no forget half pels */
804
            src_x = clip(src_x, -16, s->width);
805
            if (src_x == s->width)
806
                dxy &= ~1;
807
            src_y = clip(src_y, -16, s->height);
808
            if (src_y == s->height)
809
                dxy &= ~2;
810
                    
811
            ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
812
            dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
813
            pix_op[dxy](dest, ptr, s->linesize, 8);
814
        }
815
        /* In case of 8X8, we construct a single chroma motion vector
816
           with a special rounding */
817
        mx = 0;
818
        my = 0;
819
        for(i=0;i<4;i++) {
820
            mx += s->mv[dir][i][0];
821
            my += s->mv[dir][i][1];
822
        }
823
        if (mx >= 0)
824
            mx = (h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
825
        else {
826
            mx = -mx;
827
            mx = -(h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
828
        }
829
        if (my >= 0)
830
            my = (h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
831
        else {
832
            my = -my;
833
            my = -(h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
834
        }
835
        dxy = ((my & 1) << 1) | (mx & 1);
836
        mx >>= 1;
837
        my >>= 1;
838

    
839
        src_x = mb_x * 8 + mx;
840
        src_y = mb_y * 8 + my;
841
        src_x = clip(src_x, -8, s->width/2);
842
        if (src_x == s->width/2)
843
            dxy &= ~1;
844
        src_y = clip(src_y, -8, s->height/2);
845
        if (src_y == s->height/2)
846
            dxy &= ~2;
847
        
848
        offset = (src_y * (s->linesize >> 1)) + src_x;
849
        ptr = ref_picture[1] + offset;
850
        pix_op[dxy](dest_cb, ptr, s->linesize >> 1, 8);
851
        ptr = ref_picture[2] + offset;
852
        pix_op[dxy](dest_cr, ptr, s->linesize >> 1, 8);
853
        break;
854
    case MV_TYPE_FIELD:
855
        if (s->picture_structure == PICT_FRAME) {
856
            /* top field */
857
            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
858
                        ref_picture, s->field_select[dir][0] ? s->linesize : 0,
859
                        1, pix_op,
860
                        s->mv[dir][0][0], s->mv[dir][0][1], 8);
861
            /* bottom field */
862
            mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
863
                        ref_picture, s->field_select[dir][1] ? s->linesize : 0,
864
                        1, pix_op,
865
                        s->mv[dir][1][0], s->mv[dir][1][1], 8);
866
        } else {
867
            
868

    
869
        }
870
        break;
871
    }
872
}
873

    
874

    
875
/* put block[] to dest[] */
876
static inline void put_dct(MpegEncContext *s, 
877
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
878
{
879
    if (!s->mpeg2)
880
        s->dct_unquantize(s, block, i, s->qscale);
881
    ff_idct (block);
882
    put_pixels_clamped(block, dest, line_size);
883
}
884

    
885
/* add block[] to dest[] */
886
static inline void add_dct(MpegEncContext *s, 
887
                           DCTELEM *block, int i, UINT8 *dest, int line_size)
888
{
889
    if (s->block_last_index[i] >= 0) {
890
        if (!s->mpeg2)
891
            if(s->encoding || (!s->h263_msmpeg4))
892
                s->dct_unquantize(s, block, i, s->qscale);
893
        ff_idct (block);
894
        add_pixels_clamped(block, dest, line_size);
895
    }
896
}
897

    
898
/* generic function called after a macroblock has been parsed by the
899
   decoder or after it has been encoded by the encoder.
900

901
   Important variables used:
902
   s->mb_intra : true if intra macroblock
903
   s->mv_dir   : motion vector direction
904
   s->mv_type  : motion vector type
905
   s->mv       : motion vector
906
   s->interlaced_dct : true if interlaced dct used (mpeg2)
907
 */
908
void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
909
{
910
    int mb_x, mb_y;
911
    int dct_linesize, dct_offset;
912
    op_pixels_func *op_pix;
913
    qpel_mc_func *op_qpix;
914

    
915
    mb_x = s->mb_x;
916
    mb_y = s->mb_y;
917

    
918
#ifdef FF_POSTPROCESS
919
    quant_store[mb_y][mb_x]=s->qscale;
920
    //printf("[%02d][%02d] %d\n",mb_x,mb_y,s->qscale);
921
#endif
922

    
923
    /* update DC predictors for P macroblocks */
924
    if (!s->mb_intra) {
925
        if (s->h263_pred || s->h263_aic) {
926
          if(s->mbintra_table[mb_x + mb_y*s->mb_width])
927
          {
928
            int wrap, xy, v;
929
            s->mbintra_table[mb_x + mb_y*s->mb_width]=0;
930
            wrap = 2 * s->mb_width + 2;
931
            xy = 2 * mb_x + 1 +  (2 * mb_y + 1) * wrap;
932
            v = 1024;
933
            
934
            s->dc_val[0][xy] = v;
935
            s->dc_val[0][xy + 1] = v;
936
            s->dc_val[0][xy + wrap] = v;
937
            s->dc_val[0][xy + 1 + wrap] = v;
938
            /* ac pred */
939
            memset(s->ac_val[0][xy], 0, 16 * sizeof(INT16));
940
            memset(s->ac_val[0][xy + 1], 0, 16 * sizeof(INT16));
941
            memset(s->ac_val[0][xy + wrap], 0, 16 * sizeof(INT16));
942
            memset(s->ac_val[0][xy + 1 + wrap], 0, 16 * sizeof(INT16));
943
            if (s->h263_msmpeg4) {
944
                s->coded_block[xy] = 0;
945
                s->coded_block[xy + 1] = 0;
946
                s->coded_block[xy + wrap] = 0;
947
                s->coded_block[xy + 1 + wrap] = 0;
948
            }
949
            /* chroma */
950
            wrap = s->mb_width + 2;
951
            xy = mb_x + 1 + (mb_y + 1) * wrap;
952
            s->dc_val[1][xy] = v;
953
            s->dc_val[2][xy] = v;
954
            /* ac pred */
955
            memset(s->ac_val[1][xy], 0, 16 * sizeof(INT16));
956
            memset(s->ac_val[2][xy], 0, 16 * sizeof(INT16));
957
          }
958
        } else {
959
            s->last_dc[0] = 128 << s->intra_dc_precision;
960
            s->last_dc[1] = 128 << s->intra_dc_precision;
961
            s->last_dc[2] = 128 << s->intra_dc_precision;
962
        }
963
    }
964
    else if (s->h263_pred || s->h263_aic)
965
        s->mbintra_table[mb_x + mb_y*s->mb_width]=1;
966

    
967
    /* update motion predictor, not for B-frames as they need the motion_val from the last P/S-Frame */
968
    if (s->out_format == FMT_H263) {
969
      if(s->pict_type!=B_TYPE){
970
        int xy, wrap, motion_x, motion_y;
971
        
972
        wrap = 2 * s->mb_width + 2;
973
        xy = 2 * mb_x + 1 + (2 * mb_y + 1) * wrap;
974
        if (s->mb_intra) {
975
            motion_x = 0;
976
            motion_y = 0;
977
            goto motion_init;
978
        } else if (s->mv_type == MV_TYPE_16X16) {
979
            motion_x = s->mv[0][0][0];
980
            motion_y = s->mv[0][0][1];
981
        motion_init:
982
            /* no update if 8X8 because it has been done during parsing */
983
            s->motion_val[xy][0] = motion_x;
984
            s->motion_val[xy][1] = motion_y;
985
            s->motion_val[xy + 1][0] = motion_x;
986
            s->motion_val[xy + 1][1] = motion_y;
987
            s->motion_val[xy + wrap][0] = motion_x;
988
            s->motion_val[xy + wrap][1] = motion_y;
989
            s->motion_val[xy + 1 + wrap][0] = motion_x;
990
            s->motion_val[xy + 1 + wrap][1] = motion_y;
991
        }
992
      }
993
    }
994
    
995
    if (!s->intra_only) {
996
        UINT8 *dest_y, *dest_cb, *dest_cr;
997
        UINT8 *mbskip_ptr;
998

    
999
        /* avoid copy if macroblock skipped in last frame too */
1000
        if (!s->encoding && s->pict_type != B_TYPE) {
1001
            mbskip_ptr = &s->mbskip_table[s->mb_y * s->mb_width + s->mb_x];
1002
            if (s->mb_skiped) {
1003
                s->mb_skiped = 0;
1004
                /* if previous was skipped too, then nothing to do ! */
1005
                if (*mbskip_ptr != 0) 
1006
                    goto the_end;
1007
                *mbskip_ptr = 1; /* indicate that this time we skiped it */
1008
            } else {
1009
                *mbskip_ptr = 0; /* not skipped */
1010
            }
1011
        }
1012

    
1013
        dest_y = s->current_picture[0] + (mb_y * 16 * s->linesize) + mb_x * 16;
1014
        dest_cb = s->current_picture[1] + (mb_y * 8 * (s->linesize >> 1)) + mb_x * 8;
1015
        dest_cr = s->current_picture[2] + (mb_y * 8 * (s->linesize >> 1)) + mb_x * 8;
1016

    
1017
        if (s->interlaced_dct) {
1018
            dct_linesize = s->linesize * 2;
1019
            dct_offset = s->linesize;
1020
        } else {
1021
            dct_linesize = s->linesize;
1022
            dct_offset = s->linesize * 8;
1023
        }
1024

    
1025
        if (!s->mb_intra) {
1026
            /* motion handling */
1027
            if (!s->no_rounding){
1028
                op_pix = put_pixels_tab;
1029
                op_qpix= qpel_mc_rnd_tab;
1030
            }else{
1031
                op_pix = put_no_rnd_pixels_tab;
1032
                op_qpix= qpel_mc_no_rnd_tab;
1033
            }
1034

    
1035
            if (s->mv_dir & MV_DIR_FORWARD) {
1036
                MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
1037
                if (!s->no_rounding) 
1038
                    op_pix = avg_pixels_tab;
1039
                else
1040
                    op_pix = avg_no_rnd_pixels_tab;
1041
            }
1042
            if (s->mv_dir & MV_DIR_BACKWARD) {
1043
                MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
1044
            }
1045

    
1046
            /* add dct residue */
1047
            add_dct(s, block[0], 0, dest_y, dct_linesize);
1048
            add_dct(s, block[1], 1, dest_y + 8, dct_linesize);
1049
            add_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
1050
            add_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
1051

    
1052
            add_dct(s, block[4], 4, dest_cb, s->linesize >> 1);
1053
            add_dct(s, block[5], 5, dest_cr, s->linesize >> 1);
1054
        } else {
1055
            /* dct only in intra block */
1056
            put_dct(s, block[0], 0, dest_y, dct_linesize);
1057
            put_dct(s, block[1], 1, dest_y + 8, dct_linesize);
1058
            put_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
1059
            put_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
1060

    
1061
            put_dct(s, block[4], 4, dest_cb, s->linesize >> 1);
1062
            put_dct(s, block[5], 5, dest_cr, s->linesize >> 1);
1063
        }
1064
    }
1065
 the_end:
1066
    emms_c();
1067
}
1068

    
1069
static void encode_picture(MpegEncContext *s, int picture_number)
1070
{
1071
    int mb_x, mb_y, wrap, last_gob, pdif = 0;
1072
    UINT8 *ptr;
1073
    int i, motion_x, motion_y;
1074

    
1075
    s->picture_number = picture_number;
1076

    
1077
    s->last_mc_mb_var = s->mc_mb_var;
1078
    /* Reset the average MB variance */
1079
    s->avg_mb_var = 0;
1080
    s->mc_mb_var = 0;
1081
    /* Estimate motion for every MB */
1082
    for(mb_y=0; mb_y < s->mb_height; mb_y++) {
1083
        for(mb_x=0; mb_x < s->mb_width; mb_x++) {
1084
            int xy= mb_y * s->mb_width + mb_x;
1085
            s->mb_x = mb_x;
1086
            s->mb_y = mb_y;
1087

    
1088
            /* compute motion vector and macro block type (intra or non intra) */
1089
            motion_x = 0;
1090
            motion_y = 0;
1091
            if (s->pict_type == P_TYPE) {
1092
                s->mb_intra = estimate_motion(s, mb_x, mb_y,
1093
                                              &motion_x,
1094
                                              &motion_y);
1095
            } else {
1096
                s->mb_intra = 1;
1097
            }
1098
            /* Store MB type and MV */
1099
            s->mb_type[xy] = s->mb_intra;
1100
            s->mv_table[0][xy] = motion_x;
1101
            s->mv_table[1][xy] = motion_y;
1102
        }
1103
    }
1104
    emms_c();
1105

    
1106
    if(s->avg_mb_var < s->mc_mb_var && s->pict_type != B_TYPE){ //FIXME subtract MV bits
1107
        int i;
1108
        s->pict_type= I_TYPE;
1109
        s->picture_in_gop_number=0;
1110
        for(i=0; i<s->mb_num; i++){
1111
            s->mb_type[i] = 1;
1112
            s->mv_table[0][i] = 0;
1113
            s->mv_table[1][i] = 0;
1114
        }
1115
    }
1116

    
1117
    /* find best f_code */
1118
    if(s->pict_type==P_TYPE){
1119
        int mv_num[8];
1120
        int i;
1121
        int loose=0;
1122
        UINT8 * fcode_tab= s->fcode_tab;
1123

    
1124
        for(i=0; i<8; i++) mv_num[i]=0;
1125

    
1126
        for(i=0; i<s->mb_num; i++){
1127
            if(s->mb_type[i] == 0){
1128
                mv_num[ fcode_tab[s->mv_table[0][i] + MAX_MV] ]++;
1129
                mv_num[ fcode_tab[s->mv_table[1][i] + MAX_MV] ]++;
1130
//printf("%d %d %d\n", s->mv_table[0][i], fcode_tab[s->mv_table[0][i] + MAX_MV], i);
1131
            }
1132
//else printf("I");
1133
        }
1134

    
1135
        for(i=MAX_FCODE; i>1; i--){
1136
            loose+= mv_num[i];
1137
            if(loose > 4) break; //FIXME this is pretty ineffective
1138
        }
1139
        s->f_code= i;
1140
    }else{
1141
        s->f_code= 1;
1142
    }
1143

    
1144
//printf("f_code %d ///\n", s->f_code);
1145
    /* convert MBs with too long MVs to I-Blocks */
1146
    if(s->pict_type==P_TYPE){
1147
        int i;
1148
        const int f_code= s->f_code;
1149
        UINT8 * fcode_tab= s->fcode_tab;
1150

    
1151
        for(i=0; i<s->mb_num; i++){
1152
            if(s->mb_type[i] == 0){
1153
                if(   fcode_tab[s->mv_table[0][i] + MAX_MV] > f_code
1154
                   || fcode_tab[s->mv_table[0][i] + MAX_MV] == 0
1155
                   || fcode_tab[s->mv_table[1][i] + MAX_MV] > f_code
1156
                   || fcode_tab[s->mv_table[1][i] + MAX_MV] == 0 ){
1157
                    s->mb_type[i] = 1;
1158
                    s->mv_table[0][i] = 0;
1159
                    s->mv_table[1][i] = 0;
1160
                }
1161
            }
1162
        }
1163
    }
1164

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

    
1167
    if (!s->fixed_qscale) 
1168
        s->qscale = rate_estimate_qscale(s);
1169

    
1170
    /* precompute matrix */
1171
    if (s->out_format == FMT_MJPEG) {
1172
        /* for mjpeg, we do include qscale in the matrix */
1173
        s->intra_matrix[0] = default_intra_matrix[0];
1174
        for(i=1;i<64;i++)
1175
            s->intra_matrix[i] = (default_intra_matrix[i] * s->qscale) >> 3;
1176
        convert_matrix(s->q_intra_matrix, s->q_intra_matrix16, s->intra_matrix, 8);
1177
    } else {
1178
        convert_matrix(s->q_intra_matrix, s->q_intra_matrix16, s->intra_matrix, s->qscale);
1179
        convert_matrix(s->q_non_intra_matrix, s->q_non_intra_matrix16, s->non_intra_matrix, s->qscale);
1180
    }
1181

    
1182
    switch(s->out_format) {
1183
    case FMT_MJPEG:
1184
        mjpeg_picture_header(s);
1185
        break;
1186
    case FMT_H263:
1187
        if (s->h263_msmpeg4) 
1188
            msmpeg4_encode_picture_header(s, picture_number);
1189
        else if (s->h263_pred)
1190
            mpeg4_encode_picture_header(s, picture_number);
1191
        else if (s->h263_rv10) 
1192
            rv10_encode_picture_header(s, picture_number);
1193
        else
1194
            h263_encode_picture_header(s, picture_number);
1195
        break;
1196
    case FMT_MPEG1:
1197
        mpeg1_encode_picture_header(s, picture_number);
1198
        break;
1199
    }
1200
        
1201
    /* init last dc values */
1202
    /* note: quant matrix value (8) is implied here */
1203
    s->last_dc[0] = 128;
1204
    s->last_dc[1] = 128;
1205
    s->last_dc[2] = 128;
1206
    s->mb_incr = 1;
1207
    s->last_mv[0][0][0] = 0;
1208
    s->last_mv[0][0][1] = 0;
1209
    s->mv_type = MV_TYPE_16X16;
1210
    s->mv_dir = MV_DIR_FORWARD;
1211

    
1212
    /* Get the GOB height based on picture height */
1213
    if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4) {
1214
        if (s->height <= 400)
1215
            s->gob_index = 1;
1216
        else if (s->height <= 800)
1217
            s->gob_index = 2;
1218
        else
1219
            s->gob_index = 4;
1220
    }
1221
        
1222
    s->avg_mb_var = s->avg_mb_var / s->mb_num;        
1223
    
1224
    s->block_wrap[0]=
1225
    s->block_wrap[1]=
1226
    s->block_wrap[2]=
1227
    s->block_wrap[3]= s->mb_width*2 + 2;
1228
    s->block_wrap[4]=
1229
    s->block_wrap[5]= s->mb_width + 2;
1230
    for(mb_y=0; mb_y < s->mb_height; mb_y++) {
1231
        /* Put GOB header based on RTP MTU */
1232
        /* TODO: Put all this stuff in a separate generic function */
1233
        if (s->rtp_mode) {
1234
            if (!mb_y) {
1235
                s->ptr_lastgob = s->pb.buf;
1236
                s->ptr_last_mb_line = s->pb.buf;
1237
            } else if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4 && !(mb_y % s->gob_index)) {
1238
                last_gob = h263_encode_gob_header(s, mb_y);
1239
                if (last_gob) {
1240
                    s->first_gob_line = 1;
1241
                }
1242
            }
1243
        }
1244
        
1245
        s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
1246
        s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
1247
        s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
1248
        s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
1249
        s->block_index[4]= s->block_wrap[4]*(mb_y + 1)                    + s->block_wrap[0]*(s->mb_height*2 + 2);
1250
        s->block_index[5]= s->block_wrap[4]*(mb_y + 1 + s->mb_height + 2) + s->block_wrap[0]*(s->mb_height*2 + 2);
1251
        for(mb_x=0; mb_x < s->mb_width; mb_x++) {
1252

    
1253
            s->mb_x = mb_x;
1254
            s->mb_y = mb_y;
1255
            s->block_index[0]+=2;
1256
            s->block_index[1]+=2;
1257
            s->block_index[2]+=2;
1258
            s->block_index[3]+=2;
1259
            s->block_index[4]++;
1260
            s->block_index[5]++;
1261
#if 0
1262
            /* compute motion vector and macro block type (intra or non intra) */
1263
            motion_x = 0;
1264
            motion_y = 0;
1265
            if (s->pict_type == P_TYPE) {
1266
                s->mb_intra = estimate_motion(s, mb_x, mb_y,
1267
                                              &motion_x,
1268
                                              &motion_y);
1269
            } else {
1270
                s->mb_intra = 1;
1271
            }
1272
#endif
1273

    
1274
            s->mb_intra = s->mb_type[mb_y * s->mb_width + mb_x];
1275
            motion_x = s->mv_table[0][mb_y * s->mb_width + mb_x];
1276
            motion_y = s->mv_table[1][mb_y * s->mb_width + mb_x];
1277
            
1278
            /* get the pixels */
1279
            wrap = s->linesize;
1280
            ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
1281
            get_pixels(s->block[0], ptr, wrap);
1282
            get_pixels(s->block[1], ptr + 8, wrap);
1283
            get_pixels(s->block[2], ptr + 8 * wrap, wrap);
1284
            get_pixels(s->block[3], ptr + 8 * wrap + 8, wrap);
1285
            wrap = s->linesize >> 1;
1286
            ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;
1287
            get_pixels(s->block[4], ptr, wrap);
1288

    
1289
            wrap = s->linesize >> 1;
1290
            ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
1291
            get_pixels(s->block[5], ptr, wrap);
1292

    
1293
            /* subtract previous frame if non intra */
1294
            if (!s->mb_intra) {
1295
                int dxy, offset, mx, my;
1296

    
1297
                dxy = ((motion_y & 1) << 1) | (motion_x & 1);
1298
                ptr = s->last_picture[0] + 
1299
                    ((mb_y * 16 + (motion_y >> 1)) * s->linesize) + 
1300
                    (mb_x * 16 + (motion_x >> 1));
1301

    
1302
                sub_pixels_2(s->block[0], ptr, s->linesize, dxy);
1303
                sub_pixels_2(s->block[1], ptr + 8, s->linesize, dxy);
1304
                sub_pixels_2(s->block[2], ptr + s->linesize * 8, s->linesize, dxy);
1305
                sub_pixels_2(s->block[3], ptr + 8 + s->linesize * 8, s->linesize ,dxy);
1306

    
1307
                if (s->out_format == FMT_H263) {
1308
                    /* special rounding for h263 */
1309
                    dxy = 0;
1310
                    if ((motion_x & 3) != 0)
1311
                        dxy |= 1;
1312
                    if ((motion_y & 3) != 0)
1313
                        dxy |= 2;
1314
                    mx = motion_x >> 2;
1315
                    my = motion_y >> 2;
1316
                } else {
1317
                    mx = motion_x / 2;
1318
                    my = motion_y / 2;
1319
                    dxy = ((my & 1) << 1) | (mx & 1);
1320
                    mx >>= 1;
1321
                    my >>= 1;
1322
                }
1323
                offset = ((mb_y * 8 + my) * (s->linesize >> 1)) + (mb_x * 8 + mx);
1324
                ptr = s->last_picture[1] + offset;
1325
                sub_pixels_2(s->block[4], ptr, s->linesize >> 1, dxy);
1326
                ptr = s->last_picture[2] + offset;
1327
                sub_pixels_2(s->block[5], ptr, s->linesize >> 1, dxy);
1328
            }
1329
            emms_c();
1330
            
1331
#if 0
1332
            {
1333
                float adap_parm;
1334
                
1335
                adap_parm = ((s->avg_mb_var << 1) + s->mb_var[s->mb_width*mb_y+mb_x] + 1.0) /
1336
                            ((s->mb_var[s->mb_width*mb_y+mb_x] << 1) + s->avg_mb_var + 1.0);
1337
            
1338
                printf("\ntype=%c qscale=%2d adap=%0.2f dquant=%4.2f var=%4d avgvar=%4d", 
1339
                        (s->mb_type[s->mb_width*mb_y+mb_x] > 0) ? 'I' : 'P', 
1340
                        s->qscale, adap_parm, s->qscale*adap_parm,
1341
                        s->mb_var[s->mb_width*mb_y+mb_x], s->avg_mb_var);
1342
            }
1343
#endif
1344
            /* DCT & quantize */
1345
            if (s->h263_msmpeg4) {
1346
                msmpeg4_dc_scale(s);
1347
            } else if (s->h263_pred) {
1348
                h263_dc_scale(s);
1349
            } else {
1350
                /* default quantization values */
1351
                s->y_dc_scale = 8;
1352
                s->c_dc_scale = 8;
1353
            }
1354
            for(i=0;i<6;i++) {
1355
                s->block_last_index[i] = dct_quantize(s, s->block[i], i, s->qscale);
1356
            }
1357

    
1358
            /* huffman encode */
1359
            switch(s->out_format) {
1360
            case FMT_MPEG1:
1361
                mpeg1_encode_mb(s, s->block, motion_x, motion_y);
1362
                break;
1363
            case FMT_H263:
1364
                if (s->h263_msmpeg4)
1365
                    msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
1366
                else if(s->h263_pred)
1367
                    mpeg4_encode_mb(s, s->block, motion_x, motion_y);
1368
                else
1369
                    h263_encode_mb(s, s->block, motion_x, motion_y);
1370
                break;
1371
            case FMT_MJPEG:
1372
                mjpeg_encode_mb(s, s->block);
1373
                break;
1374
            }
1375

    
1376
            /* decompress blocks so that we keep the state of the decoder */
1377
            s->mv[0][0][0] = motion_x;
1378
            s->mv[0][0][1] = motion_y;
1379

    
1380
            MPV_decode_mb(s, s->block);
1381
        }
1382

    
1383

    
1384
        /* Obtain average GOB size for RTP */
1385
        if (s->rtp_mode) {
1386
            if (!mb_y)
1387
                s->mb_line_avgsize = pbBufPtr(&s->pb) - s->ptr_last_mb_line;
1388
            else if (!(mb_y % s->gob_index)) {    
1389
                s->mb_line_avgsize = (s->mb_line_avgsize + pbBufPtr(&s->pb) - s->ptr_last_mb_line) >> 1;
1390
                s->ptr_last_mb_line = pbBufPtr(&s->pb);
1391
            }
1392
            //fprintf(stderr, "\nMB line: %d\tSize: %u\tAvg. Size: %u", s->mb_y, 
1393
            //                    (s->pb.buf_ptr - s->ptr_last_mb_line), s->mb_line_avgsize);
1394
            s->first_gob_line = 0;
1395
        }
1396
    }
1397
    
1398
    if (s->h263_msmpeg4 && s->pict_type == I_TYPE)
1399
        msmpeg4_encode_ext_header(s);
1400

    
1401
    //if (s->gob_number)
1402
    //    fprintf(stderr,"\nNumber of GOB: %d", s->gob_number);
1403
    
1404
    /* Send the last GOB if RTP */    
1405
    if (s->rtp_mode) {
1406
        flush_put_bits(&s->pb);
1407
        pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
1408
        /* Call the RTP callback to send the last GOB */
1409
        if (s->rtp_callback)
1410
            s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
1411
        s->ptr_lastgob = pbBufPtr(&s->pb);
1412
        //fprintf(stderr,"\nGOB: %2d size: %d (last)", s->gob_number, pdif);
1413
    }
1414

    
1415
}
1416

    
1417
static int dct_quantize_c(MpegEncContext *s, 
1418
                        DCTELEM *block, int n,
1419
                        int qscale)
1420
{
1421
    int i, j, level, last_non_zero, q;
1422
    const int *qmat;
1423
    int minLevel, maxLevel;
1424

    
1425
    if(s->avctx!=NULL && s->avctx->codec->id==CODEC_ID_MPEG4){
1426
        /* mpeg4 */
1427
        minLevel= -2048;
1428
        maxLevel= 2047;
1429
    }else if(s->out_format==FMT_MPEG1){
1430
        /* mpeg1 */
1431
        minLevel= -255;
1432
        maxLevel= 255;
1433
    }else if(s->out_format==FMT_MJPEG){
1434
        /* (m)jpeg */
1435
        minLevel= -1023;
1436
        maxLevel= 1023;
1437
    }else{
1438
        /* h263 / msmpeg4 */
1439
        minLevel= -128;
1440
        maxLevel= 127;
1441
    }
1442

    
1443
    av_fdct (block);
1444

    
1445
    /* we need this permutation so that we correct the IDCT
1446
       permutation. will be moved into DCT code */
1447
    block_permute(block);
1448

    
1449
    if (s->mb_intra) {
1450
        if (n < 4)
1451
            q = s->y_dc_scale;
1452
        else
1453
            q = s->c_dc_scale;
1454
        q = q << 3;
1455
        
1456
        /* note: block[0] is assumed to be positive */
1457
        block[0] = (block[0] + (q >> 1)) / q;
1458
        i = 1;
1459
        last_non_zero = 0;
1460
        if (s->out_format == FMT_H263) {
1461
            qmat = s->q_non_intra_matrix;
1462
        } else {
1463
            qmat = s->q_intra_matrix;
1464
        }
1465
    } else {
1466
        i = 0;
1467
        last_non_zero = -1;
1468
        qmat = s->q_non_intra_matrix;
1469
    }
1470

    
1471
    for(;i<64;i++) {
1472
        j = zigzag_direct[i];
1473
        level = block[j];
1474
        level = level * qmat[j];
1475
#ifdef PARANOID
1476
        {
1477
            static int count = 0;
1478
            int level1, level2, qmat1;
1479
            double val;
1480
            if (qmat == s->q_non_intra_matrix) {
1481
                qmat1 = default_non_intra_matrix[j] * s->qscale;
1482
            } else {
1483
                qmat1 = default_intra_matrix[j] * s->qscale;
1484
            }
1485
            if (av_fdct != jpeg_fdct_ifast)
1486
                val = ((double)block[j] * 8.0) / (double)qmat1;
1487
            else
1488
                val = ((double)block[j] * 8.0 * 2048.0) / 
1489
                    ((double)qmat1 * aanscales[j]);
1490
            level1 = (int)val;
1491
            level2 = level / (1 << (QMAT_SHIFT - 3));
1492
            if (level1 != level2) {
1493
                fprintf(stderr, "%d: quant error qlevel=%d wanted=%d level=%d qmat1=%d qmat=%d wantedf=%0.6f\n", 
1494
                        count, level2, level1, block[j], qmat1, qmat[j],
1495
                        val);
1496
                count++;
1497
            }
1498

    
1499
        }
1500
#endif
1501
        /* XXX: slight error for the low range. Test should be equivalent to
1502
           (level <= -(1 << (QMAT_SHIFT - 3)) || level >= (1 <<
1503
           (QMAT_SHIFT - 3)))
1504
        */
1505
        if (((level << (31 - (QMAT_SHIFT - 3))) >> (31 - (QMAT_SHIFT - 3))) != 
1506
            level) {
1507
            level = level / (1 << (QMAT_SHIFT - 3));
1508
            /* XXX: currently, this code is not optimal. the range should be:
1509
               mpeg1: -255..255
1510
               mpeg2: -2048..2047
1511
               h263:  -128..127
1512
               mpeg4: -2048..2047
1513
            */
1514
            if (level > maxLevel)
1515
                level = maxLevel;
1516
            else if (level < minLevel)
1517
                level = minLevel;
1518

    
1519
            block[j] = level;
1520
            last_non_zero = i;
1521
        } else {
1522
            block[j] = 0;
1523
        }
1524
    }
1525
    return last_non_zero;
1526
}
1527

    
1528
static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
1529
                                   DCTELEM *block, int n, int qscale)
1530
{
1531
    int i, level, nCoeffs;
1532
    const UINT16 *quant_matrix;
1533

    
1534
    if(s->alternate_scan) nCoeffs= 64;
1535
    else nCoeffs= s->block_last_index[n]+1;
1536
    
1537
    if (s->mb_intra) {
1538
        if (n < 4) 
1539
            block[0] = block[0] * s->y_dc_scale;
1540
        else
1541
            block[0] = block[0] * s->c_dc_scale;
1542
        /* XXX: only mpeg1 */
1543
        quant_matrix = s->intra_matrix;
1544
        for(i=1;i<nCoeffs;i++) {
1545
            int j= zigzag_direct[i];
1546
            level = block[j];
1547
            if (level) {
1548
                if (level < 0) {
1549
                    level = -level;
1550
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
1551
                    level = (level - 1) | 1;
1552
                    level = -level;
1553
                } else {
1554
                    level = (int)(level * qscale * quant_matrix[j]) >> 3;
1555
                    level = (level - 1) | 1;
1556
                }
1557
#ifdef PARANOID
1558
                if (level < -2048 || level > 2047)
1559
                    fprintf(stderr, "unquant error %d %d\n", i, level);
1560
#endif
1561
                block[j] = level;
1562
            }
1563
        }
1564
    } else {
1565
        i = 0;
1566
        quant_matrix = s->non_intra_matrix;
1567
        for(;i<nCoeffs;i++) {
1568
            int j= zigzag_direct[i];
1569
            level = block[j];
1570
            if (level) {
1571
                if (level < 0) {
1572
                    level = -level;
1573
                    level = (((level << 1) + 1) * qscale *
1574
                             ((int) (quant_matrix[j]))) >> 4;
1575
                    level = (level - 1) | 1;
1576
                    level = -level;
1577
                } else {
1578
                    level = (((level << 1) + 1) * qscale *
1579
                             ((int) (quant_matrix[j]))) >> 4;
1580
                    level = (level - 1) | 1;
1581
                }
1582
#ifdef PARANOID
1583
                if (level < -2048 || level > 2047)
1584
                    fprintf(stderr, "unquant error %d %d\n", i, level);
1585
#endif
1586
                block[j] = level;
1587
            }
1588
        }
1589
    }
1590
}
1591

    
1592
static void dct_unquantize_h263_c(MpegEncContext *s, 
1593
                                  DCTELEM *block, int n, int qscale)
1594
{
1595
    int i, level, qmul, qadd;
1596
    int nCoeffs;
1597
    
1598
    if (s->mb_intra) {
1599
        if (!s->h263_aic) {
1600
            if (n < 4) 
1601
                block[0] = block[0] * s->y_dc_scale;
1602
            else
1603
                block[0] = block[0] * s->c_dc_scale;
1604
        }
1605
        i = 1;
1606
        nCoeffs= 64; //does not allways use zigzag table 
1607
    } else {
1608
        i = 0;
1609
        nCoeffs= zigzag_end[ s->block_last_index[n] ];
1610
    }
1611

    
1612
    qmul = s->qscale << 1;
1613
    if (s->h263_aic && s->mb_intra)
1614
        qadd = 0;
1615
    else
1616
        qadd = (s->qscale - 1) | 1;
1617

    
1618
    for(;i<nCoeffs;i++) {
1619
        level = block[i];
1620
        if (level) {
1621
            if (level < 0) {
1622
                level = level * qmul - qadd;
1623
            } else {
1624
                level = level * qmul + qadd;
1625
            }
1626
#ifdef PARANOID
1627
                if (level < -2048 || level > 2047)
1628
                    fprintf(stderr, "unquant error %d %d\n", i, level);
1629
#endif
1630
            block[i] = level;
1631
        }
1632
    }
1633
}
1634

    
1635
/* rate control */
1636

    
1637
/* an I frame is I_FRAME_SIZE_RATIO bigger than a P frame */
1638
#define I_FRAME_SIZE_RATIO 3.0
1639
#define QSCALE_K           20
1640

    
1641
static void rate_control_init(MpegEncContext *s)
1642
{
1643
#if 1
1644
    emms_c();
1645

    
1646
    //initial values, they dont really matter as they will be totally different within a few frames
1647
    s->i_pred.coeff= s->p_pred.coeff= 7.0;
1648
    s->i_pred.count= s->p_pred.count= 1.0;
1649
    
1650
    s->i_pred.decay= s->p_pred.decay= 0.4;
1651
    
1652
    // use more bits at the beginning, otherwise high motion at the begin will look like shit
1653
    s->qsum=100;
1654
    s->qcount=100;
1655

    
1656
    s->short_term_qsum=0.001;
1657
    s->short_term_qcount=0.001;
1658
#else
1659
    s->wanted_bits = 0;
1660

    
1661
    if (s->intra_only) {
1662
        s->I_frame_bits = ((INT64)s->bit_rate * FRAME_RATE_BASE) / s->frame_rate;
1663
        s->P_frame_bits = s->I_frame_bits;
1664
    } else {
1665
        s->P_frame_bits = (int) ((float)(s->gop_size * s->bit_rate) / 
1666
                                 (float)((float)s->frame_rate / FRAME_RATE_BASE * (I_FRAME_SIZE_RATIO + s->gop_size - 1)));
1667
        s->I_frame_bits = (int)(s->P_frame_bits * I_FRAME_SIZE_RATIO);
1668
    }
1669

    
1670
#if defined(DEBUG)
1671
    printf("I_frame_size=%d P_frame_size=%d\n",
1672
           s->I_frame_bits, s->P_frame_bits);
1673
#endif
1674
#endif
1675
}
1676

    
1677
static double predict(Predictor *p, double q, double var)
1678
{
1679
    return p->coeff*var / (q*p->count);
1680
}
1681

    
1682
static void update_predictor(Predictor *p, double q, double var, double size)
1683
{
1684
    double new_coeff= size*q / (var + 1);
1685
    if(var<1000) return;
1686
/*{
1687
int pred= predict(p, q, var);
1688
int error= abs(pred-size);
1689
static double sum=0;
1690
static int count=0;
1691
if(count>5) sum+=error;
1692
count++;
1693
if(256*256*256*64%count==0){
1694
    printf("%d %f %f\n", count, sum/count, p->coeff);
1695
}
1696
}*/
1697
    p->count*= p->decay;
1698
    p->coeff*= p->decay;
1699
    p->count++;
1700
    p->coeff+= new_coeff;
1701
}
1702

    
1703
static int rate_estimate_qscale(MpegEncContext *s)
1704
{
1705
#if 1
1706
    int qmin= s->qmin;
1707
    int qmax= s->qmax;
1708
    int rate_q=5;
1709
    float q;
1710
    int qscale;
1711
    float br_compensation;
1712
    double diff;
1713
    double short_term_q;
1714
    double long_term_q;
1715
    int last_qscale= s->qscale;
1716
    double fps;
1717
    INT64 wanted_bits;
1718
    emms_c();
1719
    
1720
    fps= (double)s->frame_rate / FRAME_RATE_BASE;
1721
    wanted_bits= s->bit_rate*(double)s->picture_number/fps;
1722

    
1723
    
1724
    if(s->picture_number>2){
1725
        /* update predictors */
1726
        if(s->last_pict_type == I_TYPE){
1727
        //FIXME
1728
        }else{ //P Frame
1729
//printf("%d %d %d %f\n", s->qscale, s->last_mc_mb_var, s->frame_bits, s->p_pred.coeff);
1730
            update_predictor(&s->p_pred, s->qscale, s->last_mc_mb_var, s->frame_bits);
1731
        }
1732
    }
1733

    
1734
    if(s->pict_type == I_TYPE){
1735
        //FIXME
1736
        rate_q= s->qsum/s->qcount;
1737
    }else{ //P Frame
1738
        int i;
1739
        int diff, best_diff=1000000000;
1740
        for(i=1; i<=31; i++){
1741
            diff= predict(&s->p_pred, i, s->mc_mb_var) - (double)s->bit_rate/fps;
1742
            if(diff<0) diff= -diff;
1743
            if(diff<best_diff){
1744
                best_diff= diff;
1745
                rate_q= i;
1746
            }
1747
        }
1748
    }
1749

    
1750
    s->short_term_qsum*=s->qblur;
1751
    s->short_term_qcount*=s->qblur;
1752

    
1753
    s->short_term_qsum+= rate_q;
1754
    s->short_term_qcount++;
1755
    short_term_q= s->short_term_qsum/s->short_term_qcount;
1756
    
1757
    long_term_q= s->qsum/s->qcount*s->total_bits/wanted_bits;
1758

    
1759
//    q= (long_term_q - short_term_q)*s->qcompress + short_term_q;
1760
    q= 1/((1/long_term_q - 1/short_term_q)*s->qcompress + 1/short_term_q);
1761

    
1762
    diff= s->total_bits - wanted_bits;
1763
    br_compensation= (s->bit_rate_tolerance - diff)/s->bit_rate_tolerance;
1764
    if(br_compensation<=0.0) br_compensation=0.001;
1765
    q/=br_compensation;
1766

    
1767
    qscale= (int)(q + 0.5);
1768
    if     (qscale<qmin) qscale=qmin;
1769
    else if(qscale>qmax) qscale=qmax;
1770
    
1771
    if     (qscale<last_qscale-s->max_qdiff) qscale=last_qscale-s->max_qdiff;
1772
    else if(qscale>last_qscale+s->max_qdiff) qscale=last_qscale+s->max_qdiff;
1773

    
1774
    s->qsum+= qscale;
1775
    s->qcount++;
1776

    
1777
    s->last_pict_type= s->pict_type;
1778
//printf("q:%d diff:%d comp:%f rate_q:%d st_q:%d fvar:%d last_size:%d\n", qscale, (int)diff, br_compensation, 
1779
//       rate_q, (int)short_term_q, s->mc_mb_var, s->frame_bits);
1780
//printf("%d %d\n", s->bit_rate, (int)fps);
1781
    return qscale;
1782
#else
1783
    INT64 diff, total_bits = s->total_bits;
1784
    float q;
1785
    int qscale;
1786
    if (s->pict_type == I_TYPE) {
1787
        s->wanted_bits += s->I_frame_bits;
1788
    } else {
1789
        s->wanted_bits += s->P_frame_bits;
1790
    }
1791
    diff = s->wanted_bits - total_bits;
1792
    q = 31.0 - (float)diff / (QSCALE_K * s->mb_height * s->mb_width);
1793
    /* adjust for I frame */
1794
    if (s->pict_type == I_TYPE && !s->intra_only) {
1795
        q /= I_FRAME_SIZE_RATIO;
1796
    }
1797

    
1798
    /* using a too small Q scale leeds to problems in mpeg1 and h263
1799
       because AC coefficients are clamped to 255 or 127 */
1800
    qmin = 3;
1801
    if (q < qmin)
1802
        q = qmin;
1803
    else if (q > 31)
1804
        q = 31;
1805
    qscale = (int)(q + 0.5);
1806
#if defined(DEBUG)
1807
    printf("\n%d: total=%0.0f wanted=%0.0f br=%0.1f diff=%d qest=%2.1f\n", 
1808
           s->picture_number, 
1809
           (double)total_bits, 
1810
           (double)s->wanted_bits,
1811
           (float)s->frame_rate / FRAME_RATE_BASE * 
1812
           total_bits / s->picture_number, 
1813
           (int)diff, q);
1814
#endif
1815
    return qscale;
1816
#endif
1817
}
1818

    
1819
AVCodec mpeg1video_encoder = {
1820
    "mpeg1video",
1821
    CODEC_TYPE_VIDEO,
1822
    CODEC_ID_MPEG1VIDEO,
1823
    sizeof(MpegEncContext),
1824
    MPV_encode_init,
1825
    MPV_encode_picture,
1826
    MPV_encode_end,
1827
};
1828

    
1829
AVCodec h263_encoder = {
1830
    "h263",
1831
    CODEC_TYPE_VIDEO,
1832
    CODEC_ID_H263,
1833
    sizeof(MpegEncContext),
1834
    MPV_encode_init,
1835
    MPV_encode_picture,
1836
    MPV_encode_end,
1837
};
1838

    
1839
AVCodec h263p_encoder = {
1840
    "h263p",
1841
    CODEC_TYPE_VIDEO,
1842
    CODEC_ID_H263P,
1843
    sizeof(MpegEncContext),
1844
    MPV_encode_init,
1845
    MPV_encode_picture,
1846
    MPV_encode_end,
1847
};
1848

    
1849
AVCodec rv10_encoder = {
1850
    "rv10",
1851
    CODEC_TYPE_VIDEO,
1852
    CODEC_ID_RV10,
1853
    sizeof(MpegEncContext),
1854
    MPV_encode_init,
1855
    MPV_encode_picture,
1856
    MPV_encode_end,
1857
};
1858

    
1859
AVCodec mjpeg_encoder = {
1860
    "mjpeg",
1861
    CODEC_TYPE_VIDEO,
1862
    CODEC_ID_MJPEG,
1863
    sizeof(MpegEncContext),
1864
    MPV_encode_init,
1865
    MPV_encode_picture,
1866
    MPV_encode_end,
1867
};
1868

    
1869
AVCodec mpeg4_encoder = {
1870
    "mpeg4",
1871
    CODEC_TYPE_VIDEO,
1872
    CODEC_ID_MPEG4,
1873
    sizeof(MpegEncContext),
1874
    MPV_encode_init,
1875
    MPV_encode_picture,
1876
    MPV_encode_end,
1877
};
1878

    
1879
AVCodec msmpeg4_encoder = {
1880
    "msmpeg4",
1881
    CODEC_TYPE_VIDEO,
1882
    CODEC_ID_MSMPEG4,
1883
    sizeof(MpegEncContext),
1884
    MPV_encode_init,
1885
    MPV_encode_picture,
1886
    MPV_encode_end,
1887
};