Statistics
| Branch: | Revision:

ffmpeg / libavcodec / h263.c @ 098eefe1

History | View | Annotate | Download (80.9 KB)

1
/*
2
 * H263/MPEG4 backend for ffmpeg encoder and decoder
3
 * Copyright (c) 2000,2001 Gerard Lantau.
4
 * H263+ support.
5
 * Copyright (c) 2001 Juan J. Sierralta P.
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 2 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
 *
21
 * ac prediction encoding by Michael Niedermayer <michaelni@gmx.at>
22
 */
23
#include "common.h"
24
#include "dsputil.h"
25
#include "avcodec.h"
26
#include "mpegvideo.h"
27
#include "h263data.h"
28
#include "mpeg4data.h"
29

    
30
//rounded divison & shift
31
#define RDIV(a,b) ((a) > 0 ? ((a)+((b)>>1))/(b) : ((a)-((b)>>1))/(b))
32
#define RSHIFT(a,b) ((a) > 0 ? ((a) + (1<<((b)-1)))>>(b) : ((a) + (1<<((b)-1))-1)>>(b))
33
#define ABS(a) (((a)>=0)?(a):(-(a)))
34

    
35
static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
36
                              int n);
37
static void h263_encode_motion(MpegEncContext * s, int val);
38
static void h263p_encode_umotion(MpegEncContext * s, int val);
39
static void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
40
                               int n, int dc, UINT8 *scan_table);
41
static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
42
static int h263p_decode_umotion(MpegEncContext * s, int pred);
43
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
44
                             int n, int coded);
45
static int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
46
                              int n, int coded);
47
static inline int mpeg4_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr, int *dir_ptr);
48
static void mpeg4_inv_pred_ac(MpegEncContext * s, INT16 *block, int n,
49
                              int dir);
50
extern UINT32 inverse[256];
51

    
52
static UINT16 mv_penalty[MAX_FCODE][MAX_MV*2+1];
53
static UINT8 fcode_tab[MAX_MV*2+1];
54

    
55
int h263_get_picture_format(int width, int height)
56
{
57
    int format;
58

    
59
    if (width == 128 && height == 96)
60
        format = 1;
61
    else if (width == 176 && height == 144)
62
        format = 2;
63
    else if (width == 352 && height == 288)
64
        format = 3;
65
    else if (width == 704 && height == 576)
66
        format = 4;
67
    else if (width == 1408 && height == 1152)
68
        format = 5;
69
    else
70
        format = 7;
71
    return format;
72
}
73

    
74
void h263_encode_picture_header(MpegEncContext * s, int picture_number)
75
{
76
    int format;
77

    
78
    align_put_bits(&s->pb);
79

    
80
    /* Update the pointer to last GOB */
81
    s->ptr_lastgob = pbBufPtr(&s->pb);
82
    s->gob_number = 0;
83

    
84
    put_bits(&s->pb, 22, 0x20); /* PSC */
85
    put_bits(&s->pb, 8, (((INT64)s->picture_number * 30 * FRAME_RATE_BASE) / 
86
                         s->frame_rate) & 0xff);
87

    
88
    put_bits(&s->pb, 1, 1);        /* marker */
89
    put_bits(&s->pb, 1, 0);        /* h263 id */
90
    put_bits(&s->pb, 1, 0);        /* split screen off */
91
    put_bits(&s->pb, 1, 0);        /* camera  off */
92
    put_bits(&s->pb, 1, 0);        /* freeze picture release off */
93
    
94
    format = h263_get_picture_format(s->width, s->height);
95
    if (!s->h263_plus) {
96
        /* H.263v1 */
97
        put_bits(&s->pb, 3, format);
98
        put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
99
        /* By now UMV IS DISABLED ON H.263v1, since the restrictions
100
        of H.263v1 UMV implies to check the predicted MV after
101
        calculation of the current MB to see if we're on the limits */
102
        put_bits(&s->pb, 1, 0);        /* unrestricted motion vector: off */
103
        put_bits(&s->pb, 1, 0);        /* SAC: off */
104
        put_bits(&s->pb, 1, 0);        /* advanced prediction mode: off */
105
        put_bits(&s->pb, 1, 0);        /* not PB frame */
106
        put_bits(&s->pb, 5, s->qscale);
107
        put_bits(&s->pb, 1, 0);        /* Continuous Presence Multipoint mode: off */
108
    } else {
109
        /* H.263v2 */
110
        /* H.263 Plus PTYPE */
111
        put_bits(&s->pb, 3, 7);
112
        put_bits(&s->pb,3,1); /* Update Full Extended PTYPE */
113
        if (format == 7)
114
            put_bits(&s->pb,3,6); /* Custom Source Format */
115
        else
116
            put_bits(&s->pb, 3, format);
117
            
118
        put_bits(&s->pb,1,0); /* Custom PCF: off */
119
        s->umvplus = (s->pict_type == P_TYPE) && s->unrestricted_mv;
120
        put_bits(&s->pb, 1, s->umvplus); /* Unrestricted Motion Vector */
121
        put_bits(&s->pb,1,0); /* SAC: off */
122
        put_bits(&s->pb,1,0); /* Advanced Prediction Mode: off */
123
        put_bits(&s->pb,1,0); /* Advanced Intra Coding: off */
124
        put_bits(&s->pb,1,0); /* Deblocking Filter: off */
125
        put_bits(&s->pb,1,0); /* Slice Structured: off */
126
        put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
127
        put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
128
        put_bits(&s->pb,1,0); /* Alternative Inter VLC: off */
129
        put_bits(&s->pb,1,0); /* Modified Quantization: off */
130
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
131
        put_bits(&s->pb,3,0); /* Reserved */
132
                
133
        put_bits(&s->pb, 3, s->pict_type == P_TYPE);
134
                
135
        put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
136
        put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
137
        put_bits(&s->pb,1,0); /* Rounding Type */
138
        put_bits(&s->pb,2,0); /* Reserved */
139
        put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
140
                
141
        /* This should be here if PLUSPTYPE */
142
        put_bits(&s->pb, 1, 0);        /* Continuous Presence Multipoint mode: off */
143
                
144
                if (format == 7) {
145
            /* Custom Picture Format (CPFMT) */
146
                
147
            put_bits(&s->pb,4,2); /* Aspect ratio: CIF 12:11 (4:3) picture */
148
            put_bits(&s->pb,9,(s->width >> 2) - 1);
149
            put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
150
            put_bits(&s->pb,9,(s->height >> 2));
151
        }
152
        
153
        /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
154
        if (s->umvplus)
155
            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
156
        put_bits(&s->pb, 5, s->qscale);
157
    }
158

    
159
    put_bits(&s->pb, 1, 0);        /* no PEI */
160
}
161

    
162
int h263_encode_gob_header(MpegEncContext * s, int mb_line)
163
{
164
    int pdif=0;
165
    
166
    /* Check to see if we need to put a new GBSC */
167
    /* for RTP packetization                    */
168
    if (s->rtp_mode) {
169
        pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
170
        if (pdif >= s->rtp_payload_size) {
171
            /* Bad luck, packet must be cut before */
172
            align_put_bits(&s->pb);
173
            flush_put_bits(&s->pb);
174
            /* Call the RTP callback to send the last GOB */
175
            if (s->rtp_callback) {
176
                pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
177
                s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
178
            }
179
            s->ptr_lastgob = pbBufPtr(&s->pb);
180
            put_bits(&s->pb, 17, 1); /* GBSC */
181
            s->gob_number = mb_line / s->gob_index;
182
            put_bits(&s->pb, 5, s->gob_number); /* GN */
183
            put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
184
            put_bits(&s->pb, 5, s->qscale); /* GQUANT */
185
            //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
186
            return pdif;
187
       } else if (pdif + s->mb_line_avgsize >= s->rtp_payload_size) {
188
           /* Cut the packet before we can't */
189
           align_put_bits(&s->pb);
190
           flush_put_bits(&s->pb);
191
           /* Call the RTP callback to send the last GOB */
192
           if (s->rtp_callback) {
193
               pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
194
               s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
195
           }
196
           s->ptr_lastgob = pbBufPtr(&s->pb);
197
           put_bits(&s->pb, 17, 1); /* GBSC */
198
           s->gob_number = mb_line / s->gob_index;
199
           put_bits(&s->pb, 5, s->gob_number); /* GN */
200
           put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
201
           put_bits(&s->pb, 5, s->qscale); /* GQUANT */
202
           //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
203
           return pdif;
204
       }
205
   }
206
   return 0;
207
}
208

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

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

    
217
        ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
218
        ac_val1= ac_val;
219
        if(dir[n]){
220
            ac_val-= s->block_wrap[n]*16;
221
            for(i=1; i<8; i++){
222
                const int level= block[n][block_permute_op(i   )];
223
                score0+= ABS(level);
224
                score1+= ABS(level - ac_val[i+8]);
225
                ac_val1[i  ]=    block[n][block_permute_op(i<<3)];
226
                ac_val1[i+8]= level;
227
            }
228
        }else{
229
            ac_val-= 16;
230
            for(i=1; i<8; i++){
231
                const int level= block[n][block_permute_op(i<<3)];
232
                score0+= ABS(level);
233
                score1+= ABS(level - ac_val[i]);
234
                ac_val1[i  ]= level;
235
                ac_val1[i+8]=    block[n][block_permute_op(i   )];
236
            }
237
        }
238
    }
239

    
240
    return score0 > score1 ? 1 : 0;    
241
}
242

    
243
void mpeg4_encode_mb(MpegEncContext * s,
244
                    DCTELEM block[6][64],
245
                    int motion_x, int motion_y)
246
{
247
    int cbpc, cbpy, i, cbp, pred_x, pred_y;
248
    int bits;
249
    
250
    //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
251
    if (!s->mb_intra) {
252
        /* compute cbp */
253
        cbp = 0;
254
        for (i = 0; i < 6; i++) {
255
        if (s->block_last_index[i] >= 0)
256
            cbp |= 1 << (5 - i);
257
        }
258
        if ((cbp | motion_x | motion_y) == 0) {
259
            /* skip macroblock */
260
            put_bits(&s->pb, 1, 1);
261
            s->misc_bits++;
262
            s->last_bits++;
263
            s->skip_count++;
264
            return;
265
        }
266
        put_bits(&s->pb, 1, 0);        /* mb coded */
267
        cbpc = cbp & 3;
268
        put_bits(&s->pb,
269
                inter_MCBPC_bits[cbpc],
270
                inter_MCBPC_code[cbpc]);
271
        cbpy = cbp >> 2;
272
        cbpy ^= 0xf;
273
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
274
            
275
        bits= get_bit_count(&s->pb);
276
        s->misc_bits+= bits - s->last_bits;
277
        s->last_bits=bits;
278

    
279
        /* motion vectors: 16x16 mode only now */
280
        h263_pred_motion(s, 0, &pred_x, &pred_y);
281
      
282
        h263_encode_motion(s, motion_x - pred_x);
283
        h263_encode_motion(s, motion_y - pred_y);
284

    
285
        bits= get_bit_count(&s->pb);
286
        s->mv_bits+= bits - s->last_bits;
287
        s->last_bits=bits;
288

    
289
        /* encode each block */
290
        for (i = 0; i < 6; i++) {
291
            mpeg4_encode_block(s, block[i], i, 0, zigzag_direct);
292
        }
293
        bits= get_bit_count(&s->pb);
294
        s->p_tex_bits+= bits - s->last_bits;
295
        s->last_bits=bits;
296
        s->p_count++;
297
    } else {
298
        int dc_diff[6];   //dc values with the dc prediction subtracted 
299
        int dir[6];  //prediction direction
300
        int zigzag_last_index[6];
301
        UINT8 *scan_table[6];
302

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

    
307
            dc_diff[i]= level - mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
308
            if (i < 4) {
309
                *dc_ptr = level * s->y_dc_scale;
310
            } else {
311
                *dc_ptr = level * s->c_dc_scale;
312
            }
313
        }
314

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

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

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

    
326
                for(last_index=63; last_index>=0; last_index--) //FIXME optimize
327
                    if(block[i][st[last_index]]) break;
328
                zigzag_last_index[i]= s->block_last_index[i];
329
                s->block_last_index[i]= last_index;
330
                scan_table[i]= st;
331
            }
