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