h263.c 136 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
2
/*
 * H263/MPEG4 backend for ffmpeg encoder and decoder
Fabrice Bellard's avatar
Fabrice Bellard committed
3
 * Copyright (c) 2000,2001 Fabrice Bellard.
4
 * H263+ support.
Fabrice Bellard's avatar
Fabrice Bellard committed
5
6
 * Copyright (c) 2001 Juan J. Sierralta P.
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
7
8
9
10
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
12
 * This library is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Fabrice Bellard's avatar
Fabrice Bellard committed
14
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
16
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
17
18
19
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
 *
21
 * ac prediction encoding & b-frame support by Michael Niedermayer <michaelni@gmx.at>
Fabrice Bellard's avatar
Fabrice Bellard committed
22
 */
23
24
 
//#define DEBUG
Fabrice Bellard's avatar
Fabrice Bellard committed
25
26
27
28
29
30
31
#include "common.h"
#include "dsputil.h"
#include "avcodec.h"
#include "mpegvideo.h"
#include "h263data.h"
#include "mpeg4data.h"

Michael Niedermayer's avatar
Michael Niedermayer committed
32
33
34
//rounded divison & shift
#define RSHIFT(a,b) ((a) > 0 ? ((a) + (1<<((b)-1)))>>(b) : ((a) + (1<<((b)-1))-1)>>(b))

Felix Bünemann's avatar
Felix Bünemann committed
35
36
#define PRINT_MB_TYPE(a) {}
//#define PRINT_MB_TYPE(a) printf(a)
Michael Niedermayer's avatar
Michael Niedermayer committed
37

38
39
40
41
42
43
44
45
46
#define INTRA_MCBPC_VLC_BITS 6
#define INTER_MCBPC_VLC_BITS 6
#define CBPY_VLC_BITS 6
#define MV_VLC_BITS 9
#define DC_VLC_BITS 9
#define SPRITE_TRAJ_VLC_BITS 6
#define MB_TYPE_B_VLC_BITS 4
#define TEX_VLC_BITS 9

Fabrice Bellard's avatar
Fabrice Bellard committed
47
48
static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
			      int n);
49
static void h263_encode_motion(MpegEncContext * s, int val, int fcode);
50
static void h263p_encode_umotion(MpegEncContext * s, int val);
Fabrice Bellard's avatar
Fabrice Bellard committed
51
static void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
52
53
			       int n, int dc, UINT8 *scan_table, 
                               PutBitContext *dc_pb, PutBitContext *ac_pb);
Michael Niedermayer's avatar
Michael Niedermayer committed
54
static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
55
static int h263p_decode_umotion(MpegEncContext * s, int pred);
Fabrice Bellard's avatar
Fabrice Bellard committed
56
57
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
                             int n, int coded);
58
59
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr);
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
Michael Niedermayer's avatar
Michael Niedermayer committed
60
                              int n, int coded, int intra);
61
static int h263_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr);
62
63
static void mpeg4_inv_pred_ac(MpegEncContext * s, INT16 *block, int n,
                              int dir);
64
65
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s);

66
extern UINT32 inverse[256];
Fabrice Bellard's avatar
Fabrice Bellard committed
67

68
static UINT16 mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
69
static UINT8 fcode_tab[MAX_MV*2+1];
70
static UINT8 umv_fcode_tab[MAX_MV*2+1];
71

72
73
74
static UINT16 uni_DCtab_lum  [512][2];
static UINT16 uni_DCtab_chrom[512][2];

Fabrice Bellard's avatar
Fabrice Bellard committed
75
76
77
78
79
int h263_get_picture_format(int width, int height)
{
    int format;

    if (width == 128 && height == 96)
80
        format = 1;
Fabrice Bellard's avatar
Fabrice Bellard committed
81
    else if (width == 176 && height == 144)
82
        format = 2;
Fabrice Bellard's avatar
Fabrice Bellard committed
83
    else if (width == 352 && height == 288)
84
        format = 3;
Fabrice Bellard's avatar
Fabrice Bellard committed
85
    else if (width == 704 && height == 576)
86
        format = 4;
Fabrice Bellard's avatar
Fabrice Bellard committed
87
    else if (width == 1408 && height == 1152)
88
        format = 5;
Fabrice Bellard's avatar
Fabrice Bellard committed
89
90
91
92
93
94
95
    else
        format = 7;
    return format;
}