332
        }else{
333
            for(i=0; i<6; i++)
334
                scan_table[i]= zigzag_direct;
335
        }
336

    
337
        /* compute cbp */
338
        cbp = 0;
339
        for (i = 0; i < 6; i++) {
340
            if (s->block_last_index[i] >= 1)
341
                cbp |= 1 << (5 - i);
342
        }
343

    
344
        cbpc = cbp & 3;
345
        if (s->pict_type == I_TYPE) {
346
            put_bits(&s->pb,
347
                intra_MCBPC_bits[cbpc],
348
                intra_MCBPC_code[cbpc]);
349
        } else {
350
            put_bits(&s->pb, 1, 0);        /* mb coded */
351
            put_bits(&s->pb,
352
                inter_MCBPC_bits[cbpc + 4],
353
                inter_MCBPC_code[cbpc + 4]);
354
        }
355
        put_bits(&s->pb, 1, s->ac_pred);
356
        cbpy = cbp >> 2;
357
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
358

    
359
        bits= get_bit_count(&s->pb);
360
        s->misc_bits+= bits - s->last_bits;
361
        s->last_bits=bits;
362

    
363
        /* encode each block */
364
        for (i = 0; i < 6; i++) {
365
            mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i]);
366
        }
367

    
368
        bits= get_bit_count(&s->pb);
369
        s->i_tex_bits+= bits - s->last_bits;
370
        s->last_bits=bits;
371
        s->i_count++;
372

    
373
        /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
374
        if(s->ac_pred){
375
            for(i=0; i<6; i++){
376
                int j;    
377
                INT16 *ac_val;
378

    
379
                ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
380

    
381
                if(dir[i]){
382
                    for(j=1; j<8; j++) 
383
                        block[i][block_permute_op(j   )]= ac_val[j+8];
384
                }else{
385
                    for(j=1; j<8; j++) 
386
                        block[i][block_permute_op(j<<3)]= ac_val[j  ];
387
                }
388
                s->block_last_index[i]= zigzag_last_index[i];
389
            }
390
        }
391
    }
392
}
393

    
394
void h263_encode_mb(MpegEncContext * s,
395
                    DCTELEM block[6][64],
396
                    int motion_x, int motion_y)
397
{
398
    int cbpc, cbpy, i, cbp, pred_x, pred_y;
399
   
400
    //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
401
   if (!s->mb_intra) {
402
           /* compute cbp */
403
           cbp = 0;
404
           for (i = 0; i < 6; i++) {
405
              if (s->block_last_index[i] >= 0)
406
                   cbp |= 1 << (5 - i);
407
           }
408
           if ((cbp | motion_x | motion_y) == 0) {
409
              /* skip macroblock */
410
              put_bits(&s->pb, 1, 1);
411
              return;
412
           }
413
           put_bits(&s->pb, 1, 0);        /* mb coded */
414
           cbpc = cbp & 3;
415
           put_bits(&s->pb,
416
                inter_MCBPC_bits[cbpc],
417
                inter_MCBPC_code[cbpc]);
418
           cbpy = cbp >> 2;
419
           cbpy ^= 0xf;
420
           put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
421

    
422
           /* motion vectors: 16x16 mode only now */
423
      h263_pred_motion(s, 0, &pred_x, &pred_y);
424
      
425
      if (!s->umvplus) {  
426
         h263_encode_motion(s, motion_x - pred_x);
427
         h263_encode_motion(s, motion_y - pred_y);
428
      }
429
      else {
430
         h263p_encode_umotion(s, motion_x - pred_x);
431
         h263p_encode_umotion(s, motion_y - pred_y);
432
         if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
433
            /* To prevent Start Code emulation */
434
            put_bits(&s->pb,1,1);
435
      }
436
   } else {
437
        /* compute cbp */
438
        cbp = 0;
439
        for (i = 0; i < 6; i++) {
440
            if (s->block_last_index[i] >= 1)
441
                cbp |= 1 << (5 - i);
442
        }
443

    
444
        cbpc = cbp & 3;
445
        if (s->pict_type == I_TYPE) {
446
            put_bits(&s->pb,
447
                     intra_MCBPC_bits[cbpc],
448
                     intra_MCBPC_code[cbpc]);
449
        } else {
450
            put_bits(&s->pb, 1, 0);        /* mb coded */
451
            put_bits(&s->pb,
452
                     inter_MCBPC_bits[cbpc + 4],
453
                     inter_MCBPC_code[cbpc + 4]);
454
        }
455
        if (s->h263_pred) {
456
            /* XXX: currently, we do not try to use ac prediction */
457
            put_bits(&s->pb, 1, 0);        /* no ac prediction */
458
        }
459
        cbpy = cbp >> 2;
460
        put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
461
    }
462

    
463
    /* encode each block */
464
    if (s->h263_pred) {
465
        for (i = 0; i < 6; i++) {
466
//            mpeg4_encode_block(s, block[i], i);
467
        }
468
    } else {
469
        for (i = 0; i < 6; i++) {
470
            h263_encode_block(s, block[i], i);
471
        }
472
    }
473
}
474

    
475
void h263_pred_acdc(MpegEncContext * s, INT16 *block, int n)
476
{
477
    int x, y, wrap, a, c, pred_dc, scale, i;
478
    INT16 *dc_val, *ac_val, *ac_val1;
479

    
480
    /* find prediction */
481
    if (n < 4) {
482
        x = 2 * s->mb_x + 1 + (n & 1);
483
        y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
484
        wrap = s->mb_width * 2 + 2;
485
        dc_val = s->dc_val[0];
486
        ac_val = s->ac_val[0][0];
487
        scale = s->y_dc_scale;
488
    } else {
489
        x = s->mb_x + 1;
490
        y = s->mb_y + 1;
491
        wrap = s->mb_width + 2;
492
        dc_val = s->dc_val[n - 4 + 1];
493
        ac_val = s->ac_val[n - 4 + 1][0];
494
        scale = s->c_dc_scale;
495
    }
496
    
497
    ac_val += ((y) * wrap + (x)) * 16;
498
    ac_val1 = ac_val;
499
    
500
    /* B C
501
     * A X 
502
     */
503
    a = dc_val[(x - 1) + (y) * wrap];
504
    c = dc_val[(x) + (y - 1) * wrap];
505
    
506
    pred_dc = 1024;
507
    if (s->ac_pred) {
508
        if (s->h263_aic_dir) {
509
            /* left prediction */
510
            if (a != 1024) {
511
                ac_val -= 16;
512
                for(i=1;i<8;i++) {
513
                    block[block_permute_op(i*8)] += ac_val[i];
514
                }
515
                pred_dc = a;
516
            }
517
        } else {
518
            /* top prediction */
519
            if (c != 1024) {
520
                ac_val -= 16 * wrap;
521
                for(i=1;i<8;i++) {
522
                    block[block_permute_op(i)] += ac_val[i + 8];
523
                }
524
                pred_dc = c;
525
            }
526
        }
527
    } else {
528
        /* just DC prediction */
529
        if (a != 1024 && c != 1024)
530
            pred_dc = (a + c) >> 1;
531
        else if (a != 1024)
532
            pred_dc = a;
533
        else
534
            pred_dc = c;
535
    }
536
    
537
    /* we assume pred is positive */
538
    block[0]=block[0]*scale + pred_dc;
539
    
540
    if (block[0] < 0)
541
        block[0] = 0;
542
    else if (!(block[0] & 1))
543
        block[0]++;
544
    
545
    /* Update AC/DC tables */
546
    dc_val[(x) + (y) * wrap] = block[0];
547
    
548
    /* left copy */
549
    for(i=1;i<8;i++)
550
        ac_val1[i] = block[block_permute_op(i * 8)];
551
    /* top copy */
552
    for(i=1;i<8;i++)
553
        ac_val1[8 + i] = block[block_permute_op(i)];
554
}
555

    
556
INT16 *h263_pred_motion(MpegEncContext * s, int block, 
557
                        int *px, int *py)
558
{
559
    int xy, wrap;
560
    INT16 *A, *B, *C, *mot_val;
561
    static const int off[4]= {2, 1, 1, -1};
562

    
563
    wrap = s->block_wrap[0];
564
    xy = s->block_index[block];
565

    
566
    mot_val = s->motion_val[xy];
567

    
568
    /* special case for first line */
569
    if ((s->mb_y == 0 || s->first_slice_line || s->first_gob_line) && block<2) {
570
        A = s->motion_val[xy - 1];
571
        *px = A[0];
572
        *py = A[1];
573
    } else {
574
        A = s->motion_val[xy - 1];
575
        B = s->motion_val[xy - wrap];
576
        C = s->motion_val[xy + off[block] - wrap];
577
        *px = mid_pred(A[0], B[0], C[0]);
578
        *py = mid_pred(A[1], B[1], C[1]);
579
    }
580
    return mot_val;
581
}
582

    
583
static void h263_encode_motion(MpegEncContext * s, int val)
584
{
585
    int range, l, m, bit_size, sign, code, bits;
586

    
587
    if (val == 0) {
588
        /* zero vector */
589
        code = 0;
590
        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
591
    } else {
592
        bit_size = s->f_code - 1;
593
        range = 1 << bit_size;
594
        /* modulo encoding */
595
        l = range * 32;
596
        m = 2 * l;
597
        if (val < -l) {
598
            val += m;
599
        } else if (val >= l) {
600
            val -= m;
601
        }
602

    
603
        if (val >= 0) {
604
            val--;
605
            code = (val >> bit_size) + 1;
606
            bits = val & (range - 1);
607
            sign = 0;
608
        } else {
609
            val = -val;
610
            val--;
611
            code = (val >> bit_size) + 1;
612
            bits = val & (range - 1);
613
            sign = 1;
614
        }
615

    
616
        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
617
        if (bit_size > 0) {
618
            put_bits(&s->pb, bit_size, bits);
619
        }
620
    }
621
}
622

    
623
/* Encode MV differences on H.263+ with Unrestricted MV mode */
624
static void h263p_encode_umotion(MpegEncContext * s, int val)
625
{
626
    short sval = 0; 
627
    short i = 0;
628
    short n_bits = 0;
629
    short temp_val;
630
    int code = 0;
631
    int tcode;
632
    
633
    if ( val == 0)
634
        put_bits(&s->pb, 1, 1);
635
    else if (val == 1)
636
        put_bits(&s->pb, 3, 0);
637
    else if (val == -1)
638
        put_bits(&s->pb, 3, 2);
639
    else {
640
        
641
        sval = ((val < 0) ? (short)(-val):(short)val);
642
        temp_val = sval;
643
        
644
        while (temp_val != 0) {
645
            temp_val = temp_val >> 1;
646
            n_bits++;
647
        }
648
        
649
        i = n_bits - 1;
650
        while (i > 0) {
651
            tcode = (sval & (1 << (i-1))) >> (i-1);
652
            tcode = (tcode << 1) | 1;
653
            code = (code << 2) | tcode;
654
            i--;
655
        }
656
        code = ((code << 1) | (val < 0)) << 1;
657
        put_bits(&s->pb, (2*n_bits)+1, code);
658
        //printf("\nVal = %d\tCode = %d", sval, code);
659
    }
660
}
661

    
662
static void init_mv_penalty_and_fcode(MpegEncContext *s)
663
{
664
    int f_code;
665
    int mv;
666
    for(f_code=1; f_code<=MAX_FCODE; f_code++){
667
        for(mv=-MAX_MV; mv<=MAX_MV; mv++){
668
            int len;
669

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

    
674
                bit_size = s->f_code - 1;
675
                range = 1 << bit_size;
676

    
677
                val=mv;
678
                if (val < 0) 
679
                    val = -val;
680
                val--;
681
                code = (val >> bit_size) + 1;
682
                if(code<33){
683
                    len= mvtab[code][1] + 1 + bit_size;
684
                }else{
685
                    len= mvtab[32][1] + 2 + bit_size;
686
                }
687
            }
688

    
689
            mv_penalty[f_code][mv+MAX_MV]= len;
690
        }
691
    }
