fixing motion estimation with h263p hopefully
[ffmpeg.git] / libavcodec / h263.c
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 static UINT8 umv_fcode_tab[MAX_MV*2+1];
55
56 int h263_get_picture_format(int width, int height)
57 {
58     int format;
59
60     if (width == 128 && height == 96)
61         format = 1;
62     else if (width == 176 && height == 144)
63         format = 2;
64     else if (width == 352 && height == 288)
65         format = 3;
66     else if (width == 704 && height == 576)
67         format = 4;
68     else if (width == 1408 && height == 1152)
69         format = 5;
70     else
71         format = 7;
72     return format;
73 }
74
75 void h263_encode_picture_header(MpegEncContext * s, int picture_number)
76 {
77     int format;
78
79     align_put_bits(&s->pb);
80
81     /* Update the pointer to last GOB */
82     s->ptr_lastgob = pbBufPtr(&s->pb);
83     s->gob_number = 0;
84
85     put_bits(&s->pb, 22, 0x20); /* PSC */
86     put_bits(&s->pb, 8, (((INT64)s->picture_number * 30 * FRAME_RATE_BASE) / 
87                          s->frame_rate) & 0xff);
88
89     put_bits(&s->pb, 1, 1);     /* marker */
90     put_bits(&s->pb, 1, 0);     /* h263 id */
91     put_bits(&s->pb, 1, 0);     /* split screen off */
92     put_bits(&s->pb, 1, 0);     /* camera  off */
93     put_bits(&s->pb, 1, 0);     /* freeze picture release off */
94     
95     format = h263_get_picture_format(s->width, s->height);
96     if (!s->h263_plus) {
97         /* H.263v1 */
98         put_bits(&s->pb, 3, format);
99         put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
100         /* By now UMV IS DISABLED ON H.263v1, since the restrictions
101         of H.263v1 UMV implies to check the predicted MV after
102         calculation of the current MB to see if we're on the limits */
103         put_bits(&s->pb, 1, 0); /* unrestricted motion vector: off */
104         put_bits(&s->pb, 1, 0); /* SAC: off */
105         put_bits(&s->pb, 1, 0); /* advanced prediction mode: off */
106         put_bits(&s->pb, 1, 0); /* not PB frame */
107         put_bits(&s->pb, 5, s->qscale);
108         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
109     } else {
110         /* H.263v2 */
111         /* H.263 Plus PTYPE */
112         put_bits(&s->pb, 3, 7);
113         put_bits(&s->pb,3,1); /* Update Full Extended PTYPE */
114         if (format == 7)
115             put_bits(&s->pb,3,6); /* Custom Source Format */
116         else
117             put_bits(&s->pb, 3, format);
118             
119         put_bits(&s->pb,1,0); /* Custom PCF: off */
120         s->umvplus = (s->pict_type == P_TYPE) && s->unrestricted_mv;
121         put_bits(&s->pb, 1, s->umvplus); /* Unrestricted Motion Vector */
122         put_bits(&s->pb,1,0); /* SAC: off */
123         put_bits(&s->pb,1,0); /* Advanced Prediction Mode: off */
124         put_bits(&s->pb,1,0); /* Advanced Intra Coding: off */
125         put_bits(&s->pb,1,0); /* Deblocking Filter: off */
126         put_bits(&s->pb,1,0); /* Slice Structured: off */
127         put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
128         put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
129         put_bits(&s->pb,1,0); /* Alternative Inter VLC: off */
130         put_bits(&s->pb,1,0); /* Modified Quantization: off */
131         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
132         put_bits(&s->pb,3,0); /* Reserved */
133                 
134         put_bits(&s->pb, 3, s->pict_type == P_TYPE);
135                 
136         put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
137         put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
138         put_bits(&s->pb,1,0); /* Rounding Type */
139         put_bits(&s->pb,2,0); /* Reserved */
140         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
141                 
142         /* This should be here if PLUSPTYPE */
143         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
144                 
145                 if (format == 7) {
146             /* Custom Picture Format (CPFMT) */
147                 
148             put_bits(&s->pb,4,2); /* Aspect ratio: CIF 12:11 (4:3) picture */
149             put_bits(&s->pb,9,(s->width >> 2) - 1);
150             put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
151             put_bits(&s->pb,9,(s->height >> 2));
152         }
153         
154         /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
155         if (s->umvplus)
156             put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
157         put_bits(&s->pb, 5, s->qscale);
158     }
159
160     put_bits(&s->pb, 1, 0);     /* no PEI */
161 }
162
163 int h263_encode_gob_header(MpegEncContext * s, int mb_line)
164 {
165     int pdif=0;
166     
167     /* Check to see if we need to put a new GBSC */
168     /* for RTP packetization                    */
169     if (s->rtp_mode) {
170         pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
171         if (pdif >= s->rtp_payload_size) {
172             /* Bad luck, packet must be cut before */
173             align_put_bits(&s->pb);
174             flush_put_bits(&s->pb);
175             /* Call the RTP callback to send the last GOB */
176             if (s->rtp_callback) {
177                 pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
178                 s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
179             }
180             s->ptr_lastgob = pbBufPtr(&s->pb);
181             put_bits(&s->pb, 17, 1); /* GBSC */
182             s->gob_number = mb_line / s->gob_index;
183             put_bits(&s->pb, 5, s->gob_number); /* GN */
184             put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
185             put_bits(&s->pb, 5, s->qscale); /* GQUANT */
186             //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
187             return pdif;
188        } else if (pdif + s->mb_line_avgsize >= s->rtp_payload_size) {
189            /* Cut the packet before we can't */
190            align_put_bits(&s->pb);
191            flush_put_bits(&s->pb);
192            /* Call the RTP callback to send the last GOB */
193            if (s->rtp_callback) {
194                pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
195                s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
196            }
197            s->ptr_lastgob = pbBufPtr(&s->pb);
198            put_bits(&s->pb, 17, 1); /* GBSC */
199            s->gob_number = mb_line / s->gob_index;
200            put_bits(&s->pb, 5, s->gob_number); /* GN */
201            put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
202            put_bits(&s->pb, 5, s->qscale); /* GQUANT */
203            //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
204            return pdif;
205        }
206    }
207    return 0;
208 }
209
210 static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6])
211 {
212     int score0=0, score1=0;
213     int i, n;
214
215     for(n=0; n<6; n++){
216         INT16 *ac_val, *ac_val1;
217
218         ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
219         ac_val1= ac_val;
220         if(dir[n]){
221             ac_val-= s->block_wrap[n]*16;
222             for(i=1; i<8; i++){
223                 const int level= block[n][block_permute_op(i   )];
224                 score0+= ABS(level);
225                 score1+= ABS(level - ac_val[i+8]);
226                 ac_val1[i  ]=    block[n][block_permute_op(i<<3)];
227                 ac_val1[i+8]= level;
228             }
229         }else{
230             ac_val-= 16;
231             for(i=1; i<8; i++){
232                 const int level= block[n][block_permute_op(i<<3)];
233                 score0+= ABS(level);
234                 score1+= ABS(level - ac_val[i]);
235                 ac_val1[i  ]= level;
236                 ac_val1[i+8]=    block[n][block_permute_op(i   )];
237             }
238         }
239     }
240
241     return score0 > score1 ? 1 : 0;    
242 }
243
244 void mpeg4_encode_mb(MpegEncContext * s,
245                     DCTELEM block[6][64],
246                     int motion_x, int motion_y)
247 {
248     int cbpc, cbpy, i, cbp, pred_x, pred_y;
249     int bits;
250     
251     //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
252     if (!s->mb_intra) {
253         /* compute cbp */
254         cbp = 0;
255         for (i = 0; i < 6; i++) {
256         if (s->block_last_index[i] >= 0)
257             cbp |= 1 << (5 - i);
258         }
259         if ((cbp | motion_x | motion_y) == 0) {
260             /* skip macroblock */
261             put_bits(&s->pb, 1, 1);
262             s->misc_bits++;
263             s->last_bits++;
264             s->skip_count++;
265             return;
266         }
267         put_bits(&s->pb, 1, 0); /* mb coded */
268         cbpc = cbp & 3;
269         put_bits(&s->pb,
270                 inter_MCBPC_bits[cbpc],
271                 inter_MCBPC_code[cbpc]);
272         cbpy = cbp >> 2;
273         cbpy ^= 0xf;
274         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
275             
276         bits= get_bit_count(&s->pb);
277         s->misc_bits+= bits - s->last_bits;
278         s->last_bits=bits;
279
280         /* motion vectors: 16x16 mode only now */
281         h263_pred_motion(s, 0, &pred_x, &pred_y);
282       
283         h263_encode_motion(s, motion_x - pred_x);
284         h263_encode_motion(s, motion_y - pred_y);
285
286         bits= get_bit_count(&s->pb);
287         s->mv_bits+= bits - s->last_bits;
288         s->last_bits=bits;
289
290         /* encode each block */
291         for (i = 0; i < 6; i++) {
292             mpeg4_encode_block(s, block[i], i, 0, zigzag_direct);
293         }
294         bits= get_bit_count(&s->pb);
295         s->p_tex_bits+= bits - s->last_bits;
296         s->last_bits=bits;
297         s->p_count++;
298     } else {
299         int dc_diff[6];   //dc values with the dc prediction subtracted 
300         int dir[6];  //prediction direction
301         int zigzag_last_index[6];
302         UINT8 *scan_table[6];
303
304         for(i=0; i<6; i++){
305             const int level= block[i][0];
306             UINT16 *dc_ptr;
307
308             dc_diff[i]= level - mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
309             if (i < 4) {
310                 *dc_ptr = level * s->y_dc_scale;
311             } else {
312                 *dc_ptr = level * s->c_dc_scale;
313             }
314         }
315
316         s->ac_pred= decide_ac_pred(s, block, dir);
317
318         if(s->ac_pred){
319             for(i=0; i<6; i++){
320                 UINT8 *st;
321                 int last_index;
322
323                 mpeg4_inv_pred_ac(s, block[i], i, dir[i]);
324                 if (dir[i]==0) st = ff_alternate_vertical_scan; /* left */
325                 else           st = ff_alternate_horizontal_scan; /* top */
326
327                 for(last_index=63; last_index>=0; last_index--) //FIXME optimize
328                     if(block[i][st[last_index]]) break;
329                 zigzag_last_index[i]= s->block_last_index[i];
330                 s->block_last_index[i]= last_index;
331                 scan_table[i]= st;
332             }
333         }else{
334             for(i=0; i<6; i++)
335                 scan_table[i]= zigzag_direct;
336         }
337
338         /* compute cbp */
339         cbp = 0;
340         for (i = 0; i < 6; i++) {
341             if (s->block_last_index[i] >= 1)
342                 cbp |= 1 << (5 - i);
343         }
344
345         cbpc = cbp & 3;
346         if (s->pict_type == I_TYPE) {
347             put_bits(&s->pb,
348                 intra_MCBPC_bits[cbpc],
349                 intra_MCBPC_code[cbpc]);
350         } else {
351             put_bits(&s->pb, 1, 0);     /* mb coded */
352             put_bits(&s->pb,
353                 inter_MCBPC_bits[cbpc + 4],
354                 inter_MCBPC_code[cbpc + 4]);
355         }
356         put_bits(&s->pb, 1, s->ac_pred);
357         cbpy = cbp >> 2;
358         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
359
360         bits= get_bit_count(&s->pb);
361         s->misc_bits+= bits - s->last_bits;
362         s->last_bits=bits;
363
364         /* encode each block */
365         for (i = 0; i < 6; i++) {
366             mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i]);
367         }
368
369         bits= get_bit_count(&s->pb);
370         s->i_tex_bits+= bits - s->last_bits;
371         s->last_bits=bits;
372         s->i_count++;
373
374         /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
375         if(s->ac_pred){
376             for(i=0; i<6; i++){
377                 int j;    
378                 INT16 *ac_val;
379
380                 ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
381
382                 if(dir[i]){
383                     for(j=1; j<8; j++) 
384                         block[i][block_permute_op(j   )]= ac_val[j+8];
385                 }else{
386                     for(j=1; j<8; j++) 
387                         block[i][block_permute_op(j<<3)]= ac_val[j  ];
388                 }
389                 s->block_last_index[i]= zigzag_last_index[i];
390             }
391         }
392     }
393 }
394
395 void h263_encode_mb(MpegEncContext * s,
396                     DCTELEM block[6][64],
397                     int motion_x, int motion_y)
398 {
399     int cbpc, cbpy, i, cbp, pred_x, pred_y;
400    
401     //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
402    if (!s->mb_intra) {
403            /* compute cbp */
404            cbp = 0;
405            for (i = 0; i < 6; i++) {
406               if (s->block_last_index[i] >= 0)
407                    cbp |= 1 << (5 - i);
408            }
409            if ((cbp | motion_x | motion_y) == 0) {
410               /* skip macroblock */
411               put_bits(&s->pb, 1, 1);
412               return;
413            }
414            put_bits(&s->pb, 1, 0);      /* mb coded */
415            cbpc = cbp & 3;
416            put_bits(&s->pb,
417                 inter_MCBPC_bits[cbpc],
418                 inter_MCBPC_code[cbpc]);
419            cbpy = cbp >> 2;
420            cbpy ^= 0xf;
421            put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
422
423            /* motion vectors: 16x16 mode only now */
424       h263_pred_motion(s, 0, &pred_x, &pred_y);
425       
426       if (!s->umvplus) {  
427          h263_encode_motion(s, motion_x - pred_x);
428          h263_encode_motion(s, motion_y - pred_y);
429       }
430       else {
431          h263p_encode_umotion(s, motion_x - pred_x);
432          h263p_encode_umotion(s, motion_y - pred_y);
433          if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
434             /* To prevent Start Code emulation */
435             put_bits(&s->pb,1,1);
436       }
437    } else {
438         /* compute cbp */
439         cbp = 0;
440         for (i = 0; i < 6; i++) {
441             if (s->block_last_index[i] >= 1)
442                 cbp |= 1 << (5 - i);
443         }
444
445         cbpc = cbp & 3;
446         if (s->pict_type == I_TYPE) {
447             put_bits(&s->pb,
448                      intra_MCBPC_bits[cbpc],
449                      intra_MCBPC_code[cbpc]);
450         } else {
451             put_bits(&s->pb, 1, 0);     /* mb coded */
452             put_bits(&s->pb,
453                      inter_MCBPC_bits[cbpc + 4],
454                      inter_MCBPC_code[cbpc + 4]);
455         }
456         if (s->h263_pred) {
457             /* XXX: currently, we do not try to use ac prediction */
458             put_bits(&s->pb, 1, 0);     /* no ac prediction */
459         }
460         cbpy = cbp >> 2;
461         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
462     }
463
464     /* encode each block */
465     if (s->h263_pred) {
466         for (i = 0; i < 6; i++) {
467 //          mpeg4_encode_block(s, block[i], i);
468         }
469     } else {
470         for (i = 0; i < 6; i++) {
471             h263_encode_block(s, block[i], i);
472         }
473     }
474 }
475
476 void h263_pred_acdc(MpegEncContext * s, INT16 *block, int n)
477 {
478     int x, y, wrap, a, c, pred_dc, scale, i;
479     INT16 *dc_val, *ac_val, *ac_val1;
480
481     /* find prediction */
482     if (n < 4) {
483         x = 2 * s->mb_x + 1 + (n & 1);
484         y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
485         wrap = s->mb_width * 2 + 2;
486         dc_val = s->dc_val[0];
487         ac_val = s->ac_val[0][0];
488         scale = s->y_dc_scale;
489     } else {
490         x = s->mb_x + 1;
491         y = s->mb_y + 1;
492         wrap = s->mb_width + 2;
493         dc_val = s->dc_val[n - 4 + 1];
494         ac_val = s->ac_val[n - 4 + 1][0];
495         scale = s->c_dc_scale;
496     }
497     
498     ac_val += ((y) * wrap + (x)) * 16;
499     ac_val1 = ac_val;
500     
501     /* B C
502      * A X 
503      */
504     a = dc_val[(x - 1) + (y) * wrap];
505     c = dc_val[(x) + (y - 1) * wrap];
506     
507     pred_dc = 1024;
508     if (s->ac_pred) {
509         if (s->h263_aic_dir) {
510             /* left prediction */
511             if (a != 1024) {
512                 ac_val -= 16;
513                 for(i=1;i<8;i++) {
514                     block[block_permute_op(i*8)] += ac_val[i];
515                 }
516                 pred_dc = a;
517             }
518         } else {
519             /* top prediction */
520             if (c != 1024) {
521                 ac_val -= 16 * wrap;
522                 for(i=1;i<8;i++) {
523                     block[block_permute_op(i)] += ac_val[i + 8];
524                 }
525                 pred_dc = c;
526             }
527         }
528     } else {
529         /* just DC prediction */
530         if (a != 1024 && c != 1024)
531             pred_dc = (a + c) >> 1;
532         else if (a != 1024)
533             pred_dc = a;
534         else
535             pred_dc = c;
536     }
537     
538     /* we assume pred is positive */
539     block[0]=block[0]*scale + pred_dc;
540     
541     if (block[0] < 0)
542         block[0] = 0;
543     else if (!(block[0] & 1))
544         block[0]++;
545     
546     /* Update AC/DC tables */
547     dc_val[(x) + (y) * wrap] = block[0];
548     
549     /* left copy */
550     for(i=1;i<8;i++)
551         ac_val1[i] = block[block_permute_op(i * 8)];
552     /* top copy */
553     for(i=1;i<8;i++)
554         ac_val1[8 + i] = block[block_permute_op(i)];
555 }
556
557 INT16 *h263_pred_motion(MpegEncContext * s, int block, 
558                         int *px, int *py)
559 {
560     int xy, wrap;
561     INT16 *A, *B, *C, *mot_val;
562     static const int off[4]= {2, 1, 1, -1};
563
564     wrap = s->block_wrap[0];
565     xy = s->block_index[block];
566
567     mot_val = s->motion_val[xy];
568
569     /* special case for first line */
570     if ((s->mb_y == 0 || s->first_slice_line || s->first_gob_line) && block<2) {
571         A = s->motion_val[xy - 1];
572         *px = A[0];
573         *py = A[1];
574     } else {
575         A = s->motion_val[xy - 1];
576         B = s->motion_val[xy - wrap];
577         C = s->motion_val[xy + off[block] - wrap];
578         *px = mid_pred(A[0], B[0], C[0]);
579         *py = mid_pred(A[1], B[1], C[1]);
580     }
581     return mot_val;
582 }
583
584 static void h263_encode_motion(MpegEncContext * s, int val)
585 {
586     int range, l, m, bit_size, sign, code, bits;
587
588     if (val == 0) {
589         /* zero vector */
590         code = 0;
591         put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
592     } else {
593         bit_size = s->f_code - 1;
594         range = 1 << bit_size;
595         /* modulo encoding */
596         l = range * 32;
597         m = 2 * l;
598         if (val < -l) {
599             val += m;
600         } else if (val >= l) {
601             val -= m;
602         }
603
604         if (val >= 0) {
605             val--;
606             code = (val >> bit_size) + 1;
607             bits = val & (range - 1);
608             sign = 0;
609         } else {
610             val = -val;
611             val--;
612             code = (val >> bit_size) + 1;
613             bits = val & (range - 1);
614             sign = 1;
615         }
616
617         put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
618         if (bit_size > 0) {
619             put_bits(&s->pb, bit_size, bits);
620         }
621     }
622 }
623
624 /* Encode MV differences on H.263+ with Unrestricted MV mode */
625 static void h263p_encode_umotion(MpegEncContext * s, int val)
626 {
627     short sval = 0; 
628     short i = 0;
629     short n_bits = 0;
630     short temp_val;
631     int code = 0;
632     int tcode;
633     
634     if ( val == 0)
635         put_bits(&s->pb, 1, 1);
636     else if (val == 1)
637         put_bits(&s->pb, 3, 0);
638     else if (val == -1)
639         put_bits(&s->pb, 3, 2);
640     else {
641         
642         sval = ((val < 0) ? (short)(-val):(short)val);
643         temp_val = sval;
644         
645         while (temp_val != 0) {
646             temp_val = temp_val >> 1;
647             n_bits++;
648         }
649         
650         i = n_bits - 1;
651         while (i > 0) {
652             tcode = (sval & (1 << (i-1))) >> (i-1);
653             tcode = (tcode << 1) | 1;
654             code = (code << 2) | tcode;
655             i--;
656         }
657         code = ((code << 1) | (val < 0)) << 1;
658         put_bits(&s->pb, (2*n_bits)+1, code);
659         //printf("\nVal = %d\tCode = %d", sval, code);
660     }
661 }
662
663 static void init_mv_penalty_and_fcode(MpegEncContext *s)
664 {
665     int f_code;
666     int mv;
667     for(f_code=1; f_code<=MAX_FCODE; f_code++){
668         for(mv=-MAX_MV; mv<=MAX_MV; mv++){
669             int len;
670
671             if(mv==0) len= mvtab[0][1];
672             else{
673                 int val, bit_size, range, code;
674
675                 bit_size = s->f_code - 1;
676                 range = 1 << bit_size;
677
678                 val=mv;
679                 if (val < 0) 
680                     val = -val;
681                 val--;
682                 code = (val >> bit_size) + 1;
683                 if(code<33){
684                     len= mvtab[code][1] + 1 + bit_size;
685                 }else{
686                     len= mvtab[32][1] + 2 + bit_size;
687                 }
688             }
689
690             mv_penalty[f_code][mv+MAX_MV]= len;
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     for(mv=0; mv<MAX_MV*2+1; mv++){
701         umv_fcode_tab[mv]= 1;
702     }
703 }
704
705 void h263_encode_init(MpegEncContext *s)
706 {
707     static int done = 0;
708
709     if (!done) {
710         done = 1;
711         init_rl(&rl_inter);
712         init_rl(&rl_intra);
713
714         init_mv_penalty_and_fcode(s);
715     }
716     s->mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
717     
718     // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
719     if(s->h263_plus)      s->fcode_tab= umv_fcode_tab;
720     else if(s->h263_pred) s->fcode_tab= fcode_tab;
721 }
722
723 static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
724 {
725     int level, run, last, i, j, last_index, last_non_zero, sign, slevel;
726     int code;
727     RLTable *rl = &rl_inter;
728
729     if (s->mb_intra) {
730         /* DC coef */
731             level = block[0];
732         /* 255 cannot be represented, so we clamp */
733         if (level > 254) {
734             level = 254;
735             block[0] = 254;
736         }
737         /* 0 cannot be represented also */
738         else if (!level) {
739             level = 1;
740             block[0] = 1;
741         }
742             if (level == 128)
743                 put_bits(&s->pb, 8, 0xff);
744             else
745                 put_bits(&s->pb, 8, level & 0xff);
746             i = 1;
747     } else {
748             i = 0;
749     }
750
751     /* AC coefs */
752     last_index = s->block_last_index[n];
753     last_non_zero = i - 1;
754     for (; i <= last_index; i++) {
755         j = zigzag_direct[i];
756         level = block[j];
757         if (level) {
758             run = i - last_non_zero - 1;
759             last = (i == last_index);
760             sign = 0;
761             slevel = level;
762             if (level < 0) {
763                 sign = 1;
764                 level = -level;
765             }
766             code = get_rl_index(rl, last, run, level);
767             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
768             if (code == rl->n) {
769                 put_bits(&s->pb, 1, last);
770                 put_bits(&s->pb, 6, run);
771                 put_bits(&s->pb, 8, slevel & 0xff);
772             } else {
773                 put_bits(&s->pb, 1, sign);
774             }
775             last_non_zero = i;
776         }
777     }
778 }
779
780 /***************************************************/
781
782 static void mpeg4_stuffing(PutBitContext * pbc)
783 {
784     int length;
785     put_bits(pbc, 1, 0);
786     length= (-get_bit_count(pbc))&7;
787     put_bits(pbc, length, (1<<length)-1);
788 }
789
790 static void put_string(PutBitContext * pbc, char *s)
791 {
792     while(*s){
793         put_bits(pbc, 8, *s);
794         s++;
795     }
796     put_bits(pbc, 8, 0);
797 }
798
799 static void mpeg4_encode_vol_header(MpegEncContext * s)
800 {
801     int vo_ver_id=1; //must be 2 if we want GMC or q-pel
802
803     if(get_bit_count(&s->pb)!=0) mpeg4_stuffing(&s->pb);
804     put_bits(&s->pb, 16, 0);
805     put_bits(&s->pb, 16, 0x100);        /* video obj */
806     put_bits(&s->pb, 16, 0);
807     put_bits(&s->pb, 16, 0x120);        /* video obj layer */
808
809     put_bits(&s->pb, 1, 0);             /* random access vol */
810     put_bits(&s->pb, 8, 1);             /* video obj type indication= simple obj */
811     put_bits(&s->pb, 1, 1);             /* is obj layer id= yes */
812       put_bits(&s->pb, 4, vo_ver_id);   /* is obj layer ver id */
813       put_bits(&s->pb, 3, 1);           /* is obj layer priority */
814     if(s->aspect_ratio_info) 
815         put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
816     else
817         put_bits(&s->pb, 4, 1);         /* aspect ratio info= sqare pixel */
818     put_bits(&s->pb, 1, 0);             /* vol control parameters= no */
819     put_bits(&s->pb, 2, RECT_SHAPE);    /* vol shape= rectangle */
820     put_bits(&s->pb, 1, 1);             /* marker bit */
821     put_bits(&s->pb, 16, s->time_increment_resolution=30000);
822     s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
823     if (s->time_increment_bits < 1)
824         s->time_increment_bits = 1;
825     put_bits(&s->pb, 1, 1);             /* marker bit */
826     put_bits(&s->pb, 1, 0);             /* fixed vop rate=no */
827     put_bits(&s->pb, 1, 1);             /* marker bit */
828     put_bits(&s->pb, 13, s->width);     /* vol width */
829     put_bits(&s->pb, 1, 1);             /* marker bit */
830     put_bits(&s->pb, 13, s->height);    /* vol height */
831     put_bits(&s->pb, 1, 1);             /* marker bit */
832     put_bits(&s->pb, 1, 0);             /* interlace */
833     put_bits(&s->pb, 1, 1);             /* obmc disable */
834     if (vo_ver_id == 1) {
835         put_bits(&s->pb, 1, s->vol_sprite_usage=0);             /* sprite enable */
836     }else{ /* vo_ver_id == 2 */
837         put_bits(&s->pb, 2, s->vol_sprite_usage=0);             /* sprite enable */
838     }
839     put_bits(&s->pb, 1, 0);             /* not 8 bit */
840     put_bits(&s->pb, 1, 0);             /* quant type= h263 style*/
841     if (vo_ver_id != 1)
842         put_bits(&s->pb, 1, s->quarter_sample=0);
843     put_bits(&s->pb, 1, 1);             /* complexity estimation disable */
844     put_bits(&s->pb, 1, 1);             /* resync marker disable */
845     put_bits(&s->pb, 1, 0);             /* data partitioned */
846     if (vo_ver_id != 1){
847         put_bits(&s->pb, 1, 0);         /* newpred */
848         put_bits(&s->pb, 1, 0);         /* reduced res vop */
849     }
850     put_bits(&s->pb, 1, 0);             /* scalability */
851
852     mpeg4_stuffing(&s->pb);
853     put_bits(&s->pb, 16, 0);
854     put_bits(&s->pb, 16, 0x1B2);        /* user_data */
855     put_string(&s->pb, "ffmpeg"); //FIXME append some version ...
856
857     s->no_rounding = 0;
858 }
859
860 /* write mpeg4 VOP header */
861 void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
862 {
863     if(s->pict_type==I_TYPE) mpeg4_encode_vol_header(s);
864
865     if(get_bit_count(&s->pb)!=0) mpeg4_stuffing(&s->pb);
866     put_bits(&s->pb, 16, 0);            /* vop header */
867     put_bits(&s->pb, 16, 0x1B6);        /* vop header */
868     put_bits(&s->pb, 2, s->pict_type - 1);      /* pict type: I = 0 , P = 1 */
869     /* XXX: time base + 1 not always correct */
870     put_bits(&s->pb, 1, 1);
871     put_bits(&s->pb, 1, 0);
872
873     put_bits(&s->pb, 1, 1);     /* marker */
874     put_bits(&s->pb, s->time_increment_bits, 1);        /* XXX: correct time increment */
875     put_bits(&s->pb, 1, 1);     /* marker */
876     put_bits(&s->pb, 1, 1);     /* vop coded */
877     if (    s->pict_type == P_TYPE 
878         || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
879         s->no_rounding ^= 1;
880         put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */
881     }
882     put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */
883     //FIXME sprite stuff
884
885     put_bits(&s->pb, 5, s->qscale);
886
887     if (s->pict_type != I_TYPE)
888         put_bits(&s->pb, 3, s->f_code); /* fcode_for */
889     if (s->pict_type == B_TYPE)
890         put_bits(&s->pb, 3, s->b_code); /* fcode_back */
891     //    printf("****frame %d\n", picture_number);
892 }
893
894 void h263_dc_scale(MpegEncContext * s)
895 {
896 #if 1
897     const static UINT8 y_tab[32]={
898     //  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
899         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
900     };
901     const static UINT8 c_tab[32]={
902     //  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
903         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
904     };
905     s->y_dc_scale = y_tab[s->qscale];
906     s->c_dc_scale = c_tab[s->qscale];
907 #else
908     int quant;
909     quant = s->qscale;
910     /* luminance */
911     if (quant < 5)
912         s->y_dc_scale = 8;
913     else if (quant > 4 && quant < 9)
914         s->y_dc_scale = (2 * quant);
915     else if (quant > 8 && quant < 25)
916         s->y_dc_scale = (quant + 8);
917     else
918         s->y_dc_scale = (2 * quant - 16);
919     /* chrominance */
920     if (quant < 5)
921         s->c_dc_scale = 8;
922     else if (quant > 4 && quant < 25)
923         s->c_dc_scale = ((quant + 13) / 2);
924     else
925         s->c_dc_scale = (quant - 6);
926 #endif
927 }
928
929 static inline int mpeg4_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr, int *dir_ptr)
930 {
931     int a, b, c, wrap, pred, scale;
932     UINT16 *dc_val;
933     int dummy;
934
935     /* find prediction */
936     if (n < 4) {
937         scale = s->y_dc_scale;
938     } else {
939         scale = s->c_dc_scale;
940     }
941     wrap= s->block_wrap[n];
942     dc_val = s->dc_val[0] + s->block_index[n];
943
944     /* B C
945      * A X 
946      */
947     a = dc_val[ - 1];
948     b = dc_val[ - 1 - wrap];
949     c = dc_val[ - wrap];
950
951     if (abs(a - b) < abs(b - c)) {
952         pred = c;
953         *dir_ptr = 1; /* top */
954     } else {
955         pred = a;
956         *dir_ptr = 0; /* left */
957     }
958     /* we assume pred is positive */
959 #ifdef ARCH_X86
960         asm volatile (
961                 "xorl %%edx, %%edx      \n\t"
962                 "mul %%ecx              \n\t"
963                 : "=d" (pred), "=a"(dummy)
964                 : "a" (pred + (scale >> 1)), "c" (inverse[scale])
965         );
966 #else
967     pred = (pred + (scale >> 1)) / scale;
968 #endif
969
970     /* prepare address for prediction update */
971     *dc_val_ptr = &dc_val[0];
972
973     return pred;
974 }
975
976 void mpeg4_pred_ac(MpegEncContext * s, INT16 *block, int n,
977                    int dir)
978 {
979     int i;
980     INT16 *ac_val, *ac_val1;
981
982     /* find prediction */
983     ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
984     ac_val1 = ac_val;
985     if (s->ac_pred) {
986         if (dir == 0) {
987             /* left prediction */
988             ac_val -= 16;
989             for(i=1;i<8;i++) {
990                 block[block_permute_op(i*8)] += ac_val[i];
991             }
992         } else {
993             /* top prediction */
994             ac_val -= 16 * s->block_wrap[n];
995             for(i=1;i<8;i++) {
996                 block[block_permute_op(i)] += ac_val[i + 8];
997             }
998         }
999     }
1000     /* left copy */
1001     for(i=1;i<8;i++)
1002         ac_val1[i] = block[block_permute_op(i * 8)];
1003     /* top copy */
1004     for(i=1;i<8;i++)
1005         ac_val1[8 + i] = block[block_permute_op(i)];
1006 }
1007
1008 static void mpeg4_inv_pred_ac(MpegEncContext * s, INT16 *block, int n,
1009                               int dir)
1010 {
1011     int i;
1012     INT16 *ac_val;
1013
1014     /* find prediction */
1015     ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1016  
1017     if (dir == 0) {
1018         /* left prediction */
1019         ac_val -= 16;
1020         for(i=1;i<8;i++) {
1021             block[block_permute_op(i*8)] -= ac_val[i];
1022         }
1023     } else {
1024         /* top prediction */
1025         ac_val -= 16 * s->block_wrap[n];
1026         for(i=1;i<8;i++) {
1027             block[block_permute_op(i)] -= ac_val[i + 8];
1028         }
1029     }
1030 }
1031
1032
1033 static inline void mpeg4_encode_dc(MpegEncContext * s, int level, int n)
1034 {
1035     int size, v;
1036     /* find number of bits */
1037     size = 0;
1038     v = abs(level);
1039     while (v) {
1040         v >>= 1;
1041         size++;
1042     }
1043
1044     if (n < 4) {
1045         /* luminance */
1046         put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
1047     } else {
1048         /* chrominance */
1049         put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
1050     }
1051
1052     /* encode remaining bits */
1053     if (size > 0) {
1054         if (level < 0)
1055             level = (-level) ^ ((1 << size) - 1);
1056         put_bits(&s->pb, size, level);
1057         if (size > 8)
1058             put_bits(&s->pb, 1, 1);
1059     }
1060 }
1061
1062 static void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, UINT8 *scan_table)
1063 {
1064     int level, run, last, i, j, last_index, last_non_zero, sign, slevel;
1065     int code;
1066     const RLTable *rl;
1067
1068     if (s->mb_intra) {
1069         /* mpeg4 based DC predictor */
1070         mpeg4_encode_dc(s, intra_dc, n);
1071         i = 1;
1072         rl = &rl_intra;
1073     } else {
1074         i = 0;
1075         rl = &rl_inter;
1076     }
1077
1078     /* AC coefs */
1079     last_index = s->block_last_index[n];
1080     last_non_zero = i - 1;
1081     for (; i <= last_index; i++) {
1082         j = scan_table[i];
1083         level = block[j];
1084         if (level) {
1085             run = i - last_non_zero - 1;
1086             last = (i == last_index);
1087             sign = 0;
1088             slevel = level;
1089             if (level < 0) {
1090                 sign = 1;
1091                 level = -level;
1092             }
1093             code = get_rl_index(rl, last, run, level);
1094             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1095             if (code == rl->n) {
1096                 int level1, run1;
1097                 level1 = level - rl->max_level[last][run];
1098                 if (level1 < 1) 
1099                     goto esc2;
1100                 code = get_rl_index(rl, last, run, level1);
1101                 if (code == rl->n) {
1102                 esc2:
1103                     put_bits(&s->pb, 1, 1);
1104                     if (level > MAX_LEVEL)
1105                         goto esc3;
1106                     run1 = run - rl->max_run[last][level] - 1;
1107                     if (run1 < 0)
1108                         goto esc3;
1109                     code = get_rl_index(rl, last, run1, level);
1110                     if (code == rl->n) {
1111                     esc3:
1112                         /* third escape */
1113                         put_bits(&s->pb, 1, 1);
1114                         put_bits(&s->pb, 1, last);
1115                         put_bits(&s->pb, 6, run);
1116                         put_bits(&s->pb, 1, 1);
1117                         put_bits(&s->pb, 12, slevel & 0xfff);
1118                         put_bits(&s->pb, 1, 1);
1119                     } else {
1120                         /* second escape */
1121                         put_bits(&s->pb, 1, 0);
1122                         put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1123                         put_bits(&s->pb, 1, sign);
1124                     }
1125                 } else {
1126                     /* first escape */
1127                     put_bits(&s->pb, 1, 0);
1128                     put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1129                     put_bits(&s->pb, 1, sign);
1130                 }
1131             } else {
1132                 put_bits(&s->pb, 1, sign);
1133             }
1134             last_non_zero = i;
1135         }
1136     }
1137 }
1138
1139
1140
1141 /***********************************************/
1142 /* decoding */
1143
1144 static VLC intra_MCBPC_vlc;
1145 static VLC inter_MCBPC_vlc;
1146 static VLC cbpy_vlc;
1147 static VLC mv_vlc;
1148 static VLC dc_lum, dc_chrom;
1149 static VLC sprite_trajectory;
1150 static VLC mb_type_b_vlc;
1151
1152 void init_rl(RLTable *rl)
1153 {
1154     INT8 max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
1155     UINT8 index_run[MAX_RUN+1];
1156     int last, run, level, start, end, i;
1157
1158     /* compute max_level[], max_run[] and index_run[] */
1159     for(last=0;last<2;last++) {
1160         if (last == 0) {
1161             start = 0;
1162             end = rl->last;
1163         } else {
1164             start = rl->last;
1165             end = rl->n;
1166         }
1167
1168         memset(max_level, 0, MAX_RUN + 1);
1169         memset(max_run, 0, MAX_LEVEL + 1);
1170         memset(index_run, rl->n, MAX_RUN + 1);
1171         for(i=start;i<end;i++) {
1172             run = rl->table_run[i];
1173             level = rl->table_level[i];
1174             if (index_run[run] == rl->n)
1175                 index_run[run] = i;
1176             if (level > max_level[run])
1177                 max_level[run] = level;
1178             if (run > max_run[level])
1179                 max_run[level] = run;
1180         }
1181         rl->max_level[last] = malloc(MAX_RUN + 1);
1182         memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
1183         rl->max_run[last] = malloc(MAX_LEVEL + 1);
1184         memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
1185         rl->index_run[last] = malloc(MAX_RUN + 1);
1186         memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
1187     }
1188 }
1189
1190 void init_vlc_rl(RLTable *rl)
1191 {
1192     init_vlc(&rl->vlc, 9, rl->n + 1, 
1193              &rl->table_vlc[0][1], 4, 2,
1194              &rl->table_vlc[0][0], 4, 2);
1195 }
1196
1197 /* init vlcs */
1198
1199 /* XXX: find a better solution to handle static init */
1200 void h263_decode_init_vlc(MpegEncContext *s)
1201 {
1202     static int done = 0;
1203
1204     if (!done) {
1205         done = 1;
1206
1207         init_vlc(&intra_MCBPC_vlc, 6, 8, 
1208                  intra_MCBPC_bits, 1, 1,
1209                  intra_MCBPC_code, 1, 1);
1210         init_vlc(&inter_MCBPC_vlc, 9, 25, 
1211                  inter_MCBPC_bits, 1, 1,
1212                  inter_MCBPC_code, 1, 1);
1213         init_vlc(&cbpy_vlc, 6, 16,
1214                  &cbpy_tab[0][1], 2, 1,
1215                  &cbpy_tab[0][0], 2, 1);
1216         init_vlc(&mv_vlc, 9, 33,
1217                  &mvtab[0][1], 2, 1,
1218                  &mvtab[0][0], 2, 1);
1219         init_rl(&rl_inter);
1220         init_rl(&rl_intra);
1221         init_rl(&rl_intra_aic);
1222         init_vlc_rl(&rl_inter);
1223         init_vlc_rl(&rl_intra);
1224         init_vlc_rl(&rl_intra_aic);
1225         init_vlc(&dc_lum, 9, 13,
1226                  &DCtab_lum[0][1], 2, 1,
1227                  &DCtab_lum[0][0], 2, 1);
1228         init_vlc(&dc_chrom, 9, 13,
1229                  &DCtab_chrom[0][1], 2, 1,
1230                  &DCtab_chrom[0][0], 2, 1);
1231         init_vlc(&sprite_trajectory, 9, 15,
1232                  &sprite_trajectory_tab[0][1], 4, 2,
1233                  &sprite_trajectory_tab[0][0], 4, 2);
1234         init_vlc(&mb_type_b_vlc, 4, 4,
1235                  &mb_type_b_tab[0][1], 2, 1,
1236                  &mb_type_b_tab[0][0], 2, 1);
1237     }
1238 }
1239
1240 int h263_decode_gob_header(MpegEncContext *s)
1241 {
1242     unsigned int val, gfid;
1243     
1244     /* Check for GOB Start Code */
1245     val = show_bits(&s->gb, 16);
1246     if (val == 0) {
1247         /* We have a GBSC probably with GSTUFF */
1248         skip_bits(&s->gb, 16); /* Drop the zeros */
1249         while (get_bits1(&s->gb) == 0); /* Seek the '1' bit */
1250 #ifdef DEBUG
1251         fprintf(stderr,"\nGOB Start Code at MB %d\n", (s->mb_y * s->mb_width) + s->mb_x);
1252 #endif
1253         s->gob_number = get_bits(&s->gb, 5); /* GN */
1254         gfid = get_bits(&s->gb, 2); /* GFID */
1255         s->qscale = get_bits(&s->gb, 5); /* GQUANT */
1256 #ifdef DEBUG
1257         fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", s->gob_number, gfid, s->qscale);
1258 #endif
1259         return 1;
1260     }
1261     return 0;
1262             
1263 }
1264
1265 int h263_decode_mb(MpegEncContext *s,
1266                    DCTELEM block[6][64])
1267 {
1268     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
1269     INT16 *mot_val;
1270     static INT8 quant_tab[4] = { -1, -2, 1, 2 };
1271
1272     if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
1273         if (get_bits1(&s->gb)) {
1274             /* skip mb */
1275             s->mb_intra = 0;
1276             for(i=0;i<6;i++)
1277                 s->block_last_index[i] = -1;
1278             s->mv_dir = MV_DIR_FORWARD;
1279             s->mv_type = MV_TYPE_16X16;
1280             if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
1281                 const int a= s->sprite_warping_accuracy;
1282 //                int l = (1 << (s->f_code - 1)) * 32;
1283
1284                 s->mcsel=1;
1285                 s->mv[0][0][0] = RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
1286                 s->mv[0][0][1] = RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
1287 /*                if (s->mv[0][0][0] < -l) s->mv[0][0][0]= -l;
1288                 else if (s->mv[0][0][0] >= l) s->mv[0][0][0]= l-1;
1289                 if (s->mv[0][0][1] < -l) s->mv[0][0][1]= -l;
1290                 else if (s->mv[0][0][1] >= l) s->mv[0][0][1]= l-1;*/
1291
1292                 s->mb_skiped = 0;
1293             }else{
1294                 s->mcsel=0;
1295                 s->mv[0][0][0] = 0;
1296                 s->mv[0][0][1] = 0;
1297                 s->mb_skiped = 1;
1298             }
1299             return 0;
1300         }
1301         cbpc = get_vlc(&s->gb, &inter_MCBPC_vlc);
1302         //fprintf(stderr, "\tCBPC: %d", cbpc);
1303         if (cbpc < 0)
1304             return -1;
1305         if (cbpc > 20)
1306             cbpc+=3;
1307         else if (cbpc == 20)
1308             fprintf(stderr, "Stuffing !");
1309         
1310         dquant = cbpc & 8;
1311         s->mb_intra = ((cbpc & 4) != 0);
1312         if (s->mb_intra) goto intra;
1313         
1314         if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
1315             s->mcsel= get_bits1(&s->gb);
1316         else s->mcsel= 0;
1317         cbpy = get_vlc(&s->gb, &cbpy_vlc);
1318         cbp = (cbpc & 3) | ((cbpy ^ 0xf) << 2);
1319         if (dquant) {
1320             s->qscale += quant_tab[get_bits(&s->gb, 2)];
1321             if (s->qscale < 1)
1322                 s->qscale = 1;
1323             else if (s->qscale > 31)
1324                 s->qscale = 31;
1325         }
1326         s->mv_dir = MV_DIR_FORWARD;
1327         if ((cbpc & 16) == 0) {
1328             /* 16x16 motion prediction */
1329             s->mv_type = MV_TYPE_16X16;
1330             h263_pred_motion(s, 0, &pred_x, &pred_y);
1331             if (s->umvplus_dec)
1332                mx = h263p_decode_umotion(s, pred_x);
1333             else if(!s->mcsel)
1334                mx = h263_decode_motion(s, pred_x, s->f_code);
1335             else {
1336                const int a= s->sprite_warping_accuracy;
1337 //        int l = (1 << (s->f_code - 1)) * 32;
1338                mx= RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
1339 //        if (mx < -l) mx= -l;
1340 //        else if (mx >= l) mx= l-1;
1341             }
1342             if (mx >= 0xffff)
1343                 return -1;
1344             
1345             if (s->umvplus_dec)
1346                my = h263p_decode_umotion(s, pred_y);
1347             else if(!s->mcsel)
1348                my = h263_decode_motion(s, pred_y, s->f_code);
1349             else{
1350                const int a= s->sprite_warping_accuracy;
1351 //       int l = (1 << (s->f_code - 1)) * 32;
1352                my= RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
1353 //       if (my < -l) my= -l;
1354 //       else if (my >= l) my= l-1;
1355             }
1356             if (my >= 0xffff)
1357                 return -1;
1358             s->mv[0][0][0] = mx;
1359             s->mv[0][0][1] = my;
1360             /*fprintf(stderr, "\n MB %d", (s->mb_y * s->mb_width) + s->mb_x);
1361             fprintf(stderr, "\n\tmvx: %d\t\tpredx: %d", mx, pred_x);
1362             fprintf(stderr, "\n\tmvy: %d\t\tpredy: %d", my, pred_y);*/
1363             if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
1364                skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1365                            
1366         } else {
1367             s->mv_type = MV_TYPE_8X8;
1368             for(i=0;i<4;i++) {
1369                 mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
1370                 if (s->umvplus_dec)
1371                   mx = h263p_decode_umotion(s, pred_x);
1372                 else
1373                   mx = h263_decode_motion(s, pred_x, s->f_code);
1374                 if (mx >= 0xffff)
1375                     return -1;
1376                 
1377                 if (s->umvplus_dec)
1378                   my = h263p_decode_umotion(s, pred_y);
1379                 else    
1380                   my = h263_decode_motion(s, pred_y, s->f_code);
1381                 if (my >= 0xffff)
1382                     return -1;
1383                 s->mv[0][i][0] = mx;
1384                 s->mv[0][i][1] = my;
1385                 if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
1386                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1387                 mot_val[0] = mx;
1388                 mot_val[1] = my;
1389             }
1390         }
1391     } else if(s->pict_type==B_TYPE) {
1392         int modb1; // first bit of modb
1393         int modb2; // second bit of modb
1394         int mb_type;
1395         int time_pp;
1396         int time_pb;
1397         int xy;
1398
1399         s->mb_intra = 0; //B-frames never contain intra blocks
1400         s->mcsel=0;      //     ...               true gmc blocks
1401
1402         if(s->mb_x==0){
1403             s->last_mv[0][0][0]= 
1404             s->last_mv[0][0][1]= 
1405             s->last_mv[1][0][0]= 
1406             s->last_mv[1][0][1]= 0;
1407         }
1408
1409         /* if we skipped it in the future P Frame than skip it now too */
1410         s->mb_skiped= s->mbskip_table[s->mb_y * s->mb_width + s->mb_x]; // Note, skiptab=0 if last was GMC
1411
1412         if(s->mb_skiped){
1413                 /* skip mb */
1414             for(i=0;i<6;i++)
1415                 s->block_last_index[i] = -1;
1416
1417             s->mv_dir = MV_DIR_FORWARD;
1418             s->mv_type = MV_TYPE_16X16;
1419             s->mv[0][0][0] = 0;
1420             s->mv[0][0][1] = 0;
1421             s->mv[1][0][0] = 0;
1422             s->mv[1][0][1] = 0;
1423             s->last_mv[0][0][0]=
1424             s->last_mv[0][0][1]= 
1425             s->last_mv[1][0][0]= 
1426             s->last_mv[1][0][1]= 0;
1427             s->mb_skiped = 1;
1428             return 0;
1429         }
1430
1431         modb1= get_bits1(&s->gb);
1432         if(modb1==0){
1433             modb2= get_bits1(&s->gb);
1434             mb_type= get_vlc(&s->gb, &mb_type_b_vlc);
1435             if(modb2==0) cbp= get_bits(&s->gb, 6);
1436             else cbp=0;
1437             if (mb_type && cbp) {
1438                 if(get_bits1(&s->gb)){
1439                     s->qscale +=get_bits1(&s->gb)*4 - 2;
1440                     if (s->qscale < 1)
1441                         s->qscale = 1;
1442                     else if (s->qscale > 31)
1443                         s->qscale = 31;
1444                 }
1445             }
1446         }else{
1447             mb_type=4; //like 0 but no vectors coded
1448             cbp=0;
1449         }
1450         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
1451         mx=my=0; //for case 4, we could put this to the mb_type=4 but than gcc compains about uninitalized mx/my
1452         switch(mb_type)
1453         {
1454         case 0: 
1455             mx = h263_decode_motion(s, 0, 1);
1456             my = h263_decode_motion(s, 0, 1);
1457         case 4: 
1458             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1459             xy= s->block_index[0];
1460             time_pp= s->last_non_b_time[0] - s->last_non_b_time[1];
1461             time_pb= s->time - s->last_non_b_time[1];
1462 //if(time_pp>3000 )printf("%d %d  ", time_pp, time_pb);
1463             //FIXME 4MV
1464             //FIXME avoid divides
1465             s->mv[0][0][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
1466             s->mv[0][0][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
1467             s->mv[1][0][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
1468                                 : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp + mx;
1469             s->mv[1][0][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1] 
1470                                 : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp + my;
1471 /*            s->mv[0][0][0] = 
1472             s->mv[0][0][1] = 
1473             s->mv[1][0][0] = 
1474             s->mv[1][0][1] = 1000;*/
1475             break;
1476         case 1: 
1477             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
1478             mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1479             my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1480             s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1481             s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1482
1483             mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1484             my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1485             s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1486             s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1487             break;
1488         case 2: 
1489             s->mv_dir = MV_DIR_BACKWARD;
1490             mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1491             my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1492             s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1493             s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1494             break;
1495         case 3:
1496             s->mv_dir = MV_DIR_FORWARD;
1497             mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1498             my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1499             s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1500             s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1501             break;
1502         default: return -1;
1503         }
1504     } else { /* I-Frame */
1505         cbpc = get_vlc(&s->gb, &intra_MCBPC_vlc);
1506         if (cbpc < 0)
1507             return -1;
1508         dquant = cbpc & 4;
1509         s->mb_intra = 1;
1510 intra:
1511         s->ac_pred = 0;
1512         if (s->h263_pred || s->h263_aic) {
1513             s->ac_pred = get_bits1(&s->gb);
1514             if (s->ac_pred && s->h263_aic)
1515                 s->h263_aic_dir = get_bits1(&s->gb);
1516         }
1517         if (s->h263_aic) {
1518             s->y_dc_scale = 2 * s->qscale;
1519             s->c_dc_scale = 2 * s->qscale;
1520         }
1521         cbpy = get_vlc(&s->gb, &cbpy_vlc);
1522         cbp = (cbpc & 3) | (cbpy << 2);
1523         if (dquant) {
1524             s->qscale += quant_tab[get_bits(&s->gb, 2)];
1525             if (s->qscale < 1)
1526                 s->qscale = 1;
1527             else if (s->qscale > 31)
1528                 s->qscale = 31;
1529         }
1530     }
1531
1532     /* decode each block */
1533     if (s->h263_pred) {
1534         for (i = 0; i < 6; i++) {
1535             if (mpeg4_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1) < 0)
1536                 return -1;
1537         }
1538     } else {
1539         for (i = 0; i < 6; i++) {
1540             if (h263_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1) < 0)
1541                 return -1;
1542         }
1543     }
1544     return 0;
1545 }
1546
1547 static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
1548 {
1549     int code, val, sign, shift, l, m;
1550
1551     code = get_vlc(&s->gb, &mv_vlc);
1552     if (code < 0)
1553         return 0xffff;
1554
1555     if (code == 0)
1556         return pred;
1557     sign = get_bits1(&s->gb);
1558     shift = f_code - 1;
1559     val = (code - 1) << shift;
1560     if (shift > 0)
1561         val |= get_bits(&s->gb, shift);
1562     val++;
1563     if (sign)
1564         val = -val;
1565     val += pred;
1566     
1567     /* modulo decoding */
1568     if (!s->h263_long_vectors) {
1569         l = (1 << (f_code - 1)) * 32;
1570         m = 2 * l;
1571         if (val < -l) {
1572             val += m;
1573         } else if (val >= l) {
1574             val -= m;
1575         }
1576     } else {
1577         /* horrible h263 long vector mode */
1578         if (pred < -31 && val < -63)
1579             val += 64;
1580         if (pred > 32 && val > 63)
1581             val -= 64;
1582         
1583     }
1584     return val;
1585 }
1586
1587 /* Decodes RVLC of H.263+ UMV */
1588 static int h263p_decode_umotion(MpegEncContext * s, int pred)
1589 {
1590    int code = 0, sign;
1591    
1592    if (get_bits1(&s->gb)) /* Motion difference = 0 */
1593       return pred;
1594    
1595    code = 2 + get_bits1(&s->gb);
1596    
1597    while (get_bits1(&s->gb))
1598    {
1599       code <<= 1;
1600       code += get_bits1(&s->gb);
1601    }
1602    sign = code & 1;
1603    code >>= 1;
1604    
1605    code = (sign) ? (pred - code) : (pred + code);
1606 #ifdef DEBUG
1607    fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
1608 #endif
1609    return code;   
1610
1611 }
1612
1613 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
1614                              int n, int coded)
1615 {
1616     int code, level, i, j, last, run;
1617     RLTable *rl = &rl_inter;
1618     const UINT8 *scan_table;
1619
1620     scan_table = zigzag_direct;
1621     if (s->h263_aic && s->mb_intra) {
1622         rl = &rl_intra_aic;
1623         i = 0;
1624         if (s->ac_pred) {
1625             if (s->h263_aic_dir) 
1626                 scan_table = ff_alternate_vertical_scan; /* left */
1627             else
1628                 scan_table = ff_alternate_horizontal_scan; /* top */
1629         }
1630     } else if (s->mb_intra) {
1631         /* DC coef */
1632         if (s->h263_rv10 && s->rv10_version == 3 && s->pict_type == I_TYPE) {
1633             int component, diff;
1634             component = (n <= 3 ? 0 : n - 4 + 1);
1635             level = s->last_dc[component];
1636             if (s->rv10_first_dc_coded[component]) {
1637                 diff = rv_decode_dc(s, n);
1638                 if (diff == 0xffff)
1639                     return -1;
1640                 level += diff;
1641                 level = level & 0xff; /* handle wrap round */
1642                 s->last_dc[component] = level;
1643             } else {
1644                 s->rv10_first_dc_coded[component] = 1;
1645             }
1646         } else {
1647             level = get_bits(&s->gb, 8);
1648             if (level == 255)
1649                 level = 128;
1650         }
1651         block[0] = level;
1652         i = 1;
1653     } else {
1654         i = 0;
1655     }
1656     if (!coded) {
1657         if (s->mb_intra && s->h263_aic)
1658             goto not_coded;
1659         s->block_last_index[n] = i - 1;
1660         return 0;
1661     }
1662
1663     for(;;) {
1664         code = get_vlc(&s->gb, &rl->vlc);
1665         if (code < 0)
1666             return -1;
1667         if (code == rl->n) {
1668             /* escape */
1669             last = get_bits1(&s->gb);
1670             run = get_bits(&s->gb, 6);
1671             level = (INT8)get_bits(&s->gb, 8);
1672             if (s->h263_rv10 && level == -128) {
1673                 /* XXX: should patch encoder too */
1674                 level = get_bits(&s->gb, 12);
1675                 level = (level << 20) >> 20;
1676             }
1677         } else {
1678             run = rl->table_run[code];
1679             level = rl->table_level[code];
1680             last = code >= rl->last;
1681             if (get_bits1(&s->gb))
1682                 level = -level;
1683         }
1684         i += run;
1685         if (i >= 64)
1686             return -1;
1687         j = scan_table[i];
1688         block[j] = level;
1689         if (last)
1690             break;
1691         i++;
1692     }
1693 not_coded:    
1694     if (s->mb_intra && s->h263_aic) {
1695         h263_pred_acdc(s, block, n);
1696         i = 63;
1697     }
1698     s->block_last_index[n] = i;
1699     return 0;
1700 }
1701
1702 static int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
1703 {
1704     int level, pred, code;
1705     UINT16 *dc_val;
1706
1707     if (n < 4) 
1708         code = get_vlc(&s->gb, &dc_lum);
1709     else 
1710         code = get_vlc(&s->gb, &dc_chrom);
1711     if (code < 0)
1712         return -1;
1713     if (code == 0) {
1714         level = 0;
1715     } else {
1716         level = get_bits(&s->gb, code);
1717         if ((level >> (code - 1)) == 0) /* if MSB not set it is negative*/
1718             level = - (level ^ ((1 << code) - 1));
1719         if (code > 8)
1720             skip_bits1(&s->gb); /* marker */
1721     }
1722
1723     pred = mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
1724     level += pred;
1725     if (level < 0)
1726         level = 0;
1727     if (n < 4) {
1728         *dc_val = level * s->y_dc_scale;
1729     } else {
1730         *dc_val = level * s->c_dc_scale;
1731     }
1732     return level;
1733 }
1734
1735 static int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
1736                               int n, int coded)
1737 {
1738     int code, level, i, j, last, run;
1739     int dc_pred_dir;
1740     RLTable *rl;
1741     const UINT8 *scan_table;
1742
1743     if (s->mb_intra) {
1744         /* DC coef */
1745         level = mpeg4_decode_dc(s, n, &dc_pred_dir);
1746         if (level < 0)
1747             return -1;
1748         block[0] = level;
1749         i = 1;
1750         if (!coded) 
1751             goto not_coded;
1752         rl = &rl_intra;
1753         if (s->ac_pred) {
1754             if (dc_pred_dir == 0) 
1755                 scan_table = ff_alternate_vertical_scan; /* left */
1756             else
1757                 scan_table = ff_alternate_horizontal_scan; /* top */
1758         } else {
1759             scan_table = zigzag_direct;
1760         }
1761     } else {
1762         i = 0;
1763         if (!coded) {
1764             s->block_last_index[n] = i - 1;
1765             return 0;
1766         }
1767         rl = &rl_inter;
1768         scan_table = zigzag_direct;
1769     }
1770
1771     for(;;) {
1772         code = get_vlc(&s->gb, &rl->vlc);
1773         if (code < 0)
1774             return -1;
1775         if (code == rl->n) {
1776             /* escape */
1777             if (get_bits1(&s->gb) != 0) {
1778                 if (get_bits1(&s->gb) != 0) {
1779                     /* third escape */
1780                     last = get_bits1(&s->gb);
1781                     run = get_bits(&s->gb, 6);
1782                     get_bits1(&s->gb); /* marker */
1783                     level = get_bits(&s->gb, 12);
1784                     level = (level << 20) >> 20; /* sign extend */
1785                     skip_bits1(&s->gb); /* marker */
1786                 } else {
1787                     /* second escape */
1788                     code = get_vlc(&s->gb, &rl->vlc);
1789                     if (code < 0 || code >= rl->n)
1790                         return -1;
1791                     run = rl->table_run[code];
1792                     level = rl->table_level[code];
1793                     last = code >= rl->last;
1794                     run += rl->max_run[last][level] + 1;
1795                     if (get_bits1(&s->gb))
1796                         level = -level;
1797                 }
1798             } else {
1799                 /* first escape */
1800                 code = get_vlc(&s->gb, &rl->vlc);
1801                 if (code < 0 || code >= rl->n)
1802                     return -1;
1803                 run = rl->table_run[code];
1804                 level = rl->table_level[code];
1805                 last = code >= rl->last;
1806                 level += rl->max_level[last][run];
1807                 if (get_bits1(&s->gb))
1808                     level = -level;
1809             }
1810         } else {
1811             run = rl->table_run[code];
1812             level = rl->table_level[code];
1813             last = code >= rl->last;
1814             if (get_bits1(&s->gb))
1815                 level = -level;
1816         }
1817         i += run;
1818         if (i >= 64)
1819             return -1;
1820         j = scan_table[i];
1821         block[j] = level;
1822         i++;
1823         if (last)
1824             break;
1825     }
1826  not_coded:
1827     if (s->mb_intra) {
1828         mpeg4_pred_ac(s, block, n, dc_pred_dir);
1829         if (s->ac_pred) {
1830             i = 64; /* XXX: not optimal */
1831         }
1832     }
1833     s->block_last_index[n] = i - 1;
1834     return 0;
1835 }
1836
1837 /* most is hardcoded. should extend to handle all h263 streams */
1838 int h263_decode_picture_header(MpegEncContext *s)
1839 {
1840     int format, width, height;
1841
1842     /* picture header */
1843     if (get_bits(&s->gb, 22) != 0x20)
1844         return -1;
1845     s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
1846     
1847     if (get_bits1(&s->gb) != 1)
1848         return -1;      /* marker */
1849     if (get_bits1(&s->gb) != 0)
1850         return -1;      /* h263 id */
1851     skip_bits1(&s->gb); /* split screen off */
1852     skip_bits1(&s->gb); /* camera  off */
1853     skip_bits1(&s->gb); /* freeze picture release off */
1854
1855     /* Reset GOB number */
1856     s->gob_number = 0;
1857         
1858     format = get_bits(&s->gb, 3);
1859
1860     if (format != 7 && format != 6) {
1861         s->h263_plus = 0;
1862         /* H.263v1 */
1863         width = h263_format[format][0];
1864         height = h263_format[format][1];
1865         if (!width)
1866             return -1;
1867         
1868         s->width = width;
1869         s->height = height;
1870         s->pict_type = I_TYPE + get_bits1(&s->gb);
1871
1872         s->unrestricted_mv = get_bits1(&s->gb); 
1873         s->h263_long_vectors = s->unrestricted_mv;
1874
1875         if (get_bits1(&s->gb) != 0)
1876             return -1;  /* SAC: off */
1877         if (get_bits1(&s->gb) != 0) {
1878             s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
1879         }   
1880         
1881         if (get_bits1(&s->gb) != 0)
1882             return -1;  /* not PB frame */
1883
1884         s->qscale = get_bits(&s->gb, 5);
1885         skip_bits1(&s->gb);     /* Continuous Presence Multipoint mode: off */
1886     } else {
1887         int ufep;
1888         
1889         /* H.263v2 */
1890         s->h263_plus = 1;
1891         ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
1892         
1893         if (ufep == 1) {
1894             /* OPPTYPE */       
1895             format = get_bits(&s->gb, 3);
1896             skip_bits(&s->gb,1); /* Custom PCF */
1897             s->umvplus_dec = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */
1898             skip_bits1(&s->gb); /* Syntax-based Arithmetic Coding (SAC) */
1899             if (get_bits1(&s->gb) != 0) {
1900                 s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
1901             }
1902             if (get_bits1(&s->gb) != 0) { /* Advanced Intra Coding (AIC) */
1903                 s->h263_aic = 1;
1904             }
1905             skip_bits(&s->gb, 7);
1906             skip_bits(&s->gb, 3); /* Reserved */
1907         } else if (ufep != 0)
1908             return -1;
1909             
1910         /* MPPTYPE */
1911         s->pict_type = get_bits(&s->gb, 3) + 1;
1912         if (s->pict_type != I_TYPE &&
1913             s->pict_type != P_TYPE)
1914             return -1;
1915         skip_bits(&s->gb, 2);
1916         s->no_rounding = get_bits1(&s->gb);
1917         //fprintf(stderr, "\nRTYPE: %d", s->no_rounding);
1918         skip_bits(&s->gb, 4);
1919         
1920         /* Get the picture dimensions */
1921         if (ufep) {
1922             if (format == 6) {
1923                 /* Custom Picture Format (CPFMT) */
1924                 skip_bits(&s->gb, 4); /* aspect ratio */
1925                 width = (get_bits(&s->gb, 9) + 1) * 4;
1926                 skip_bits1(&s->gb);
1927                 height = get_bits(&s->gb, 9) * 4;
1928 #ifdef DEBUG 
1929                 fprintf(stderr,"\nH.263+ Custom picture: %dx%d\n",width,height);
1930 #endif            
1931             }
1932             else {
1933                 width = h263_format[format][0];
1934                 height = h263_format[format][1];
1935             }
1936             if ((width == 0) || (height == 0))
1937                 return -1;
1938             s->width = width;
1939             s->height = height;
1940             if (s->umvplus_dec) {
1941                 skip_bits1(&s->gb); /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
1942             }
1943         }
1944             
1945         s->qscale = get_bits(&s->gb, 5);
1946     }
1947     /* PEI */
1948     while (get_bits1(&s->gb) != 0) {
1949         skip_bits(&s->gb, 8);
1950     }
1951     s->f_code = 1;
1952     return 0;
1953 }
1954
1955 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
1956 {
1957     int i;
1958     int a= 2<<s->sprite_warping_accuracy;
1959     int rho= 3-s->sprite_warping_accuracy;
1960     int r=16/a;
1961     const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
1962     int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
1963     int sprite_ref[4][2];
1964     int virtual_ref[2][2];
1965     int w2, h2;
1966     int alpha=0, beta=0;
1967     int w= s->width;
1968     int h= s->height;
1969 //printf("SP %d\n", s->sprite_warping_accuracy);
1970     for(i=0; i<s->num_sprite_warping_points; i++){
1971         int length;
1972         int x=0, y=0;
1973
1974         length= get_vlc(&s->gb, &sprite_trajectory);
1975         if(length){
1976             x= get_bits(&s->gb, length);
1977 //printf("lx %d %d\n", length, x);
1978             if ((x >> (length - 1)) == 0) /* if MSB not set it is negative*/
1979                 x = - (x ^ ((1 << length) - 1));
1980         }
1981         if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
1982         
1983         length= get_vlc(&s->gb, &sprite_trajectory);
1984         if(length){
1985             y=get_bits(&s->gb, length);
1986 //printf("ly %d %d\n", length, y);
1987             if ((y >> (length - 1)) == 0) /* if MSB not set it is negative*/
1988                 y = - (y ^ ((1 << length) - 1));
1989         }
1990         skip_bits1(&s->gb); /* marker bit */
1991 //printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
1992 //if(i>0 && (x!=0 || y!=0)) printf("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n");
1993 //x=y=0;
1994         d[i][0]= x;
1995         d[i][1]= y;
1996     }
1997
1998     while((1<<alpha)<w) alpha++;
1999     while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
2000     w2= 1<<alpha;
2001     h2= 1<<beta;
2002
2003 // Note, the 4th point isnt used for GMC
2004     if(s->divx_version==500 && s->divx_build==413){
2005         sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
2006         sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
2007         sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
2008         sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
2009         sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
2010         sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
2011     } else {
2012         sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
2013         sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
2014         sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
2015         sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
2016         sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
2017         sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
2018     }
2019 /*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
2020     sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
2021     
2022 // this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
2023 // perhaps it should be reordered to be more readable ...
2024 // the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
2025 // so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
2026     virtual_ref[0][0]= 16*(vop_ref[0][0] + w2) 
2027         + 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);
2028     virtual_ref[0][1]= 16*vop_ref[0][1] 
2029         + 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);
2030     virtual_ref[1][0]= 16*vop_ref[0][0] 
2031         + 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);
2032     virtual_ref[1][1]= 16*(vop_ref[0][1] + h2) 
2033         + 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);
2034
2035     switch(s->num_sprite_warping_points)
2036     {
2037         case 0:
2038             s->sprite_offset[0][0]= 0;
2039             s->sprite_offset[0][1]= 0;
2040             s->sprite_offset[1][0]= 0;
2041             s->sprite_offset[1][1]= 0;
2042             s->sprite_delta[0][0][0]= a;
2043             s->sprite_delta[0][0][1]= 0;
2044             s->sprite_delta[0][1][0]= 0;
2045             s->sprite_delta[0][1][1]= a;
2046             s->sprite_delta[1][0][0]= a;
2047             s->sprite_delta[1][0][1]= 0;
2048             s->sprite_delta[1][1][0]= 0;
2049             s->sprite_delta[1][1][1]= a;
2050             s->sprite_shift[0][0]= 0;
2051             s->sprite_shift[0][1]= 0;
2052             s->sprite_shift[1][0]= 0;
2053             s->sprite_shift[1][1]= 0;
2054             break;
2055         case 1: //GMC only
2056             s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
2057             s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
2058             s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
2059             s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
2060             s->sprite_delta[0][0][0]= a;
2061             s->sprite_delta[0][0][1]= 0;
2062             s->sprite_delta[0][1][0]= 0;
2063             s->sprite_delta[0][1][1]= a;
2064             s->sprite_delta[1][0][0]= a;
2065             s->sprite_delta[1][0][1]= 0;
2066             s->sprite_delta[1][1][0]= 0;
2067             s->sprite_delta[1][1][1]= a;
2068             s->sprite_shift[0][0]= 0;
2069             s->sprite_shift[0][1]= 0;
2070             s->sprite_shift[1][0]= 0;
2071             s->sprite_shift[1][1]= 0;
2072             break;
2073         case 2:
2074         case 3: //FIXME
2075             s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
2076                                                   + ((-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
2077                                                     +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1]));
2078             s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
2079                                                   + ((-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
2080                                                     +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1]));
2081             s->sprite_offset[1][0]= ((-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)
2082                                  +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)
2083                                  +2*w2*r*sprite_ref[0][0] - 16*w2);
2084             s->sprite_offset[1][1]= ((-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1) 
2085                                  +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)
2086                                  +2*w2*r*sprite_ref[0][1] - 16*w2);
2087             s->sprite_delta[0][0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
2088             s->sprite_delta[0][0][1]=   ( r*sprite_ref[0][1] - virtual_ref[0][1]);
2089             s->sprite_delta[0][1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);
2090             s->sprite_delta[0][1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
2091             s->sprite_delta[1][0][0]= 4*(-r*sprite_ref[0][0] + virtual_ref[0][0]);
2092             s->sprite_delta[1][0][1]= 4*( r*sprite_ref[0][1] - virtual_ref[0][1]);
2093             s->sprite_delta[1][1][0]= 4*(-r*sprite_ref[0][1] + virtual_ref[0][1]);
2094             s->sprite_delta[1][1][1]= 4*(-r*sprite_ref[0][0] + virtual_ref[0][0]);
2095             s->sprite_shift[0][0]= alpha+rho;
2096             s->sprite_shift[0][1]= alpha+rho;
2097             s->sprite_shift[1][0]= alpha+rho+2;
2098             s->sprite_shift[1][1]= alpha+rho+2;
2099             break;
2100 //        case 3:
2101             break;
2102     }
2103 /*printf("%d %d\n", s->sprite_delta[0][0][0], a<<s->sprite_shift[0][0]);
2104 printf("%d %d\n", s->sprite_delta[0][0][1], 0);
2105 printf("%d %d\n", s->sprite_delta[0][1][0], 0);
2106 printf("%d %d\n", s->sprite_delta[0][1][1], a<<s->sprite_shift[0][1]);
2107 printf("%d %d\n", s->sprite_delta[1][0][0], a<<s->sprite_shift[1][0]);
2108 printf("%d %d\n", s->sprite_delta[1][0][1], 0);
2109 printf("%d %d\n", s->sprite_delta[1][1][0], 0);
2110 printf("%d %d\n", s->sprite_delta[1][1][1], a<<s->sprite_shift[1][1]);*/
2111     /* try to simplify the situation */ 
2112     if(   s->sprite_delta[0][0][0] == a<<s->sprite_shift[0][0]
2113        && s->sprite_delta[0][0][1] == 0
2114        && s->sprite_delta[0][1][0] == 0
2115        && s->sprite_delta[0][1][1] == a<<s->sprite_shift[0][1]
2116        && s->sprite_delta[1][0][0] == a<<s->sprite_shift[1][0]
2117        && s->sprite_delta[1][0][1] == 0
2118        && s->sprite_delta[1][1][0] == 0
2119        && s->sprite_delta[1][1][1] == a<<s->sprite_shift[1][1])
2120     {
2121         s->sprite_offset[0][0]>>=s->sprite_shift[0][0];
2122         s->sprite_offset[0][1]>>=s->sprite_shift[0][1];
2123         s->sprite_offset[1][0]>>=s->sprite_shift[1][0];
2124         s->sprite_offset[1][1]>>=s->sprite_shift[1][1];
2125         s->sprite_delta[0][0][0]= a;
2126         s->sprite_delta[0][0][1]= 0;
2127         s->sprite_delta[0][1][0]= 0;
2128         s->sprite_delta[0][1][1]= a;
2129         s->sprite_delta[1][0][0]= a;
2130         s->sprite_delta[1][0][1]= 0;
2131         s->sprite_delta[1][1][0]= 0;
2132         s->sprite_delta[1][1][1]= a;
2133         s->sprite_shift[0][0]= 0;
2134         s->sprite_shift[0][1]= 0;
2135         s->sprite_shift[1][0]= 0;
2136         s->sprite_shift[1][1]= 0;
2137         s->real_sprite_warping_points=1;
2138     }
2139     else
2140         s->real_sprite_warping_points= s->num_sprite_warping_points;
2141
2142 }
2143
2144 /* decode mpeg4 VOP header */
2145 int mpeg4_decode_picture_header(MpegEncContext * s)
2146 {
2147     int time_incr, startcode, state, v;
2148
2149  redo:
2150     /* search next start code */
2151     align_get_bits(&s->gb);
2152     state = 0xff;
2153     for(;;) {
2154         v = get_bits(&s->gb, 8);
2155         if (state == 0x000001) {
2156             state = ((state << 8) | v) & 0xffffff;
2157             startcode = state;
2158             break;
2159         }
2160         state = ((state << 8) | v) & 0xffffff;
2161         if( get_bits_count(&s->gb) > s->gb.size*8-32){
2162             printf("no VOP startcode found\n");
2163             return -1;
2164         }
2165     }
2166 //printf("startcode %X %d\n", startcode, get_bits_count(&s->gb));
2167     if (startcode == 0x120) { // Video Object Layer
2168         int width, height, vo_ver_id;
2169
2170         /* vol header */
2171         skip_bits(&s->gb, 1); /* random access */
2172         skip_bits(&s->gb, 8); /* vo_type */
2173         if (get_bits1(&s->gb) != 0) { /* is_ol_id */
2174             vo_ver_id = get_bits(&s->gb, 4); /* vo_ver_id */
2175             skip_bits(&s->gb, 3); /* vo_priority */
2176         } else {
2177             vo_ver_id = 1;
2178         }
2179         
2180         s->aspect_ratio_info= get_bits(&s->gb, 4);
2181         if(s->aspect_ratio_info == EXTENDET_PAR){
2182             skip_bits(&s->gb, 8); //par_width
2183             skip_bits(&s->gb, 8); // par_height
2184         }
2185
2186         if(get_bits1(&s->gb)){ /* vol control parameter */
2187             printf("vol control parameter not supported\n");
2188             return -1;   
2189         }
2190         s->shape = get_bits(&s->gb, 2); /* vol shape */
2191         if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");
2192         if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
2193             printf("Gray shape not supported\n");
2194             skip_bits(&s->gb, 4);  //video_object_layer_shape_extension
2195         }
2196
2197         skip_bits1(&s->gb);   /* marker */
2198         
2199         s->time_increment_resolution = get_bits(&s->gb, 16);
2200         s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
2201         if (s->time_increment_bits < 1)
2202             s->time_increment_bits = 1;
2203         skip_bits1(&s->gb);   /* marker */
2204
2205         if (get_bits1(&s->gb) != 0) {   /* fixed_vop_rate  */
2206             skip_bits(&s->gb, s->time_increment_bits);
2207         }
2208
2209         if (s->shape != BIN_ONLY_SHAPE) {
2210             if (s->shape == RECT_SHAPE) {
2211                 skip_bits1(&s->gb);   /* marker */
2212                 width = get_bits(&s->gb, 13);
2213                 skip_bits1(&s->gb);   /* marker */
2214                 height = get_bits(&s->gb, 13);
2215                 skip_bits1(&s->gb);   /* marker */
2216                 if(width && height){ /* they should be non zero but who knows ... */
2217                     s->width = width;
2218                     s->height = height;
2219 //                    printf("%d %d\n", width, height);
2220                 }
2221             }
2222             
2223             if(get_bits1(&s->gb)) printf("interlaced not supported\n");   /* interlaced */
2224             if(!get_bits1(&s->gb)) printf("OBMC not supported\n");   /* OBMC Disable */
2225             if (vo_ver_id == 1) {
2226                 s->vol_sprite_usage = get_bits1(&s->gb); /* vol_sprite_usage */
2227             } else {
2228                 s->vol_sprite_usage = get_bits(&s->gb, 2); /* vol_sprite_usage */
2229             }
2230             if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");
2231             if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
2232                 if(s->vol_sprite_usage==STATIC_SPRITE){
2233                     s->sprite_width = get_bits(&s->gb, 13);
2234                     skip_bits1(&s->gb); /* marker */
2235                     s->sprite_height= get_bits(&s->gb, 13);
2236                     skip_bits1(&s->gb); /* marker */
2237                     s->sprite_left  = get_bits(&s->gb, 13);
2238                     skip_bits1(&s->gb); /* marker */
2239                     s->sprite_top   = get_bits(&s->gb, 13);
2240                     skip_bits1(&s->gb); /* marker */
2241                 }
2242                 s->num_sprite_warping_points= get_bits(&s->gb, 6);
2243                 s->sprite_warping_accuracy = get_bits(&s->gb, 2);
2244                 s->sprite_brightness_change= get_bits1(&s->gb);
2245                 if(s->vol_sprite_usage==STATIC_SPRITE)
2246                     s->low_latency_sprite= get_bits1(&s->gb);            
2247             }
2248             // FIXME sadct disable bit if verid!=1 && shape not rect
2249             
2250             if (get_bits1(&s->gb) == 1) {   /* not_8_bit */
2251                 s->quant_precision = get_bits(&s->gb, 4); /* quant_precision */
2252                 if(get_bits(&s->gb, 4)!=8) printf("N-bit not supported\n"); /* bits_per_pixel */
2253             } else {
2254                 s->quant_precision = 5;
2255             }
2256             
2257             // FIXME a bunch of grayscale shape things
2258             if(get_bits1(&s->gb)) printf("Quant-Type not supported\n");  /* vol_quant_type */ //FIXME
2259             if(vo_ver_id != 1)
2260                  s->quarter_sample= get_bits1(&s->gb);
2261             else s->quarter_sample=0;
2262
2263             if(!get_bits1(&s->gb)) printf("Complexity estimation not supported\n");
2264 #if 0
2265             if(get_bits1(&s->gb)) printf("resync disable\n");
2266 #else
2267             skip_bits1(&s->gb);   /* resync_marker_disabled */
2268 #endif
2269             s->data_partioning= get_bits1(&s->gb);
2270             if(s->data_partioning){
2271                 printf("data partitioning not supported\n");
2272                 skip_bits1(&s->gb); // reversible vlc
2273             }
2274             
2275             if(vo_ver_id != 1) {
2276                 s->new_pred= get_bits1(&s->gb);
2277                 if(s->new_pred){
2278                     printf("new pred not supported\n");
2279                     skip_bits(&s->gb, 2); /* requested upstream message type */
2280                     skip_bits1(&s->gb); /* newpred segment type */
2281                 }
2282                 s->reduced_res_vop= get_bits1(&s->gb);
2283                 if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");
2284             }
2285             else{
2286                 s->new_pred=0;
2287                 s->reduced_res_vop= 0;
2288             }
2289
2290             s->scalability= get_bits1(&s->gb);
2291             if (s->scalability) {
2292                 printf("scalability not supported\n");
2293             }
2294         }
2295 //printf("end Data %X %d\n", show_bits(&s->gb, 32), get_bits_count(&s->gb)&0x7);
2296         goto redo;
2297     } else if (startcode == 0x1b2) { //userdata
2298         char buf[256];
2299         int i;
2300         int e;
2301         int ver, build;
2302
2303 //printf("user Data %X\n", show_bits(&s->gb, 32));
2304         buf[0]= show_bits(&s->gb, 8);
2305         for(i=1; i<256; i++){
2306             buf[i]= show_bits(&s->gb, 16)&0xFF;
2307             if(buf[i]==0) break;
2308             skip_bits(&s->gb, 8);
2309         }
2310         buf[255]=0;
2311         e=sscanf(buf, "DivX%dBuild%d", &ver, &build);
2312         if(e==2){
2313             s->divx_version= ver;
2314             s->divx_build= build;
2315             if(s->picture_number==0){
2316                 printf("This file was encoded with DivX%d Build%d\n", ver, build);
2317                 if(ver==500 && build==413){ //most likely all version are indeed totally buggy but i dunno for sure ...
2318                     printf("WARNING: this version of DivX is not MPEG4 compatible, trying to workaround these bugs...\n");
2319                 }else{
2320                     printf("hmm, i havnt seen that version of divx yet, lets assume they fixed these bugs ...\n"
2321                            "using mpeg4 decoder, if it fails contact the developers (of ffmpeg)\n");
2322                 }
2323             }
2324         }
2325 //printf("User Data: %s\n", buf);
2326         goto redo;
2327     } else if (startcode != 0x1b6) { //VOP
2328         goto redo;
2329     }
2330
2331     s->pict_type = get_bits(&s->gb, 2) + 1;     /* pict type: I = 0 , P = 1 */
2332 //printf("pic: %d\n", s->pict_type); 
2333     time_incr=0;
2334     while (get_bits1(&s->gb) != 0) 
2335         time_incr++;
2336
2337     check_marker(&s->gb, "before time_increment");
2338     s->time_increment= get_bits(&s->gb, s->time_increment_bits);
2339     if(s->pict_type!=B_TYPE){
2340         s->time_base+= time_incr;
2341         s->last_non_b_time[1]= s->last_non_b_time[0];
2342         s->last_non_b_time[0]= s->time_base*s->time_increment_resolution + s->time_increment;
2343     }else{
2344         s->time= (s->last_non_b_time[1]/s->time_increment_resolution + time_incr)*s->time_increment_resolution;
2345         s->time+= s->time_increment;
2346     }
2347
2348     if(check_marker(&s->gb, "before vop_coded")==0 && s->picture_number==0){
2349         printf("hmm, seems the headers arnt complete, trying to guess time_increment_bits\n");
2350         for(s->time_increment_bits++ ;s->time_increment_bits<16; s->time_increment_bits++){
2351             if(get_bits1(&s->gb)) break;
2352         }
2353         printf("my guess is %d bits ;)\n",s->time_increment_bits);
2354     }
2355     /* vop coded */
2356     if (get_bits1(&s->gb) != 1)
2357         goto redo;
2358 //printf("time %d %d %d || %d %d %d\n", s->time_increment_bits, s->time_increment, s->time_base,
2359 //s->time, s->last_non_b_time[0], s->last_non_b_time[1]);  
2360     if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == P_TYPE
2361                           || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {
2362         /* rounding type for motion estimation */
2363         s->no_rounding = get_bits1(&s->gb);
2364     } else {
2365         s->no_rounding = 0;
2366     }
2367 //FIXME reduced res stuff
2368
2369      if (s->shape != RECT_SHAPE) {
2370          if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {
2371              int width, height, hor_spat_ref, ver_spat_ref;
2372  
2373              width = get_bits(&s->gb, 13);
2374              skip_bits1(&s->gb);   /* marker */
2375              height = get_bits(&s->gb, 13);
2376              skip_bits1(&s->gb);   /* marker */
2377              hor_spat_ref = get_bits(&s->gb, 13); /* hor_spat_ref */
2378              skip_bits1(&s->gb);   /* marker */
2379              ver_spat_ref = get_bits(&s->gb, 13); /* ver_spat_ref */
2380          }
2381          skip_bits1(&s->gb); /* change_CR_disable */
2382  
2383          if (get_bits1(&s->gb) != 0) {
2384              skip_bits(&s->gb, 8); /* constant_alpha_value */
2385          }
2386      }
2387 //FIXME complexity estimation stuff
2388      
2389      if (s->shape != BIN_ONLY_SHAPE) {
2390          skip_bits(&s->gb, 3); /* intra dc VLC threshold */
2391          //FIXME interlaced specific bits
2392      }
2393
2394      if(s->pict_type == S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){
2395          if(s->num_sprite_warping_points){
2396              mpeg4_decode_sprite_trajectory(s);
2397          }
2398          if(s->sprite_brightness_change) printf("sprite_brightness_change not supported\n");
2399          if(s->vol_sprite_usage==STATIC_SPRITE) printf("static sprite not supported\n");
2400      }
2401
2402      if (s->shape != BIN_ONLY_SHAPE) {
2403          /* note: we do not use quant_precision to avoid problem if no
2404             MPEG4 vol header as it is found on some old opendivx
2405             movies */
2406          s->qscale = get_bits(&s->gb, 5);
2407          if(s->qscale==0){
2408              printf("Error, header damaged or not MPEG4 header (qscale=0)\n");
2409              return -1; // makes no sense to continue, as there is nothing left from the image then
2410          }
2411   
2412          if (s->pict_type != I_TYPE) {
2413              s->f_code = get_bits(&s->gb, 3);   /* fcode_for */
2414              if(s->f_code==0){
2415                  printf("Error, header damaged or not MPEG4 header (f_code=0)\n");
2416                  return -1; // makes no sense to continue, as the MV decoding will break very quickly
2417              }
2418          }
2419          if (s->pict_type == B_TYPE) {
2420              s->b_code = get_bits(&s->gb, 3);
2421 //printf("b-code %d\n", s->b_code);
2422          }
2423 //printf("quant:%d fcode:%d\n", s->qscale, s->f_code);
2424          if(!s->scalability){
2425              if (s->shape!=RECT_SHAPE && s->pict_type!=I_TYPE) {
2426                  skip_bits1(&s->gb); // vop shape coding type
2427              }
2428          }
2429      }
2430      s->picture_number++; // better than pic number==0 allways ;)
2431      return 0;
2432 }
2433
2434 /* don't understand why they choose a different header ! */
2435 int intel_h263_decode_picture_header(MpegEncContext *s)
2436 {
2437     int format;
2438
2439     /* picture header */
2440     if (get_bits(&s->gb, 22) != 0x20)
2441         return -1;
2442     skip_bits(&s->gb, 8); /* picture timestamp */
2443
2444     if (get_bits1(&s->gb) != 1)
2445         return -1;      /* marker */
2446     if (get_bits1(&s->gb) != 0)
2447         return -1;      /* h263 id */
2448     skip_bits1(&s->gb); /* split screen off */
2449     skip_bits1(&s->gb); /* camera  off */
2450     skip_bits1(&s->gb); /* freeze picture release off */
2451
2452     format = get_bits(&s->gb, 3);
2453     if (format != 7)
2454         return -1;
2455
2456     s->h263_plus = 0;
2457
2458     s->pict_type = I_TYPE + get_bits1(&s->gb);
2459     
2460     s->unrestricted_mv = get_bits1(&s->gb); 
2461     s->h263_long_vectors = s->unrestricted_mv;
2462
2463     if (get_bits1(&s->gb) != 0)
2464         return -1;      /* SAC: off */
2465     if (get_bits1(&s->gb) != 0)
2466         return -1;      /* advanced prediction mode: off */
2467     if (get_bits1(&s->gb) != 0)
2468         return -1;      /* not PB frame */
2469
2470     /* skip unknown header garbage */
2471     skip_bits(&s->gb, 41);
2472
2473     s->qscale = get_bits(&s->gb, 5);
2474     skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */
2475
2476     /* PEI */
2477     while (get_bits1(&s->gb) != 0) {
2478         skip_bits(&s->gb, 8);
2479     }
2480     s->f_code = 1;
2481     return 0;
2482 }
2483