void h263_encode_picture_header(MpegEncContext * s, int picture_number)
{
96
    int format;
Fabrice Bellard's avatar
Fabrice Bellard committed
97
98

    align_put_bits(&s->pb);
99
100

    /* Update the pointer to last GOB */
101
    s->ptr_lastgob = pbBufPtr(&s->pb);
102
103
104
    s->gob_number = 0;

    put_bits(&s->pb, 22, 0x20); /* PSC */
105
    put_bits(&s->pb, 8, (((INT64)s->picture_number * 30 * FRAME_RATE_BASE) / 
Fabrice Bellard's avatar
Fabrice Bellard committed
106
107
108
109
110
111
112
                         s->frame_rate) & 0xff);

    put_bits(&s->pb, 1, 1);	/* marker */
    put_bits(&s->pb, 1, 0);	/* h263 id */
    put_bits(&s->pb, 1, 0);	/* split screen off */
    put_bits(&s->pb, 1, 0);	/* camera  off */
    put_bits(&s->pb, 1, 0);	/* freeze picture release off */
113
114
    
    format = h263_get_picture_format(s->width, s->height);
Fabrice Bellard's avatar
Fabrice Bellard committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
    if (!s->h263_plus) {
        /* H.263v1 */
        put_bits(&s->pb, 3, format);
        put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
        /* By now UMV IS DISABLED ON H.263v1, since the restrictions
        of H.263v1 UMV implies to check the predicted MV after
        calculation of the current MB to see if we're on the limits */
        put_bits(&s->pb, 1, 0);	/* unrestricted motion vector: off */
        put_bits(&s->pb, 1, 0);	/* SAC: off */
        put_bits(&s->pb, 1, 0);	/* advanced prediction mode: off */
        put_bits(&s->pb, 1, 0);	/* not PB frame */
        put_bits(&s->pb, 5, s->qscale);
        put_bits(&s->pb, 1, 0);	/* Continuous Presence Multipoint mode: off */
    } else {
        /* H.263v2 */
        /* H.263 Plus PTYPE */
        put_bits(&s->pb, 3, 7);
        put_bits(&s->pb,3,1); /* Update Full Extended PTYPE */
133
134
135
136
137
        if (format == 7)
            put_bits(&s->pb,3,6); /* Custom Source Format */
        else
            put_bits(&s->pb, 3, format);
            
Fabrice Bellard's avatar
Fabrice Bellard committed
138
        put_bits(&s->pb,1,0); /* Custom PCF: off */
139
140
        s->umvplus = (s->pict_type == P_TYPE) && s->unrestricted_mv;
        put_bits(&s->pb, 1, s->umvplus); /* Unrestricted Motion Vector */
Fabrice Bellard's avatar
Fabrice Bellard committed
141
142
        put_bits(&s->pb,1,0); /* SAC: off */
        put_bits(&s->pb,1,0); /* Advanced Prediction Mode: off */
143
        put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
Fabrice Bellard's avatar
Fabrice Bellard committed
144
145
146
147
148
149
150
151
152
153
154
155
156
        put_bits(&s->pb,1,0); /* Deblocking Filter: off */
        put_bits(&s->pb,1,0); /* Slice Structured: off */
        put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
        put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
        put_bits(&s->pb,1,0); /* Alternative Inter VLC: off */
        put_bits(&s->pb,1,0); /* Modified Quantization: off */
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
        put_bits(&s->pb,3,0); /* Reserved */
		
        put_bits(&s->pb, 3, s->pict_type == P_TYPE);
		
        put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
        put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
157
158
159
160
161
        if (s->pict_type == I_TYPE)
            s->no_rounding = 0;
        else
            s->no_rounding ^= 1;
        put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
Fabrice Bellard's avatar
Fabrice Bellard committed
162
163
164
165
166
167
        put_bits(&s->pb,2,0); /* Reserved */
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
		
        /* This should be here if PLUSPTYPE */
        put_bits(&s->pb, 1, 0);	/* Continuous Presence Multipoint mode: off */
		
168
169
		if (format == 7) {
            /* Custom Picture Format (CPFMT) */
Fabrice Bellard's avatar
Fabrice Bellard committed
170
		
171
172
173
	    if (s->aspect_ratio_info)
            put_bits(&s->pb,4,s->aspect_ratio_info);
	    else
174
175
176
177
178
179
            put_bits(&s->pb,4,2); /* Aspect ratio: CIF 12:11 (4:3) picture */
            put_bits(&s->pb,9,(s->width >> 2) - 1);
            put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
            put_bits(&s->pb,9,(s->height >> 2));
        }
        
Fabrice Bellard's avatar
Fabrice Bellard committed
180
        /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
181
        if (s->umvplus)
Fabrice Bellard's avatar
Fabrice Bellard committed
182
183
184
185
186
            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
        put_bits(&s->pb, 5, s->qscale);
    }

    put_bits(&s->pb, 1, 0);	/* no PEI */
187
188
189
190
191
192
193
194

    if(s->h263_aic){
         s->y_dc_scale_table= 
         s->c_dc_scale_table= h263_aic_dc_scale_table;
    }else{
        s->y_dc_scale_table=
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
195
196
}

197
198
199
200
201
202
203
int h263_encode_gob_header(MpegEncContext * s, int mb_line)
{
    int pdif=0;
    
    /* Check to see if we need to put a new GBSC */
    /* for RTP packetization                    */
    if (s->rtp_mode) {
204
        pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
205
206
207
        if (pdif >= s->rtp_payload_size) {
            /* Bad luck, packet must be cut before */
            align_put_bits(&s->pb);
208
209
210
            flush_put_bits(&s->pb);
            /* Call the RTP callback to send the last GOB */
            if (s->rtp_callback) {
211
                pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
212
213
                s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
            }
214
            s->ptr_lastgob = pbBufPtr(&s->pb);
215
            put_bits(&s->pb, 17, 1); /* GBSC */
216
            s->gob_number = mb_line / s->gob_index;
217
            put_bits(&s->pb, 5, s->gob_number); /* GN */
218
            put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
219
            put_bits(&s->pb, 5, s->qscale); /* GQUANT */
220
            //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
221
222
223
224
            return pdif;
       } else if (pdif + s->mb_line_avgsize >= s->rtp_payload_size) {
           /* Cut the packet before we can't */
           align_put_bits(&s->pb);
225
226
227
           flush_put_bits(&s->pb);
           /* Call the RTP callback to send the last GOB */
           if (s->rtp_callback) {
228
               pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
229
230
               s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
           }
231
           s->ptr_lastgob = pbBufPtr(&s->pb);
232
           put_bits(&s->pb, 17, 1); /* GBSC */
233
           s->gob_number = mb_line / s->gob_index;
234
           put_bits(&s->pb, 5, s->gob_number); /* GN */
235
           put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
236
           put_bits(&s->pb, 5, s->qscale); /* GQUANT */
237
           //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
238
239
240
241
242
           return pdif;
       }
   }
   return 0;
}
243
244
245
246
247
248
249
250
251

static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6])
{
    int score0=0, score1=0;
    int i, n;

    for(n=0; n<6; n++){
        INT16 *ac_val, *ac_val1;

Michael Niedermayer's avatar
Michael Niedermayer committed
252
        ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
253
254
        ac_val1= ac_val;
        if(dir[n]){
Michael Niedermayer's avatar
Michael Niedermayer committed
255
            ac_val-= s->block_wrap[n]*16;
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
            for(i=1; i<8; i++){
                const int level= block[n][block_permute_op(i   )];
                score0+= ABS(level);
                score1+= ABS(level - ac_val[i+8]);
                ac_val1[i  ]=    block[n][block_permute_op(i<<3)];
                ac_val1[i+8]= level;
            }
        }else{
            ac_val-= 16;
            for(i=1; i<8; i++){
                const int level= block[n][block_permute_op(i<<3)];
                score0+= ABS(level);
                score1+= ABS(level - ac_val[i]);
                ac_val1[i  ]= level;
                ac_val1[i+8]=    block[n][block_permute_op(i   )];
            }
        }
    }

    return score0 > score1 ? 1 : 0;    
}