692
    
693

    
694
    for(f_code=MAX_FCODE; f_code>0; f_code--){
695
        for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
696
            fcode_tab[mv+MAX_MV]= f_code;
697
        }
698
    }
699
}
700

    
701
void h263_encode_init(MpegEncContext *s)
702
{
703
    static int done = 0;
704

    
705
    if (!done) {
706
        done = 1;
707
        init_rl(&rl_inter);
708
        init_rl(&rl_intra);
709

    
710
        init_mv_penalty_and_fcode(s);
711
    }
712
    s->mv_penalty= mv_penalty;
713
    
714
    // use fcodes >1 only for mpeg4&h263 FIXME
715
    if(!s->h263_msmpeg4) s->fcode_tab= fcode_tab;
716
}
717

    
718
static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
719
{
720
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel;
721
    int code;
722
    RLTable *rl = &rl_inter;
723

    
724
    if (s->mb_intra) {
725
        /* DC coef */
726
            level = block[0];
727
        /* 255 cannot be represented, so we clamp */
728
        if (level > 254) {
729
            level = 254;
730
            block[0] = 254;
731
        }
732
        /* 0 cannot be represented also */
733
        else if (!level) {
734
            level = 1;
735
            block[0] = 1;
736
        }
737
            if (level == 128)
738
                put_bits(&s->pb, 8, 0xff);
739
            else
740
                put_bits(&s->pb, 8, level & 0xff);
741
            i = 1;
742
    } else {
743
            i = 0;
744
    }
745

    
746
    /* AC coefs */
747
    last_index = s->block_last_index[n];
748
    last_non_zero = i - 1;
749
    for (; i <= last_index; i++) {
750
        j = zigzag_direct[i];
751
        level = block[j];
752
        if (level) {
753
            run = i - last_non_zero - 1;
754
            last = (i == last_index);
755
            sign = 0;
756
            slevel = level;
757
            if (level < 0) {
758
                sign = 1;
759
                level = -level;
760
            }
761
            code = get_rl_index(rl, last, run, level);
762
            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
763
            if (code == rl->n) {
764
                put_bits(&s->pb, 1, last);
765
                put_bits(&s->pb, 6, run);
766
                put_bits(&s->pb, 8, slevel & 0xff);
767
            } else {
768
                put_bits(&s->pb, 1, sign);
769
            }
770
            last_non_zero = i;
771
        }
772
    }
773
}
774

    
775
/***************************************************/
776

    
777
static void mpeg4_stuffing(PutBitContext * pbc)
778
{
779
    int length;
780
    put_bits(pbc, 1, 0);
781
    length= (-get_bit_count(pbc))&7;
782
    put_bits(pbc, length, (1<<length)-1);
783
}
784

    
785
static void put_string(PutBitContext * pbc, char *s)
786
{
787
    while(*s){
788
        put_bits(pbc, 8, *s);
789
        s++;
790
    }
791
    put_bits(pbc, 8, 0);
792
}
793

    
794
static void mpeg4_encode_vol_header(MpegEncContext * s)
795
{
796
    int vo_ver_id=1; //must be 2 if we want GMC or q-pel
797

    
798
    if(get_bit_count(&s->pb)!=0) mpeg4_stuffing(&s->pb);
799
    put_bits(&s->pb, 16, 0);
800
    put_bits(&s->pb, 16, 0x100);        /* video obj */
801
    put_bits(&s->pb, 16, 0);
802
    put_bits(&s->pb, 16, 0x120);        /* video obj layer */
803

    
804
    put_bits(&s->pb, 1, 0);                /* random access vol */
805
    put_bits(&s->pb, 8, 1);                /* video obj type indication= simple obj */
806
    put_bits(&s->pb, 1, 1);                /* is obj layer id= yes */
807
      put_bits(&s->pb, 4, vo_ver_id);        /* is obj layer ver id */
808
      put_bits(&s->pb, 3, 1);                /* is obj layer priority */
809
    if(s->aspect_ratio_info) 
810
        put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
811
    else
812
        put_bits(&s->pb, 4, 1);                /* aspect ratio info= sqare pixel */
813
    put_bits(&s->pb, 1, 0);                /* vol control parameters= no */
814
    put_bits(&s->pb, 2, RECT_SHAPE);        /* vol shape= rectangle */
815
    put_bits(&s->pb, 1, 1);                /* marker bit */
816
    put_bits(&s->pb, 16, s->time_increment_resolution=30000);
817
    s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
818
    if (s->time_increment_bits < 1)
819
        s->time_increment_bits = 1;
820
    put_bits(&s->pb, 1, 1);                /* marker bit */
821
    put_bits(&s->pb, 1, 0);                /* fixed vop rate=no */
822
    put_bits(&s->pb, 1, 1);                /* marker bit */
823
    put_bits(&s->pb, 13, s->width);        /* vol width */
824
    put_bits(&s->pb, 1, 1);                /* marker bit */
825
    put_bits(&s->pb, 13, s->height);        /* vol height */
826
    put_bits(&s->pb, 1, 1);                /* marker bit */
827
    put_bits(&s->pb, 1, 0);                /* interlace */
828
    put_bits(&s->pb, 1, 1);                /* obmc disable */
829
    if (vo_ver_id == 1) {
830
        put_bits(&s->pb, 1, s->vol_sprite_usage=0);                /* sprite enable */
831
    }else{ /* vo_ver_id == 2 */
832
        put_bits(&s->pb, 2, s->vol_sprite_usage=0);                /* sprite enable */
833
    }
834
    put_bits(&s->pb, 1, 0);                /* not 8 bit */
835
    put_bits(&s->pb, 1, 0);                /* quant type= h263 style*/
836
    if (vo_ver_id != 1)
837
        put_bits(&s->pb, 1, s->quarter_sample=0);
838
    put_bits(&s->pb, 1, 1);                /* complexity estimation disable */
839
    put_bits(&s->pb, 1, 1);                /* resync marker disable */
840
    put_bits(&s->pb, 1, 0);                /* data partitioned */
841
    if (vo_ver_id != 1){
842
        put_bits(&s->pb, 1, 0);                /* newpred */
843
        put_bits(&s->pb, 1, 0);                /* reduced res vop */
844
    }
845
    put_bits(&s->pb, 1, 0);                /* scalability */
846

    
847
    mpeg4_stuffing(&s->pb);
848
    put_bits(&s->pb, 16, 0);
849
    put_bits(&s->pb, 16, 0x1B2);        /* user_data */
850
    put_string(&s->pb, "ffmpeg"); //FIXME append some version ...
851

    
852
    s->no_rounding = 0;
853
}
854

    
855
/* write mpeg4 VOP header */
856
void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
857
{
858
    if(s->pict_type==I_TYPE) mpeg4_encode_vol_header(s);
859

    
860
    if(get_bit_count(&s->pb)!=0) mpeg4_stuffing(&s->pb);
861
    put_bits(&s->pb, 16, 0);                /* vop header */
862
    put_bits(&s->pb, 16, 0x1B6);        /* vop header */
863
    put_bits(&s->pb, 2, s->pict_type - 1);        /* pict type: I = 0 , P = 1 */
864
    /* XXX: time base + 1 not always correct */
865
    put_bits(&s->pb, 1, 1);
866
    put_bits(&s->pb, 1, 0);
867

    
868
    put_bits(&s->pb, 1, 1);        /* marker */
869
    put_bits(&s->pb, s->time_increment_bits, 1);        /* XXX: correct time increment */
870
    put_bits(&s->pb, 1, 1);        /* marker */
871
    put_bits(&s->pb, 1, 1);        /* vop coded */
872
    if (    s->pict_type == P_TYPE 
873
        || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
874
        s->no_rounding ^= 1;
875
        put_bits(&s->pb, 1, s->no_rounding);        /* rounding type */
876
    }
877
    put_bits(&s->pb, 3, 0);        /* intra dc VLC threshold */
878
    //FIXME sprite stuff
879

    
880
    put_bits(&s->pb, 5, s->qscale);
881

    
882
    if (s->pict_type != I_TYPE)
883
        put_bits(&s->pb, 3, s->f_code);        /* fcode_for */
884
    if (s->pict_type == B_TYPE)
885
        put_bits(&s->pb, 3, s->b_code);        /* fcode_back */
886
    //    printf("****frame %d\n", picture_number);
887
}
888

    
889
void h263_dc_scale(MpegEncContext * s)
890
{
891
#if 1
892
    const static UINT8 y_tab[32]={
893
    //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
894
        0, 8, 8, 8, 8,10,12,14,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,34,36,38,40,42,44,46
895
    };
896
    const static UINT8 c_tab[32]={
897
    //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
898
        0, 8, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,20,21,22,23,24,25
899
    };
900
    s->y_dc_scale = y_tab[s->qscale];
901
    s->c_dc_scale = c_tab[s->qscale];
902
#else
903
    int quant;
904
    quant = s->qscale;
905
    /* luminance */
906
    if (quant < 5)
907
        s->y_dc_scale = 8;
908
    else if (quant > 4 && quant < 9)
909
        s->y_dc_scale = (2 * quant);
910
    else if (quant > 8 && quant < 25)
911
        s->y_dc_scale = (quant + 8);
912
    else
913
        s->y_dc_scale = (2 * quant - 16);
914
    /* chrominance */
915
    if (quant < 5)
916
        s->c_dc_scale = 8;
917
    else if (quant > 4 && quant < 25)
918
        s->c_dc_scale = ((quant + 13) / 2);
919
    else
920
        s->c_dc_scale = (quant - 6);
921
#endif
922
}
923

    
924
static inline int mpeg4_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr, int *dir_ptr)
925
{
926
    int a, b, c, wrap, pred, scale;
927
    UINT16 *dc_val;
928
    int dummy;
929

    
930
    /* find prediction */
931
    if (n < 4) {
932
        scale = s->y_dc_scale;
933
    } else {
934
        scale = s->c_dc_scale;
935
    }
936
    wrap= s->block_wrap[n];
937
    dc_val = s->dc_val[0] + s->block_index[n];
938

    
939
    /* B C
940
     * A X 
941
     */
942
    a = dc_val[ - 1];
943
    b = dc_val[ - 1 - wrap];
944
    c = dc_val[ - wrap];
945

    
946
    if (abs(a - b) < abs(b - c)) {
947
        pred = c;
948
        *dir_ptr = 1; /* top */
949
    } else {
950
        pred = a;
951
        *dir_ptr = 0; /* left */
952
    }
953
    /* we assume pred is positive */
954
#ifdef ARCH_X86
955
        asm volatile (
956
                "xorl %%edx, %%edx        \n\t"
957
                "mul %%ecx                \n\t"
958
                : "=d" (pred), "=a"(dummy)
959
                : "a" (pred + (scale >> 1)), "c" (inverse[scale])
960
        );
961
#else
962
    pred = (pred + (scale >> 1)) / scale;
963
#endif
964

    
965
    /* prepare address for prediction update */
966
    *dc_val_ptr = &dc_val[0];
967

    
968
    return pred;
969
}
970

    
971
void mpeg4_pred_ac(MpegEncContext * s, INT16 *block, int n,
972
                   int dir)
973
{
974
    int i;
975
    INT16 *ac_val, *ac_val1;
976

    
977
    /* find prediction */
978
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
979
    ac_val1 = ac_val;
980
    if (s->ac_pred) {
981
        if (dir == 0) {
982
            /* left prediction */
983
            ac_val -= 16;
984
            for(i=1;i<8;i++) {
985
                block[block_permute_op(i*8)] += ac_val[i];
986
            }
987
        } else {
988
            /* top prediction */
989
            ac_val -= 16 * s->block_wrap[n];
990
            for(i=1;i<8;i++) {
991
                block[block_permute_op(i)] += ac_val[i + 8];
992
            }
993
        }
994
    }
995
    /* left copy */
996
    for(i=1;i<8;i++)
997
        ac_val1[i] = block[block_permute_op(i * 8)];
998
    /* top copy */
999
    for(i=1;i<8;i++)
1000
        ac_val1[8 + i] = block[block_permute_op(i)];
1001
}
1002

    
1003
static void mpeg4_inv_pred_ac(MpegEncContext * s, INT16 *block, int n,
1004
                              int dir)
