]> git.sesse.net Git - ffmpeg/blob - libavcodec/vc9.c
7a6f2182cbfcded7657a857bbfeb721fb077497b
[ffmpeg] / libavcodec / vc9.c
1 /*
2  * VC-9 and WMV3 decoder
3  * Copyright (c) 2005 Anonymous
4  * Copyright (c) 2005 Alex Beregszaszi
5  * Copyright (c) 2005 Michael Niedermayer
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library 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 GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22
23 /**
24  * @file vc9.c
25  * VC-9 and WMV3 decoder
26  *
27  * TODO: Norm-6 bitplane imode, most AP stuff, optimize, all of MB layer :)
28  * TODO: use MPV_ !!
29  */
30 #include "common.h"
31 #include "dsputil.h"
32 #include "avcodec.h"
33 #include "mpegvideo.h"
34 #include "vc9data.h"
35
36 extern const uint32_t ff_table0_dc_lum[120][2], ff_table1_dc_lum[120][2];
37 extern const uint32_t ff_table0_dc_chroma[120][2], ff_table1_dc_chroma[120][2];
38 extern VLC ff_msmp4_dc_luma_vlc[2], ff_msmp4_dc_chroma_vlc[2];
39 #define MB_INTRA_VLC_BITS 9
40 extern VLC ff_msmp4_mb_i_vlc;
41 #define DC_VLC_BITS 9
42 static const uint16_t table_mb_intra[64][2];
43
44 /* Some inhibiting stuff */
45 #define HAS_ADVANCED_PROFILE   1
46 #define TRACE                  1
47
48 #if TRACE
49 #  define INIT_VLC(vlc, nb_bits, nb_codes, bits, bits_wrap, bits_size, \
50                    codes, codes_wrap, codes_size, use_static)          \
51   if (init_vlc(vlc, nb_bits, nb_codes, bits, bits_wrap, bits_size,     \
52                codes, codes_wrap, codes_size, use_static) < 0)         \
53   {                                                                    \
54     av_log(v->s.avctx, AV_LOG_ERROR, "Error for " # vlc " (%i)\n", i);   \
55     return -1;                                                         \
56   }
57 #else
58 #  define INIT_VLC(vlc, nb_bits, nb_codes, bits, bits_wrap, bits_size, \
59                    codes, codes_wrap, codes_size, use_static)          \
60   init_vlc(vlc, nb_bits, nb_codes, bits, bits_wrap, bits_size,         \
61            codes, codes_wrap, codes_size, use_static)
62 #endif
63
64 #define PROFILE_SIMPLE   0
65 #define PROFILE_MAIN     1
66 #define PROFILE_ADVANCED 3
67
68 #define QUANT_FRAME_IMPLICIT   0
69 #define QUANT_FRAME_EXPLICIT   1
70 #define QUANT_NON_UNIFORM      2
71 #define QUANT_UNIFORM          3
72
73 /* Where quant can be changed */
74 #define DQPROFILE_FOUR_EDGES   0
75 #define DQPROFILE_DOUBLE_EDGES 1
76 #define DQPROFILE_SINGLE_EDGE  2
77 #define DQPROFILE_ALL_MBS      3
78
79 /* Which edge is quantized with ALTPQUANT */
80 #define DQSINGLE_BEDGE_LEFT   0
81 #define DQSINGLE_BEDGE_TOP    1
82 #define DQSINGLE_BEDGE_RIGHT  2
83 #define DQSINGLE_BEDGE_BOTTOM 3
84
85 /* Which pair of edges is quantized with ALTPQUANT */
86 #define DQDOUBLE_BEDGE_TOPLEFT     0
87 #define DQDOUBLE_BEDGE_TOPRIGHT    1
88 #define DQDOUBLE_BEDGE_BOTTOMRIGHT 2
89 #define DQDOUBLE_BEDGE_BOTTOMLEFT  3
90
91 /* MV P modes */
92 #define MV_PMODE_1MV_HPEL_BILIN   0
93 #define MV_PMODE_1MV              1
94 #define MV_PMODE_1MV_HPEL         2
95 #define MV_PMODE_MIXED_MV         3
96 #define MV_PMODE_INTENSITY_COMP   4
97
98 #define BMV_TYPE_BACKWARD          0
99 #define BMV_TYPE_FORWARD           1
100 #define BMV_TYPE_INTERPOLATED      3
101
102 /* MV P mode - the 5th element is only used for mode 1 */
103 static const uint8_t mv_pmode_table[2][5] = {
104   { MV_PMODE_1MV_HPEL_BILIN, MV_PMODE_1MV, MV_PMODE_1MV_HPEL, MV_PMODE_MIXED_MV, MV_PMODE_INTENSITY_COMP },
105   { MV_PMODE_1MV, MV_PMODE_MIXED_MV, MV_PMODE_1MV_HPEL, MV_PMODE_1MV_HPEL_BILIN, MV_PMODE_INTENSITY_COMP }
106 };
107
108 /* One more frame type */
109 #define BI_TYPE 7
110
111 /* FIXME Worse than ugly */
112 static const int fps_nr[5] = { 24, 25, 30, 50, 60 },
113   fps_dr[2] = { 1000, 1001 };
114 static const uint8_t pquant_table[3][32] = {
115   {  /* Implicit quantizer */
116      0,  1,  2,  3,  4,  5,  6,  7,  8,  6,  7,  8,  9, 10, 11, 12,
117     13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 29, 31
118   },
119   {  /* Explicit quantizer, pquantizer uniform */
120      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
121     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
122   },
123   {  /* Explicit quantizer, pquantizer non-uniform */
124      0,  1,  1,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13,
125     14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 31
126   }
127 };
128
129 // FIXME move this into the context
130 #define VC9_BFRACTION_VLC_BITS 7
131 static VLC vc9_bfraction_vlc;
132 #define VC9_IMODE_VLC_BITS 4
133 static VLC vc9_imode_vlc;
134 #define VC9_NORM2_VLC_BITS 3
135 static VLC vc9_norm2_vlc;
136 #if TILE_VLC_METHOD == 1
137 #define VC9_NORM6_VLC_BITS 9
138 static VLC vc9_norm6_vlc;
139 #endif
140 #if TILE_VLC_METHOD == 2
141 #define VC9_NORM6_FIRST_BITS 8
142 #define VC9_NORM6_SECOND 8
143 static VLC vc9_norm6_first, vc9_norm6_second;
144 #endif
145 /* Could be optimized, one table only needs 8 bits */
146 #define VC9_TTMB_VLC_BITS 9 //12
147 static VLC vc9_ttmb_vlc[3];
148 #define VC9_MV_DIFF_VLC_BITS 9 //15
149 static VLC vc9_mv_diff_vlc[4];
150 #define VC9_CBPCY_P_VLC_BITS 9 //14
151 static VLC vc9_cbpcy_p_vlc[4];
152 #define VC9_4MV_BLOCK_PATTERN_VLC_BITS 6
153 static VLC vc9_4mv_block_pattern_vlc[4];
154
155 //We mainly need data and is_raw, so this struct could be avoided
156 //to save a level of indirection; feel free to modify
157 typedef struct BitPlane {
158     uint8_t *data;
159     int width, stride;
160     int height;
161     uint8_t is_raw;
162 } BitPlane;
163
164 typedef struct VC9Context{
165   /* No MpegEnc context, might be good to use it */
166   MpegEncContext s;
167
168   /***************************/
169   /* Sequence Header         */
170   /***************************/
171   /* Simple/Main Profile */
172   int res_sm; //reserved, 2b
173   int res_x8; //reserved
174   int multires; //frame-level RESPIC syntax element present
175   int res_fasttx; //always 1
176   int res_transtab; //always 0
177   int rangered; //RANGEREDFRM (range reduction) syntax element present
178   int res_rtm_flag; //reserved, set to 1
179   int reserved; //duh
180
181 #if HAS_ADVANCED_PROFILE
182   /* Advanced Profile */
183   int level; //3
184   int chromaformat; //2
185   int postprocflag; //frame-based processing use
186   int broadcast; //TFF/RFF present
187     int interlace; //Progressive/interlaced (RPTFTM syntax element)
188   int tfcntrflag; //TFCNTR present
189   int panscanflag; //NUMPANSCANWIN, TOPLEFT{X,Y}, BOTRIGHT{X,Y} presents
190     int extended_dmv;
191   int color_prim; //8
192   int transfer_char; //8
193   int matrix_coef; //8
194   int hrd_param_flag;
195 #endif
196
197   /* All Profiles */
198   /* TODO: move all int to flags */
199   int profile; //2
200   int frmrtq_postproc; //3
201   int bitrtq_postproc; //5
202     int loopfilter;
203     int fastuvmc; //Rounding of qpel vector to hpel ? (not in Simple)
204   int extended_mv; //Ext MV in P/B (not in Simple)
205   int dquant; //How qscale varies with MBs, 2bits (not in Simple)
206   int vstransform; //variable-size transform46
207   
208
209   int overlap; //overlapped transforms in use
210   int quantizer_mode; //2, quantizer mode used for sequence, see QUANT_*
211   int finterpflag; //INTERPFRM present
212
213
214   /*****************************/
215   /* Frame decoding            */
216   /*****************************/
217   /* All profiles */
218   uint8_t mv_mode, mv_mode2; /* MV coding mode */
219   uint8_t pq, altpq; /* Quantizers */
220   uint8_t dquantfrm, dqprofile, dqsbedge, dqbilevel; /* pquant parameters */
221   int tile; /* 3x2 if (width_mb%3) else 2x3 */
222   int ac_table_level;
223   VLC *luma_dc_vlc, *chroma_dc_vlc; /* transac/dcfrm bits are indexes */
224   uint8_t ttmbf, ttfrm; /* Transform type */
225   uint8_t lumscale, lumshift; /* Luma compensation parameters */
226   int16_t bfraction; /* Relative position % anchors=> how to scale MVs */
227   uint8_t halfpq; /* Uniform quant over image and qp+.5 */
228   uint8_t respic;
229   int buffer_fullness; /* For HRD ? */
230   /* Ranges:
231    * 0 -> [-64n 63.f] x [-32, 31.f]
232    * 1 -> [-128, 127.f] x [-64, 63.f]
233    * 2 -> [-512, 511.f] x [-128, 127.f]
234    * 3 -> [-1024, 1023.f] x [-256, 255.f]
235    */
236   uint8_t mvrange;
237   uint8_t pquantizer;
238   uint8_t *previous_line_cbpcy; /* To use for predicted CBPCY */
239   VLC *cbpcy_vlc /* Current CBPCY VLC table */,
240     *ttmb_vlc /* Current MB Transform Type VLC table */;
241   BitPlane mv_type_mb_plane; /* bitplane for mv_type == (4MV) */
242   BitPlane skip_mb_plane, /* bitplane for skipped MBs */
243     direct_mb_plane; /* bitplane for "direct" MBs */
244
245   /* S/M only ? */
246   uint8_t rangeredfrm; /* out_sample = CLIP((in_sample-128)*2+128) */
247   uint8_t interpfrm;
248
249 #if HAS_ADVANCED_PROFILE
250   /* Advanced */
251   uint8_t fcm; //0->Progressive, 2->Frame-Interlace, 3->Field-Interlace
252   uint8_t numpanscanwin;
253   uint8_t tfcntr;
254   uint8_t rptfrm, tff, rff;
255   uint8_t topleftx;
256   uint8_t toplefty;
257   uint8_t bottomrightx;
258   uint8_t bottomrighty;
259   uint8_t uvsamp;
260   uint8_t postproc;
261   int hrd_num_leaky_buckets;
262   uint8_t bit_rate_exponent;
263   uint8_t buffer_size_exponent;
264   BitPlane ac_pred_plane; //AC prediction flags bitplane
265   BitPlane over_flags_plane; //Overflags bitplane
266   uint8_t condover;
267   uint16_t *hrd_rate, *hrd_buffer;
268   VLC *luma_ac2_vlc, *chroma_ac2_vlc;
269 #endif
270 } VC9Context;
271
272 /* FIXME Slow and ugly */
273 static int get_prefix(GetBitContext *gb, int stop, int len)
274 {
275 #if 1
276   int i = 0, tmp = !stop;
277
278   while (i != len && tmp != stop)
279   {
280     tmp = get_bits(gb, 1);
281     i++;
282   }
283   return i;
284 #else
285   unsigned int buf;
286   int log;
287
288   OPEN_READER(re, gb);
289   UPDATE_CACHE(re, gb);
290   buf=GET_CACHE(re, gb); //Still not sure
291   if (stop) buf = ~buf;
292   
293   log= av_log2(-buf); //FIXME: -?
294   if (log < limit){
295     LAST_SKIP_BITS(re, gb, log+1);
296     CLOSE_READER(re, gb);
297     return log;
298   }
299   
300   LAST_SKIP_BITS(re, gb, limit);
301   CLOSE_READER(re, gb);
302   return limit;
303 #endif
304 }
305
306 static int vc9_init_common(VC9Context *v)
307 {
308     static int done = 0;
309     int i;
310
311     /* Set the bit planes */
312     /* FIXME memset better ? (16bytes) */
313     v->mv_type_mb_plane = (struct BitPlane) { NULL, 0, 0, 0 };
314     v->direct_mb_plane = (struct BitPlane) { NULL, 0, 0, 0 };
315     v->skip_mb_plane = (struct BitPlane) { NULL, 0, 0, 0 };
316 #if HAS_ADVANCED_PROFILE
317     v->ac_pred_plane = v->over_flags_plane = (struct BitPlane) { NULL, 0, 0, 0 };
318     v->hrd_rate = v->hrd_buffer = NULL;
319 #endif
320
321     /* VLC tables */
322 #if TILE_VLC_METHOD == 1
323 #  if 0 // spec -> actual tables converter
324     for(i=0; i<64; i++){
325         int code= (vc9_norm6_spec[i][1] << vc9_norm6_spec[i][4]) + vc9_norm6_spec[i][3];
326         av_log(NULL, AV_LOG_DEBUG, "0x%03X, ", code);
327         if(i%16==15) av_log(NULL, AV_LOG_DEBUG, "\n");
328     }
329     for(i=0; i<64; i++){
330         int code= vc9_norm6_spec[i][2] + vc9_norm6_spec[i][4];
331         av_log(NULL, AV_LOG_DEBUG, "%2d, ", code);
332         if(i%16==15) av_log(NULL, AV_LOG_DEBUG, "\n");
333     }
334 #  endif
335 #endif
336     if(!done)
337     {
338         done = 1;
339         INIT_VLC(&vc9_bfraction_vlc, VC9_BFRACTION_VLC_BITS, 23,
340                  vc9_bfraction_bits, 1, 1,
341                  vc9_bfraction_codes, 1, 1, 1);
342         INIT_VLC(&vc9_norm2_vlc, VC9_NORM2_VLC_BITS, 4,
343                  vc9_norm2_bits, 1, 1,
344                  vc9_norm2_codes, 1, 1, 1);
345 #if TILE_VLC_METHOD == 1
346         INIT_VLC(&vc9_norm6_vlc, VC9_NORM6_VLC_BITS, 64,
347                  vc9_norm6_bits, 1, 1,
348                  vc9_norm6_codes, 2, 2, 1);
349 #endif
350 #if TILE_VLC_METHOD == 2
351         INIT_VLC(&vc9_norm6_first, VC9_NORM6_FIRST_BITS, 64,
352                  &vc9_norm6_first[0][1], 1, 1,
353                  &vc9_norm6_first[0][0], 1, 1, 1);
354         INIT_VLC(&vc9_norm6_second, VC9_NORM6_SECOND_BITS, 64,
355                  vc9_norm6_second[0][1], 1, 1,
356                  vc9_norm6_second[0][1], 1, 1, 1);
357 #endif
358         INIT_VLC(&vc9_imode_vlc, VC9_IMODE_VLC_BITS, 7,
359                  vc9_imode_bits, 1, 1,
360                  vc9_imode_codes, 1, 1, 1);
361         for (i=0; i<3; i++)
362         {
363             INIT_VLC(&vc9_ttmb_vlc[i], VC9_TTMB_VLC_BITS, 16,
364                      vc9_ttmb_bits[i], 1, 1,
365                      vc9_ttmb_codes[i], 2, 2, 1);
366         }
367         for(i=0; i<4; i++)
368         {
369             INIT_VLC(&vc9_4mv_block_pattern_vlc[i], VC9_4MV_BLOCK_PATTERN_VLC_BITS, 16,
370                      vc9_4mv_block_pattern_bits[i], 1, 1,
371                      vc9_4mv_block_pattern_codes[i], 1, 1, 1);
372             INIT_VLC(&vc9_cbpcy_p_vlc[i], VC9_CBPCY_P_VLC_BITS, 64,
373                      vc9_cbpcy_p_bits[i], 1, 1,
374                      vc9_cbpcy_p_codes[i], 2, 2, 1);
375             INIT_VLC(&vc9_mv_diff_vlc[i], VC9_MV_DIFF_VLC_BITS, 73,
376                      vc9_mv_diff_bits[i], 1, 1,
377                      vc9_mv_diff_codes[i], 2, 2, 1);
378         }
379     }
380
381     /* Other defaults */
382     v->pq = -1;
383     v->mvrange = 0; /* 7.1.1.18, p80 */
384
385     return 0;
386 }
387
388 #if HAS_ADVANCED_PROFILE
389 /* 6.2.1, p32 */
390 static int decode_hrd(VC9Context *v, GetBitContext *gb)
391 {
392     int i, num;
393
394     num = get_bits(gb, 5);
395
396     if (v->hrd_rate || num != v->hrd_num_leaky_buckets)
397     {
398         av_freep(&v->hrd_rate);
399     }
400     if (!v->hrd_rate) v->hrd_rate = av_malloc(num*sizeof(uint16_t));
401     if (!v->hrd_rate) return -1;
402
403     if (v->hrd_buffer || num != v->hrd_num_leaky_buckets)
404     {
405         av_freep(&v->hrd_buffer);
406     }
407     if (!v->hrd_buffer) v->hrd_buffer = av_malloc(num*sizeof(uint16_t));
408     if (!v->hrd_buffer) return -1;
409
410     v->hrd_num_leaky_buckets = num;
411
412     //exponent in base-2 for rate
413     v->bit_rate_exponent = get_bits(gb, 4);
414     //exponent in base-2 for buffer_size
415     v->buffer_size_exponent = get_bits(gb, 4);
416
417     for (i=0; i<num; i++)
418     {
419         //mantissae, ordered (if not, use a function ?
420         v->hrd_rate[i] = get_bits(gb, 16);
421         if (i && v->hrd_rate[i-1]>=v->hrd_rate[i])
422         {
423             av_log(v->s.avctx, AV_LOG_ERROR, "HDR Rates aren't strictly increasing:"
424                    "%i vs %i\n", v->hrd_rate[i-1], v->hrd_rate[i]);
425             return -1;
426         }
427         v->hrd_buffer[i] = get_bits(gb, 16);
428         if (i && v->hrd_buffer[i-1]<v->hrd_buffer[i])
429         {
430             av_log(v->s.avctx, AV_LOG_ERROR, "HDR Buffers aren't decreasing:"
431                    "%i vs %i\n", v->hrd_buffer[i-1], v->hrd_buffer[i]);
432             return -1;
433         }
434     }
435     return 0;
436 }
437
438 /* Table 2, p18 */
439 static int decode_advanced_sequence_header(AVCodecContext *avctx, GetBitContext *gb)
440 {
441     VC9Context *v = avctx->priv_data;
442     int nr, dr, aspect_ratio;
443
444     v->postprocflag = get_bits(gb, 1);
445     v->broadcast = get_bits(gb, 1);
446     v->interlace = get_bits(gb, 1);
447
448     v->tfcntrflag = get_bits(gb, 1);
449     v->finterpflag = get_bits(gb, 1); //common
450     v->panscanflag = get_bits(gb, 1);
451     v->reserved = get_bits(gb, 1);
452     if (v->reserved)
453     {
454         av_log(avctx, AV_LOG_ERROR, "RESERVED should be 0 (is %i)\n",
455                v->reserved);
456         return -1;
457     }
458     if (v->extended_mv)
459         v->extended_dmv = get_bits(gb, 1);
460
461     /* 6.1.7, p21 */
462     if (get_bits(gb, 1) /* pic_size_flag */)
463     {
464         avctx->coded_width = get_bits(gb, 12);
465         avctx->coded_height = get_bits(gb, 12);
466         if ( get_bits(gb, 1) /* disp_size_flag */)
467         {
468             avctx->width = get_bits(gb, 14);
469             avctx->height = get_bits(gb, 14);
470         }
471
472         /* 6.1.7.4, p22 */
473         if ( get_bits(gb, 1) /* aspect_ratio_flag */)
474         {
475             aspect_ratio = get_bits(gb, 4); //SAR
476             if (aspect_ratio == 0x0F) //FF_ASPECT_EXTENDED
477             {
478                 avctx->sample_aspect_ratio.num = get_bits(gb, 8);
479                 avctx->sample_aspect_ratio.den = get_bits(gb, 8);
480             }
481             else if (aspect_ratio == 0x0E)
482             {
483                 av_log(avctx, AV_LOG_DEBUG, "Reserved AR found\n");
484             }
485             else
486             {
487               avctx->sample_aspect_ratio = vc9_pixel_aspect[aspect_ratio];
488             }
489         }
490     }
491     else
492     {
493         avctx->coded_width = avctx->width;
494         avctx->coded_height = avctx->height;
495     }
496
497     /* 6.1.8, p23 */
498     if ( !get_bits(gb, 1) /* framerateflag */)
499     {
500         if ( get_bits(gb, 1) /* framerateind */)
501         {
502             nr = get_bits(gb, 8);
503             dr = get_bits(gb, 4);
504             if (nr<1)
505             {
506                 av_log(avctx, AV_LOG_ERROR, "0 is forbidden for FRAMERATENR\n");
507                 return -1;
508             }
509             if (nr>5)
510             {
511                 av_log(avctx, AV_LOG_ERROR,
512                        "Reserved FRAMERATENR %i not handled\n", nr);
513            }
514             if (dr<1)
515             {
516                 av_log(avctx, AV_LOG_ERROR, "0 is forbidden for FRAMERATEDR\n");
517            }
518             if (dr>2)
519             {
520                 av_log(avctx, AV_LOG_ERROR,
521                        "Reserved FRAMERATEDR %i not handled\n", dr);
522             }
523             avctx->frame_rate_base = fps_nr[dr];
524             avctx->frame_rate = fps_nr[nr];
525         }
526         else
527         {
528             nr = get_bits(gb, 16);
529             // 0.03125->2048Hz / 0.03125Hz
530             avctx->frame_rate = 1000000;
531             avctx->frame_rate_base = 31250*(1+nr);
532         }
533     }
534
535     /* 6.1.9, p25 */
536     if ( get_bits(gb, 1) /* color_format_flag */)
537     {
538         //Chromacity coordinates of color primaries
539         //like ITU-R BT.709-2, BT.470-2, ...
540         v->color_prim = get_bits(gb, 8);
541         if (v->color_prim<1)
542         {
543             av_log(avctx, AV_LOG_ERROR, "0 for COLOR_PRIM is reserved\n");
544             return -1;
545         }
546         if (v->color_prim == 3 || v->color_prim>6)
547         {
548             av_log(avctx, AV_LOG_DEBUG, "Reserved COLOR_PRIM %i found\n",
549                    v->color_prim);
550             return -1;
551         }
552
553         //Opto-electronic transfer characteristics
554         v->transfer_char = get_bits(gb, 8);
555         if (v->transfer_char == 3 || v->transfer_char>8)
556         {
557             av_log(avctx, AV_LOG_DEBUG, "Reserved TRANSFERT_CHAR %i found\n",
558                    v->color_prim);
559             return -1;
560         }
561
562         //Matrix coefficient for primariev->YCbCr
563         v->matrix_coef = get_bits(gb, 8);
564         if (v->matrix_coef < 1) return -1; //forbidden
565         if ((v->matrix_coef>3 && v->matrix_coef<6) || v->matrix_coef>7)
566         {
567             av_log(avctx, AV_LOG_DEBUG, "Reserved MATRIX_COEF %i found\n",
568                    v->color_prim);
569             return -1;
570         }
571     }
572
573     //Hypothetical reference decoder indicator flag
574     v->hrd_param_flag = get_bits(gb, 1);
575     if (v->hrd_param_flag)
576     {
577       if (decode_hrd(v, gb) < 0) return -1;
578     }
579
580     av_log(avctx, AV_LOG_DEBUG, "Advanced profile not supported yet\n");
581     return -1;
582 }
583 #endif
584
585 /* Figure 7-8, p16-17 */
586 static int decode_sequence_header(AVCodecContext *avctx, GetBitContext *gb)
587 {
588     VC9Context *v = avctx->priv_data;
589
590     v->profile = get_bits(gb, 2);
591     av_log(avctx, AV_LOG_DEBUG, "Profile: %i\n", v->profile);
592
593 #if HAS_ADVANCED_PROFILE
594     if (v->profile > PROFILE_MAIN)
595     {
596         v->level = get_bits(gb, 3);
597         v->chromaformat = get_bits(gb, 2);
598         if (v->chromaformat != 1)
599         {
600             av_log(avctx, AV_LOG_ERROR,
601                    "Only 4:2:0 chroma format supported\n");
602             return -1;
603         }
604     }
605     else
606 #endif
607     {
608         v->res_sm = get_bits(gb, 2); //reserved
609         if (v->res_sm)
610         {
611             av_log(avctx, AV_LOG_ERROR,
612                    "Reserved RES_SM=%i is forbidden\n", v->res_sm);
613             //return -1;
614         }
615     }
616
617     // (fps-2)/4 (->30)
618     v->frmrtq_postproc = get_bits(gb, 3); //common
619     // (bitrate-32kbps)/64kbps
620     v->bitrtq_postproc = get_bits(gb, 5); //common
621     v->s.loop_filter = get_bits(gb, 1); //common
622
623 #if HAS_ADVANCED_PROFILE
624     if (v->profile <= PROFILE_MAIN)
625 #endif
626     {
627         v->res_x8 = get_bits(gb, 1); //reserved
628         if (v->res_x8)
629         {
630             av_log(avctx, AV_LOG_ERROR,
631                    "1 for reserved RES_X8 is forbidden\n");
632             //return -1;
633         }
634         v->multires = get_bits(gb, 1);
635         v->res_fasttx = get_bits(gb, 1);
636         if (!v->res_fasttx)
637         {
638             av_log(avctx, AV_LOG_ERROR,
639                    "0 for reserved RES_FASTTX is forbidden\n");
640             //return -1;
641         }
642     }
643
644     v->fastuvmc =  get_bits(gb, 1); //common
645     if (!v->profile && !v->fastuvmc)
646     {
647         av_log(avctx, AV_LOG_ERROR,
648                "FASTUVMC unavailable in Simple Profile\n");
649         return -1;
650     }
651     v->extended_mv =  get_bits(gb, 1); //common
652     if (!v->profile && v->extended_mv)
653     {
654         av_log(avctx, AV_LOG_ERROR,
655                "Extended MVs unavailable in Simple Profile\n");
656         return -1;
657     }
658     v->dquant =  get_bits(gb, 2); //common
659     v->vstransform =  get_bits(gb, 1); //common
660     
661 #if HAS_ADVANCED_PROFILE
662     if (v->profile <= PROFILE_MAIN)
663 #endif
664     {
665         v->res_transtab = get_bits(gb, 1);
666         if (v->res_transtab)
667         {
668             av_log(avctx, AV_LOG_ERROR,
669                    "1 for reserved RES_TRANSTAB is forbidden\n");
670             return -1;
671         }
672     }
673
674     v->overlap = get_bits(gb, 1); //common
675
676 #if HAS_ADVANCED_PROFILE
677     if (v->profile <= PROFILE_MAIN)
678 #endif
679     {
680         v->s.resync_marker = get_bits(gb, 1);
681         v->rangered = get_bits(gb, 1);
682     }
683
684     v->s.max_b_frames = avctx->max_b_frames = get_bits(gb, 3); //common
685     v->quantizer_mode = get_bits(gb, 2); //common
686
687 #if HAS_ADVANCED_PROFILE
688     if (v->profile <= PROFILE_MAIN)
689 #endif
690     {
691         v->finterpflag = get_bits(gb, 1); //common
692         v->res_rtm_flag = get_bits(gb, 1); //reserved
693         if (!v->res_rtm_flag)
694         {
695             av_log(avctx, AV_LOG_ERROR,
696                    "0 for reserved RES_RTM_FLAG is forbidden\n");
697             //return -1;
698         }
699 #if TRACE
700         av_log(avctx, AV_LOG_INFO,
701                "Profile %i:\nfrmrtq_postproc=%i, bitrtq_postproc=%i\n"
702                "LoopFilter=%i, MultiRes=%i, FastUVMV=%i, Extended MV=%i\n"
703                "Rangered=%i, VSTransform=%i, Overlap=%i, SyncMarker=%i\n"
704                "DQuant=%i, Quantizer mode=%i, Max B frames=%i\n",
705                v->profile, v->frmrtq_postproc, v->bitrtq_postproc,
706                v->loopfilter, v->multires, v->fastuvmc, v->extended_mv,
707                v->rangered, v->vstransform, v->overlap, v->s.resync_marker,
708                v->dquant, v->quantizer_mode, avctx->max_b_frames
709                );
710         return 0;
711 #endif
712     }
713 #if HAS_ADVANCED_PROFILE
714     else return decode_advanced_sequence_header(avctx, gb);
715 #endif
716 }
717
718
719 #if HAS_ADVANCED_PROFILE
720 /*****************************************************************************/
721 /* Entry point decoding (Advanced Profile)                                   */
722 /*****************************************************************************/
723 static int advanced_entry_point_process(AVCodecContext *avctx, GetBitContext *gb)
724 {
725     VC9Context *v = avctx->priv_data;
726     int range_mapy_flag, range_mapuv_flag, i;
727     if (v->profile != PROFILE_ADVANCED)
728     {
729         av_log(avctx, AV_LOG_ERROR,
730                "Entry point are only defined in Advanced Profile!\n");
731         return -1; //Only for advanced profile!
732     }
733     if (v->hrd_param_flag)
734     {
735         //Update buffer fullness
736         av_log(avctx, AV_LOG_DEBUG, "Buffer fullness update\n");
737         for (i=0; i<v->hrd_num_leaky_buckets; i++)
738             skip_bits(gb, 8);
739     }
740     if ((range_mapy_flag = get_bits(gb, 1)))
741     {
742         //RANGE_MAPY
743         av_log(avctx, AV_LOG_DEBUG, "RANGE_MAPY\n");
744         skip_bits(gb, 3);
745     }
746     if ((range_mapuv_flag = get_bits(gb, 1)))
747     {
748         //RANGE_MAPUV
749         av_log(avctx, AV_LOG_DEBUG, "RANGE_MAPUV\n");
750         skip_bits(gb, 3);
751     }
752     if (v->panscanflag)
753     {
754         //NUMPANSCANWIN
755         v->numpanscanwin = get_bits(gb, 3);
756         av_log(avctx, AV_LOG_DEBUG, "NUMPANSCANWIN: %u\n", v->numpanscanwin);
757     }
758     return 0;
759 }
760 #endif
761
762 /******************************************************************************/
763 /* Bitplane decoding: 8.7, p56                                                */
764 /******************************************************************************/
765 #define IMODE_RAW     0
766 #define IMODE_NORM2   1
767 #define IMODE_DIFF2   2
768 #define IMODE_NORM6   3
769 #define IMODE_DIFF6   4
770 #define IMODE_ROWSKIP 5
771 #define IMODE_COLSKIP 6
772 int alloc_bitplane(BitPlane *bp, int width, int height)
773 {
774     if (!bp || bp->width<0 || bp->height<0) return -1;
775     bp->data = (uint8_t*)av_malloc(width*height);
776     if (!bp->data) return -1;
777     bp->width = bp->stride = width; //FIXME Needed for aligned data ?
778     bp->height = height;
779     return 0;
780 }
781
782 void free_bitplane(BitPlane *bp)
783 {
784     bp->width = bp->stride = bp->height = 0;
785     if (bp->data) av_freep(&bp->data);
786 }
787
788 static void decode_rowskip(uint8_t* plane, int width, int height, int stride, VC9Context *v){
789     int x, y;
790     GetBitContext *gb = &v->s.gb;
791
792     for (y=0; y<height; y++){
793         if (!get_bits(gb, 1)) //rowskip
794             memset(plane, 0, width);
795         else
796             for (x=0; x<width; x++) 
797                 plane[x] = get_bits(gb, 1);
798         plane += stride;
799     }
800 }
801
802 //FIXME optimize
803 static void decode_colskip(uint8_t* plane, int width, int height, int stride, VC9Context *v){
804     int x, y;
805     GetBitContext *gb = &v->s.gb;
806
807     for (x=0; x<width; x++){
808         if (!get_bits(gb, 1)) //colskip
809             for (y=0; y<height; y++)
810                 plane[y*stride] = 0;
811         else
812             for (y=0; y<height; y++)
813                 plane[y*stride] = get_bits(gb, 1);
814         plane ++;
815     }
816 }
817
818 //FIXME optimize
819 //FIXME Use BitPlane struct or return if table is raw (no bits read here but
820 //      later on)
821 //Elements must be either 0 or 1
822 static int bitplane_decoding(BitPlane *bp, VC9Context *v)
823 {
824     GetBitContext *gb = &v->s.gb;
825
826     int imode, x, y, code, use_vertical_tile, tile_w, tile_h;
827     uint8_t invert, *planep = bp->data;
828
829     invert = get_bits(gb, 1);
830     imode = get_vlc2(gb, vc9_imode_vlc.table, VC9_IMODE_VLC_BITS, 2);
831
832     bp->is_raw = 0;
833     switch (imode)
834     {
835     case IMODE_RAW:
836         //Data is actually read in the MB layer (same for all tests == "raw")
837         bp->is_raw = 1; //invert ignored
838         return invert;
839     case IMODE_DIFF2:
840     case IMODE_NORM2:
841         if ((bp->height*bp->width) & 1) *(++planep) = get_bits(gb, 1);
842         for(x=0; x<(bp->height*bp->width)>>1; x++){
843             code = get_vlc2(gb, vc9_norm2_vlc.table, VC9_NORM2_VLC_BITS, 2);
844             *(++planep) = code&1; //lsb => left
845             *(++planep) = (code>>1)&1; //msb => right
846             //FIXME width->stride
847         }
848         break;
849     case IMODE_DIFF6:
850     case IMODE_NORM6:
851         use_vertical_tile=  bp->height%3==0 &&  bp->width%3!=0;
852         tile_w= use_vertical_tile ? 2 : 3;
853         tile_h= use_vertical_tile ? 3 : 2;
854
855         for(y=  bp->height%tile_h; y< bp->height; y+=tile_h){
856             for(x=  bp->width%tile_w; x< bp->width; x+=tile_w){
857 #if TILE_VLC_METHOD == 1 //FIXME Too much optimized ?
858                 code = get_vlc2(gb, vc9_norm6_vlc.table, VC9_NORM6_VLC_BITS, 2);
859                 if(code<0){
860                     av_log(v->s.avctx, AV_LOG_DEBUG, "inavlid NORM-6 VLC\n");
861                     return -1;
862                 }
863 #endif
864 #if TILE_VLC_METHOD == 2 //TODO Optimize VLC decoding
865                 code = get_vlc2(gb, vc9_norm6_first.table, VC9_NORM6_FIRST_BITS, 2);
866                 if (vc9_norm6_mode[code] == 1)
867                 {
868 #  if TRACE
869                     code = get_bits(gb, 5);
870                     assert(code>-1 && code<20);
871                     code = vc9_norm6_flc_val[code];
872 #  else
873                     code = vc9_norm6_flc_val[get_bits(gb, 5)];
874 #  endif
875                 }
876                 else if (vc9_norm6_mode[code] == 2)
877                 {
878 #  if TRACE
879                     code = get_vlc2(gb, vc9_norm6_second.table, VC9_NORM6_SECOND_BITS, 2);
880                     assert(code>-1 && code<22);
881                     code = vc9_norm6_second_val[code];
882 #  else
883                     code = vc9_norm6_second_val[get_vlc2(gb, vc9_norm6_second.table, VC9_NORM6_SECOND_BITS, 2)];
884 #  endif
885 #endif //TILE_VLC_METHOD == 2
886                 //FIXME following is a pure guess and probably wrong
887                 //FIXME A bitplane (0 | !0), so could the shifts be avoided ?
888                 planep[x     + 0*bp->stride]= (code>>0)&1;
889                 planep[x + 1 + 0*bp->stride]= (code>>1)&1;
890                 //FIXME Does branch prediction help here?
891                 if(use_vertical_tile){
892                     planep[x + 0 + 1*bp->stride]= (code>>2)&1;
893                     planep[x + 1 + 1*bp->stride]= (code>>3)&1;
894                     planep[x + 0 + 2*bp->stride]= (code>>4)&1;
895                     planep[x + 1 + 2*bp->stride]= (code>>5)&1;
896                 }else{
897                     planep[x + 2 + 0*bp->stride]= (code>>2)&1;
898                     planep[x + 0 + 1*bp->stride]= (code>>3)&1;
899                     planep[x + 1 + 1*bp->stride]= (code>>4)&1;
900                     planep[x + 2 + 1*bp->stride]= (code>>5)&1;
901                 }
902             }
903         }
904
905         x=  bp->width % tile_w;
906         decode_colskip(bp->data  ,             x, bp->height         , bp->stride, v);
907         decode_rowskip(bp->data+x, bp->width - x, bp->height % tile_h, bp->stride, v);
908
909         break;
910     case IMODE_ROWSKIP:
911         decode_rowskip(bp->data, bp->width, bp->height, bp->stride, v);
912         break;
913     case IMODE_COLSKIP: //Teh ugly
914         decode_colskip(bp->data, bp->width, bp->height, bp->stride, v);
915         break;
916     default: break;
917     }
918
919     /* Applying diff operator */
920     if (imode == IMODE_DIFF2 || imode == IMODE_DIFF6)
921     {
922         planep = bp->data;
923         planep[0] ^= invert;
924         for (x=1; x<bp->width; x++)
925             planep[x] ^= planep[x-1];
926         for (y=1; y<bp->height; y++)
927         {
928             planep += bp->stride;
929             planep[0] ^= planep[-bp->stride];
930             for (x=1; x<bp->width; x++)
931             {
932                 if (planep[x-1] != planep[x-bp->stride]) planep[x] ^= invert;
933                 else                                     planep[x] ^= planep[x-1];
934             }
935         }
936     }
937     else if (invert)
938     {
939         planep = bp->data;
940         for (x=0; x<bp->width*bp->height; x++) planep[x] = !planep[x]; //FIXME stride
941     }
942     return (imode<<1) + invert;
943 }
944
945 /*****************************************************************************/
946 /* VOP Dquant decoding                                                       */
947 /*****************************************************************************/
948 static int vop_dquant_decoding(VC9Context *v)
949 {
950     GetBitContext *gb = &v->s.gb;
951     int pqdiff;
952
953     //variable size
954     if (v->dquant == 2)
955     {
956         pqdiff = get_bits(gb, 3);
957         if (pqdiff == 7) v->altpq = get_bits(gb, 5);
958         else v->altpq = v->pq + pqdiff + 1;
959     }
960     else
961     {
962         v->dquantfrm = get_bits(gb, 1);
963         if ( v->dquantfrm )
964         {
965             v->dqprofile = get_bits(gb, 2);
966             switch (v->dqprofile)
967             {
968             case DQPROFILE_SINGLE_EDGE:
969             case DQPROFILE_DOUBLE_EDGES:
970                 v->dqsbedge = get_bits(gb, 2);
971                 break;
972             case DQPROFILE_ALL_MBS:
973                 v->dqbilevel = get_bits(gb, 1);
974             default: break; //Forbidden ?
975             }
976             if (!v->dqbilevel || v->dqprofile != DQPROFILE_ALL_MBS)
977             {
978                 pqdiff = get_bits(gb, 3);
979                 if (pqdiff == 7) v->altpq = get_bits(gb, 5);
980                 else v->altpq = v->pq + pqdiff + 1;
981             }
982         }
983     }
984     return 0;
985 }
986
987 /*****************************************************************************/
988 /* All Profiles picture header decoding specific functions                   */
989 /* Only pro/epilog differs between Simple/Main and Advanced => check caller  */
990 /*****************************************************************************/
991
992 /* Tables 11+12, p62-65 */
993 static int decode_b_picture_primary_header(VC9Context *v)
994 {
995     GetBitContext *gb = &v->s.gb;
996     int pqindex, status;
997
998     /* Prolog common to all frametypes should be done in caller */
999     if (v->profile == PROFILE_SIMPLE)
1000     {
1001         av_log(v->s.avctx, AV_LOG_ERROR, "Found a B frame while in Simple Profile!\n");
1002         return FRAME_SKIPED;
1003     }
1004
1005     v->bfraction = vc9_bfraction_lut[get_vlc2(gb, vc9_bfraction_vlc.table,
1006                                               VC9_BFRACTION_VLC_BITS, 2)];
1007     if (v->bfraction < -1)
1008     {
1009         av_log(v->s.avctx, AV_LOG_ERROR, "Invalid BFRaction\n");
1010         return FRAME_SKIPED;
1011     }
1012     else if (!v->bfraction)
1013     {
1014         /* We actually have a BI frame */
1015         v->s.pict_type = BI_TYPE;
1016         v->buffer_fullness = get_bits(gb, 7);
1017     }
1018
1019     /* Read the quantization stuff */
1020     pqindex = get_bits(gb, 5);
1021     if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)
1022         v->pq = pquant_table[0][pqindex];
1023     else
1024     {
1025         v->pq = pquant_table[v->quantizer_mode-1][pqindex];
1026     }
1027     if (pqindex < 9) v->halfpq = get_bits(gb, 1);
1028     if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)
1029         v->pquantizer = get_bits(gb, 1);
1030
1031     /* Read the MV type/mode */
1032     if (v->extended_mv == 1)
1033         v->mvrange = get_prefix(gb, 0, 3);
1034     if (v->s.pict_type != BI_TYPE)
1035     {
1036         v->mv_mode = get_bits(gb, 1);
1037         if (v->pq < 13)
1038         {
1039             if (!v->mv_mode)
1040             {
1041                 v->mv_mode = get_bits(gb, 2);
1042                 if (v->mv_mode)
1043                 av_log(v->s.avctx, AV_LOG_ERROR,
1044                        "mv_mode for lowquant B frame was %i\n", v->mv_mode);
1045             }
1046         }
1047         else
1048         {
1049             if (!v->mv_mode)
1050             {
1051                 if (get_bits(gb, 1))
1052                      av_log(v->s.avctx, AV_LOG_ERROR,
1053                             "mv_mode for highquant B frame was %i\n", v->mv_mode);
1054             }
1055             v->mv_mode = 1-v->mv_mode; //To match (pq < 13) mapping
1056         }
1057     }
1058
1059     return 0;
1060 }
1061
1062 static int decode_b_picture_secondary_header(VC9Context *v)
1063 {
1064     GetBitContext *gb = &v->s.gb;
1065     int status;
1066
1067     bitplane_decoding(&v->skip_mb_plane, v);
1068     if (status < 0) return -1;
1069 #if TRACE
1070     if (v->mv_mode == MV_PMODE_MIXED_MV)
1071     {
1072         status = bitplane_decoding(&v->mv_type_mb_plane, v);
1073         if (status < 0)
1074             return -1;
1075 #if TRACE
1076         av_log(v->s.avctx, AV_LOG_DEBUG, "MB MV Type plane encoding: "
1077                "Imode: %i, Invert: %i\n", status>>1, status&1);
1078 #endif
1079     }
1080
1081     //bitplane
1082     status = bitplane_decoding(&v->direct_mb_plane, v);
1083     if (status < 0) return -1;
1084 #if TRACE
1085     av_log(v->s.avctx, AV_LOG_DEBUG, "MB Direct plane encoding: "
1086            "Imode: %i, Invert: %i\n", status>>1, status&1);
1087 #endif
1088
1089     av_log(v->s.avctx, AV_LOG_DEBUG, "Skip MB plane encoding: "
1090            "Imode: %i, Invert: %i\n", status>>1, status&1);
1091 #endif
1092
1093     /* FIXME: what is actually chosen for B frames ? */
1094     v->s.mv_table_index = get_bits(gb, 2); //but using vc9_ tables
1095     v->cbpcy_vlc = &vc9_cbpcy_p_vlc[get_bits(gb, 2)];
1096
1097     if (v->dquant)
1098     {
1099         vop_dquant_decoding(v);
1100     }
1101
1102     if (v->vstransform)
1103     {
1104         v->ttmbf = get_bits(gb, 1);
1105         if (v->ttmbf)
1106         {
1107             v->ttfrm = get_bits(gb, 2);
1108             av_log(v->s.avctx, AV_LOG_INFO, "Transform used: %ix%i\n",
1109                    (v->ttfrm & 2) ? 4 : 8, (v->ttfrm & 1) ? 4 : 8);
1110         }
1111     }
1112     /* Epilog (AC/DC syntax) should be done in caller */
1113     return 0;
1114 }
1115
1116 /* Tables 5+7, p53-54 and 55-57 */
1117 static int decode_i_picture_header(VC9Context *v)
1118 {
1119     GetBitContext *gb = &v->s.gb;
1120     int pqindex, status = 0;
1121
1122     /* Prolog common to all frametypes should be done in caller */
1123     //BF = Buffer Fullness
1124     if (v->profile <= PROFILE_MAIN && get_bits(gb, 7))
1125     {
1126         av_log(v->s.avctx, AV_LOG_DEBUG, "I BufferFullness not 0\n");
1127     }
1128
1129     /* Quantizer stuff */
1130     pqindex = get_bits(gb, 5);
1131     if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)
1132         v->pq = pquant_table[0][pqindex];
1133     else
1134     {
1135         v->pq = pquant_table[v->quantizer_mode-1][pqindex];
1136     }
1137     if (pqindex < 9) v->halfpq = get_bits(gb, 1);
1138     if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)
1139         v->pquantizer = get_bits(gb, 1);
1140     av_log(v->s.avctx, AV_LOG_DEBUG, "I frame: QP=%i (+%i/2)\n",
1141            v->pq, v->halfpq);
1142 #if HAS_ADVANCED_PROFILE
1143     if (v->profile <= PROFILE_MAIN)
1144 #endif
1145     {
1146         if (v->extended_mv) v->mvrange = get_prefix(gb, 0, 3);
1147         if (v->multires) v->respic = get_bits(gb, 2);
1148     }
1149 #if HAS_ADVANCED_PROFILE
1150     else
1151     {
1152         v->s.ac_pred = get_bits(gb, 1);
1153         if (v->postprocflag) v->postproc = get_bits(gb, 1);
1154         /* 7.1.1.34 + 8.5.2 */
1155         if (v->overlap && v->pq<9)
1156         {
1157             v->condover = get_bits(gb, 1);
1158             if (v->condover)
1159             {
1160                 v->condover = 2+get_bits(gb, 1);
1161                 if (v->condover == 3)
1162                 {
1163                     status = bitplane_decoding(&v->over_flags_plane, v);
1164                     if (status < 0) return -1;
1165 #if TRACE
1166                     av_log(v->s.avctx, AV_LOG_DEBUG, "Overflags plane encoding: "
1167                            "Imode: %i, Invert: %i\n", status>>1, status&1);
1168 #endif
1169                 }
1170             }
1171         }
1172     }
1173 #endif
1174
1175     /* Epilog (AC/DC syntax) should be done in caller */
1176     return status;
1177 }
1178
1179 /* Table 9, p58-60 */
1180 static int decode_p_picture_primary_header(VC9Context *v)
1181 {
1182     /* INTERFRM, FRMCNT, RANGEREDFRM read in caller */
1183     GetBitContext *gb = &v->s.gb;
1184     int lowquant, pqindex, status = 0;
1185
1186     pqindex = get_bits(gb, 5);
1187     if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)
1188         v->pq = pquant_table[0][pqindex];
1189     else
1190     {
1191         v->pq = pquant_table[v->quantizer_mode-1][pqindex];
1192     }
1193     if (pqindex < 9) v->halfpq = get_bits(gb, 1);
1194     if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)
1195         v->pquantizer = get_bits(gb, 1);
1196     av_log(v->s.avctx, AV_LOG_DEBUG, "P Frame: QP=%i (+%i/2)\n",
1197            v->pq, v->halfpq);
1198     if (v->extended_mv == 1) v->mvrange = get_prefix(gb, 0, 3);
1199 #if HAS_ADVANCED_PROFILE
1200     if (v->profile > PROFILE_MAIN)
1201     {
1202         if (v->postprocflag) v->postproc = get_bits(gb, 1);
1203     }
1204     else
1205 #endif
1206         if (v->multires) v->respic = get_bits(gb, 2);
1207     lowquant = (v->pquantizer>12) ? 0 : 1;
1208     v->mv_mode = mv_pmode_table[lowquant][get_prefix(gb, 1, 4)];
1209     if (v->mv_mode == MV_PMODE_INTENSITY_COMP)
1210     {
1211         v->mv_mode2 = mv_pmode_table[lowquant][get_prefix(gb, 1, 3)];
1212         v->lumscale = get_bits(gb, 6);
1213         v->lumshift = get_bits(gb, 6);
1214     }
1215     return 0;
1216 }
1217
1218 static int decode_p_picture_secondary_header(VC9Context *v)
1219 {
1220     GetBitContext *gb = &v->s.gb;
1221     int status = 0;
1222     if ((v->mv_mode == MV_PMODE_INTENSITY_COMP &&
1223          v->mv_mode2 == MV_PMODE_MIXED_MV)
1224         || v->mv_mode == MV_PMODE_MIXED_MV)
1225     {
1226         status = bitplane_decoding(&v->mv_type_mb_plane, v);
1227         if (status < 0) return -1;
1228 #if TRACE
1229         av_log(v->s.avctx, AV_LOG_DEBUG, "MB MV Type plane encoding: "
1230                "Imode: %i, Invert: %i\n", status>>1, status&1);
1231 #endif
1232     }
1233
1234     status = bitplane_decoding(&v->skip_mb_plane, v);
1235     if (status < 0) return -1;
1236 #if TRACE
1237     av_log(v->s.avctx, AV_LOG_DEBUG, "MB Skip plane encoding: "
1238            "Imode: %i, Invert: %i\n", status>>1, status&1);
1239 #endif
1240
1241     /* Hopefully this is correct for P frames */
1242     v->s.mv_table_index =get_bits(gb, 2); //but using vc9_ tables
1243     v->cbpcy_vlc = &vc9_cbpcy_p_vlc[get_bits(gb, 2)];
1244
1245     if (v->dquant)
1246     {
1247         av_log(v->s.avctx, AV_LOG_INFO, "VOP DQuant info\n");
1248         vop_dquant_decoding(v);
1249     }
1250
1251     v->ttfrm = 0; //FIXME Is that so ?
1252     if (v->vstransform)
1253     {
1254         v->ttmbf = get_bits(gb, 1);
1255         if (v->ttmbf)
1256         {
1257             v->ttfrm = get_bits(gb, 2);
1258             av_log(v->s.avctx, AV_LOG_INFO, "Transform used: %ix%i\n",
1259                    (v->ttfrm & 2) ? 4 : 8, (v->ttfrm & 1) ? 4 : 8);
1260         }
1261     }
1262     /* Epilog (AC/DC syntax) should be done in caller */
1263     return 0;
1264 }
1265
1266
1267 static int standard_decode_picture_primary_header(VC9Context *v)
1268 {
1269     GetBitContext *gb = &v->s.gb;
1270     int status = 0;
1271
1272     if (v->finterpflag) v->interpfrm = get_bits(gb, 1);
1273     skip_bits(gb, 2); //framecnt unused
1274     if (v->rangered) v->rangeredfrm = get_bits(gb, 1);
1275     v->s.pict_type = get_bits(gb, 1);
1276     if (v->s.avctx->max_b_frames)
1277     {
1278         if (!v->s.pict_type)
1279         {
1280             if (get_bits(gb, 1)) v->s.pict_type = I_TYPE;
1281             else v->s.pict_type = B_TYPE;
1282         }
1283         else v->s.pict_type = P_TYPE;
1284     }
1285     else v->s.pict_type++;
1286
1287     switch (v->s.pict_type)
1288     {
1289     case I_TYPE: status = decode_i_picture_header(v); break;
1290     case P_TYPE: status = decode_p_picture_primary_header(v); break;
1291     case BI_TYPE:
1292     case B_TYPE: status = decode_b_picture_primary_header(v); break;
1293     }
1294
1295     if (status == FRAME_SKIPED)
1296     {
1297       av_log(v->s.avctx, AV_LOG_INFO, "Skipping frame...\n");
1298       return status;
1299     }
1300     return 0;
1301 }
1302
1303 static int standard_decode_picture_secondary_header(VC9Context *v)
1304 {
1305     GetBitContext *gb = &v->s.gb;
1306     int status = 0, index;
1307
1308     switch (v->s.pict_type)
1309     {
1310     case P_TYPE: status = decode_p_picture_secondary_header(v); break;
1311     case B_TYPE: status = decode_b_picture_secondary_header(v); break;
1312     }
1313
1314     /* AC Syntax */
1315     v->ac_table_level = decode012(gb);
1316     if (v->s.pict_type == I_TYPE || v->s.pict_type == BI_TYPE)
1317     {
1318         index = decode012(gb);
1319         v->luma_ac2_vlc = NULL + index; //FIXME Add AC2 table
1320         v->chroma_ac2_vlc = NULL + index;
1321     }
1322     /* DC Syntax */
1323     index = decode012(gb);
1324     v->luma_dc_vlc = &ff_msmp4_dc_luma_vlc[index];
1325     v->chroma_dc_vlc = &ff_msmp4_dc_chroma_vlc[index];
1326    
1327     return 0;
1328 }
1329
1330
1331 #if HAS_ADVANCED_PROFILE
1332 /******************************************************************************/
1333 /* Advanced Profile picture header decoding specific functions                */
1334 /******************************************************************************/
1335 static int advanced_decode_picture_primary_header(VC9Context *v)
1336 {
1337     GetBitContext *gb = &v->s.gb;
1338     static const int type_table[4] = { P_TYPE, B_TYPE, I_TYPE, BI_TYPE };
1339     int type, i;
1340
1341     if (v->interlace)
1342     {
1343         v->fcm = get_bits(gb, 1);
1344         if (v->fcm) v->fcm = 2+get_bits(gb, 1);
1345     }
1346
1347     type = get_prefix(gb, 0, 4);
1348     if (type > 4 || type < 0) return FRAME_SKIPED;
1349     v->s.pict_type = type_table[type];
1350     av_log(v->s.avctx, AV_LOG_INFO, "AP Frame Type: %i\n", v->s.pict_type);
1351
1352     if (v->tfcntrflag) v->tfcntr = get_bits(gb, 8);
1353     if (v->broadcast)
1354     {
1355         if (!v->interlace) v->rptfrm = get_bits(gb, 2);
1356         else
1357         {
1358             v->tff = get_bits(gb, 1);
1359             v->rff = get_bits(gb, 1);
1360         }
1361     }
1362
1363     if (v->panscanflag)
1364     {
1365 #if 0
1366         for (i=0; i<v->numpanscanwin; i++)
1367         {
1368             v->topleftx[i] = get_bits(gb, 16);
1369             v->toplefty[i] = get_bits(gb, 16);
1370             v->bottomrightx[i] = get_bits(gb, 16);
1371             v->bottomrighty[i] = get_bits(gb, 16);
1372         }
1373 #else
1374         skip_bits(gb, 16*4*v->numpanscanwin);
1375 #endif
1376     }
1377     v->s.no_rounding = !get_bits(gb, 1);
1378     v->uvsamp = get_bits(gb, 1);
1379     if (v->finterpflag == 1) v->interpfrm = get_bits(gb, 1);
1380
1381     switch(v->s.pict_type)
1382     {
1383     case I_TYPE: if (decode_i_picture_header(v) < 0) return -1;
1384     case P_TYPE: if (decode_p_picture_primary_header(v) < 0) return -1;
1385     case BI_TYPE:
1386     case B_TYPE: if (decode_b_picture_primary_header(v) < 0) return FRAME_SKIPED;
1387     default: break;
1388     }
1389     return 0;
1390 }
1391
1392 static int advanced_decode_picture_secondary_header(VC9Context *v)
1393 {
1394     GetBitContext *gb = &v->s.gb;
1395     int index;
1396
1397     switch(v->s.pict_type)
1398     {
1399     case P_TYPE: if (decode_p_picture_secondary_header(v) < 0) return -1;
1400     case B_TYPE: if (decode_b_picture_secondary_header(v) < 0) return FRAME_SKIPED;
1401     default: break;
1402     }
1403
1404     /* AC Syntax */
1405     v->ac_table_level = decode012(gb);
1406     if (v->s.pict_type == I_TYPE || v->s.pict_type == BI_TYPE)
1407     {
1408         index = decode012(gb); //FIXME
1409         v->luma_ac2_vlc = NULL + index;
1410         v->chroma_ac2_vlc = NULL + index;
1411     }
1412     /* DC Syntax */
1413     index = decode012(gb);
1414     v->luma_dc_vlc = &ff_msmp4_dc_luma_vlc[index];
1415     v->chroma_dc_vlc = &ff_msmp4_dc_chroma_vlc[index];
1416
1417     return 0;
1418 }
1419 #endif
1420
1421 /******************************************************************************/
1422 /* Block decoding functions                                                   */
1423 /******************************************************************************/
1424 /* 7.1.4, p91 and 8.1.1.7, p(1)04 */
1425 /* FIXME proper integration (unusable and lots of parameters to send */
1426 int decode_luma_intra_block(VC9Context *v, int mquant)
1427 {
1428     GetBitContext *gb = &v->s.gb;
1429     int dcdiff;
1430
1431     dcdiff = get_vlc2(gb, v->luma_dc_vlc->table,
1432                       DC_VLC_BITS, 2);
1433     if (dcdiff)
1434     {
1435         if (dcdiff == 119 /* ESC index value */)
1436         {
1437             /* TODO: Optimize */
1438             if (mquant == 1) dcdiff = get_bits(gb, 10);
1439             else if (mquant == 2) dcdiff = get_bits(gb, 9);
1440             else dcdiff = get_bits(gb, 8);
1441         }
1442         else
1443         {
1444             if (mquant == 1)
1445                 dcdiff = (dcdiff<<2) + get_bits(gb, 2) - 3;
1446             else if (mquant == 2)
1447                 dcdiff = (dcdiff<<1) + get_bits(gb, 1) - 1;
1448         }
1449         if (get_bits(gb, 1))
1450             dcdiff = -dcdiff;
1451     }
1452     /* FIXME: 8.1.1.15, p(1)13, coeff scaling for Adv Profile */
1453
1454     return 0;
1455 }
1456
1457 /******************************************************************************/
1458 /* MacroBlock decoding functions                                              */
1459 /******************************************************************************/
1460 /* 8.1.1.5, p(1)02-(1)03 */
1461 /* We only need to store 3 flags, but math with 4 is easier */
1462 #define GET_CBPCY(table, bits)                                      \
1463     predicted_cbpcy = get_vlc2(gb, table, bits, 2);             \
1464     cbpcy[0] = (p_cbpcy[-1] == p_cbpcy[2])                          \
1465          ? previous_cbpcy[1] : p_cbpcy[+2];                         \
1466     cbpcy[0] ^= ((predicted_cbpcy>>5)&0x01);                        \
1467     cbpcy[1] = (p_cbpcy[2] == p_cbpcy[3]) ? cbpcy[0] : p_cbpcy[3];  \
1468     cbpcy[1] ^= ((predicted_cbpcy>>4)&0x01);                        \
1469     cbpcy[2] = (previous_cbpcy[1] == cbpcy[0])                      \
1470          ? previous_cbpcy[3] : cbpcy[0];                            \
1471     cbpcy[2] ^= ((predicted_cbpcy>>3)&0x01);                        \
1472     cbpcy[3] = (cbpcy[1] == cbpcy[0]) ? cbpcy[2] : cbpcy[1];        \
1473     cbpcy[3] ^= ((predicted_cbpcy>>2)&0x01);
1474      
1475 /* 8.1, p100 */
1476 static int standard_decode_i_mbs(VC9Context *v)
1477 {
1478     GetBitContext *gb = &v->s.gb;
1479     MpegEncContext *s = &v->s;
1480     int current_mb = 0; /* MB/Block Position info */
1481     /* FIXME: better to use a pointer than using (x<<4) */
1482     uint8_t cbpcy[4], previous_cbpcy[4], predicted_cbpcy,
1483         *p_cbpcy /* Pointer to skip some math */;
1484
1485     /* Reset CBPCY predictors */
1486     memset(v->previous_line_cbpcy, 0, s->mb_stride<<2);
1487
1488     /* Select ttmb table depending on pq */
1489     if (v->pq < 5) v->ttmb_vlc = &vc9_ttmb_vlc[0];
1490     else if (v->pq < 13) v->ttmb_vlc = &vc9_ttmb_vlc[1];
1491     else v->ttmb_vlc = &vc9_ttmb_vlc[2];
1492
1493     for (s->mb_y=0; s->mb_y<s->mb_height; s->mb_y++)
1494     {
1495         /* Init CBPCY for line */
1496         *((uint32_t*)previous_cbpcy) = 0x00000000;
1497         p_cbpcy = v->previous_line_cbpcy+4;
1498
1499         for (s->mb_x=0; s->mb_x<s->mb_width; s->mb_x++, p_cbpcy += 4)
1500         {
1501             /* Get CBPCY */
1502             GET_CBPCY(ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS);
1503
1504             s->ac_pred = get_bits(gb, 1);
1505
1506             /* TODO: Decode blocks from that mb wrt cbpcy */
1507
1508             /* Update for next block */
1509 #if TRACE > 2
1510             av_log(s->avctx, AV_LOG_DEBUG, "Block %4i: p_cbpcy=%i%i%i%i, previous_cbpcy=%i%i%i%i,"
1511                    " cbpcy=%i%i%i%i\n", current_mb,
1512                    p_cbpcy[0], p_cbpcy[1], p_cbpcy[2], p_cbpcy[3],
1513                    previous_cbpcy[0], previous_cbpcy[1], previous_cbpcy[2], previous_cbpcy[3],
1514                    cbpcy[0], cbpcy[1], cbpcy[2], cbpcy[3]);
1515 #endif
1516             *((uint32_t*)p_cbpcy) = *((uint32_t*)previous_cbpcy);
1517             *((uint32_t*)previous_cbpcy) = *((uint32_t*)cbpcy);
1518             current_mb++;
1519         }
1520     }
1521     return 0;
1522 }
1523
1524 #define GET_MQUANT()                                           \
1525   if (v->dquantfrm)                                            \
1526   {                                                            \
1527     if (v->dqprofile == DQPROFILE_ALL_MBS)                     \
1528     {                                                          \
1529       if (v->dqbilevel)                                        \
1530       {                                                        \
1531         mquant = (get_bits(gb, 1)) ? v->pq : v->altpq;         \
1532       }                                                        \
1533       else                                                     \
1534       {                                                        \
1535         mqdiff = get_bits(gb, 3);                              \
1536         if (mqdiff != 7) mquant = v->pq + mqdiff;              \
1537         else mquant = get_bits(gb, 5);                         \
1538       }                                                        \
1539     }                                                          \
1540   }
1541
1542 /* MVDATA decoding from 8.3.5.2, p(1)20 */
1543 #define GET_MVDATA(_dmv_x, _dmv_y)                                  \
1544   index = 1 + get_vlc2(gb, vc9_mv_diff_vlc[s->mv_table_index].table,\
1545                        VC9_MV_DIFF_VLC_BITS, 2);                    \
1546   if (index > 36)                                                   \
1547   {                                                                 \
1548     mb_has_coeffs = 1;                                              \
1549     index -= 37;                                                    \
1550   }                                                                 \
1551   else mb_has_coeffs = 0;                                           \
1552   s->mb_intra = 0;                                                  \
1553   if (!index) { _dmv_x = _dmv_y = 0; }                              \
1554   else if (index == 35)                                             \
1555   {                                                                 \
1556     _dmv_x = get_bits(gb, k_x);                                 \
1557     _dmv_y = get_bits(gb, k_y);                                 \
1558     s->mb_intra = 1;                                                \
1559   }                                                                 \
1560   else                                                              \
1561   {                                                                 \
1562     index1 = index%6;                                               \
1563     if (hpel_flag && index1 == 5) val = 1;                          \
1564     else                          val = 0;                          \
1565     val = get_bits(gb, size_table[index1] - val);               \
1566     sign = 0 - (val&1);                                             \
1567     _dmv_x = (sign ^ ((val>>1) + offset_table[index1])) - sign;     \
1568                                                                     \
1569     index1 = index/6;                                               \
1570     if (hpel_flag && index1 == 5) val = 1;                          \
1571     else                          val = 0;                          \
1572     val = get_bits(gb, size_table[index1] - val);               \
1573     sign = 0 - (val&1);                                             \
1574     _dmv_y = (sign ^ ((val>>1) + offset_table[index1])) - sign;     \
1575   }
1576
1577 /* 8.1, p(1)15 */
1578 static int decode_p_mbs(VC9Context *v)
1579 {
1580     MpegEncContext *s = &v->s;
1581     GetBitContext *gb = &v->s.gb;
1582     int current_mb = 0, i; /* MB/Block Position info */
1583     uint8_t cbpcy[4], previous_cbpcy[4], predicted_cbpcy,
1584         *p_cbpcy /* Pointer to skip some math */;
1585     int hybrid_pred; /* Prediction types */
1586     int mv_mode_bit = 0; 
1587     int mqdiff, mquant; /* MB quantization */
1588     int ttmb; /* MB Transform type */
1589
1590     static const int size_table[6] = { 0, 2, 3, 4, 5, 8 },
1591         offset_table[6] = { 0, 1, 3, 7, 15, 31 };
1592         int mb_has_coeffs = 1; /* last_flag */
1593     int dmv_x, dmv_y; /* Differential MV components */
1594     int k_x, k_y; /* Long MV fixed bitlength */
1595     int hpel_flag; /* Some MB properties */
1596     int index, index1; /* LUT indices */
1597     int val, sign; /* MVDATA temp values */
1598
1599     /* Select ttmb table depending on pq */
1600     if (v->pq < 5) v->ttmb_vlc = &vc9_ttmb_vlc[0];
1601     else if (v->pq < 13) v->ttmb_vlc = &vc9_ttmb_vlc[1];
1602     else v->ttmb_vlc = &vc9_ttmb_vlc[2];
1603
1604     /* Select proper long MV range */
1605     switch (v->mvrange)
1606     {
1607     case 1: k_x = 10; k_y = 9; break;
1608     case 2: k_x = 12; k_y = 10; break;
1609     case 3: k_x = 13; k_y = 11; break;
1610     default: /*case 0 too */ k_x = 9; k_y = 8; break;
1611     }
1612
1613     hpel_flag = v->mv_mode & 1; //MV_PMODE is HPEL
1614     k_x -= hpel_flag;
1615     k_y -= hpel_flag;
1616
1617     /* Reset CBPCY predictors */
1618     memset(v->previous_line_cbpcy, 0, s->mb_stride<<2);
1619
1620     for (s->mb_y=0; s->mb_y<s->mb_height; s->mb_y++)
1621     {
1622         /* Init CBPCY for line */
1623         *((uint32_t*)previous_cbpcy) = 0x00000000;
1624         p_cbpcy = v->previous_line_cbpcy+4;
1625
1626         for (s->mb_x=0; s->mb_x<s->mb_width; s->mb_x++, p_cbpcy += 4)
1627         {
1628             if (v->mv_type_mb_plane.is_raw)
1629                 v->mv_type_mb_plane.data[current_mb] = get_bits(gb, 1);
1630             if (v->skip_mb_plane.is_raw)
1631                 v->skip_mb_plane.data[current_mb] = get_bits(gb, 1);
1632             if (!mv_mode_bit) /* 1MV mode */
1633             {
1634                 if (!v->skip_mb_plane.data[current_mb])
1635                 {
1636                     GET_MVDATA(dmv_x, dmv_y);
1637
1638                     /* hybrid mv pred, 8.3.5.3.4 */
1639                     if (v->mv_mode == MV_PMODE_1MV ||
1640                         v->mv_mode == MV_PMODE_MIXED_MV)
1641                         hybrid_pred = get_bits(gb, 1);
1642                     if (s->mb_intra && !mb_has_coeffs)
1643                     {
1644                         GET_MQUANT();
1645                         s->ac_pred = get_bits(gb, 1);
1646                     }
1647                     else if (mb_has_coeffs)
1648                     {
1649                         if (s->mb_intra) s->ac_pred = get_bits(gb, 1);
1650                         predicted_cbpcy = get_vlc2(gb, v->cbpcy_vlc->table, VC9_CBPCY_P_VLC_BITS, 2);
1651                         cbpcy[0] = (p_cbpcy[-1] == p_cbpcy[2]) ? previous_cbpcy[1] : p_cbpcy[2];
1652                         cbpcy[0] ^= ((predicted_cbpcy>>5)&0x01);
1653                         cbpcy[1] = (p_cbpcy[2] == p_cbpcy[3]) ? cbpcy[0] : p_cbpcy[3];
1654                         cbpcy[1] ^= ((predicted_cbpcy>>4)&0x01);
1655                         cbpcy[2] = (previous_cbpcy[1] == cbpcy[0]) ? previous_cbpcy[3] : cbpcy[0];
1656                         cbpcy[2] ^= ((predicted_cbpcy>>3)&0x01);
1657                         cbpcy[3] = (cbpcy[1] == cbpcy[0]) ? cbpcy[2] : cbpcy[1];
1658                         cbpcy[3] ^= ((predicted_cbpcy>>2)&0x01);
1659                         //GET_CBPCY(v->cbpcy_vlc->table, VC9_CBPCY_P_VLC_BITS);
1660
1661                         GET_MQUANT();
1662                     }
1663                     if (!v->ttmbf)
1664                         ttmb = get_vlc2(gb, v->ttmb_vlc->table,
1665                                             VC9_TTMB_VLC_BITS, 12);
1666                     /* TODO: decode blocks from that mb wrt cbpcy */
1667                 }
1668                 else //Skipped
1669                 {
1670                     /* hybrid mv pred, 8.3.5.3.4 */
1671                     if (v->mv_mode == MV_PMODE_1MV ||
1672                         v->mv_mode == MV_PMODE_MIXED_MV)
1673                         hybrid_pred = get_bits(gb, 1);
1674                 }
1675             } //1MV mode
1676             else //4MV mode
1677             {
1678               if (!v->skip_mb_plane.data[current_mb] /* unskipped MB */)
1679                 {
1680                     /* Get CBPCY */
1681                     GET_CBPCY(v->cbpcy_vlc->table, VC9_CBPCY_P_VLC_BITS);
1682                     for (i=0; i<4; i++) //For all 4 Y blocks
1683                     {
1684                         if (cbpcy[i] /* cbpcy set for this block */)
1685                         {
1686                             GET_MVDATA(dmv_x, dmv_y);
1687                         }
1688                         if (v->mv_mode == MV_PMODE_MIXED_MV /* Hybrid pred */)
1689                             hybrid_pred = get_bits(gb, 1);
1690                         GET_MQUANT();
1691                         if (s->mb_intra /* One of the 4 blocks is intra */ &&
1692                             index /* non-zero pred for that block */)
1693                             s->ac_pred = get_bits(gb, 1);
1694                         if (!v->ttmbf)
1695                             ttmb = get_vlc2(gb, v->ttmb_vlc->table,
1696                                             VC9_TTMB_VLC_BITS, 12);
1697             
1698                         /* TODO: Process blocks wrt cbpcy */
1699             
1700                     }
1701                 }
1702                 else //Skipped MB
1703                 {
1704                     for (i=0; i<4; i++) //All 4 Y blocks
1705                     {
1706                         if (v->mv_mode == MV_PMODE_MIXED_MV /* Hybrid pred */)
1707                             hybrid_pred = get_bits(gb, 1);
1708                         
1709                         /* TODO: do something */
1710                     }
1711                 }
1712             }
1713
1714             /* Update for next block */
1715 #if TRACE > 2
1716             av_log(s->avctx, AV_LOG_DEBUG, "Block %4i: p_cbpcy=%i%i%i%i, previous_cbpcy=%i%i%i%i,"
1717                    " cbpcy=%i%i%i%i\n", current_mb,
1718                    p_cbpcy[0], p_cbpcy[1], p_cbpcy[2], p_cbpcy[3],
1719                    previous_cbpcy[0], previous_cbpcy[1], previous_cbpcy[2], previous_cbpcy[3],
1720                    cbpcy[0], cbpcy[1], cbpcy[2], cbpcy[3]);
1721 #endif
1722             *((uint32_t*)p_cbpcy) = *((uint32_t*)previous_cbpcy);
1723             *((uint32_t*)previous_cbpcy) = *((uint32_t*)cbpcy);
1724             current_mb++;
1725         }
1726     }
1727     return 0;
1728 }
1729
1730 static int decode_b_mbs(VC9Context *v)
1731 {
1732     MpegEncContext *s = &v->s;
1733     GetBitContext *gb = &v->s.gb;
1734     int current_mb = 0, i /* MB / B postion information */;
1735     int b_mv_type = BMV_TYPE_BACKWARD;
1736     int mquant, mqdiff; /* MB quant stuff */
1737     int ttmb; /* MacroBlock transform type */
1738     
1739     static const int size_table[6] = { 0, 2, 3, 4, 5, 8 },
1740         offset_table[6] = { 0, 1, 3, 7, 15, 31 };
1741     int mb_has_coeffs = 1; /* last_flag */
1742     int dmv1_x, dmv1_y, dmv2_x, dmv2_y; /* Differential MV components */
1743     int k_x, k_y; /* Long MV fixed bitlength */
1744     int hpel_flag; /* Some MB properties */
1745     int index, index1; /* LUT indices */
1746     int val, sign; /* MVDATA temp values */
1747     
1748     /* Select proper long MV range */
1749     switch (v->mvrange)
1750     {
1751     case 1: k_x = 10; k_y = 9; break;
1752     case 2: k_x = 12; k_y = 10; break;
1753     case 3: k_x = 13; k_y = 11; break;
1754     default: /*case 0 too */ k_x = 9; k_y = 8; break;
1755     }
1756     hpel_flag = v->mv_mode & 1; //MV_PMODE is HPEL
1757     k_x -= hpel_flag;
1758     k_y -= hpel_flag;
1759
1760     /* Select ttmb table depending on pq */
1761     if (v->pq < 5) v->ttmb_vlc = &vc9_ttmb_vlc[0];
1762     else if (v->pq < 13) v->ttmb_vlc = &vc9_ttmb_vlc[1];
1763     else v->ttmb_vlc = &vc9_ttmb_vlc[2];
1764
1765     for (s->mb_y=0; s->mb_y<s->mb_height; s->mb_y++)
1766     {
1767         for (s->mb_x=0; s->mb_x<s->mb_width; s->mb_x++)
1768         {
1769             if (v->direct_mb_plane.is_raw)
1770                 v->direct_mb_plane.data[current_mb] = get_bits(gb, 1);
1771             if (v->skip_mb_plane.is_raw)
1772                 v->skip_mb_plane.data[current_mb] = get_bits(gb, 1);
1773             
1774             if (!v->direct_mb_plane.data[current_mb])
1775             {
1776                 if (v->skip_mb_plane.data[current_mb])
1777                 {
1778                     b_mv_type = decode012(gb);
1779                     if (v->bfraction > 420 /*1/2*/ &&
1780                         b_mv_type < 3) b_mv_type = 1-b_mv_type;
1781                 }
1782                 else
1783                 { 
1784                     /* FIXME getting tired commenting */
1785                     GET_MVDATA(dmv1_x, dmv1_y);
1786                     if (!s->mb_intra /* b_mv1 tells not intra */)
1787                     {
1788                         /* FIXME: actually read it */
1789                         b_mv_type = decode012(gb);
1790                         if (v->bfraction > 420 /*1/2*/ &&
1791                             b_mv_type < 3) b_mv_type = 1-b_mv_type;
1792                     }
1793                 }
1794             }
1795             if (!v->skip_mb_plane.data[current_mb])
1796             {
1797                 if (mb_has_coeffs /* BMV1 == "last" */)
1798                 {
1799                     GET_MQUANT();
1800                     if (s->mb_intra /* intra mb */)
1801                         s->ac_pred = get_bits(gb, 1);
1802                 }
1803                 else
1804                 {
1805                     /* if bmv1 tells MVs are interpolated */
1806                     if (b_mv_type == BMV_TYPE_INTERPOLATED)
1807                     {
1808                         GET_MVDATA(dmv2_x, dmv2_y);
1809                     }
1810                     /* GET_MVDATA has reset some stuff */
1811                     if (mb_has_coeffs /* b_mv2 == "last" */)
1812                     {
1813                         if (s->mb_intra /* intra_mb */)
1814                             s->ac_pred = get_bits(gb, 1);
1815                         GET_MQUANT();
1816                     }
1817                 }
1818             }
1819             //End1
1820             if (v->ttmbf)
1821                 ttmb = get_vlc2(gb, v->ttmb_vlc->table,
1822                                    VC9_TTMB_VLC_BITS, 12);
1823
1824             //End2
1825             for (i=0; i<6; i++)
1826             {
1827                 /* FIXME: process the block */
1828             }
1829
1830             current_mb++;
1831         }
1832     }
1833     return 0;
1834 }
1835
1836 #if HAS_ADVANCED_PROFILE
1837 static int advanced_decode_i_mbs(VC9Context *v)
1838 {
1839     MpegEncContext *s = &v->s;
1840     GetBitContext *gb = &v->s.gb;
1841     int mqdiff, mquant, current_mb = 0, over_flags_mb = 0;
1842
1843     for (s->mb_y=0; s->mb_y<s->mb_height; s->mb_y++)
1844     {
1845         for (s->mb_x=0; s->mb_x<s->mb_width; s->mb_x++)
1846         {
1847             if (v->ac_pred_plane.is_raw)
1848                 s->ac_pred = get_bits(gb, 1);
1849             else
1850                 s->ac_pred = v->ac_pred_plane.data[current_mb];
1851             if (v->condover == 3 && v->over_flags_plane.is_raw)
1852                 over_flags_mb = get_bits(gb, 1);
1853             GET_MQUANT();
1854
1855             /* TODO: lots */
1856         }
1857         current_mb++;
1858     }
1859     return 0;
1860 }
1861 #endif
1862
1863 static int vc9_decode_init(AVCodecContext *avctx)
1864 {
1865     VC9Context *v = avctx->priv_data;
1866     MpegEncContext *s = &v->s;
1867     GetBitContext gb;
1868
1869     if (!avctx->extradata_size || !avctx->extradata) return -1;
1870     avctx->pix_fmt = PIX_FMT_YUV420P;
1871     v->s.avctx = avctx;
1872
1873     if(ff_h263_decode_init(avctx) < 0)
1874         return -1;
1875     if (vc9_init_common(v) < 0) return -1;
1876
1877     avctx->coded_width = avctx->width;
1878     avctx->coded_height = avctx->height;
1879     if (avctx->codec_id == CODEC_ID_WMV3)
1880     {
1881         int count = 0;
1882
1883         // looks like WMV3 has a sequence header stored in the extradata
1884         // advanced sequence header may be before the first frame
1885         // the last byte of the extradata is a version number, 1 for the
1886         // samples we can decode
1887
1888         init_get_bits(&gb, avctx->extradata, avctx->extradata_size);
1889         
1890         decode_sequence_header(avctx, &gb);
1891
1892         count = avctx->extradata_size*8 - get_bits_count(&gb);
1893         if (count>0)
1894         {
1895             av_log(avctx, AV_LOG_INFO, "Extra data: %i bits left, value: %X\n",
1896                    count, get_bits(&gb, count));
1897         }
1898         else
1899         {
1900             av_log(avctx, AV_LOG_INFO, "Read %i bits in overflow\n", -count);
1901         }
1902     }
1903     avctx->has_b_frames= !!(avctx->max_b_frames);
1904
1905     s->mb_width = (avctx->coded_width+15)>>4;
1906     s->mb_height = (avctx->coded_height+15)>>4;
1907
1908     /* Allocate mb bitplanes */
1909     if (alloc_bitplane(&v->mv_type_mb_plane, s->mb_width, s->mb_height) < 0)
1910         return -1;
1911     if (alloc_bitplane(&v->mv_type_mb_plane, s->mb_width, s->mb_height) < 0)
1912         return -1;
1913     if (alloc_bitplane(&v->skip_mb_plane, s->mb_width, s->mb_height) < 0)
1914         return -1;
1915     if (alloc_bitplane(&v->direct_mb_plane, s->mb_width, s->mb_height) < 0)
1916         return -1;
1917
1918     /* For predictors */
1919     v->previous_line_cbpcy = (uint8_t *)av_malloc(s->mb_stride*4);
1920     if (!v->previous_line_cbpcy) return -1;
1921
1922 #if HAS_ADVANCED_PROFILE
1923     if (v->profile > PROFILE_MAIN)
1924     {
1925         if (alloc_bitplane(&v->over_flags_plane, s->mb_width, s->mb_height) < 0)
1926             return -1;
1927         if (alloc_bitplane(&v->ac_pred_plane, s->mb_width, s->mb_height) < 0)
1928             return -1;
1929     }
1930 #endif
1931
1932     return 0;
1933     }
1934
1935 static int vc9_decode_frame(AVCodecContext *avctx,
1936                             void *data, int *data_size,
1937                             uint8_t *buf, int buf_size)
1938 {
1939     VC9Context *v = avctx->priv_data;
1940     MpegEncContext *s = &v->s;
1941     int ret = FRAME_SKIPED, len, start_code;
1942     AVFrame *pict = data;
1943     uint8_t *tmp_buf;
1944     v->s.avctx = avctx;
1945
1946     //buf_size = 0 -> last frame
1947     if (!buf_size) return 0;
1948
1949     len = avpicture_get_size(avctx->pix_fmt, avctx->width,
1950                              avctx->height);
1951     tmp_buf = (uint8_t *)av_mallocz(len);
1952     avpicture_fill((AVPicture *)pict, tmp_buf, avctx->pix_fmt,
1953                    avctx->width, avctx->height);
1954
1955     if (avctx->codec_id == CODEC_ID_VC9)
1956     {
1957 #if 0
1958         // search for IDU's
1959         // FIXME
1960         uint32_t scp = 0;
1961         int scs = 0, i = 0;
1962
1963         while (i < buf_size)
1964         {
1965             for (; i < buf_size && scp != 0x000001; i++)
1966                 scp = ((scp<<8)|buf[i])&0xffffff;
1967
1968             if (scp != 0x000001)
1969                 break; // eof ?
1970         
1971             scs = buf[i++];     
1972
1973             init_get_bits(gb, buf+i, (buf_size-i)*8);
1974         
1975             switch(scs)
1976             {
1977             case 0x0A: //Sequence End Code
1978                 return 0;
1979             case 0x0B: //Slice Start Code
1980                 av_log(avctx, AV_LOG_ERROR, "Slice coding not supported\n");
1981                 return -1;
1982             case 0x0C: //Field start code
1983                 av_log(avctx, AV_LOG_ERROR, "Interlaced coding not supported\n");
1984                 return -1;
1985             case 0x0D: //Frame start code
1986                 break;
1987             case 0x0E: //Entry point Start Code
1988                 if (v->profile <= MAIN_PROFILE)
1989                     av_log(avctx, AV_LOG_ERROR,
1990                            "Found an entry point in profile %i\n", v->profile);
1991                 advanced_entry_point_process(avctx, gb);
1992                 break;
1993             case 0x0F: //Sequence header Start Code
1994                 decode_sequence_header(avctx, gb);
1995                 break;
1996             default:
1997                 av_log(avctx, AV_LOG_ERROR,
1998                        "Unsupported IDU suffix %lX\n", scs);
1999             }
2000             
2001             i += get_bits_count(gb)*8;
2002         }
2003 #else
2004         av_abort();
2005 #endif
2006     }
2007     else
2008         init_get_bits(&v->s.gb, buf, buf_size*8);
2009
2010     s->flags= avctx->flags;
2011     s->flags2= avctx->flags2;
2012
2013     /* no supplementary picture */
2014     if (buf_size == 0) {
2015         /* special case for last picture */
2016         if (s->low_delay==0 && s->next_picture_ptr) {
2017             *pict= *(AVFrame*)s->next_picture_ptr;
2018             s->next_picture_ptr= NULL;
2019
2020             *data_size = sizeof(AVFrame);
2021         }
2022
2023         return 0;
2024     }
2025
2026     //No IDU - we mimic ff_h263_decode_frame
2027     s->bitstream_buffer_size=0;
2028         
2029     if (!s->context_initialized) {
2030         if (MPV_common_init(s) < 0) //we need the idct permutaton for reading a custom matrix
2031             return -1;
2032     }
2033     
2034     //we need to set current_picture_ptr before reading the header, otherwise we cant store anyting im there
2035     if(s->current_picture_ptr==NULL || s->current_picture_ptr->data[0]){
2036         s->current_picture_ptr= &s->picture[ff_find_unused_picture(s, 0)];
2037     }
2038 #if HAS_ADVANCED_PROFILE
2039     if (v->profile > PROFILE_MAIN)
2040         ret= advanced_decode_picture_primary_header(v);
2041     else
2042 #endif
2043         ret= standard_decode_picture_primary_header(v);
2044     if (ret == FRAME_SKIPED) return buf_size;
2045     /* skip if the header was thrashed */
2046     if (ret < 0){
2047         av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");
2048         return -1;
2049     }
2050
2051     //No bug workaround yet, no DCT conformance
2052
2053     //WMV9 does have resized images
2054     if (v->profile <= PROFILE_MAIN && v->multires){
2055         //Parse context stuff in here, don't know how appliable it is
2056     }
2057     //Not sure about context initialization
2058
2059     // for hurry_up==5
2060     s->current_picture.pict_type= s->pict_type;
2061     s->current_picture.key_frame= s->pict_type == I_TYPE;
2062
2063     /* skip b frames if we dont have reference frames */
2064     if(s->last_picture_ptr==NULL && (s->pict_type==B_TYPE || s->dropable))
2065         return buf_size; //FIXME simulating all buffer consumed
2066     /* skip b frames if we are in a hurry */
2067     if(avctx->hurry_up && s->pict_type==B_TYPE)
2068         return buf_size; //FIXME simulating all buffer consumed
2069     /* skip everything if we are in a hurry>=5 */
2070     if(avctx->hurry_up>=5)
2071         return buf_size; //FIXME simulating all buffer consumed
2072     
2073     if(s->next_p_frame_damaged){
2074         if(s->pict_type==B_TYPE)
2075             return buf_size; //FIXME simulating all buffer consumed
2076         else
2077             s->next_p_frame_damaged=0;
2078     }
2079
2080     if(MPV_frame_start(s, avctx) < 0)
2081         return -1;
2082
2083     ff_er_frame_start(s);
2084
2085     //wmv9 may or may not have skip bits
2086 #if HAS_ADVANCED_PROFILE
2087     if (v->profile > PROFILE_MAIN)
2088         ret= advanced_decode_picture_secondary_header(v);
2089     else
2090 #endif
2091         ret = standard_decode_picture_secondary_header(v);
2092     if (ret<0) return FRAME_SKIPED; //FIXME Non fatal for now
2093
2094     //We consider the image coded in only one slice
2095 #if HAS_ADVANCED_PROFILE
2096     if (v->profile > PROFILE_MAIN)
2097     {
2098         switch(s->pict_type)
2099         {
2100             case I_TYPE: ret = advanced_decode_i_mbs(v); break;
2101             case P_TYPE: ret = decode_p_mbs(v); break;
2102             case B_TYPE:
2103             case BI_TYPE: ret = decode_b_mbs(v); break;
2104             default: ret = FRAME_SKIPED;
2105         }
2106         if (ret == FRAME_SKIPED) return buf_size; //We ignore for now failures
2107     }
2108     else
2109 #endif
2110     {
2111         switch(s->pict_type)
2112         {
2113             case I_TYPE: ret = standard_decode_i_mbs(v); break;
2114             case P_TYPE: ret = decode_p_mbs(v); break;
2115             case B_TYPE:
2116             case BI_TYPE: ret = decode_b_mbs(v); break;
2117             default: ret = FRAME_SKIPED;
2118         }
2119         if (ret == FRAME_SKIPED) return buf_size;
2120     }
2121
2122     ff_er_frame_end(s);
2123
2124     MPV_frame_end(s);
2125
2126     assert(s->current_picture.pict_type == s->current_picture_ptr->pict_type);
2127     assert(s->current_picture.pict_type == s->pict_type);
2128     if(s->pict_type==B_TYPE || s->low_delay){
2129         *pict= *(AVFrame*)&s->current_picture;
2130         ff_print_debug_info(s, pict);
2131     } else {
2132         *pict= *(AVFrame*)&s->last_picture;
2133         if(pict)
2134             ff_print_debug_info(s, pict);
2135     }
2136
2137     /* Return the Picture timestamp as the frame number */
2138     /* we substract 1 because it is added on utils.c    */
2139     avctx->frame_number = s->picture_number - 1;
2140
2141     /* dont output the last pic after seeking */
2142     if(s->last_picture_ptr || s->low_delay)
2143         *data_size = sizeof(AVFrame);
2144
2145     av_log(avctx, AV_LOG_DEBUG, "Consumed %i/%i bits\n",
2146            get_bits_count(&s->gb), buf_size*8);
2147
2148     /* Fake consumption of all data */
2149     *data_size = len;
2150     return buf_size; //Number of bytes consumed
2151 }
2152
2153 static int vc9_decode_end(AVCodecContext *avctx)
2154 {
2155     VC9Context *v = avctx->priv_data;
2156
2157 #if HAS_ADVANCED_PROFILE
2158     av_freep(&v->hrd_rate);
2159     av_freep(&v->hrd_buffer);
2160 #endif
2161     MPV_common_end(&v->s);
2162     free_bitplane(&v->mv_type_mb_plane);
2163     free_bitplane(&v->skip_mb_plane);
2164     free_bitplane(&v->direct_mb_plane);
2165     return 0;
2166 }
2167
2168 AVCodec vc9_decoder = {
2169     "vc9",
2170     CODEC_TYPE_VIDEO,
2171     CODEC_ID_VC9,
2172     sizeof(VC9Context),
2173     vc9_decode_init,
2174     NULL,
2175     vc9_decode_end,
2176     vc9_decode_frame,
2177     CODEC_CAP_DELAY,
2178     NULL
2179 };
2180
2181 AVCodec wmv3_decoder = {
2182     "wmv3",
2183     CODEC_TYPE_VIDEO,
2184     CODEC_ID_WMV3,
2185     sizeof(VC9Context),
2186     vc9_decode_init,
2187     NULL,
2188     vc9_decode_end,
2189     vc9_decode_frame,
2190     CODEC_CAP_DELAY,
2191     NULL
2192 };