void mpeg4_encode_mb(MpegEncContext * s,
		    DCTELEM block[6][64],
		    int motion_x, int motion_y)
{
282
    int cbpc, cbpy, i, pred_x, pred_y;
283
    int bits;
284
285
286
287
    PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
    PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=B_TYPE ? &s->tex_pb : &s->pb;
    PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=I_TYPE ? &s->pb2    : &s->pb;
    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
288
    
289
290
291
    //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
    if (!s->mb_intra) {
        /* compute cbp */
292
        int cbp = 0;
293
        for (i = 0; i < 6; i++) {
294
295
            if (s->block_last_index[i] >= 0)
                cbp |= 1 << (5 - i);
296
        }
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315

        if(s->pict_type==B_TYPE){
            static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
            int mb_type=  mb_type_table[s->mv_dir];
            
            if(s->mb_x==0){
                s->last_mv[0][0][0]= 
                s->last_mv[0][0][1]= 
                s->last_mv[1][0][0]= 
                s->last_mv[1][0][1]= 0;
            }

            /* nothing to do if this MB was skiped in the next P Frame */
            if(s->mbskip_table[s->mb_y * s->mb_width + s->mb_x]){
                s->skip_count++;
                s->mv[0][0][0]= 
                s->mv[0][0][1]= 
                s->mv[1][0][0]= 
                s->mv[1][0][1]= 0;
316
                s->mv_dir= MV_DIR_FORWARD; //doesnt matter
317
318
319
320
321
322
                return;
            }

            if ((cbp | motion_x | motion_y | mb_type) ==0) {
                /* direct MB with MV={0,0} */
                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
323
324
325
326
327

                if(interleaved_stats){
                    s->misc_bits++;
                    s->last_bits++;
                }
328
329
330
331
332
333
334
335
336
337
338
                s->skip_count++;
                return;
            }
            put_bits(&s->pb, 1, 0);	/* mb coded modb1=0 */
            put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
            put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we dont need it :)
            if(cbp) put_bits(&s->pb, 6, cbp);
            
            if(cbp && mb_type)
                put_bits(&s->pb, 1, 0); /* no q-scale change */

339
340
341
342
343
            if(interleaved_stats){
                bits= get_bit_count(&s->pb);
                s->misc_bits+= bits - s->last_bits;
                s->last_bits=bits;
            }
Michael Niedermayer's avatar
Michael Niedermayer committed
344

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
            switch(mb_type)
            {
            case 0: /* direct */
                h263_encode_motion(s, motion_x, 1);
                h263_encode_motion(s, motion_y, 1);                
                break;
            case 1: /* bidir */
                h263_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
                h263_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
                h263_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
                h263_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
                s->last_mv[0][0][0]= s->mv[0][0][0];
                s->last_mv[0][0][1]= s->mv[0][0][1];
                s->last_mv[1][0][0]= s->mv[1][0][0];
                s->last_mv[1][0][1]= s->mv[1][0][1];
                break;
            case 2: /* backward */
                h263_encode_motion(s, motion_x - s->last_mv[1][0][0], s->b_code);
                h263_encode_motion(s, motion_y - s->last_mv[1][0][1], s->b_code);
                s->last_mv[1][0][0]= motion_x;
                s->last_mv[1][0][1]= motion_y;
                break;
            case 3: /* forward */
                h263_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);
                h263_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);
                s->last_mv[0][0][0]= motion_x;
                s->last_mv[0][0][1]= motion_y;
                break;
373
374
            default:
                printf("unknown mb type\n");
375
376
                return;
            }
377
378
379
380
381
382

            if(interleaved_stats){
                bits= get_bit_count(&s->pb);
                s->mv_bits+= bits - s->last_bits;
                s->last_bits=bits;
            }
383

384
385
            /* encode each block */
            for (i = 0; i < 6; i++) {
386
387
388
389
390
391
392
                mpeg4_encode_block(s, block[i], i, 0, zigzag_direct, NULL, &s->pb);
            }

            if(interleaved_stats){
                bits= get_bit_count(&s->pb);
                s->p_tex_bits+= bits - s->last_bits;
                s->last_bits=bits;
393
394
395
            }
        }else{ /* s->pict_type==B_TYPE */
            if ((cbp | motion_x | motion_y) == 0 && s->mv_type==MV_TYPE_16X16) {
Michael Niedermayer's avatar
Michael Niedermayer committed
396
397
398
399
                /* check if the B frames can skip it too, as we must skip it if we skip here 
                   why didnt they just compress the skip-mb bits instead of reusing them ?! */
                if(s->max_b_frames>0){
                    int i;
400
401
402
403
404
405
406
407
408
409
410
                    int x,y, offset;
                    uint8_t *p_pic;

                    x= s->mb_x*16;
                    y= s->mb_y*16;
                    if(x+16 > s->width)  x= s->width-16;
                    if(y+16 > s->height) y= s->height-16;

                    offset= x + y*s->linesize;
                    p_pic= s->new_picture[0] + offset;
                    
Michael Niedermayer's avatar
Michael Niedermayer committed
411
412
                    s->mb_skiped=1;
                    for(i=0; i<s->max_b_frames; i++){
Michael Niedermayer's avatar
Michael Niedermayer committed
413
414
415
416
417
418
419
                        uint8_t *b_pic;
                        int diff;

                        if(s->coded_order[i+1].pict_type!=B_TYPE) break;

                        b_pic= s->coded_order[i+1].picture[0] + offset;
                        diff= pix_abs16x16(p_pic, b_pic, s->linesize);
420
                        if(diff>s->qscale*70){ //FIXME check that 70 is optimal
Michael Niedermayer's avatar
Michael Niedermayer committed
421
422
423
424
425
426
427
428
429
430
                            s->mb_skiped=0;
                            break;
                        }
                    }
                }else
                    s->mb_skiped=1; 

                if(s->mb_skiped==1){
                    /* skip macroblock */
                    put_bits(&s->pb, 1, 1);
431
432
433
434
435

                    if(interleaved_stats){
                        s->misc_bits++;
                        s->last_bits++;
                    }
Michael Niedermayer's avatar
Michael Niedermayer committed
436
437
438
                    s->skip_count++;
                    return;
                }
439
            }
440

441
442
443
444
445
446
447
448
            put_bits(&s->pb, 1, 0);	/* mb coded */
            if(s->mv_type==MV_TYPE_16X16){
                cbpc = cbp & 3;
                put_bits(&s->pb,
                        inter_MCBPC_bits[cbpc],
                        inter_MCBPC_code[cbpc]);
                cbpy = cbp >> 2;
                cbpy ^= 0xf;
449
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
450
                    
451
452
453
454
455
                if(interleaved_stats){
                    bits= get_bit_count(&s->pb);
                    s->misc_bits+= bits - s->last_bits;
                    s->last_bits=bits;
                }
456

457
458
459
460
461
462
463
464
465
466
467
468
                /* motion vectors: 16x16 mode */
                h263_pred_motion(s, 0, &pred_x, &pred_y);
            
                h263_encode_motion(s, motion_x - pred_x, s->f_code);
                h263_encode_motion(s, motion_y - pred_y, s->f_code);
            }else{
                cbpc = (cbp & 3)+16;
                put_bits(&s->pb,
                        inter_MCBPC_bits[cbpc],
                        inter_MCBPC_code[cbpc]);
                cbpy = cbp >> 2;
                cbpy ^= 0xf;
469
                put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
470

471
472
473
474
475
                if(interleaved_stats){
                    bits= get_bit_count(&s->pb);
                    s->misc_bits+= bits - s->last_bits;
                    s->last_bits=bits;
                }
476
477
478
479
480
481
482
483

                for(i=0; i<4; i++){
                    /* motion vectors: 8x8 mode*/
                    h263_pred_motion(s, i, &pred_x, &pred_y);

                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x, s->f_code);
                    h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y, s->f_code);
                }