1005
{
1006
    int i;
1007
    INT16 *ac_val;
1008

    
1009
    /* find prediction */
1010
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1011
 
1012
    if (dir == 0) {
1013
        /* left prediction */
1014
        ac_val -= 16;
1015
        for(i=1;i<8;i++) {
1016
            block[block_permute_op(i*8)] -= ac_val[i];
1017
        }
1018
    } else {
1019
        /* top prediction */
1020
        ac_val -= 16 * s->block_wrap[n];
1021
        for(i=1;i<8;i++) {
1022
            block[block_permute_op(i)] -= ac_val[i + 8];
1023
        }
1024
    }
1025
}
1026

    
1027

    
1028
static inline void mpeg4_encode_dc(MpegEncContext * s, int level, int n)
1029
{
1030
    int size, v;
1031
    /* find number of bits */
1032
    size = 0;
1033
    v = abs(level);
1034
    while (v) {
1035
        v >>= 1;
1036
        size++;
1037
    }
1038

    
1039
    if (n < 4) {
1040
        /* luminance */
1041
        put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
1042
    } else {
1043
        /* chrominance */
1044
        put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
1045
    }
1046

    
1047
    /* encode remaining bits */
1048
    if (size > 0) {
1049
        if (level < 0)
1050
            level = (-level) ^ ((1 << size) - 1);
1051
        put_bits(&s->pb, size, level);
1052
        if (size > 8)
1053
            put_bits(&s->pb, 1, 1);
1054
    }
1055
}
1056

    
1057
static void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, UINT8 *scan_table)
1058
{
1059
    int level, run, last, i, j, last_index, last_non_zero, sign, slevel;
1060
    int code;
1061
    const RLTable *rl;
1062

    
1063
    if (s->mb_intra) {
1064
        /* mpeg4 based DC predictor */
1065
        mpeg4_encode_dc(s, intra_dc, n);
1066
        i = 1;
1067
        rl = &rl_intra;
1068
    } else {
1069
        i = 0;
1070
        rl = &rl_inter;
1071
    }
1072

    
1073
    /* AC coefs */
1074
    last_index = s->block_last_index[n];
1075
    last_non_zero = i - 1;
1076
    for (; i <= last_index; i++) {
1077
        j = scan_table[i];
1078
        level = block[j];
1079
        if (level) {
1080
            run = i - last_non_zero - 1;
1081
            last = (i == last_index);
1082
            sign = 0;
1083
            slevel = level;
1084
            if (level < 0) {
1085
                sign = 1;
1086
                level = -level;
1087
            }
1088
            code = get_rl_index(rl, last, run, level);
1089
            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1090
            if (code == rl->n) {
1091
                int level1, run1;
1092
                level1 = level - rl->max_level[last][run];
1093
                if (level1 < 1) 
1094
                    goto esc2;
1095
                code = get_rl_index(rl, last, run, level1);
1096
                if (code == rl->n) {
1097
                esc2:
1098
                    put_bits(&s->pb, 1, 1);
1099
                    if (level > MAX_LEVEL)
1100
                        goto esc3;
1101
                    run1 = run - rl->max_run[last][level] - 1;
1102
                    if (run1 < 0)
1103
                        goto esc3;
1104
                    code = get_rl_index(rl, last, run1, level);
1105
                    if (code == rl->n) {
1106
                    esc3:
1107
                        /* third escape */
1108
                        put_bits(&s->pb, 1, 1);
1109
                        put_bits(&s->pb, 1, last);
1110
                        put_bits(&s->pb, 6, run);
1111
                        put_bits(&s->pb, 1, 1);
1112
                        put_bits(&s->pb, 12, slevel & 0xfff);
1113
                        put_bits(&s->pb, 1, 1);
1114
                    } else {
1115
                        /* second escape */
1116
                        put_bits(&s->pb, 1, 0);
1117
                        put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1118
                        put_bits(&s->pb, 1, sign);
1119
                    }
1120
                } else {
1121
                    /* first escape */
1122
                    put_bits(&s->pb, 1, 0);
1123
                    put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1124
                    put_bits(&s->pb, 1, sign);
1125
                }
1126
            } else {
1127
                put_bits(&s->pb, 1, sign);
1128
            }
1129
            last_non_zero = i;
1130
        }
1131
    }
1132
}
1133

    
1134

    
1135

    
1136
/***********************************************/
1137
/* decoding */
1138

    
1139
static VLC intra_MCBPC_vlc;
1140
static VLC inter_MCBPC_vlc;
1141
static VLC cbpy_vlc;
1142
static VLC mv_vlc;
1143
static VLC dc_lum, dc_chrom;
1144
static VLC sprite_trajectory;
1145
static VLC mb_type_b_vlc;
1146

    
1147
void init_rl(RLTable *rl)
1148
{
1149
    INT8 max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
1150
    UINT8 index_run[MAX_RUN+1];
1151
    int last, run, level, start, end, i;
1152

    
1153
    /* compute max_level[], max_run[] and index_run[] */
1154
    for(last=0;last<2;last++) {
1155
        if (last == 0) {
1156
            start = 0;
1157
            end = rl->last;
1158
        } else {
1159
            start = rl->last;
1160
            end = rl->n;
1161
        }
1162

    
1163
        memset(max_level, 0, MAX_RUN + 1);
1164
        memset(max_run, 0, MAX_LEVEL + 1);
1165
        memset(index_run, rl->n, MAX_RUN + 1);
1166
        for(i=start;i<end;i++) {
1167
            run = rl->table_run[i];
1168
            level = rl->table_level[i];
1169
            if (index_run[run] == rl->n)
1170
                index_run[run] = i;
1171
            if (level > max_level[run])
1172
                max_level[run] = level;
1173
            if (run > max_run[level])
1174
                max_run[level] = run;
1175
        }
1176
        rl->max_level[last] = malloc(MAX_RUN + 1);
1177
        memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
1178
        rl->max_run[last] = malloc(MAX_LEVEL + 1);
1179
        memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
1180
        rl->index_run[last] = malloc(MAX_RUN + 1);
1181
        memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
1182
    }
1183
}
1184

    
1185
void init_vlc_rl(RLTable *rl)
1186
{
1187
    init_vlc(&rl->vlc, 9, rl->n + 1, 
1188
             &rl->table_vlc[0][1], 4, 2,
1189
             &rl->table_vlc[0][0], 4, 2);
1190
}
1191

    
1192
/* init vlcs */
1193

    
1194
/* XXX: find a better solution to handle static init */
1195
void h263_decode_init_vlc(MpegEncContext *s)
1196
{
1197
    static int done = 0;
1198

    
1199
    if (!done) {
1200
        done = 1;
1201

    
1202
        init_vlc(&intra_MCBPC_vlc, 6, 8, 
1203
                 intra_MCBPC_bits, 1, 1,
1204
                 intra_MCBPC_code, 1, 1);
1205
        init_vlc(&inter_MCBPC_vlc, 9, 25, 
1206
                 inter_MCBPC_bits, 1, 1,
1207
                 inter_MCBPC_code, 1, 1);
1208
        init_vlc(&cbpy_vlc, 6, 16,
1209
                 &cbpy_tab[0][1], 2, 1,
1210
                 &cbpy_tab[0][0], 2, 1);
1211
        init_vlc(&mv_vlc, 9, 33,
1212
                 &mvtab[0][1], 2, 1,
1213
                 &mvtab[0][0], 2, 1);
1214
        init_rl(&rl_inter);
1215
        init_rl(&rl_intra);
1216
        init_rl(&rl_intra_aic);
1217
        init_vlc_rl(&rl_inter);
1218
        init_vlc_rl(&rl_intra);
1219
        init_vlc_rl(&rl_intra_aic);
1220
        init_vlc(&dc_lum, 9, 13,
1221
                 &DCtab_lum[0][1], 2, 1,
1222
                 &DCtab_lum[0][0], 2, 1);
1223
        init_vlc(&dc_chrom, 9, 13,
1224
                 &DCtab_chrom[0][1], 2, 1,
1225
                 &DCtab_chrom[0][0], 2, 1);
1226
        init_vlc(&sprite_trajectory, 9, 15,
1227
                 &sprite_trajectory_tab[0][1], 4, 2,
1228
                 &sprite_trajectory_tab[0][0], 4, 2);
1229
        init_vlc(&mb_type_b_vlc, 4, 4,
1230
                 &mb_type_b_tab[0][1], 2, 1,
1231
                 &mb_type_b_tab[0][0], 2, 1);
1232
    }
1233
}
1234

    
1235
int h263_decode_gob_header(MpegEncContext *s)
1236
{
1237
    unsigned int val, gfid;
1238
    
1239
    /* Check for GOB Start Code */
1240
    val = show_bits(&s->gb, 16);
1241
    if (val == 0) {
1242
        /* We have a GBSC probably with GSTUFF */
1243
        skip_bits(&s->gb, 16); /* Drop the zeros */
1244
        while (get_bits1(&s->gb) == 0); /* Seek the '1' bit */
1245
#ifdef DEBUG
1246
        fprintf(stderr,"\nGOB Start Code at MB %d\n", (s->mb_y * s->mb_width) + s->mb_x);
1247
#endif
1248
        s->gob_number = get_bits(&s->gb, 5); /* GN */
1249
        gfid = get_bits(&s->gb, 2); /* GFID */
1250
        s->qscale = get_bits(&s->gb, 5); /* GQUANT */
1251
#ifdef DEBUG
1252
        fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", s->gob_number, gfid, s->qscale);
1253
#endif
1254
        return 1;
1255
    }
1256
    return 0;
1257
            
1258
}
1259

    
1260
int h263_decode_mb(MpegEncContext *s,
1261
                   DCTELEM block[6][64])
1262
{
1263
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
1264
    INT16 *mot_val;
1265
    static INT8 quant_tab[4] = { -1, -2, 1, 2 };
1266

    
1267
    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
1268
        if (get_bits1(&s->gb)) {
1269
            /* skip mb */
1270
            s->mb_intra = 0;
1271
            for(i=0;i<6;i++)
1272
                s->block_last_index[i] = -1;
1273
            s->mv_dir = MV_DIR_FORWARD;
1274
            s->mv_type = MV_TYPE_16X16;
1275
            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
1276
                const int a= s->sprite_warping_accuracy;
1277
//                int l = (1 << (s->f_code - 1)) * 32;
1278

    
1279
                s->mcsel=1;
1280
                s->mv[0][0][0] = RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
1281
                s->mv[0][0][1] = RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
1282
/*                if (s->mv[0][0][0] < -l) s->mv[0][0][0]= -l;
1283
                else if (s->mv[0][0][0] >= l) s->mv[0][0][0]= l-1;
1284
                if (s->mv[0][0][1] < -l) s->mv[0][0][1]= -l;
1285
                else if (s->mv[0][0][1] >= l) s->mv[0][0][1]= l-1;*/
1286

    
1287
                s->mb_skiped = 0;
1288
            }else{
1289
                s->mcsel=0;
1290
                s->mv[0][0][0] = 0;
1291
                s->mv[0][0][1] = 0;
1292
                s->mb_skiped = 1;
1293
            }
1294
            return 0;
1295
        }
1296
        cbpc = get_vlc(&s->gb, &inter_MCBPC_vlc);
1297
        //fprintf(stderr, "\tCBPC: %d", cbpc);
1298
        if (cbpc < 0)
1299
            return -1;
1300
        if (cbpc > 20)
1301
            cbpc+=3;
1302
        else if (cbpc == 20)
1303
            fprintf(stderr, "Stuffing !");
1304
        
1305
        dquant = cbpc & 8;
1306
        s->mb_intra = ((cbpc & 4) != 0);
1307
        if (s->mb_intra) goto intra;
1308
        
1309
        if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
1310
            s->mcsel= get_bits1(&s->gb);
1311
        else s->mcsel= 0;
1312
        cbpy = get_vlc(&s->gb, &cbpy_vlc);
1313
        cbp = (cbpc & 3) | ((cbpy ^ 0xf) << 2);