Michael Niedermayer's avatar
Michael Niedermayer committed
484
            }
485
486
487
488
489
490

            if(interleaved_stats){ 
                bits= get_bit_count(&s->pb);
                s->mv_bits+= bits - s->last_bits;
                s->last_bits=bits;
            }
491

492
493
            /* encode each block */
            for (i = 0; i < 6; i++) {
494
495
496
497
498
499
500
                mpeg4_encode_block(s, block[i], i, 0, zigzag_direct, NULL, tex_pb);
            }

            if(interleaved_stats){
                bits= get_bit_count(&s->pb);
                s->p_tex_bits+= bits - s->last_bits;
                s->last_bits=bits;
501
502
            }
            s->p_count++;
503
504
        }
    } else {
505
        int cbp;
506
507
508
509
510
511
512
513
514
        int dc_diff[6];   //dc values with the dc prediction subtracted 
        int dir[6];  //prediction direction
        int zigzag_last_index[6];
        UINT8 *scan_table[6];

        for(i=0; i<6; i++){
            const int level= block[i][0];
            UINT16 *dc_ptr;

515
            dc_diff[i]= level - ff_mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
            if (i < 4) {
                *dc_ptr = level * s->y_dc_scale;
            } else {
                *dc_ptr = level * s->c_dc_scale;
            }
        }

        s->ac_pred= decide_ac_pred(s, block, dir);

        if(s->ac_pred){
            for(i=0; i<6; i++){
                UINT8 *st;
                int last_index;

                mpeg4_inv_pred_ac(s, block[i], i, dir[i]);
                if (dir[i]==0) st = ff_alternate_vertical_scan; /* left */
                else           st = ff_alternate_horizontal_scan; /* top */

                for(last_index=63; last_index>=0; last_index--) //FIXME optimize
                    if(block[i][st[last_index]]) break;
                zigzag_last_index[i]= s->block_last_index[i];
                s->block_last_index[i]= last_index;
                scan_table[i]= st;
            }
        }else{
            for(i=0; i<6; i++)
                scan_table[i]= zigzag_direct;
        }

        /* compute cbp */
        cbp = 0;
        for (i = 0; i < 6; i++) {
            if (s->block_last_index[i] >= 1)
                cbp |= 1 << (5 - i);
        }

        cbpc = cbp & 3;
        if (s->pict_type == I_TYPE) {
            put_bits(&s->pb,
                intra_MCBPC_bits[cbpc],
                intra_MCBPC_code[cbpc]);
        } else {
            put_bits(&s->pb, 1, 0);	/* mb coded */
            put_bits(&s->pb,
                inter_MCBPC_bits[cbpc + 4],
                inter_MCBPC_code[cbpc + 4]);
        }
563
        put_bits(pb2, 1, s->ac_pred);
564
        cbpy = cbp >> 2;
565
        put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
566

567
568
569
570
571
        if(interleaved_stats){
            bits= get_bit_count(&s->pb);
            s->misc_bits+= bits - s->last_bits;
            s->last_bits=bits;
        }
572

573
574
        /* encode each block */
        for (i = 0; i < 6; i++) {
575
            mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
576
577
        }

578
579
580
581
582
        if(interleaved_stats){
            bits= get_bit_count(&s->pb);
            s->i_tex_bits+= bits - s->last_bits;
            s->last_bits=bits;
        }
583
584
        s->i_count++;

585
586
587
588
589
590
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
        if(s->ac_pred){
            for(i=0; i<6; i++){
                int j;    
                INT16 *ac_val;

Michael Niedermayer's avatar
Michael Niedermayer committed
591
                ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
592
593
594
595
596
597
598
599
600
601
602
603
604
605

                if(dir[i]){
                    for(j=1; j<8; j++) 
                        block[i][block_permute_op(j   )]= ac_val[j+8];
                }else{
                    for(j=1; j<8; j++) 
                        block[i][block_permute_op(j<<3)]= ac_val[j  ];
                }
                s->block_last_index[i]= zigzag_last_index[i];
            }
        }
    }
}

Fabrice Bellard's avatar
Fabrice Bellard committed
606
607
608
609
610
void h263_encode_mb(MpegEncContext * s,
		    DCTELEM block[6][64],
		    int motion_x, int motion_y)
{
    int cbpc, cbpy, i, cbp, pred_x, pred_y;
611
612
613
614
615
    INT16 pred_dc;
    INT16 rec_intradc[6];
    UINT16 *dc_ptr[6];
           
    //printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
616
    if (!s->mb_intra) {
617
        /* compute cbp */
618
619
620
621
622
623
624
625
626
627
        cbp = 0;
        for (i = 0; i < 6; i++) {
            if (s->block_last_index[i] >= 0)
                cbp |= 1 << (5 - i);
        }
        if ((cbp | motion_x | motion_y) == 0) {
            /* skip macroblock */
            put_bits(&s->pb, 1, 1);
            return;
        }
628
        put_bits(&s->pb, 1, 0);	/* mb coded */
629
630
        cbpc = cbp & 3;
        put_bits(&s->pb,
631
632
		    inter_MCBPC_bits[cbpc],
		    inter_MCBPC_code[cbpc]);
633
634
635
636
        cbpy = cbp >> 2;
        cbpy ^= 0xf;
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);

637
        /* motion vectors: 16x16 mode only now */
638
        h263_pred_motion(s, 0, &pred_x, &pred_y);
639
      
640
641
642
643
644
645
646
647
        if (!s->umvplus) {  
            h263_encode_motion(s, motion_x - pred_x, s->f_code);
            h263_encode_motion(s, motion_y - pred_y, s->f_code);
        }
        else {
            h263p_encode_umotion(s, motion_x - pred_x);
            h263p_encode_umotion(s, motion_y - pred_y);
            if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
648
                /* To prevent Start Code emulation */
649
650
                put_bits(&s->pb,1,1);
        }
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
    } else {
        int li = s->h263_aic ? 0 : 1;
        
        cbp = 0;
        for(i=0; i<6; i++) {
            /* Predict DC */
            if (s->h263_aic && s->mb_intra) {
                INT16 level = block[i][0];
            
                pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
                level -= pred_dc;
                /* Quant */
                if (level < 0)
                    level = (level + (s->qscale >> 1))/(s->y_dc_scale);
                else
                    level = (level - (s->qscale >> 1))/(s->y_dc_scale);
                    
                /* AIC can change CBP */
                if (level == 0 && s->block_last_index[i] == 0)
                    s->block_last_index[i] = -1;
                else if (level < -127)
                    level = -127;
                else if (level > 127)
                    level = 127;
                
                block[i][0] = level;
                /* Reconstruction */ 
                rec_intradc[i] = (s->y_dc_scale*level) + pred_dc;
                /* Oddify */
                rec_intradc[i] |= 1;
                //if ((rec_intradc[i] % 2) == 0)
                //    rec_intradc[i]++;
                /* Clipping */
                if (rec_intradc[i] < 0)
                    rec_intradc[i] = 0;
                else if (rec_intradc[i] > 2047)
                    rec_intradc[i] = 2047;
                                
                /* Update AC/DC tables */
                *dc_ptr[i] = rec_intradc[i];
            }
            /* compute cbp */
            if (s->block_last_index[i] >= li)
                cbp |= 1 << (5 - i);
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
696

697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
        cbpc = cbp & 3;
        if (s->pict_type == I_TYPE) {
            put_bits(&s->pb,
                intra_MCBPC_bits[cbpc],
                intra_MCBPC_code[cbpc]);
        } else {
            put_bits(&s->pb, 1, 0);	/* mb coded */
            put_bits(&s->pb,
                inter_MCBPC_bits[cbpc + 4],
                inter_MCBPC_code[cbpc + 4]);
        }
        if (s->h263_aic) {
            /* XXX: currently, we do not try to use ac prediction */
            put_bits(&s->pb, 1, 0);	/* no AC prediction */
        }
        cbpy = cbp >> 2;
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
Fabrice Bellard's avatar
Fabrice Bellard committed
714
715
    }

716
717
    for(i=0; i<6; i++) {
        /* encode each block */
718
        h263_encode_block(s, block[i], i);
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
    
        /* Update INTRADC for decoding */
        if (s->h263_aic && s->mb_intra) {
            block[i][0] = rec_intradc[i];
            
        }
    }
}

static int h263_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr)
{
    int x, y, wrap, a, c, pred_dc, scale;
    INT16 *dc_val, *ac_val;

    /* find prediction */
    if (n < 4) {
        x = 2 * s->mb_x + 1 + (n & 1);
        y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
        wrap = s->mb_width * 2 + 2;
        dc_val = s->dc_val[0];
        ac_val = s->ac_val[0][0];
        scale = s->y_dc_scale;
    } else {
        x = s->mb_x + 1;
        y = s->mb_y + 1;
        wrap = s->mb_width + 2;
        dc_val = s->dc_val[n - 4 + 1];
        ac_val = s->ac_val[n - 4 + 1][0];
        scale = s->c_dc_scale;
Fabrice Bellard's avatar
Fabrice Bellard committed
748
    }
749
750
751
752
753
754
755
    /* B C
     * A X 
     */
    a = dc_val[(x - 1) + (y) * wrap];
    c = dc_val[(x) + (y - 1) * wrap];
    
    /* No prediction outside GOB boundary */
756
    if (s->first_slice_line && ((n < 2) || (n > 3)))
757
758
759
760
761
762
763
764
765
766
767
768
769
770
        c = 1024;
    pred_dc = 1024;
    /* just DC prediction */
    if (a != 1024 && c != 1024)
        pred_dc = (a + c) >> 1;
    else if (a != 1024)
        pred_dc = a;
    else
        pred_dc = c;
    
    /* we assume pred is positive */
    //pred_dc = (pred_dc + (scale >> 1)) / scale;
    *dc_val_ptr = &dc_val[x + y * wrap];
    return pred_dc;
Fabrice Bellard's avatar
Fabrice Bellard committed
771
772
}

773