1314
        if (dquant) {
1315
            s->qscale += quant_tab[get_bits(&s->gb, 2)];
1316
            if (s->qscale < 1)
1317
                s->qscale = 1;
1318
            else if (s->qscale > 31)
1319
                s->qscale = 31;
1320
        }
1321
        s->mv_dir = MV_DIR_FORWARD;
1322
        if ((cbpc & 16) == 0) {
1323
            /* 16x16 motion prediction */
1324
            s->mv_type = MV_TYPE_16X16;
1325
            h263_pred_motion(s, 0, &pred_x, &pred_y);
1326
            if (s->umvplus_dec)
1327
               mx = h263p_decode_umotion(s, pred_x);
1328
            else if(!s->mcsel)
1329
               mx = h263_decode_motion(s, pred_x, s->f_code);
1330
            else {
1331
               const int a= s->sprite_warping_accuracy;
1332
//        int l = (1 << (s->f_code - 1)) * 32;
1333
               mx= RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
1334
//        if (mx < -l) mx= -l;
1335
//        else if (mx >= l) mx= l-1;
1336
            }
1337
            if (mx >= 0xffff)
1338
                return -1;
1339
            
1340
            if (s->umvplus_dec)
1341
               my = h263p_decode_umotion(s, pred_y);
1342
            else if(!s->mcsel)
1343
               my = h263_decode_motion(s, pred_y, s->f_code);
1344
            else{
1345
               const int a= s->sprite_warping_accuracy;
1346
//       int l = (1 << (s->f_code - 1)) * 32;
1347
               my= RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
1348
//       if (my < -l) my= -l;
1349
//       else if (my >= l) my= l-1;
1350
            }
1351
            if (my >= 0xffff)
1352
                return -1;
1353
            s->mv[0][0][0] = mx;
1354
            s->mv[0][0][1] = my;
1355
            /*fprintf(stderr, "\n MB %d", (s->mb_y * s->mb_width) + s->mb_x);
1356
            fprintf(stderr, "\n\tmvx: %d\t\tpredx: %d", mx, pred_x);
1357
            fprintf(stderr, "\n\tmvy: %d\t\tpredy: %d", my, pred_y);*/
1358
            if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
1359
               skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1360
                           
1361
        } else {
1362
            s->mv_type = MV_TYPE_8X8;
1363
            for(i=0;i<4;i++) {
1364
                mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
1365
                if (s->umvplus_dec)
1366
                  mx = h263p_decode_umotion(s, pred_x);
1367
                else
1368
                  mx = h263_decode_motion(s, pred_x, s->f_code);
1369
                if (mx >= 0xffff)
1370
                    return -1;
1371
                
1372
                if (s->umvplus_dec)
1373
                  my = h263p_decode_umotion(s, pred_y);
1374
                else    
1375
                  my = h263_decode_motion(s, pred_y, s->f_code);
1376
                if (my >= 0xffff)
1377
                    return -1;
1378
                s->mv[0][i][0] = mx;
1379
                s->mv[0][i][1] = my;
1380
                if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
1381
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1382
                mot_val[0] = mx;
1383
                mot_val[1] = my;
1384
            }
1385
        }
1386
    } else if(s->pict_type==B_TYPE) {
1387
        int modb1; // first bit of modb
1388
        int modb2; // second bit of modb
1389
        int mb_type;
1390
        int time_pp;
1391
        int time_pb;
1392
        int xy;
1393

    
1394
        s->mb_intra = 0; //B-frames never contain intra blocks
1395
        s->mcsel=0;      //     ...               true gmc blocks
1396

    
1397
        if(s->mb_x==0){
1398
            s->last_mv[0][0][0]= 
1399
            s->last_mv[0][0][1]= 
1400
            s->last_mv[1][0][0]= 
1401
            s->last_mv[1][0][1]= 0;
1402
        }
1403

    
1404
        /* if we skipped it in the future P Frame than skip it now too */
1405
        s->mb_skiped= s->mbskip_table[s->mb_y * s->mb_width + s->mb_x]; // Note, skiptab=0 if last was GMC
1406

    
1407
        if(s->mb_skiped){
1408
                /* skip mb */
1409
            for(i=0;i<6;i++)
1410
                s->block_last_index[i] = -1;
1411

    
1412
            s->mv_dir = MV_DIR_FORWARD;
1413
            s->mv_type = MV_TYPE_16X16;
1414
            s->mv[0][0][0] = 0;
1415
            s->mv[0][0][1] = 0;
1416
            s->mv[1][0][0] = 0;
1417
            s->mv[1][0][1] = 0;
1418
            s->last_mv[0][0][0]=
1419
            s->last_mv[0][0][1]= 
1420
            s->last_mv[1][0][0]= 
1421
            s->last_mv[1][0][1]= 0;
1422
            s->mb_skiped = 1;
1423
            return 0;
1424
        }
1425

    
1426
        modb1= get_bits1(&s->gb);
1427
        if(modb1==0){
1428
            modb2= get_bits1(&s->gb);
1429
            mb_type= get_vlc(&s->gb, &mb_type_b_vlc);
1430
            if(modb2==0) cbp= get_bits(&s->gb, 6);
1431
            else cbp=0;
1432
            if (mb_type && cbp) {
1433
                if(get_bits1(&s->gb)){
1434
                    s->qscale +=get_bits1(&s->gb)*4 - 2;
1435
                    if (s->qscale < 1)
1436
                        s->qscale = 1;
1437
                    else if (s->qscale > 31)
1438
                        s->qscale = 31;
1439
                }
1440
            }
1441
        }else{
1442
            mb_type=4; //like 0 but no vectors coded
1443
            cbp=0;
1444
        }
1445
        s->mv_type = MV_TYPE_16X16; // we'll switch to 8x8 only if the last P frame had 8x8 for this MB and mb_type=0 here
1446
        mx=my=0; //for case 4, we could put this to the mb_type=4 but than gcc compains about uninitalized mx/my
1447
        switch(mb_type)
1448
        {
1449
        case 0: 
1450
            mx = h263_decode_motion(s, 0, 1);
1451
            my = h263_decode_motion(s, 0, 1);
1452
        case 4: 
1453
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1454
            xy= s->block_index[0];
1455
            time_pp= s->last_non_b_time[0] - s->last_non_b_time[1];
1456
            time_pb= s->time - s->last_non_b_time[1];
1457
//if(time_pp>3000 )printf("%d %d  ", time_pp, time_pb);
1458
            //FIXME 4MV
1459
            //FIXME avoid divides
1460
            s->mv[0][0][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
1461
            s->mv[0][0][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
1462
            s->mv[1][0][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
1463
                                : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp + mx;
1464
            s->mv[1][0][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1] 
1465
                                : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp + my;
1466
/*            s->mv[0][0][0] = 
1467
            s->mv[0][0][1] = 
1468
            s->mv[1][0][0] = 
1469
            s->mv[1][0][1] = 1000;*/
1470
            break;
1471
        case 1: 
1472
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
1473
            mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1474
            my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1475
            s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1476
            s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1477

    
1478
            mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1479
            my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1480
            s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1481
            s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1482
            break;
1483
        case 2: 
1484
            s->mv_dir = MV_DIR_BACKWARD;
1485
            mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1486
            my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1487
            s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1488
            s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1489
            break;
1490
        case 3:
1491
            s->mv_dir = MV_DIR_FORWARD;
1492
            mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1493
            my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1494
            s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1495
            s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1496
            break;
1497
        default: return -1;
1498
        }
1499
    } else { /* I-Frame */
1500
        cbpc = get_vlc(&s->gb, &intra_MCBPC_vlc);
1501
        if (cbpc < 0)
1502
            return -1;
1503
        dquant = cbpc & 4;
1504
        s->mb_intra = 1;
1505
intra:
1506
        s->ac_pred = 0;
1507
        if (s->h263_pred || s->h263_aic) {
1508
            s->ac_pred = get_bits1(&s->gb);
1509
            if (s->ac_pred && s->h263_aic)
1510
                s->h263_aic_dir = get_bits1(&s->gb);
1511
        }
1512
        if (s->h263_aic) {
1513
            s->y_dc_scale = 2 * s->qscale;
1514
            s->c_dc_scale = 2 * s->qscale;
1515
        }
1516
        cbpy = get_vlc(&s->gb, &cbpy_vlc);
1517
        cbp = (cbpc & 3) | (cbpy << 2);
1518
        if (dquant) {
1519
            s->qscale += quant_tab[get_bits(&s->gb, 2)];
1520
            if (s->qscale < 1)
1521
                s->qscale = 1;
1522
            else if (s->qscale > 31)
1523
                s->qscale = 31;
1524
        }
1525
    }
1526

    
1527
    /* decode each block */
1528
    if (s->h263_pred) {
1529
        for (i = 0; i < 6; i++) {
1530
            if (mpeg4_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1) < 0)
1531
                return -1;
1532
        }
1533
    } else {
1534
        for (i = 0; i < 6; i++) {
1535
            if (h263_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1) < 0)
1536
                return -1;
1537
        }
1538
    }
1539
    return 0;
1540
}
1541

    
1542
static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
1543
{
1544
    int code, val, sign, shift, l, m;
1545

    
1546
    code = get_vlc(&s->gb, &mv_vlc);
1547
    if (code < 0)
1548
        return 0xffff;
1549

    
1550
    if (code == 0)
1551
        return pred;
1552
    sign = get_bits1(&s->gb);
1553
    shift = f_code - 1;
1554
    val = (code - 1) << shift;
1555
    if (shift > 0)
1556
        val |= get_bits(&s->gb, shift);
1557
    val++;
1558
    if (sign)
1559
        val = -val;
1560
    val += pred;
1561
    
1562
    /* modulo decoding */
1563
    if (!s->h263_long_vectors) {
1564
        l = (1 << (f_code - 1)) * 32;
1565
        m = 2 * l;
1566
        if (val < -l) {
1567
            val += m;
1568
        } else if (val >= l) {
1569
            val -= m;
1570
        }
1571
    } else {
1572
        /* horrible h263 long vector mode */
1573
        if (pred < -31 && val < -63)
1574
            val += 64;
1575
        if (pred > 32 && val > 63)
1576
            val -= 64;
1577
        
1578
    }
1579
    return val;
1580
}
1581

    
1582
/* Decodes RVLC of H.263+ UMV */
1583
static int h263p_decode_umotion(MpegEncContext * s, int pred)
1584
{
1585
   int code = 0, sign;
1586
   
1587
   if (get_bits1(&s->gb)) /* Motion difference = 0 */
1588
      return pred;
1589
   
1590
   code = 2 + get_bits1(&s->gb);
1591
   
1592
   while (get_bits1(&s->gb))
1593
   {
1594
      code <<= 1;
1595
      code += get_bits1(&s->gb);
1596
   }
1597
   sign = code & 1;
1598
   code >>= 1;
1599
   
1600
   code = (sign) ? (pred - code) : (pred + code);
1601
#ifdef DEBUG
1602
   fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
1603
#endif
1604
   return code;   
1605

    
1606
}
1607

    
1608
static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
1609
                             int n, int coded)