774
void h263_pred_acdc(MpegEncContext * s, INT16 *block, int n)
775
{
776
777
    int x, y, wrap, a, c, pred_dc, scale, i;
    INT16 *dc_val, *ac_val, *ac_val1;
778
779
780
781
782
783
784

    /* find prediction */
    if (n < 4) {
        x = 2 * s->mb_x + 1 + (n & 1);
        y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
        wrap = s->mb_width * 2 + 2;
        dc_val = s->dc_val[0];
785
        ac_val = s->ac_val[0][0];
786
787
788
789
790
791
        scale = s->y_dc_scale;
    } else {
        x = s->mb_x + 1;
        y = s->mb_y + 1;
        wrap = s->mb_width + 2;
        dc_val = s->dc_val[n - 4 + 1];
792
        ac_val = s->ac_val[n - 4 + 1][0];
793
794
        scale = s->c_dc_scale;
    }
795
796
797
798
    
    ac_val += ((y) * wrap + (x)) * 16;
    ac_val1 = ac_val;
    
799
800
801
802
803
804
    /* B C
     * A X 
     */
    a = dc_val[(x - 1) + (y) * wrap];
    c = dc_val[(x) + (y - 1) * wrap];
    
805
    /* No prediction outside GOB boundary */
806
    if (s->first_slice_line && ((n < 2) || (n > 3)))
807
        c = 1024;
808
    pred_dc = 1024;
809
810
811
    if (s->ac_pred) {
        if (s->h263_aic_dir) {
            /* left prediction */
812
813
814
815
816
817
            if (a != 1024) {
                ac_val -= 16;
                for(i=1;i<8;i++) {
                    block[block_permute_op(i*8)] += ac_val[i];
                }
                pred_dc = a;
818
819
820
            }
        } else {
            /* top prediction */
821
822
823
824
825
826
            if (c != 1024) {
                ac_val -= 16 * wrap;
                for(i=1;i<8;i++) {
                    block[block_permute_op(i)] += ac_val[i + 8];
                }
                pred_dc = c;
827
828
            }
        }
829
830
831
832
833
834
835
836
    } else {
        /* just DC prediction */
        if (a != 1024 && c != 1024)
            pred_dc = (a + c) >> 1;
        else if (a != 1024)
            pred_dc = a;
        else
            pred_dc = c;
837
    }
838
839
840
841
842
843
844
845
846
847
848
849
    
    /* we assume pred is positive */
    block[0]=block[0]*scale + pred_dc;
    
    if (block[0] < 0)
        block[0] = 0;
    else if (!(block[0] & 1))
        block[0]++;
    
    /* Update AC/DC tables */
    dc_val[(x) + (y) * wrap] = block[0];
    
850
851
852
853
854
855
856
857
    /* left copy */
    for(i=1;i<8;i++)
        ac_val1[i] = block[block_permute_op(i * 8)];
    /* top copy */
    for(i=1;i<8;i++)
        ac_val1[8 + i] = block[block_permute_op(i)];
}

Fabrice Bellard's avatar
Fabrice Bellard committed
858
859
860
INT16 *h263_pred_motion(MpegEncContext * s, int block, 
                        int *px, int *py)
{
Michael Niedermayer's avatar
Michael Niedermayer committed
861
    int xy, wrap;
Fabrice Bellard's avatar
Fabrice Bellard committed
862
    INT16 *A, *B, *C, *mot_val;
863
    static const int off[4]= {2, 1, 1, -1};
Fabrice Bellard's avatar
Fabrice Bellard committed
864

Michael Niedermayer's avatar
Michael Niedermayer committed
865
866
    wrap = s->block_wrap[0];
    xy = s->block_index[block];
Fabrice Bellard's avatar
Fabrice Bellard committed
867

Zdenek Kabelac's avatar
Zdenek Kabelac committed
868
    mot_val = s->motion_val[xy];
Fabrice Bellard's avatar
Fabrice Bellard committed
869

870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
    A = s->motion_val[xy - 1];
    /* special case for first (slice) line */
    if ((s->mb_y == 0 || s->first_slice_line) && block<3) {
        // we cant just change some MVs to simulate that as we need them for the B frames (and ME)
        // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
        if(block==0){ //most common case
            if(s->mb_x  == s->resync_mb_x){ //rare
                *px= *py = 0;
            }else if(s->mb_x + 1 == s->resync_mb_x){ //rare
                C = s->motion_val[xy + off[block] - wrap];
                if(s->mb_x==0){
                    *px = C[0];
                    *py = C[1];
                }else{
                    *px = mid_pred(A[0], 0, C[0]);
                    *py = mid_pred(A[1], 0, C[1]);
                }
            }else{
                *px = A[0];
                *py = A[1];
            }
        }else if(block==1){
            if(s->mb_x + 1 == s->resync_mb_x){ //rare
                C = s->motion_val[xy + off[block] - wrap];
                *px = mid_pred(A[0], 0, C[0]);
                *py = mid_pred(A[1], 0, C[1]);
            }else{
                *px = A[0];
                *py = A[1];
            }
        }else{ /* block==2*/
            B = s->motion_val[xy - wrap];
            C = s->motion_val[xy + off[block] - wrap];
            if(s->mb_x == s->resync_mb_x) //rare
                A[0]=A[1]=0;
    
            *px = mid_pred(A[0], B[0], C[0]);
            *py = mid_pred(A[1], B[1], C[1]);
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
909
    } else {
910
911
        B = s->motion_val[xy - wrap];
        C = s->motion_val[xy + off[block] - wrap];
Fabrice Bellard's avatar
Fabrice Bellard committed
912
913
914
915
916
917
        *px = mid_pred(A[0], B[0], C[0]);
        *py = mid_pred(A[1], B[1], C[1]);
    }
    return mot_val;
}

918
static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
Fabrice Bellard's avatar
Fabrice Bellard committed
919
920
921
922
923
924
925
926
{
    int range, l, m, bit_size, sign, code, bits;

    if (val == 0) {
        /* zero vector */
        code = 0;
        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
    } else {
927
        bit_size = f_code - 1;
Fabrice Bellard's avatar
Fabrice Bellard committed
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
        range = 1 << bit_size;
        /* modulo encoding */
        l = range * 32;
        m = 2 * l;
        if (val < -l) {
            val += m;
        } else if (val >= l) {
            val -= m;
        }

        if (val >= 0) {
            sign = 0;
        } else {
            val = -val;
            sign = 1;
        }
944
945
946
        val--;
        code = (val >> bit_size) + 1;
        bits = val & (range - 1);
Fabrice Bellard's avatar
Fabrice Bellard committed
947
948
949
950
951
952
953
954

        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
        if (bit_size > 0) {
            put_bits(&s->pb, bit_size, bits);
        }
    }
}

955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
/* Encode MV differences on H.263+ with Unrestricted MV mode */
static void h263p_encode_umotion(MpegEncContext * s, int val)
{
    short sval = 0; 
    short i = 0;
    short n_bits = 0;
    short temp_val;
    int code = 0;
    int tcode;
    
    if ( val == 0)
        put_bits(&s->pb, 1, 1);
    else if (val == 1)
        put_bits(&s->pb, 3, 0);
    else if (val == -1)
        put_bits(&s->pb, 3, 2);
    else {
        
        sval = ((val < 0) ? (short)(-val):(short)val);
        temp_val = sval;
        
        while (temp_val != 0) {
            temp_val = temp_val >> 1;
            n_bits++;
        }
        
        i = n_bits - 1;
        while (i > 0) {
            tcode = (sval & (1 << (i-1))) >> (i-1);
            tcode = (tcode << 1) | 1;
            code = (code << 2) | tcode;
            i--;
        }
        code = ((code << 1) | (val < 0)) << 1;
        put_bits(&s->pb, (2*n_bits)+1, code);
        //printf("\nVal = %d\tCode = %d", sval, code);
    }
}

994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
static void init_mv_penalty_and_fcode(MpegEncContext *s)
{
    int f_code;
    int mv;
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
            int len;

            if(mv==0) len= mvtab[0][1];
            else{
                int val, bit_size, range, code;

                bit_size = s->f_code - 1;
                range = 1 << bit_size;

                val=mv;
                if (val < 0) 
                    val = -val;
                val--;
                code = (val >> bit_size) + 1;
                if(code<33){
                    len= mvtab[code][1] + 1 + bit_size;
                }else{
                    len= mvtab[32][1] + 2 + bit_size;
                }
            }

            mv_penalty[f_code][mv+MAX_MV]= len;
        }
    }

    for(f_code=MAX_FCODE; f_code>0; f_code--){
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
            fcode_tab[mv+MAX_MV]= f_code;
        }
    }