1610
{
1611
    int code, level, i, j, last, run;
1612
    RLTable *rl = &rl_inter;
1613
    const UINT8 *scan_table;
1614

    
1615
    scan_table = zigzag_direct;
1616
    if (s->h263_aic && s->mb_intra) {
1617
        rl = &rl_intra_aic;
1618
        i = 0;
1619
        if (s->ac_pred) {
1620
            if (s->h263_aic_dir) 
1621
                scan_table = ff_alternate_vertical_scan; /* left */
1622
            else
1623
                scan_table = ff_alternate_horizontal_scan; /* top */
1624
        }
1625
    } else if (s->mb_intra) {
1626
        /* DC coef */
1627
        if (s->h263_rv10 && s->rv10_version == 3 && s->pict_type == I_TYPE) {
1628
            int component, diff;
1629
            component = (n <= 3 ? 0 : n - 4 + 1);
1630
            level = s->last_dc[component];
1631
            if (s->rv10_first_dc_coded[component]) {
1632
                diff = rv_decode_dc(s, n);
1633
                if (diff == 0xffff)
1634
                    return -1;
1635
                level += diff;
1636
                level = level & 0xff; /* handle wrap round */
1637
                s->last_dc[component] = level;
1638
            } else {
1639
                s->rv10_first_dc_coded[component] = 1;
1640
            }
1641
        } else {
1642
            level = get_bits(&s->gb, 8);
1643
            if (level == 255)
1644
                level = 128;
1645
        }
1646
        block[0] = level;
1647
        i = 1;
1648
    } else {
1649
        i = 0;
1650
    }
1651
    if (!coded) {
1652
        if (s->mb_intra && s->h263_aic)
1653
            goto not_coded;
1654
        s->block_last_index[n] = i - 1;
1655
        return 0;
1656
    }
1657

    
1658
    for(;;) {
1659
        code = get_vlc(&s->gb, &rl->vlc);
1660
        if (code < 0)
1661
            return -1;
1662
        if (code == rl->n) {
1663
            /* escape */
1664
            last = get_bits1(&s->gb);
1665
            run = get_bits(&s->gb, 6);
1666
            level = (INT8)get_bits(&s->gb, 8);
1667
            if (s->h263_rv10 && level == -128) {
1668
                /* XXX: should patch encoder too */
1669
                level = get_bits(&s->gb, 12);
1670
                level = (level << 20) >> 20;
1671
            }
1672
        } else {
1673
            run = rl->table_run[code];
1674
            level = rl->table_level[code];
1675
            last = code >= rl->last;
1676
            if (get_bits1(&s->gb))
1677
                level = -level;
1678
        }
1679
        i += run;
1680
        if (i >= 64)
1681
            return -1;
1682
        j = scan_table[i];
1683
        block[j] = level;
1684
        if (last)
1685
            break;
1686
        i++;
1687
    }
1688
not_coded:    
1689
    if (s->mb_intra && s->h263_aic) {
1690
        h263_pred_acdc(s, block, n);
1691
        i = 63;
1692
    }
1693
    s->block_last_index[n] = i;
1694
    return 0;
1695
}
1696

    
1697
static int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
1698
{
1699
    int level, pred, code;
1700
    UINT16 *dc_val;
1701

    
1702
    if (n < 4) 
1703
        code = get_vlc(&s->gb, &dc_lum);
1704
    else 
1705
        code = get_vlc(&s->gb, &dc_chrom);
1706
    if (code < 0)
1707
        return -1;
1708
    if (code == 0) {
1709
        level = 0;
1710
    } else {
1711
        level = get_bits(&s->gb, code);
1712
        if ((level >> (code - 1)) == 0) /* if MSB not set it is negative*/
1713
            level = - (level ^ ((1 << code) - 1));
1714
        if (code > 8)
1715
            skip_bits1(&s->gb); /* marker */
1716
    }
1717

    
1718
    pred = mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
1719
    level += pred;
1720
    if (level < 0)
1721
        level = 0;
1722
    if (n < 4) {
1723
        *dc_val = level * s->y_dc_scale;
1724
    } else {
1725
        *dc_val = level * s->c_dc_scale;
1726
    }
1727
    return level;
1728
}
1729

    
1730
static int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
1731
                              int n, int coded)
1732
{
1733
    int code, level, i, j, last, run;
1734
    int dc_pred_dir;
1735
    RLTable *rl;
1736
    const UINT8 *scan_table;
1737

    
1738
    if (s->mb_intra) {
1739
        /* DC coef */
1740
        level = mpeg4_decode_dc(s, n, &dc_pred_dir);
1741
        if (level < 0)
1742
            return -1;
1743
        block[0] = level;
1744
        i = 1;
1745
        if (!coded) 
1746
            goto not_coded;
1747
        rl = &rl_intra;
1748
        if (s->ac_pred) {
1749
            if (dc_pred_dir == 0) 
1750
                scan_table = ff_alternate_vertical_scan; /* left */
1751
            else
1752
                scan_table = ff_alternate_horizontal_scan; /* top */
1753
        } else {
1754
            scan_table = zigzag_direct;
1755
        }
1756
    } else {
1757
        i = 0;
1758
        if (!coded) {
1759
            s->block_last_index[n] = i - 1;
1760
            return 0;
1761
        }
1762
        rl = &rl_inter;
1763
        scan_table = zigzag_direct;
1764
    }
1765

    
1766
    for(;;) {
1767
        code = get_vlc(&s->gb, &rl->vlc);
1768
        if (code < 0)
1769
            return -1;
1770
        if (code == rl->n) {
1771
            /* escape */
1772
            if (get_bits1(&s->gb) != 0) {
1773
                if (get_bits1(&s->gb) != 0) {
1774
                    /* third escape */
1775
                    last = get_bits1(&s->gb);
1776
                    run = get_bits(&s->gb, 6);
1777
                    get_bits1(&s->gb); /* marker */
1778
                    level = get_bits(&s->gb, 12);
1779
                    level = (level << 20) >> 20; /* sign extend */
1780
                    skip_bits1(&s->gb); /* marker */
1781
                } else {
1782
                    /* second escape */
1783
                    code = get_vlc(&s->gb, &rl->vlc);
1784
                    if (code < 0 || code >= rl->n)
1785
                        return -1;
1786
                    run = rl->table_run[code];
1787
                    level = rl->table_level[code];
1788
                    last = code >= rl->last;
1789
                    run += rl->max_run[last][level] + 1;
1790
                    if (get_bits1(&s->gb))
1791
                        level = -level;
1792
                }
1793
            } else {
1794
                /* first escape */
1795
                code = get_vlc(&s->gb, &rl->vlc);
1796
                if (code < 0 || code >= rl->n)
1797
                    return -1;
1798
                run = rl->table_run[code];
1799
                level = rl->table_level[code];
1800
                last = code >= rl->last;
1801
                level += rl->max_level[last][run];
1802
                if (get_bits1(&s->gb))
1803
                    level = -level;
1804
            }
1805
        } else {
1806
            run = rl->table_run[code];
1807
            level = rl->table_level[code];
1808
            last = code >= rl->last;
1809
            if (get_bits1(&s->gb))
1810
                level = -level;
1811
        }
1812
        i += run;
1813
        if (i >= 64)
1814
            return -1;
1815
        j = scan_table[i];
1816
        block[j] = level;
1817
        i++;
1818
        if (last)
1819
            break;
1820
    }
1821
 not_coded:
1822
    if (s->mb_intra) {
1823
        mpeg4_pred_ac(s, block, n, dc_pred_dir);
1824
        if (s->ac_pred) {
1825
            i = 64; /* XXX: not optimal */
1826
        }
1827
    }
1828
    s->block_last_index[n] = i - 1;
1829
    return 0;
1830
}
1831

    
1832
/* most is hardcoded. should extend to handle all h263 streams */
1833
int h263_decode_picture_header(MpegEncContext *s)
1834
{
1835
    int format, width, height;
1836

    
1837
    /* picture header */
1838
    if (get_bits(&s->gb, 22) != 0x20)
1839
        return -1;
1840
    s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
1841
    
1842
    if (get_bits1(&s->gb) != 1)
1843
        return -1;        /* marker */
1844
    if (get_bits1(&s->gb) != 0)
1845
        return -1;        /* h263 id */
1846
    skip_bits1(&s->gb);        /* split screen off */
1847
    skip_bits1(&s->gb);        /* camera  off */
1848
    skip_bits1(&s->gb);        /* freeze picture release off */
1849

    
1850
    /* Reset GOB number */
1851
    s->gob_number = 0;
1852
        
1853
    format = get_bits(&s->gb, 3);
1854

    
1855
    if (format != 7 && format != 6) {
1856
        s->h263_plus = 0;
1857
        /* H.263v1 */
1858
        width = h263_format[format][0];
1859
        height = h263_format[format][1];
1860
        if (!width)
1861
            return -1;
1862
        
1863
        s->width = width;
1864
        s->height = height;
1865
        s->pict_type = I_TYPE + get_bits1(&s->gb);
1866

    
1867
        s->unrestricted_mv = get_bits1(&s->gb); 
1868
        s->h263_long_vectors = s->unrestricted_mv;
1869

    
1870
        if (get_bits1(&s->gb) != 0)
1871
            return -1;        /* SAC: off */
1872
        if (get_bits1(&s->gb) != 0) {
1873
            s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
1874
        }   
1875
        
1876
        if (get_bits1(&s->gb) != 0)
1877
            return -1;        /* not PB frame */
1878

    
1879
        s->qscale = get_bits(&s->gb, 5);
1880
        skip_bits1(&s->gb);        /* Continuous Presence Multipoint mode: off */
1881
    } else {
1882
        int ufep;
1883
        
1884
        /* H.263v2 */
1885
        s->h263_plus = 1;
1886
        ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
1887
        
1888
        if (ufep == 1) {
1889
            /* OPPTYPE */       
1890
            format = get_bits(&s->gb, 3);
1891
            skip_bits(&s->gb,1); /* Custom PCF */
1892
            s->umvplus_dec = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */
1893
            skip_bits1(&s->gb); /* Syntax-based Arithmetic Coding (SAC) */
1894
            if (get_bits1(&s->gb) != 0) {
1895
                s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
1896
            }
1897
            if (get_bits1(&s->gb) != 0) { /* Advanced Intra Coding (AIC) */
1898
                s->h263_aic = 1;
1899
            }
1900
            skip_bits(&s->gb, 7);
1901
            skip_bits(&s->gb, 3); /* Reserved */
1902
        } else if (ufep != 0)
1903
            return -1;
1904
            
1905
        /* MPPTYPE */
1906
        s->pict_type = get_bits(&s->gb, 3) + 1;
1907
        if (s->pict_type != I_TYPE &&
1908
            s->pict_type != P_TYPE)
1909
            return -1;
1910
        skip_bits(&s->gb, 2);
1911
        s->no_rounding = get_bits1(&s->gb);
1912
        //fprintf(stderr, "\nRTYPE: %d", s->no_rounding);
1913
        skip_bits(&s->gb, 4);
1914
        
1915
        /* Get the picture dimensions */
1916
        if (ufep) {
1917
            if (format == 6) {
1918
                /* Custom Picture Format (CPFMT) */
1919
                skip_bits(&s->gb, 4); /* aspect ratio */
1920
                width = (get_bits(&s->gb, 9) + 1) * 4;
1921
                skip_bits1(&s->gb);
1922
                height = get_bits(&s->gb, 9) * 4;
1923
#ifdef DEBUG 
1924
                fprintf(stderr,"\nH.263+ Custom picture: %dx%d\n",width,height);
1925
#endif            
1926
            }
1927
            else {
1928
                width = h263_format[format][0];
1929
                height = h263_format[format][1];
1930
            }
1931
            if ((width == 0) || (height == 0))
1932
                return -1;
1933
            s->width = width;
1934
            s->height = height;
1935
            if (s->umvplus_dec) {
1936
                skip_bits1(&s->gb); /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
1937
            }
1938
        }
1939
            
1940
        s->qscale = get_bits(&s->gb, 5);
1941
    }
1942
    /* PEI */
1943
    while (get_bits1(&s->gb) != 0) {
1944
        skip_bits(&s->gb, 8);
1945
    }
1946
    s->f_code = 1;
1947
    return 0;
1948
}
1949

    
1950
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
1951
{
1952
    int i;
1953
    int a= 2<<s->sprite_warping_accuracy;
1954
    int rho= 3-s->sprite_warping_accuracy;
1955
    int r=16/a;
1956
    const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
1957
    int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
1958
    int sprite_ref[4][2];
1959
    int virtual_ref[2][2];
1960
    int w2, h2;
1961
    int alpha=0, beta=0;
1962
    int w= s->width;
1963
    int h= s->height;
1964
//printf("SP %d\n", s->sprite_warping_accuracy);
1965
    for(i=0; i<s->num_sprite_warping_points; i++){
1966
        int length;
1967
        int x=0, y=0;
1968

    
1969
        length= get_vlc(&s->gb, &sprite_trajectory);
1970
        if(length){
1971
            x= get_bits(&s->gb, length);
1972
//printf("lx %d %d\n", length, x);
1973
            if ((x >> (length - 1)) == 0) /* if MSB not set it is negative*/
1974
                x = - (x ^ ((1 << length) - 1));
1975
        }
1976
        if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
1977
        
1978
        length= get_vlc(&s->gb, &sprite_trajectory);
1979
        if(length){
1980
            y=get_bits(&s->gb, length);
1981
//printf("ly %d %d\n", length, y);
1982
            if ((y >> (length - 1)) == 0) /* if MSB not set it is negative*/
1983
                y = - (y ^ ((1 << length) - 1));
1984
        }
1985
        skip_bits1(&s->gb); /* marker bit */
1986
//printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
1987
//if(i>0 && (x!=0 || y!=0)) printf("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n");
1988
//x=y=0;
1989
        d[i][0]= x;
1990
        d[i][1]= y;
1991
    }
1992

    
1993
    while((1<<alpha)<w) alpha++;
1994
    while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
1995
    w2= 1<<alpha;
1996
    h2= 1<<beta;
1997

    
1998
// Note, the 4th point isnt used for GMC
1999
    if(s->divx_version==500 && s->divx_build==413){
2000
        sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
2001
        sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
2002
        sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
2003
        sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
2004
        sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
2005
        sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
2006
    } else {
2007
        sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
2008
        sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
2009
        sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
2010
        sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
2011
        sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
2012
        sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
2013
    }
2014
/*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
2015
    sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
2016
    
2017
// this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
2018
// perhaps it should be reordered to be more readable ...
2019
// the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
2020
// so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
2021
    virtual_ref[0][0]= 16*(vop_ref[0][0] + w2) 
2022
        + RDIV(((w - w2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + w2*(r*sprite_ref[1][0] - 16*vop_ref[1][0])),w);
2023
    virtual_ref[0][1]= 16*vop_ref[0][1] 
2024
        + RDIV(((w - w2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + w2*(r*sprite_ref[1][1] - 16*vop_ref[1][1])),w);
2025
    virtual_ref[1][0]= 16*vop_ref[0][0] 
2026
        + RDIV(((h - h2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + h2*(r*sprite_ref[2][0] - 16*vop_ref[2][0])),h);
2027
    virtual_ref[1][1]= 16*(vop_ref[0][1] + h2) 
2028
        + RDIV(((h - h2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + h2*(r*sprite_ref[2][1] - 16*vop_ref[2][1])),h);
2029

    
2030
    switch(s->num_sprite_warping_points)
2031
    {
2032
        case 0:
2033
            s->sprite_offset[0][0]= 0;
2034
            s->sprite_offset[0][1]= 0;
2035
            s->sprite_offset[1][0]= 0;
2036
            s->sprite_offset[1][1]= 0;
2037
            s->sprite_delta[0][0][0]= a;
2038
            s->sprite_delta[0][0][1]= 0;
2039
            s->sprite_delta[0][1][0]= 0;
2040
            s->sprite_delta[0][1][1]= a;
2041
            s->sprite_delta[1][0][0]= a;
2042
            s->sprite_delta[1][0][1]= 0;
2043
            s->sprite_delta[1][1][0]= 0;
2044
            s->sprite_delta[1][1][1]= a;
2045
            s->sprite_shift[0][0]= 0;
2046
            s->sprite_shift[0][1]= 0;
2047
            s->sprite_shift[1][0]= 0;
2048
            s->sprite_shift[1][1]= 0;
2049
            break;
2050
        case 1: //GMC only
2051
            s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
2052
            s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
2053
            s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
2054
            s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
2055
            s->sprite_delta[0][0][0]= a;
2056
            s->sprite_delta[0][0][1]= 0;
2057
            s->sprite_delta[0][1][0]= 0;
2058
            s->sprite_delta[0][1][1]= a;
2059
            s->sprite_delta[1][0][0]= a;
2060
            s->sprite_delta[1][0][1]= 0;
2061
            s->sprite_delta[1][1][0]= 0;
2062
            s->sprite_delta[1][1][1]= a;
2063
            s->sprite_shift[0][0]= 0;
2064
            s->sprite_shift[0][1]= 0;
2065
            s->sprite_shift[1][0]= 0;
2066
            s->sprite_shift[1][1]= 0;
2067
            break;
2068
        case 2:
2069
        case 3: //FIXME
2070
            s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
2071
                                                  + ((-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
2072
                                                    +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1]));
2073
            s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
2074
                                                  + ((-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
2075
                                                    +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1]));
2076
            s->sprite_offset[1][0]= ((-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)
2077
                                 +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)
2078
                                 +2*w2*r*sprite_ref[0][0] - 16*w2);
2079
            s->sprite_offset[1][1]= ((-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1) 
2080
                                 +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)
2081
                                 +2*w2*r*sprite_ref[0][1] - 16*w2);
2082
            s->sprite_delta[0][0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
2083
            s->sprite_delta[0][0][1]=   ( r*sprite_ref[0][1] - virtual_ref[0][1]);
2084
            s->sprite_delta[0][1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);
2085
            s->sprite_delta[0][1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
2086
            s->sprite_delta[1][0][0]= 4*(-r*sprite_ref[0][0] + virtual_ref[0][0]);
2087
            s->sprite_delta[1][0][1]= 4*( r*sprite_ref[0][1] - virtual_ref[0][1]);
2088
            s->sprite_delta[1][1][0]= 4*(-r*sprite_ref[0][1] + virtual_ref[0][1]);
2089
            s->sprite_delta[1][1][1]= 4*(-r*sprite_ref[0][0] + virtual_ref[0][0]);
2090
            s->sprite_shift[0][0]= alpha+rho;
2091
            s->sprite_shift[0][1]= alpha+rho;
2092
            s->sprite_shift[1][0]= alpha+rho+2;
2093
            s->sprite_shift[1][1]= alpha+rho+2;
2094
            break;
2095
//        case 3:
2096
            break;
2097
    }
2098
/*printf("%d %d\n", s->sprite_delta[0][0][0], a<<s->sprite_shift[0][0]);
2099
printf("%d %d\n", s->sprite_delta[0][0][1], 0);
2100
printf("%d %d\n", s->sprite_delta[0][1][0], 0);
2101
printf("%d %d\n", s->sprite_delta[0][1][1], a<<s->sprite_shift[0][1]);
2102
printf("%d %d\n", s->sprite_delta[1][0][0], a<<s->sprite_shift[1][0]);
2103
printf("%d %d\n", s->sprite_delta[1][0][1], 0);
2104
printf("%d %d\n", s->sprite_delta[1][1][0], 0);
2105
printf("%d %d\n", s->sprite_delta[1][1][1], a<<s->sprite_shift[1][1]);*/
2106
    /* try to simplify the situation */ 
2107
    if(   s->sprite_delta[0][0][0] == a<<s->sprite_shift[0][0]
2108
       && s->sprite_delta[0][0][1] == 0
2109
       && s->sprite_delta[0][1][0] == 0
2110
       && s->sprite_delta[0][1][1] == a<<s->sprite_shift[0][1]
2111
       && s->sprite_delta[1][0][0] == a<<s->sprite_shift[1][0]
2112
       && s->sprite_delta[1][0][1] == 0
2113
       && s->sprite_delta[1][1][0] == 0
2114
       && s->sprite_delta[1][1][1] == a<<s->sprite_shift[1][1])
2115
    {
2116
        s->sprite_offset[0][0]>>=s->sprite_shift[0][0];
2117
        s->sprite_offset[0][1]>>=s->sprite_shift[0][1];
2118
        s->sprite_offset[1][0]>>=s->sprite_shift[1][0];
2119
        s->sprite_offset[1][1]>>=s->sprite_shift[1][1];
2120
        s->sprite_delta[0][0][0]= a;
2121
        s->sprite_delta[0][0][1]= 0;
2122
        s->sprite_delta[0][1][0]= 0;
2123
        s->sprite_delta[0][1][1]= a;
2124
        s->sprite_delta[1][0][0]= a;
2125
        s->sprite_delta[1][0][1]= 0;
2126
        s->sprite_delta[1][1][0]= 0;
2127
        s->sprite_delta[1][1][1]= a;
2128
        s->sprite_shift[0][0]= 0;
2129
        s->sprite_shift[0][1]= 0;
2130
        s->sprite_shift[1][0]= 0;
2131
        s->sprite_shift[1][1]= 0;
2132
        s->real_sprite_warping_points=1;
2133
    }
2134
    else
2135
        s->real_sprite_warping_points= s->num_sprite_warping_points;
2136

    
2137
}
2138

    
2139
/* decode mpeg4 VOP header */
2140
int mpeg4_decode_picture_header(MpegEncContext * s)
2141
{
2142
    int time_incr, startcode, state, v;
2143

    
2144
 redo:
2145
    /* search next start code */
2146
    align_get_bits(&s->gb);
2147
    state = 0xff;
2148
    for(;;) {
2149
        v = get_bits(&s->gb, 8);
2150
        if (state == 0x000001) {
2151
            state = ((state << 8) | v) & 0xffffff;
2152
            startcode = state;
2153
            break;
2154
        }
2155
        state = ((state << 8) | v) & 0xffffff;
2156
        if( get_bits_count(&s->gb) > s->gb.size*8-32){
2157
            printf("no VOP startcode found\n");
2158
            return -1;
2159
        }
2160
    }
2161
//printf("startcode %X %d\n", startcode, get_bits_count(&s->gb));
2162
    if (startcode == 0x120) { // Video Object Layer
2163
        int width, height, vo_ver_id;
2164

    
2165
        /* vol header */
2166
        skip_bits(&s->gb, 1); /* random access */
2167
        skip_bits(&s->gb, 8); /* vo_type */
2168
        if (get_bits1(&s->gb) != 0) { /* is_ol_id */
2169
            vo_ver_id = get_bits(&s->gb, 4); /* vo_ver_id */
2170
            skip_bits(&s->gb, 3); /* vo_priority */
2171
        } else {
2172
            vo_ver_id = 1;
2173
        }
2174
        
2175
        s->aspect_ratio_info= get_bits(&s->gb, 4);
2176
        if(s->aspect_ratio_info == EXTENDET_PAR){
2177
            skip_bits(&s->gb, 8); //par_width
2178
            skip_bits(&s->gb, 8); // par_height
2179
        }
2180

    
2181
        if(get_bits1(&s->gb)){ /* vol control parameter */
2182
            printf("vol control parameter not supported\n");
2183
            return -1;   
2184
        }
2185
        s->shape = get_bits(&s->gb, 2); /* vol shape */
2186
        if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");
2187
        if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
2188
            printf("Gray shape not supported\n");
2189
            skip_bits(&s->gb, 4);  //video_object_layer_shape_extension
2190
        }
2191

    
2192
        skip_bits1(&s->gb);   /* marker */
2193
        
2194
        s->time_increment_resolution = get_bits(&s->gb, 16);
2195
        s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
2196
        if (s->time_increment_bits < 1)
2197
            s->time_increment_bits = 1;
2198
        skip_bits1(&s->gb);   /* marker */
2199

    
2200
        if (get_bits1(&s->gb) != 0) {   /* fixed_vop_rate  */
2201
            skip_bits(&s->gb, s->time_increment_bits);
2202
        }
2203

    
2204
        if (s->shape != BIN_ONLY_SHAPE) {
2205
            if (s->shape == RECT_SHAPE) {
2206
                skip_bits1(&s->gb);   /* marker */
2207
                width = get_bits(&s->gb, 13);
2208
                skip_bits1(&s->gb);   /* marker */
2209
                height = get_bits(&s->gb, 13);
2210
                skip_bits1(&s->gb);   /* marker */
2211
                if(width && height){ /* they should be non zero but who knows ... */
2212
                    s->width = width;
2213
                    s->height = height;
2214
//                    printf("%d %d\n", width, height);
2215
                }
2216
            }
2217
            
2218
            if(get_bits1(&s->gb)) printf("interlaced not supported\n");   /* interlaced */
2219
            if(!get_bits1(&s->gb)) printf("OBMC not supported\n");   /* OBMC Disable */
2220
            if (vo_ver_id == 1) {
2221
                s->vol_sprite_usage = get_bits1(&s->gb); /* vol_sprite_usage */
2222
            } else {
2223
                s->vol_sprite_usage = get_bits(&s->gb, 2); /* vol_sprite_usage */
2224
            }
2225
            if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");
2226
            if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
2227
                if(s->vol_sprite_usage==STATIC_SPRITE){
2228
                    s->sprite_width = get_bits(&s->gb, 13);
2229
                    skip_bits1(&s->gb); /* marker */
2230
                    s->sprite_height= get_bits(&s->gb, 13);
2231
                    skip_bits1(&s->gb); /* marker */
2232
                    s->sprite_left  = get_bits(&s->gb, 13);
2233
                    skip_bits1(&s->gb); /* marker */
2234
                    s->sprite_top   = get_bits(&s->gb, 13);
2235
                    skip_bits1(&s->gb); /* marker */
2236
                }
2237
                s->num_sprite_warping_points= get_bits(&s->gb, 6);
2238
                s->sprite_warping_accuracy = get_bits(&s->gb, 2);
2239
                s->sprite_brightness_change= get_bits1(&s->gb);
2240
                if(s->vol_sprite_usage==STATIC_SPRITE)
2241
                    s->low_latency_sprite= get_bits1(&s->gb);            
2242
            }
2243
            // FIXME sadct disable bit if verid!=1 && shape not rect
2244
            
2245
            if (get_bits1(&s->gb) == 1) {   /* not_8_bit */
2246
                s->quant_precision = get_bits(&s->gb, 4); /* quant_precision */
2247
                if(get_bits(&s->gb, 4)!=8) printf("N-bit not supported\n"); /* bits_per_pixel */
2248
            } else {
2249
                s->quant_precision = 5;
2250
            }
2251
            
2252
            // FIXME a bunch of grayscale shape things
2253
            if(get_bits1(&s->gb)) printf("Quant-Type not supported\n");  /* vol_quant_type */ //FIXME
2254
            if(vo_ver_id != 1)
2255
                 s->quarter_sample= get_bits1(&s->gb);
2256
            else s->quarter_sample=0;
2257

    
2258
            if(!get_bits1(&s->gb)) printf("Complexity estimation not supported\n");
2259
#if 0
2260
            if(get_bits1(&s->gb)) printf("resync disable\n");
2261
#else
2262
            skip_bits1(&s->gb);   /* resync_marker_disabled */
2263
#endif
2264
            s->data_partioning= get_bits1(&s->gb);
2265
            if(s->data_partioning){
2266
                printf("data partitioning not supported\n");
2267
                skip_bits1(&s->gb); // reversible vlc
2268
            }
2269
            
2270
            if(vo_ver_id != 1) {
2271
                s->new_pred= get_bits1(&s->gb);
2272
                if(s->new_pred){
2273
                    printf("new pred not supported\n");
2274
                    skip_bits(&s->gb, 2); /* requested upstream message type */
2275
                    skip_bits1(&s->gb); /* newpred segment type */
2276
                }
2277
                s->reduced_res_vop= get_bits1(&s->gb);
2278
                if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");
2279
            }
2280
            else{
2281
                s->new_pred=0;
2282
                s->reduced_res_vop= 0;
2283
            }
2284

    
2285
            s->scalability= get_bits1(&s->gb);
2286
            if (s->scalability) {
2287
                printf("scalability not supported\n");
2288
            }
2289
        }