1030
1031
1032
1033

    for(mv=0; mv<MAX_MV*2+1; mv++){
        umv_fcode_tab[mv]= 1;
    }
1034
1035
}

Falk Hüffner's avatar
Falk Hüffner committed
1036
static void init_uni_dc_tab(void)
1037
1038
1039
{
    int level, uni_code, uni_len;

1040
    for(level=-256; level<256; level++){
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
        int size, v, l;
        /* find number of bits */
        size = 0;
        v = abs(level);
        while (v) {
            v >>= 1;
	    size++;
        }

        if (level < 0)
            l= (-level) ^ ((1 << size) - 1);
        else
            l= level;

        /* luminance */
        uni_code= DCtab_lum[size][0];
        uni_len = DCtab_lum[size][1];

        if (size > 0) {
            uni_code<<=size; uni_code|=l;
            uni_len+=size;
            if (size > 8){
                uni_code<<=1; uni_code|=1;
                uni_len++;
            }
        }
        uni_DCtab_lum[level+256][0]= uni_code;
        uni_DCtab_lum[level+256][1]= uni_len;

        /* chrominance */
        uni_code= DCtab_chrom[size][0];
        uni_len = DCtab_chrom[size][1];
        
        if (size > 0) {
            uni_code<<=size; uni_code|=l;
            uni_len+=size;
            if (size > 8){
                uni_code<<=1; uni_code|=1;
                uni_len++;
            }
        }
        uni_DCtab_chrom[level+256][0]= uni_code;
        uni_DCtab_chrom[level+256][1]= uni_len;

    }
}

1088
void h263_encode_init(MpegEncContext *s)
Fabrice Bellard's avatar
Fabrice Bellard committed
1089
1090
1091
1092
1093
{
    static int done = 0;

    if (!done) {
        done = 1;
1094
1095
1096

        init_uni_dc_tab();

Fabrice Bellard's avatar
Fabrice Bellard committed
1097
1098
        init_rl(&rl_inter);
        init_rl(&rl_intra);
1099
        init_rl(&rl_intra_aic);
1100
1101

        init_mv_penalty_and_fcode(s);
Fabrice Bellard's avatar
Fabrice Bellard committed
1102
    }
1103
    s->mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
1104
    
1105
    // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
    switch(s->codec_id){
    case CODEC_ID_MPEG4:
        s->fcode_tab= fcode_tab;
        s->min_qcoeff= -2048;
        s->max_qcoeff=  2047;
        break;
    case CODEC_ID_H263P:
        s->fcode_tab= umv_fcode_tab;
        s->min_qcoeff= -128;
        s->max_qcoeff=  127;
        break;
1117
        //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later 
1118
1119
1120
    default: //nothing needed default table allready set in mpegvideo.c
        s->min_qcoeff= -128;
        s->max_qcoeff=  127;
1121
1122
        s->y_dc_scale_table=
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1123
1124
1125
1126
1127
1128
    }

    /* h263 type bias */
    //FIXME mpeg4 mpeg quantizer    
    s->intra_quant_bias=0;
    s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
Fabrice Bellard's avatar
Fabrice Bellard committed
1129
1130
1131
1132
}

static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
{
1133
1134
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
    RLTable *rl;
Fabrice Bellard's avatar
Fabrice Bellard committed
1135

1136
1137
    rl = &rl_inter;
    if (s->mb_intra && !s->h263_aic) {
1138
1139
        /* DC coef */
	    level = block[0];
Fabrice Bellard's avatar
Fabrice Bellard committed
1140
1141
1142
1143
1144
        /* 255 cannot be represented, so we clamp */
        if (level > 254) {
            level = 254;
            block[0] = 254;
        }
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
        /* 0 cannot be represented also */
        else if (!level) {
            level = 1;
            block[0] = 1;
        }
	    if (level == 128)
	        put_bits(&s->pb, 8, 0xff);
	    else
	        put_bits(&s->pb, 8, level & 0xff);
	    i = 1;
Fabrice Bellard's avatar
Fabrice Bellard committed
1155
    } else {
1156
	    i = 0;
1157
1158
	    if (s->h263_aic && s->mb_intra)
	        rl = &rl_intra_aic;
Fabrice Bellard's avatar
Fabrice Bellard committed
1159
    }
1160
   
Fabrice Bellard's avatar
Fabrice Bellard committed
1161
1162
1163
1164
    /* AC coefs */
    last_index = s->block_last_index[n];
    last_non_zero = i - 1;
    for (; i <= last_index; i++) {
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
        j = zigzag_direct[i];
        level = block[j];
        if (level) {
            run = i - last_non_zero - 1;
            last = (i == last_index);
            sign = 0;
            slevel = level;
            if (level < 0) {
                sign = 1;
                level = -level;
            }
Fabrice Bellard's avatar
Fabrice Bellard committed
1176
1177
1178
1179
1180
1181
1182
1183
1184
            code = get_rl_index(rl, last, run, level);
            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
            if (code == rl->n) {
                put_bits(&s->pb, 1, last);
                put_bits(&s->pb, 6, run);
                put_bits(&s->pb, 8, slevel & 0xff);
            } else {
                put_bits(&s->pb, 1, sign);
            }
1185
1186
	        last_non_zero = i;
	    }
Fabrice Bellard's avatar
Fabrice Bellard committed
1187
1188
1189
1190
1191
    }
}

/***************************************************/

1192
void ff_mpeg4_stuffing(PutBitContext * pbc)
Michael Niedermayer's avatar
Michael Niedermayer committed
1193
1194
1195
1196
{
    int length;
    put_bits(pbc, 1, 0);
    length= (-get_bit_count(pbc))&7;
1197
    if(length) put_bits(pbc, length, (1<<length)-1);
Michael Niedermayer's avatar
Michael Niedermayer committed
1198
1199
}

1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
/* must be called before writing the header */
void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
    int time_div, time_mod;

    if(s->pict_type==I_TYPE){ //we will encode a vol header
        s->time_increment_resolution= s->frame_rate/ff_gcd(s->frame_rate, FRAME_RATE_BASE);
        if(s->time_increment_resolution>=256*256) s->time_increment_resolution= 256*128;

        s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
    }

Fabrice Bellard's avatar
Fabrice Bellard committed
1211
    s->time= picture_number*(INT64)FRAME_RATE_BASE*s->time_increment_resolution/s->frame_rate;
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
    time_div= s->time/s->time_increment_resolution;
    time_mod= s->time%s->time_increment_resolution;

    if(s->pict_type==B_TYPE){
        s->bp_time= s->last_non_b_time - s->time;
    }else{
        s->last_time_base= s->time_base;
        s->time_base= time_div;
        s->pp_time= s->time - s->last_non_b_time;
        s->last_non_b_time= s->time;
    }
}

1225
static void mpeg4_encode_vol_header(MpegEncContext * s)
Fabrice Bellard's avatar
Fabrice Bellard committed
1226
{
1227
    int vo_ver_id=1; //must be 2 if we want GMC or q-pel
1228
    char buf[255];
Michael Niedermayer's avatar
Michael Niedermayer committed
1229
1230
1231

    s->vo_type= s->has_b_frames ? CORE_VO_TYPE : SIMPLE_VO_TYPE;

1232
1233
1234
1235
1236
1237
    put_bits(&s->pb, 16, 0);
    put_bits(&s->pb, 16, 0x100);        /* video obj */
    put_bits(&s->pb, 16, 0);
    put_bits(&s->pb, 16, 0x120);        /* video obj layer */

    put_bits(&s->pb, 1, 0);		/* random access vol */
Michael Niedermayer's avatar
Michael Niedermayer committed
1238
    put_bits(&s->pb, 8, s->vo_type);	/* video obj type indication */
1239
1240
1241
    put_bits(&s->pb, 1, 1);		/* is obj layer id= yes */
      put_bits(&s->pb, 4, vo_ver_id);	/* is obj layer ver id */
      put_bits(&s->pb, 3, 1);		/* is obj layer priority */
1242
1243
1244
1245
    if(s->aspect_ratio_info) 
        put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
    else
        put_bits(&s->pb, 4, 1);		/* aspect ratio info= sqare pixel */
Michael Niedermayer's avatar
Michael Niedermayer committed
1246
1247
1248

    if(s->low_delay){
        put_bits(&s->pb, 1, 1);		/* vol control parameters= yes */
Michael Niedermayer's avatar
Michael Niedermayer committed
1249
        put_bits(&s->pb, 2, 1);		/* chroma format YUV 420/YV12 */
Michael Niedermayer's avatar
Michael Niedermayer committed
1250
1251
1252
1253
1254
1255
        put_bits(&s->pb, 1, s->low_delay);
        put_bits(&s->pb, 1, 0);		/* vbv parameters= no */
    }else{
        put_bits(&s->pb, 1, 0);		/* vol control parameters= no */
    }

1256
1257
    put_bits(&s->pb, 2, RECT_SHAPE);	/* vol shape= rectangle */
    put_bits(&s->pb, 1, 1);		/* marker bit */
1258
1259
    
    put_bits(&s->pb, 16, s->time_increment_resolution);
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
    if (s->time_increment_bits < 1)
        s->time_increment_bits = 1;
    put_bits(&s->pb, 1, 1);		/* marker bit */
    put_bits(&s->pb, 1, 0);		/* fixed vop rate=no */
    put_bits(&s->pb, 1, 1);		/* marker bit */
    put_bits(&s->pb, 13, s->width);	/* vol width */
    put_bits(&s->pb, 1, 1);		/* marker bit */
    put_bits(&s->pb, 13, s->height);	/* vol height */
    put_bits(&s->pb, 1, 1);		/* marker bit */
    put_bits(&s->pb, 1, 0);		/* interlace */
    put_bits(&s->pb, 1, 1);		/* obmc disable */
    if (vo_ver_id == 1) {
        put_bits(&s->pb, 1, s->vol_sprite_usage=0);		/* sprite enable */
    }else{ /* vo_ver_id == 2 */
        put_bits(&s->pb, 2, s->vol_sprite_usage=0);		/* sprite enable */
    }
    put_bits(&s->pb, 1, 0);		/* not 8 bit */
    put_bits(&s->pb, 1, 0);		/* quant type= h263 style*/
    if (vo_ver_id != 1)
        put_bits(&s->pb, 1, s->quarter_sample=0);
    put_bits(&s->pb, 1, 1);		/* complexity estimation disable */
1281
1282
1283
1284
1285
1286
1287
    s->resync_marker= s->rtp_mode;
    put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
    if(s->data_partitioning){
        put_bits(&s->pb, 1, 0);		/* no rvlc */
    }

1288
1289
1290
1291
1292
1293
    if (vo_ver_id != 1){
        put_bits(&s->pb, 1, 0);		/* newpred */
        put_bits(&s->pb, 1, 0);		/* reduced res vop */
    }
    put_bits(&s->pb, 1, 0);		/* scalability */

1294
    ff_mpeg4_stuffing(&s->pb);
Michael Niedermayer's avatar
Michael Niedermayer committed
1295
1296