2290
//printf("end Data %X %d\n", show_bits(&s->gb, 32), get_bits_count(&s->gb)&0x7);
2291
        goto redo;
2292
    } else if (startcode == 0x1b2) { //userdata
2293
        char buf[256];
2294
        int i;
2295
        int e;
2296
        int ver, build;
2297

    
2298
//printf("user Data %X\n", show_bits(&s->gb, 32));
2299
        buf[0]= show_bits(&s->gb, 8);
2300
        for(i=1; i<256; i++){
2301
            buf[i]= show_bits(&s->gb, 16)&0xFF;
2302
            if(buf[i]==0) break;
2303
            skip_bits(&s->gb, 8);
2304
        }
2305
        buf[255]=0;
2306
        e=sscanf(buf, "DivX%dBuild%d", &ver, &build);
2307
        if(e==2){
2308
            s->divx_version= ver;
2309
            s->divx_build= build;
2310
            if(s->picture_number==0){
2311
                printf("This file was encoded with DivX%d Build%d\n", ver, build);
2312
                if(ver==500 && build==413){ //most likely all version are indeed totally buggy but i dunno for sure ...
2313
                    printf("WARNING: this version of DivX is not MPEG4 compatible, trying to workaround these bugs...\n");
2314
                }else{
2315
                    printf("hmm, i havnt seen that version of divx yet, lets assume they fixed these bugs ...\n"
2316
                           "using mpeg4 decoder, if it fails contact the developers (of ffmpeg)\n");
2317
                }
2318
            }
2319
        }
2320
//printf("User Data: %s\n", buf);
2321
        goto redo;
2322
    } else if (startcode != 0x1b6) { //VOP
2323
        goto redo;
2324
    }
2325

    
2326
    s->pict_type = get_bits(&s->gb, 2) + 1;        /* pict type: I = 0 , P = 1 */
2327
//printf("pic: %d\n", s->pict_type); 
2328
    time_incr=0;
2329
    while (get_bits1(&s->gb) != 0) 
2330
        time_incr++;
2331

    
2332
    check_marker(&s->gb, "before time_increment");
2333
    s->time_increment= get_bits(&s->gb, s->time_increment_bits);
2334
    if(s->pict_type!=B_TYPE){
2335
        s->time_base+= time_incr;
2336
        s->last_non_b_time[1]= s->last_non_b_time[0];
2337
        s->last_non_b_time[0]= s->time_base*s->time_increment_resolution + s->time_increment;
2338
    }else{
2339
        s->time= (s->last_non_b_time[1]/s->time_increment_resolution + time_incr)*s->time_increment_resolution;
2340
        s->time+= s->time_increment;
2341
    }
2342

    
2343
    if(check_marker(&s->gb, "before vop_coded")==0 && s->picture_number==0){
2344
        printf("hmm, seems the headers arnt complete, trying to guess time_increment_bits\n");
2345
        for(s->time_increment_bits++ ;s->time_increment_bits<16; s->time_increment_bits++){
2346
            if(get_bits1(&s->gb)) break;
2347
        }
2348
        printf("my guess is %d bits ;)\n",s->time_increment_bits);
2349
    }
2350
    /* vop coded */
2351
    if (get_bits1(&s->gb) != 1)
2352
        goto redo;
2353
//printf("time %d %d %d || %d %d %d\n", s->time_increment_bits, s->time_increment, s->time_base,
2354
//s->time, s->last_non_b_time[0], s->last_non_b_time[1]);  
2355
    if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == P_TYPE
2356
                          || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {
2357
        /* rounding type for motion estimation */
2358
        s->no_rounding = get_bits1(&s->gb);
2359
    } else {
2360
        s->no_rounding = 0;
2361
    }
2362
//FIXME reduced res stuff
2363

    
2364
     if (s->shape != RECT_SHAPE) {
2365
         if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {
2366
             int width, height, hor_spat_ref, ver_spat_ref;
2367
 
2368
             width = get_bits(&s->gb, 13);
2369
             skip_bits1(&s->gb);   /* marker */
2370
             height = get_bits(&s->gb, 13);
2371
             skip_bits1(&s->gb);   /* marker */
2372
             hor_spat_ref = get_bits(&s->gb, 13); /* hor_spat_ref */
2373
             skip_bits1(&s->gb);   /* marker */
2374
             ver_spat_ref = get_bits(&s->gb, 13); /* ver_spat_ref */
2375
         }
2376
         skip_bits1(&s->gb); /* change_CR_disable */
2377
 
2378
         if (get_bits1(&s->gb) != 0) {
2379
             skip_bits(&s->gb, 8); /* constant_alpha_value */
2380
         }
2381
     }
2382
//FIXME complexity estimation stuff
2383
     
2384
     if (s->shape != BIN_ONLY_SHAPE) {
2385
         skip_bits(&s->gb, 3); /* intra dc VLC threshold */
2386
         //FIXME interlaced specific bits
2387
     }
2388

    
2389
     if(s->pict_type == S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){
2390
         if(s->num_sprite_warping_points){
2391
             mpeg4_decode_sprite_trajectory(s);
2392
         }
2393
         if(s->sprite_brightness_change) printf("sprite_brightness_change not supported\n");
2394
         if(s->vol_sprite_usage==STATIC_SPRITE) printf("static sprite not supported\n");
2395
     }
2396

    
2397
     if (s->shape != BIN_ONLY_SHAPE) {
2398
         /* note: we do not use quant_precision to avoid problem if no
2399
            MPEG4 vol header as it is found on some old opendivx
2400
            movies */
2401
         s->qscale = get_bits(&s->gb, 5);
2402
         if(s->qscale==0){
2403
             printf("Error, header damaged or not MPEG4 header (qscale=0)\n");
2404
             return -1; // makes no sense to continue, as there is nothing left from the image then
2405
         }
2406
  
2407
         if (s->pict_type != I_TYPE) {
2408
             s->f_code = get_bits(&s->gb, 3);        /* fcode_for */
2409
             if(s->f_code==0){
2410
                 printf("Error, header damaged or not MPEG4 header (f_code=0)\n");
2411
                 return -1; // makes no sense to continue, as the MV decoding will break very quickly
2412
             }
2413
         }
2414
         if (s->pict_type == B_TYPE) {
2415
             s->b_code = get_bits(&s->gb, 3);
2416
//printf("b-code %d\n", s->b_code);
2417
         }
2418
//printf("quant:%d fcode:%d\n", s->qscale, s->f_code);
2419
         if(!s->scalability){
2420
             if (s->shape!=RECT_SHAPE && s->pict_type!=I_TYPE) {
2421
                 skip_bits1(&s->gb); // vop shape coding type
2422
             }
2423
         }
2424
     }
2425
     s->picture_number++; // better than pic number==0 allways ;)
2426
     return 0;
2427
}
2428

    
2429
/* don't understand why they choose a different header ! */
2430
int intel_h263_decode_picture_header(MpegEncContext *s)
2431
{
2432
    int format;
2433

    
2434
    /* picture header */
2435
    if (get_bits(&s->gb, 22) != 0x20)
2436
        return -1;
2437
    skip_bits(&s->gb, 8); /* picture timestamp */
2438

    
2439
    if (get_bits1(&s->gb) != 1)
2440
        return -1;        /* marker */
2441
    if (get_bits1(&s->gb) != 0)
2442
        return -1;        /* h263 id */
2443
    skip_bits1(&s->gb);        /* split screen off */
2444
    skip_bits1(&s->gb);        /* camera  off */
2445
    skip_bits1(&s->gb);        /* freeze picture release off */
2446

    
2447
    format = get_bits(&s->gb, 3);
2448
    if (format != 7)
2449
        return -1;
2450

    
2451
    s->h263_plus = 0;
2452

    
2453
    s->pict_type = I_TYPE + get_bits1(&s->gb);
2454
    
2455
    s->unrestricted_mv = get_bits1(&s->gb); 
2456
    s->h263_long_vectors = s->unrestricted_mv;
2457

    
2458
    if (get_bits1(&s->gb) != 0)
2459
        return -1;        /* SAC: off */
2460
    if (get_bits1(&s->gb) != 0)
2461
        return -1;        /* advanced prediction mode: off */
2462
    if (get_bits1(&s->gb) != 0)
2463
        return -1;        /* not PB frame */
2464

    
2465
    /* skip unknown header garbage */
2466
    skip_bits(&s->gb, 41);
2467

    
2468
    s->qscale = get_bits(&s->gb, 5);
2469
    skip_bits1(&s->gb);        /* Continuous Presence Multipoint mode: off */
2470

    
2471
    /* PEI */
2472
    while (get_bits1(&s->gb) != 0) {
2473
        skip_bits(&s->gb, 8);
2474
    }
2475
    s->f_code = 1;
2476
    return 0;
2477
}
2478