]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavcodec/cavs.c
simplify
[frescor/ffmpeg.git] / libavcodec / cavs.c
1 /*
2  * Chinese AVS video (AVS1-P2, JiZhun profile) decoder.
3  * Copyright (c) 2006  Stefan Gehrer <stefan.gehrer@gmx.de>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  */
19
20 /**
21  * @file cavs.c
22  * Chinese AVS video (AVS1-P2, JiZhun profile) decoder
23  * @author Stefan Gehrer <stefan.gehrer@gmx.de>
24  */
25
26 #include "avcodec.h"
27 #include "bitstream.h"
28 #include "golomb.h"
29 #include "mpegvideo.h"
30 #include "cavsdata.h"
31
32 typedef struct {
33     MpegEncContext s;
34     Picture picture; ///< currently decoded frame
35     Picture DPB[2];  ///< reference frames
36     int dist[2];     ///< temporal distances from current frame to ref frames
37     int profile, level;
38     int aspect_ratio;
39     int mb_width, mb_height;
40     int pic_type;
41     int progressive;
42     int pic_structure;
43     int skip_mode_flag; ///< select between skip_count or one skip_flag per MB
44     int loop_filter_disable;
45     int alpha_offset, beta_offset;
46     int ref_flag;
47     int mbx, mby;      ///< macroblock coordinates
48     int flags;         ///< availability flags of neighbouring macroblocks
49     int stc;           ///< last start code
50     uint8_t *cy, *cu, *cv; ///< current MB sample pointers
51     int left_qp;
52     uint8_t *top_qp;
53
54     /** mv motion vector cache
55        0:    D3  B2  B3  C2
56        4:    A1  X0  X1   -
57        8:    A3  X2  X3   -
58
59        X are the vectors in the current macroblock (5,6,9,10)
60        A is the macroblock to the left (4,8)
61        B is the macroblock to the top (1,2)
62        C is the macroblock to the top-right (3)
63        D is the macroblock to the top-left (0)
64
65        the same is repeated for backward motion vectors */
66     vector_t mv[2*4*3];
67     vector_t *top_mv[2];
68     vector_t *col_mv;
69
70     /** luma pred mode cache
71        0:    --  B2  B3
72        3:    A1  X0  X1
73        6:    A3  X2  X3   */
74     int pred_mode_Y[3*3];
75     int *top_pred_Y;
76     int l_stride, c_stride;
77     int luma_scan[4];
78     int qp;
79     int qp_fixed;
80     int cbp;
81
82     /** intra prediction is done with un-deblocked samples
83      they are saved here before deblocking the MB  */
84     uint8_t *top_border_y, *top_border_u, *top_border_v;
85     uint8_t left_border_y[16], left_border_u[10], left_border_v[10];
86     uint8_t topleft_border_y, topleft_border_u, topleft_border_v;
87
88     void (*intra_pred_l[8])(uint8_t *d,uint8_t *top,uint8_t *left,int stride);
89     void (*intra_pred_c[7])(uint8_t *d,uint8_t *top,uint8_t *left,int stride);
90     uint8_t *col_type_base;
91     uint8_t *col_type;
92
93     /* scaling factors for MV prediction */
94     int sym_factor;    ///< for scaling in symmetrical B block
95     int direct_den[2]; ///< for scaling in direct B block
96     int scale_den[2];  ///< for scaling neighbouring MVs
97
98     int got_keyframe;
99 } AVSContext;
100
101 /*****************************************************************************
102  *
103  * in-loop deblocking filter
104  *
105  ****************************************************************************/
106
107 static inline int get_bs(vector_t *mvP, vector_t *mvQ, int b) {
108     if((mvP->ref == REF_INTRA) || (mvQ->ref == REF_INTRA))
109         return 2;
110     if( (abs(mvP->x - mvQ->x) >= 4) ||  (abs(mvP->y - mvQ->y) >= 4) )
111         return 1;
112     if(b){
113         mvP += MV_BWD_OFFS;
114         mvQ += MV_BWD_OFFS;
115         if( (abs(mvP->x - mvQ->x) >= 4) ||  (abs(mvP->y - mvQ->y) >= 4) )
116             return 1;
117     }else{
118         if(mvP->ref != mvQ->ref)
119             return 1;
120     }
121     return 0;
122 }
123
124 #define SET_PARAMS                                            \
125     alpha = alpha_tab[clip(qp_avg + h->alpha_offset,0,63)];   \
126     beta  =  beta_tab[clip(qp_avg + h->beta_offset, 0,63)];   \
127     tc    =    tc_tab[clip(qp_avg + h->alpha_offset,0,63)];
128
129 /**
130  * in-loop deblocking filter for a single macroblock
131  *
132  * boundary strength (bs) mapping:
133  *
134  * --4---5--
135  * 0   2   |
136  * | 6 | 7 |
137  * 1   3   |
138  * ---------
139  *
140  */
141 static void filter_mb(AVSContext *h, enum mb_t mb_type) {
142     DECLARE_ALIGNED_8(uint8_t, bs[8]);
143     int qp_avg, alpha, beta, tc;
144     int i;
145
146     /* save un-deblocked lines */
147     h->topleft_border_y = h->top_border_y[h->mbx*16+15];
148     h->topleft_border_u = h->top_border_u[h->mbx*10+8];
149     h->topleft_border_v = h->top_border_v[h->mbx*10+8];
150     memcpy(&h->top_border_y[h->mbx*16], h->cy + 15* h->l_stride,16);
151     memcpy(&h->top_border_u[h->mbx*10+1], h->cu +  7* h->c_stride,8);
152     memcpy(&h->top_border_v[h->mbx*10+1], h->cv +  7* h->c_stride,8);
153     for(i=0;i<8;i++) {
154         h->left_border_y[i*2+0] = *(h->cy + 15 + (i*2+0)*h->l_stride);
155         h->left_border_y[i*2+1] = *(h->cy + 15 + (i*2+1)*h->l_stride);
156         h->left_border_u[i+1] = *(h->cu + 7 + i*h->c_stride);
157         h->left_border_v[i+1] = *(h->cv + 7 + i*h->c_stride);
158     }
159     if(!h->loop_filter_disable) {
160         /* determine bs */
161         if(mb_type == I_8X8)
162             *((uint64_t *)bs) = 0x0202020202020202ULL;
163         else{
164             *((uint64_t *)bs) = 0;
165             if(partition_flags[mb_type] & SPLITV){
166                 bs[2] = get_bs(&h->mv[MV_FWD_X0], &h->mv[MV_FWD_X1], mb_type > P_8X8);
167                 bs[3] = get_bs(&h->mv[MV_FWD_X2], &h->mv[MV_FWD_X3], mb_type > P_8X8);
168             }
169             if(partition_flags[mb_type] & SPLITH){
170                 bs[6] = get_bs(&h->mv[MV_FWD_X0], &h->mv[MV_FWD_X2], mb_type > P_8X8);
171                 bs[7] = get_bs(&h->mv[MV_FWD_X1], &h->mv[MV_FWD_X3], mb_type > P_8X8);
172             }
173             bs[0] = get_bs(&h->mv[MV_FWD_A1], &h->mv[MV_FWD_X0], mb_type > P_8X8);
174             bs[1] = get_bs(&h->mv[MV_FWD_A3], &h->mv[MV_FWD_X2], mb_type > P_8X8);
175             bs[4] = get_bs(&h->mv[MV_FWD_B2], &h->mv[MV_FWD_X0], mb_type > P_8X8);
176             bs[5] = get_bs(&h->mv[MV_FWD_B3], &h->mv[MV_FWD_X1], mb_type > P_8X8);
177         }
178         if( *((uint64_t *)bs) ) {
179             if(h->flags & A_AVAIL) {
180                 qp_avg = (h->qp + h->left_qp + 1) >> 1;
181                 SET_PARAMS;
182                 h->s.dsp.cavs_filter_lv(h->cy,h->l_stride,alpha,beta,tc,bs[0],bs[1]);
183                 h->s.dsp.cavs_filter_cv(h->cu,h->c_stride,alpha,beta,tc,bs[0],bs[1]);
184                 h->s.dsp.cavs_filter_cv(h->cv,h->c_stride,alpha,beta,tc,bs[0],bs[1]);
185             }
186             qp_avg = h->qp;
187             SET_PARAMS;
188             h->s.dsp.cavs_filter_lv(h->cy + 8,h->l_stride,alpha,beta,tc,bs[2],bs[3]);
189             h->s.dsp.cavs_filter_lh(h->cy + 8*h->l_stride,h->l_stride,alpha,beta,tc,
190                            bs[6],bs[7]);
191
192             if(h->flags & B_AVAIL) {
193                 qp_avg = (h->qp + h->top_qp[h->mbx] + 1) >> 1;
194                 SET_PARAMS;
195                 h->s.dsp.cavs_filter_lh(h->cy,h->l_stride,alpha,beta,tc,bs[4],bs[5]);
196                 h->s.dsp.cavs_filter_ch(h->cu,h->c_stride,alpha,beta,tc,bs[4],bs[5]);
197                 h->s.dsp.cavs_filter_ch(h->cv,h->c_stride,alpha,beta,tc,bs[4],bs[5]);
198             }
199         }
200     }
201     h->left_qp = h->qp;
202     h->top_qp[h->mbx] = h->qp;
203 }
204
205 #undef SET_PARAMS
206
207 /*****************************************************************************
208  *
209  * spatial intra prediction
210  *
211  ****************************************************************************/
212
213 static inline void load_intra_pred_luma(AVSContext *h, uint8_t *top,
214                                         uint8_t *left, int block) {
215     int i;
216
217     switch(block) {
218     case 0:
219         memcpy(&left[1],h->left_border_y,16);
220         left[0] = left[1];
221         left[17] = left[16];
222         memcpy(&top[1],&h->top_border_y[h->mbx*16],16);
223         top[17] = top[16];
224         top[0] = top[1];
225         if((h->flags & A_AVAIL) && (h->flags & B_AVAIL))
226             left[0] = top[0] = h->topleft_border_y;
227         break;
228     case 1:
229         for(i=0;i<8;i++)
230             left[i+1] = *(h->cy + 7 + i*h->l_stride);
231         memset(&left[9],left[8],9);
232         left[0] = left[1];
233         memcpy(&top[1],&h->top_border_y[h->mbx*16+8],8);
234         if(h->flags & C_AVAIL)
235             memcpy(&top[9],&h->top_border_y[(h->mbx + 1)*16],8);
236         else
237             memset(&top[9],top[8],9);
238         top[17] = top[16];
239         top[0] = top[1];
240         if(h->flags & B_AVAIL)
241             left[0] = top[0] = h->top_border_y[h->mbx*16+7];
242         break;
243     case 2:
244         memcpy(&left[1],&h->left_border_y[8],8);
245         memset(&left[9],left[8],9);
246         memcpy(&top[1],h->cy + 7*h->l_stride,16);
247         top[17] = top[16];
248         left[0] = h->left_border_y[7];
249         top[0] = top[1];
250         if(h->flags & A_AVAIL)
251             top[0] = left[0];
252         break;
253     case 3:
254         for(i=0;i<9;i++)
255             left[i] = *(h->cy + 7 + (i+7)*h->l_stride);
256         memset(&left[9],left[8],9);
257         memcpy(&top[0],h->cy + 7 + 7*h->l_stride,9);
258         memset(&top[9],top[8],9);
259         break;
260     }
261 }
262
263 static void intra_pred_vert(uint8_t *d,uint8_t *top,uint8_t *left,int stride) {
264     int y;
265     uint64_t a = unaligned64(&top[1]);
266     for(y=0;y<8;y++) {
267         *((uint64_t *)(d+y*stride)) = a;
268     }
269 }
270
271 static void intra_pred_horiz(uint8_t *d,uint8_t *top,uint8_t *left,int stride) {
272     int y;
273     uint64_t a;
274     for(y=0;y<8;y++) {
275         a = left[y+1] * 0x0101010101010101ULL;
276         *((uint64_t *)(d+y*stride)) = a;
277     }
278 }
279
280 static void intra_pred_dc_128(uint8_t *d,uint8_t *top,uint8_t *left,int stride) {
281     int y;
282     uint64_t a = 0x8080808080808080ULL;
283     for(y=0;y<8;y++)
284         *((uint64_t *)(d+y*stride)) = a;
285 }
286
287 static void intra_pred_plane(uint8_t *d,uint8_t *top,uint8_t *left,int stride) {
288     int x,y,ia;
289     int ih = 0;
290     int iv = 0;
291     uint8_t *cm = cropTbl + MAX_NEG_CROP;
292
293     for(x=0; x<4; x++) {
294         ih += (x+1)*(top[5+x]-top[3-x]);
295         iv += (x+1)*(left[5+x]-left[3-x]);
296     }
297     ia = (top[8]+left[8])<<4;
298     ih = (17*ih+16)>>5;
299     iv = (17*iv+16)>>5;
300     for(y=0; y<8; y++)
301         for(x=0; x<8; x++)
302             d[y*stride+x] = cm[(ia+(x-3)*ih+(y-3)*iv+16)>>5];
303 }
304
305 #define LOWPASS(ARRAY,INDEX)                                            \
306     (( ARRAY[(INDEX)-1] + 2*ARRAY[(INDEX)] + ARRAY[(INDEX)+1] + 2) >> 2)
307
308 static void intra_pred_lp(uint8_t *d,uint8_t *top,uint8_t *left,int stride) {
309     int x,y;
310     for(y=0; y<8; y++)
311         for(x=0; x<8; x++)
312             d[y*stride+x] = (LOWPASS(top,x+1) + LOWPASS(left,y+1)) >> 1;
313 }
314
315 static void intra_pred_down_left(uint8_t *d,uint8_t *top,uint8_t *left,int stride) {
316     int x,y;
317     for(y=0; y<8; y++)
318         for(x=0; x<8; x++)
319             d[y*stride+x] = (LOWPASS(top,x+y+2) + LOWPASS(left,x+y+2)) >> 1;
320 }
321
322 static void intra_pred_down_right(uint8_t *d,uint8_t *top,uint8_t *left,int stride) {
323     int x,y;
324     for(y=0; y<8; y++)
325         for(x=0; x<8; x++)
326             if(x==y)
327                 d[y*stride+x] = (left[1]+2*top[0]+top[1]+2)>>2;
328             else if(x>y)
329                 d[y*stride+x] = LOWPASS(top,x-y);
330             else
331                 d[y*stride+x] = LOWPASS(left,y-x);
332 }
333
334 static void intra_pred_lp_left(uint8_t *d,uint8_t *top,uint8_t *left,int stride) {
335     int x,y;
336     for(y=0; y<8; y++)
337         for(x=0; x<8; x++)
338             d[y*stride+x] = LOWPASS(left,y+1);
339 }
340
341 static void intra_pred_lp_top(uint8_t *d,uint8_t *top,uint8_t *left,int stride) {
342     int x,y;
343     for(y=0; y<8; y++)
344         for(x=0; x<8; x++)
345             d[y*stride+x] = LOWPASS(top,x+1);
346 }
347
348 #undef LOWPASS
349
350 static inline void modify_pred(const int_fast8_t *mod_table, int *mode) {
351     *mode = mod_table[*mode];
352     if(*mode < 0) {
353         av_log(NULL, AV_LOG_ERROR, "Illegal intra prediction mode\n");
354         *mode = 0;
355     }
356 }
357
358 /*****************************************************************************
359  *
360  * motion compensation
361  *
362  ****************************************************************************/
363
364 static inline void mc_dir_part(AVSContext *h,Picture *pic,int square,
365                         int chroma_height,int delta,int list,uint8_t *dest_y,
366                         uint8_t *dest_cb,uint8_t *dest_cr,int src_x_offset,
367                         int src_y_offset,qpel_mc_func *qpix_op,
368                         h264_chroma_mc_func chroma_op,vector_t *mv){
369     MpegEncContext * const s = &h->s;
370     const int mx= mv->x + src_x_offset*8;
371     const int my= mv->y + src_y_offset*8;
372     const int luma_xy= (mx&3) + ((my&3)<<2);
373     uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*h->l_stride;
374     uint8_t * src_cb= pic->data[1] + (mx>>3) + (my>>3)*h->c_stride;
375     uint8_t * src_cr= pic->data[2] + (mx>>3) + (my>>3)*h->c_stride;
376     int extra_width= 0; //(s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16;
377     int extra_height= extra_width;
378     int emu=0;
379     const int full_mx= mx>>2;
380     const int full_my= my>>2;
381     const int pic_width  = 16*h->mb_width;
382     const int pic_height = 16*h->mb_height;
383
384     if(!pic->data[0])
385         return;
386     if(mx&7) extra_width -= 3;
387     if(my&7) extra_height -= 3;
388
389     if(   full_mx < 0-extra_width
390           || full_my < 0-extra_height
391           || full_mx + 16/*FIXME*/ > pic_width + extra_width
392           || full_my + 16/*FIXME*/ > pic_height + extra_height){
393         ff_emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*h->l_stride, h->l_stride,
394                             16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
395         src_y= s->edge_emu_buffer + 2 + 2*h->l_stride;
396         emu=1;
397     }
398
399     qpix_op[luma_xy](dest_y, src_y, h->l_stride); //FIXME try variable height perhaps?
400     if(!square){
401         qpix_op[luma_xy](dest_y + delta, src_y + delta, h->l_stride);
402     }
403
404     if(emu){
405         ff_emulated_edge_mc(s->edge_emu_buffer, src_cb, h->c_stride,
406                             9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
407         src_cb= s->edge_emu_buffer;
408     }
409     chroma_op(dest_cb, src_cb, h->c_stride, chroma_height, mx&7, my&7);
410
411     if(emu){
412         ff_emulated_edge_mc(s->edge_emu_buffer, src_cr, h->c_stride,
413                             9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
414         src_cr= s->edge_emu_buffer;
415     }
416     chroma_op(dest_cr, src_cr, h->c_stride, chroma_height, mx&7, my&7);
417 }
418
419 static inline void mc_part_std(AVSContext *h,int square,int chroma_height,int delta,
420                         uint8_t *dest_y,uint8_t *dest_cb,uint8_t *dest_cr,
421                         int x_offset, int y_offset,qpel_mc_func *qpix_put,
422                         h264_chroma_mc_func chroma_put,qpel_mc_func *qpix_avg,
423                         h264_chroma_mc_func chroma_avg, vector_t *mv){
424     qpel_mc_func *qpix_op=  qpix_put;
425     h264_chroma_mc_func chroma_op= chroma_put;
426
427     dest_y  += 2*x_offset + 2*y_offset*h->l_stride;
428     dest_cb +=   x_offset +   y_offset*h->c_stride;
429     dest_cr +=   x_offset +   y_offset*h->c_stride;
430     x_offset += 8*h->mbx;
431     y_offset += 8*h->mby;
432
433     if(mv->ref >= 0){
434         Picture *ref= &h->DPB[mv->ref];
435         mc_dir_part(h, ref, square, chroma_height, delta, 0,
436                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
437                     qpix_op, chroma_op, mv);
438
439         qpix_op=  qpix_avg;
440         chroma_op= chroma_avg;
441     }
442
443     if((mv+MV_BWD_OFFS)->ref >= 0){
444         Picture *ref= &h->DPB[0];
445         mc_dir_part(h, ref, square, chroma_height, delta, 1,
446                     dest_y, dest_cb, dest_cr, x_offset, y_offset,
447                     qpix_op, chroma_op, mv+MV_BWD_OFFS);
448     }
449 }
450
451 static void inter_pred(AVSContext *h, enum mb_t mb_type) {
452     if(partition_flags[mb_type] == 0){ // 16x16
453         mc_part_std(h, 1, 8, 0, h->cy, h->cu, h->cv, 0, 0,
454                 h->s.dsp.put_cavs_qpel_pixels_tab[0],
455                 h->s.dsp.put_h264_chroma_pixels_tab[0],
456                 h->s.dsp.avg_cavs_qpel_pixels_tab[0],
457                 h->s.dsp.avg_h264_chroma_pixels_tab[0],&h->mv[MV_FWD_X0]);
458     }else{
459         mc_part_std(h, 1, 4, 0, h->cy, h->cu, h->cv, 0, 0,
460                 h->s.dsp.put_cavs_qpel_pixels_tab[1],
461                 h->s.dsp.put_h264_chroma_pixels_tab[1],
462                 h->s.dsp.avg_cavs_qpel_pixels_tab[1],
463                 h->s.dsp.avg_h264_chroma_pixels_tab[1],&h->mv[MV_FWD_X0]);
464         mc_part_std(h, 1, 4, 0, h->cy, h->cu, h->cv, 4, 0,
465                 h->s.dsp.put_cavs_qpel_pixels_tab[1],
466                 h->s.dsp.put_h264_chroma_pixels_tab[1],
467                 h->s.dsp.avg_cavs_qpel_pixels_tab[1],
468                 h->s.dsp.avg_h264_chroma_pixels_tab[1],&h->mv[MV_FWD_X1]);
469         mc_part_std(h, 1, 4, 0, h->cy, h->cu, h->cv, 0, 4,
470                 h->s.dsp.put_cavs_qpel_pixels_tab[1],
471                 h->s.dsp.put_h264_chroma_pixels_tab[1],
472                 h->s.dsp.avg_cavs_qpel_pixels_tab[1],
473                 h->s.dsp.avg_h264_chroma_pixels_tab[1],&h->mv[MV_FWD_X2]);
474         mc_part_std(h, 1, 4, 0, h->cy, h->cu, h->cv, 4, 4,
475                 h->s.dsp.put_cavs_qpel_pixels_tab[1],
476                 h->s.dsp.put_h264_chroma_pixels_tab[1],
477                 h->s.dsp.avg_cavs_qpel_pixels_tab[1],
478                 h->s.dsp.avg_h264_chroma_pixels_tab[1],&h->mv[MV_FWD_X3]);
479     }
480     /* set intra prediction modes to default values */
481     h->pred_mode_Y[3] =  h->pred_mode_Y[6] = INTRA_L_LP;
482     h->top_pred_Y[h->mbx*2+0] = h->top_pred_Y[h->mbx*2+1] = INTRA_L_LP;
483 }
484
485 /*****************************************************************************
486  *
487  * motion vector prediction
488  *
489  ****************************************************************************/
490
491 static inline void set_mvs(vector_t *mv, enum block_t size) {
492     switch(size) {
493     case BLK_16X16:
494         mv[MV_STRIDE  ] = mv[0];
495         mv[MV_STRIDE+1] = mv[0];
496     case BLK_16X8:
497         mv[1] = mv[0];
498         break;
499     case BLK_8X16:
500         mv[MV_STRIDE] = mv[0];
501         break;
502     }
503 }
504
505 static inline void store_mvs(AVSContext *h) {
506     h->col_mv[(h->mby*h->mb_width + h->mbx)*4 + 0] = h->mv[MV_FWD_X0];
507     h->col_mv[(h->mby*h->mb_width + h->mbx)*4 + 1] = h->mv[MV_FWD_X1];
508     h->col_mv[(h->mby*h->mb_width + h->mbx)*4 + 2] = h->mv[MV_FWD_X2];
509     h->col_mv[(h->mby*h->mb_width + h->mbx)*4 + 3] = h->mv[MV_FWD_X3];
510 }
511
512 static inline void scale_mv(AVSContext *h, int *d_x, int *d_y, vector_t *src, int distp) {
513     int den = h->scale_den[src->ref];
514
515     *d_x = (src->x*distp*den + 256 + (src->x>>31)) >> 9;
516     *d_y = (src->y*distp*den + 256 + (src->y>>31)) >> 9;
517 }
518
519 static inline void mv_pred_median(AVSContext *h, vector_t *mvP, vector_t *mvA, vector_t *mvB, vector_t *mvC) {
520     int ax, ay, bx, by, cx, cy;
521     int len_ab, len_bc, len_ca, len_mid;
522
523     /* scale candidates according to their temporal span */
524     scale_mv(h, &ax, &ay, mvA, mvP->dist);
525     scale_mv(h, &bx, &by, mvB, mvP->dist);
526     scale_mv(h, &cx, &cy, mvC, mvP->dist);
527     /* find the geometrical median of the three candidates */
528     len_ab = abs(ax - bx) + abs(ay - by);
529     len_bc = abs(bx - cx) + abs(by - cy);
530     len_ca = abs(cx - ax) + abs(cy - ay);
531     len_mid = mid_pred(len_ab, len_bc, len_ca);
532     if(len_mid == len_ab) {
533         mvP->x = cx;
534         mvP->y = cy;
535     } else if(len_mid == len_bc) {
536         mvP->x = ax;
537         mvP->y = ay;
538     } else {
539         mvP->x = bx;
540         mvP->y = by;
541     }
542 }
543
544 static inline void mv_pred_direct(AVSContext *h, vector_t *pmv_fw,
545                                   vector_t *col_mv) {
546     vector_t *pmv_bw = pmv_fw + MV_BWD_OFFS;
547     int den = h->direct_den[col_mv->ref];
548     int m = col_mv->x >> 31;
549
550     pmv_fw->dist = h->dist[1];
551     pmv_bw->dist = h->dist[0];
552     pmv_fw->ref = 1;
553     pmv_bw->ref = 0;
554     /* scale the co-located motion vector according to its temporal span */
555     pmv_fw->x = (((den+(den*col_mv->x*pmv_fw->dist^m)-m-1)>>14)^m)-m;
556     pmv_bw->x = m-(((den+(den*col_mv->x*pmv_bw->dist^m)-m-1)>>14)^m);
557     m = col_mv->y >> 31;
558     pmv_fw->y = (((den+(den*col_mv->y*pmv_fw->dist^m)-m-1)>>14)^m)-m;
559     pmv_bw->y = m-(((den+(den*col_mv->y*pmv_bw->dist^m)-m-1)>>14)^m);
560 }
561
562 static inline void mv_pred_sym(AVSContext *h, vector_t *src, enum block_t size) {
563     vector_t *dst = src + MV_BWD_OFFS;
564
565     /* backward mv is the scaled and negated forward mv */
566     dst->x = -((src->x * h->sym_factor + 256) >> 9);
567     dst->y = -((src->y * h->sym_factor + 256) >> 9);
568     dst->ref = 0;
569     dst->dist = h->dist[0];
570     set_mvs(dst, size);
571 }
572
573 static void mv_pred(AVSContext *h, enum mv_loc_t nP, enum mv_loc_t nC,
574                     enum mv_pred_t mode, enum block_t size, int ref) {
575     vector_t *mvP = &h->mv[nP];
576     vector_t *mvA = &h->mv[nP-1];
577     vector_t *mvB = &h->mv[nP-4];
578     vector_t *mvC = &h->mv[nC];
579     int mvAref = mvA->ref;
580     int mvBref = mvB->ref;
581     int mvCref;
582
583     mvP->ref = ref;
584     mvP->dist = h->dist[mvP->ref];
585     if(mvC->ref == NOT_AVAIL)
586         mvC = &h->mv[nP-5]; // set to top-left (mvD)
587     mvCref = mvC->ref;
588     if(mode == MV_PRED_PSKIP) {
589         if((mvAref == NOT_AVAIL) || (mvBref == NOT_AVAIL) ||
590            ((mvA->x | mvA->y | mvA->ref) == 0)  ||
591            ((mvB->x | mvB->y | mvB->ref) == 0) ) {
592             mvP->x = mvP->y = 0;
593             set_mvs(mvP,size);
594             return;
595         }
596     }
597     /* if there is only one suitable candidate, take it */
598     if((mvAref >= 0) && (mvBref < 0) && (mvCref < 0)) {
599         mvP->x = mvA->x;
600         mvP->y = mvA->y;
601     } else if((mvAref < 0) && (mvBref >= 0) && (mvCref < 0)) {
602         mvP->x = mvB->x;
603         mvP->y = mvB->y;
604     } else if((mvAref < 0) && (mvBref < 0) && (mvCref >= 0)) {
605         mvP->x = mvC->x;
606         mvP->y = mvC->y;
607     } else {
608         switch(mode) {
609         case MV_PRED_LEFT:
610             if(mvAref == mvP->ref) {
611                 mvP->x = mvA->x;
612                 mvP->y = mvA->y;
613             } else
614                 mv_pred_median(h, mvP, mvA, mvB, mvC);
615             break;
616         case MV_PRED_TOP:
617             if(mvBref == mvP->ref) {
618                 mvP->x = mvB->x;
619                 mvP->y = mvB->y;
620             } else
621                 mv_pred_median(h, mvP, mvA, mvB, mvC);
622             break;
623         case MV_PRED_TOPRIGHT:
624             if(mvCref == mvP->ref) {
625                 mvP->x = mvC->x;
626                 mvP->y = mvC->y;
627             } else
628                 mv_pred_median(h, mvP, mvA, mvB, mvC);
629             break;
630         default:
631             mv_pred_median(h, mvP, mvA, mvB, mvC);
632             break;
633         }
634     }
635     if(mode < MV_PRED_PSKIP) {
636         mvP->x += get_se_golomb(&h->s.gb);
637         mvP->y += get_se_golomb(&h->s.gb);
638     }
639     set_mvs(mvP,size);
640 }
641
642 /*****************************************************************************
643  *
644  * residual data decoding
645  *
646  ****************************************************************************/
647
648 /** kth-order exponential golomb code */
649 static inline int get_ue_code(GetBitContext *gb, int order) {
650     if(order) {
651         int ret = get_ue_golomb(gb) << order;
652         return ret + get_bits(gb,order);
653     }
654     return get_ue_golomb(gb);
655 }
656
657 /**
658  * decode coefficients from one 8x8 block, dequantize, inverse transform
659  *  and add them to sample block
660  * @param r pointer to 2D VLC table
661  * @param esc_golomb_order escape codes are k-golomb with this order k
662  * @param qp quantizer
663  * @param dst location of sample block
664  * @param stride line stride in frame buffer
665  */
666 static int decode_residual_block(AVSContext *h, GetBitContext *gb,
667                                  const residual_vlc_t *r, int esc_golomb_order,
668                                  int qp, uint8_t *dst, int stride) {
669     int i,pos = -1;
670     int level_code, esc_code, level, run, mask;
671     int level_buf[64];
672     int run_buf[64];
673     int dqm = dequant_mul[qp];
674     int dqs = dequant_shift[qp];
675     int dqa = 1 << (dqs - 1);
676     const uint8_t *scantab = ff_zigzag_direct;
677     DCTELEM block[64];
678
679     memset(block,0,64*sizeof(DCTELEM));
680     for(i=0;i<65;i++) {
681         level_code = get_ue_code(gb,r->golomb_order);
682         if(level_code >= ESCAPE_CODE) {
683             run = (level_code - ESCAPE_CODE) >> 1;
684             esc_code = get_ue_code(gb,esc_golomb_order);
685             level = esc_code + (run > r->max_run ? 1 : r->level_add[run]);
686             while(level > r->inc_limit)
687                 r++;
688             mask = -(level_code & 1);
689             level = (level^mask) - mask;
690         } else {
691             if(level_code < 0)
692                 return -1;
693             level = r->rltab[level_code][0];
694             if(!level) //end of block signal
695                 break;
696             run   = r->rltab[level_code][1];
697             r += r->rltab[level_code][2];
698         }
699         level_buf[i] = level;
700         run_buf[i] = run;
701     }
702     /* inverse scan and dequantization */
703     while(--i >= 0){
704         pos += 1 + run_buf[i];
705         if(pos > 63) {
706             av_log(h->s.avctx, AV_LOG_ERROR,
707                    "position out of block bounds at pic %d MB(%d,%d)\n",
708                    h->picture.poc, h->mbx, h->mby);
709             return -1;
710         }
711         block[scantab[pos]] = (level_buf[i]*dqm + dqa) >> dqs;
712     }
713     h->s.dsp.cavs_idct8_add(dst,block,stride);
714     return 0;
715 }
716
717
718 static inline void decode_residual_chroma(AVSContext *h) {
719     if(h->cbp & (1<<4))
720         decode_residual_block(h,&h->s.gb,chroma_2dvlc,0, chroma_qp[h->qp],
721                               h->cu,h->c_stride);
722     if(h->cbp & (1<<5))
723         decode_residual_block(h,&h->s.gb,chroma_2dvlc,0, chroma_qp[h->qp],
724                               h->cv,h->c_stride);
725 }
726
727 static inline int decode_residual_inter(AVSContext *h) {
728     int block;
729
730     /* get coded block pattern */
731     int cbp= get_ue_golomb(&h->s.gb);
732     if(cbp > 63){
733         av_log(h->s.avctx, AV_LOG_ERROR, "illegal inter cbp\n");
734         return -1;
735     }
736     h->cbp = cbp_tab[cbp][1];
737
738     /* get quantizer */
739     if(h->cbp && !h->qp_fixed)
740         h->qp += get_se_golomb(&h->s.gb);
741     for(block=0;block<4;block++)
742         if(h->cbp & (1<<block))
743             decode_residual_block(h,&h->s.gb,inter_2dvlc,0,h->qp,
744                                   h->cy + h->luma_scan[block], h->l_stride);
745     decode_residual_chroma(h);
746
747     return 0;
748 }
749
750 /*****************************************************************************
751  *
752  * macroblock level
753  *
754  ****************************************************************************/
755
756 /**
757  * initialise predictors for motion vectors and intra prediction
758  */
759 static inline void init_mb(AVSContext *h) {
760     int i;
761
762     /* copy predictors from top line (MB B and C) into cache */
763     for(i=0;i<3;i++) {
764         h->mv[MV_FWD_B2+i] = h->top_mv[0][h->mbx*2+i];
765         h->mv[MV_BWD_B2+i] = h->top_mv[1][h->mbx*2+i];
766     }
767     h->pred_mode_Y[1] = h->top_pred_Y[h->mbx*2+0];
768     h->pred_mode_Y[2] = h->top_pred_Y[h->mbx*2+1];
769     /* clear top predictors if MB B is not available */
770     if(!(h->flags & B_AVAIL)) {
771         h->mv[MV_FWD_B2] = un_mv;
772         h->mv[MV_FWD_B3] = un_mv;
773         h->mv[MV_BWD_B2] = un_mv;
774         h->mv[MV_BWD_B3] = un_mv;
775         h->pred_mode_Y[1] = h->pred_mode_Y[2] = NOT_AVAIL;
776         h->flags &= ~(C_AVAIL|D_AVAIL);
777     } else if(h->mbx) {
778         h->flags |= D_AVAIL;
779     }
780     if(h->mbx == h->mb_width-1) //MB C not available
781         h->flags &= ~C_AVAIL;
782     /* clear top-right predictors if MB C is not available */
783     if(!(h->flags & C_AVAIL)) {
784         h->mv[MV_FWD_C2] = un_mv;
785         h->mv[MV_BWD_C2] = un_mv;
786     }
787     /* clear top-left predictors if MB D is not available */
788     if(!(h->flags & D_AVAIL)) {
789         h->mv[MV_FWD_D3] = un_mv;
790         h->mv[MV_BWD_D3] = un_mv;
791     }
792     /* set pointer for co-located macroblock type */
793     h->col_type = &h->col_type_base[h->mby*h->mb_width + h->mbx];
794 }
795
796 static inline void check_for_slice(AVSContext *h);
797
798 /**
799  * save predictors for later macroblocks and increase
800  * macroblock address
801  * @returns 0 if end of frame is reached, 1 otherwise
802  */
803 static inline int next_mb(AVSContext *h) {
804     int i;
805
806     h->flags |= A_AVAIL;
807     h->cy += 16;
808     h->cu += 8;
809     h->cv += 8;
810     /* copy mvs as predictors to the left */
811     for(i=0;i<=20;i+=4)
812         h->mv[i] = h->mv[i+2];
813     /* copy bottom mvs from cache to top line */
814     h->top_mv[0][h->mbx*2+0] = h->mv[MV_FWD_X2];
815     h->top_mv[0][h->mbx*2+1] = h->mv[MV_FWD_X3];
816     h->top_mv[1][h->mbx*2+0] = h->mv[MV_BWD_X2];
817     h->top_mv[1][h->mbx*2+1] = h->mv[MV_BWD_X3];
818     /* next MB address */
819     h->mbx++;
820     if(h->mbx == h->mb_width) { //new mb line
821         h->flags = B_AVAIL|C_AVAIL;
822         /* clear left pred_modes */
823         h->pred_mode_Y[3] = h->pred_mode_Y[6] = NOT_AVAIL;
824         /* clear left mv predictors */
825         for(i=0;i<=20;i+=4)
826             h->mv[i] = un_mv;
827         h->mbx = 0;
828         h->mby++;
829         /* re-calculate sample pointers */
830         h->cy = h->picture.data[0] + h->mby*16*h->l_stride;
831         h->cu = h->picture.data[1] + h->mby*8*h->c_stride;
832         h->cv = h->picture.data[2] + h->mby*8*h->c_stride;
833         if(h->mby == h->mb_height) { //frame end
834             return 0;
835         } else {
836             //check_for_slice(h);
837         }
838     }
839     return 1;
840 }
841
842 static int decode_mb_i(AVSContext *h, int cbp_code) {
843     GetBitContext *gb = &h->s.gb;
844     int block, pred_mode_uv;
845     uint8_t top[18];
846     uint8_t left[18];
847     uint8_t *d;
848
849     init_mb(h);
850
851     /* get intra prediction modes from stream */
852     for(block=0;block<4;block++) {
853         int nA,nB,predpred;
854         int pos = scan3x3[block];
855
856         nA = h->pred_mode_Y[pos-1];
857         nB = h->pred_mode_Y[pos-3];
858         predpred = FFMIN(nA,nB);
859         if(predpred == NOT_AVAIL) // if either is not available
860             predpred = INTRA_L_LP;
861         if(!get_bits1(gb)){
862             int rem_mode= get_bits(gb, 2);
863             predpred = rem_mode + (rem_mode >= predpred);
864         }
865         h->pred_mode_Y[pos] = predpred;
866     }
867     pred_mode_uv = get_ue_golomb(gb);
868     if(pred_mode_uv > 6) {
869         av_log(h->s.avctx, AV_LOG_ERROR, "illegal intra chroma pred mode\n");
870         return -1;
871     }
872
873     /* save pred modes before they get modified */
874     h->pred_mode_Y[3] =  h->pred_mode_Y[5];
875     h->pred_mode_Y[6] =  h->pred_mode_Y[8];
876     h->top_pred_Y[h->mbx*2+0] = h->pred_mode_Y[7];
877     h->top_pred_Y[h->mbx*2+1] = h->pred_mode_Y[8];
878
879     /* modify pred modes according to availability of neighbour samples */
880     if(!(h->flags & A_AVAIL)) {
881         modify_pred(left_modifier_l, &h->pred_mode_Y[4] );
882         modify_pred(left_modifier_l, &h->pred_mode_Y[7] );
883         modify_pred(left_modifier_c, &pred_mode_uv );
884     }
885     if(!(h->flags & B_AVAIL)) {
886         modify_pred(top_modifier_l, &h->pred_mode_Y[4] );
887         modify_pred(top_modifier_l, &h->pred_mode_Y[5] );
888         modify_pred(top_modifier_c, &pred_mode_uv );
889     }
890
891     /* get coded block pattern */
892     if(h->pic_type == FF_I_TYPE)
893         cbp_code = get_ue_golomb(gb);
894     if(cbp_code > 63){
895         av_log(h->s.avctx, AV_LOG_ERROR, "illegal intra cbp\n");
896         return -1;
897     }
898     h->cbp = cbp_tab[cbp_code][0];
899     if(h->cbp && !h->qp_fixed)
900         h->qp += get_se_golomb(gb); //qp_delta
901
902     /* luma intra prediction interleaved with residual decode/transform/add */
903     for(block=0;block<4;block++) {
904         d = h->cy + h->luma_scan[block];
905         load_intra_pred_luma(h, top, left, block);
906         h->intra_pred_l[h->pred_mode_Y[scan3x3[block]]]
907             (d, top, left, h->l_stride);
908         if(h->cbp & (1<<block))
909             decode_residual_block(h,gb,intra_2dvlc,1,h->qp,d,h->l_stride);
910     }
911
912     /* chroma intra prediction */
913     /* extend borders by one pixel */
914     h->left_border_u[9] = h->left_border_u[8];
915     h->left_border_v[9] = h->left_border_v[8];
916     h->top_border_u[h->mbx*10+9] = h->top_border_u[h->mbx*10+8];
917     h->top_border_v[h->mbx*10+9] = h->top_border_v[h->mbx*10+8];
918     if(h->mbx && h->mby) {
919         h->top_border_u[h->mbx*10] = h->left_border_u[0] = h->topleft_border_u;
920         h->top_border_v[h->mbx*10] = h->left_border_v[0] = h->topleft_border_v;
921     } else {
922         h->left_border_u[0] = h->left_border_u[1];
923         h->left_border_v[0] = h->left_border_v[1];
924         h->top_border_u[h->mbx*10] = h->top_border_u[h->mbx*10+1];
925         h->top_border_v[h->mbx*10] = h->top_border_v[h->mbx*10+1];
926     }
927     h->intra_pred_c[pred_mode_uv](h->cu, &h->top_border_u[h->mbx*10],
928                                   h->left_border_u, h->c_stride);
929     h->intra_pred_c[pred_mode_uv](h->cv, &h->top_border_v[h->mbx*10],
930                                   h->left_border_v, h->c_stride);
931
932     decode_residual_chroma(h);
933     filter_mb(h,I_8X8);
934
935     /* mark motion vectors as intra */
936     h->mv[MV_FWD_X0] = intra_mv;
937     set_mvs(&h->mv[MV_FWD_X0], BLK_16X16);
938     h->mv[MV_BWD_X0] = intra_mv;
939     set_mvs(&h->mv[MV_BWD_X0], BLK_16X16);
940     if(h->pic_type != FF_B_TYPE)
941         *h->col_type = I_8X8;
942
943     return 0;
944 }
945
946 static void decode_mb_p(AVSContext *h, enum mb_t mb_type) {
947     GetBitContext *gb = &h->s.gb;
948     int ref[4];
949
950     init_mb(h);
951     switch(mb_type) {
952     case P_SKIP:
953         mv_pred(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_PSKIP, BLK_16X16, 0);
954         break;
955     case P_16X16:
956         ref[0] = h->ref_flag ? 0 : get_bits1(gb);
957         mv_pred(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_MEDIAN,   BLK_16X16,ref[0]);
958         break;
959     case P_16X8:
960         ref[0] = h->ref_flag ? 0 : get_bits1(gb);
961         ref[2] = h->ref_flag ? 0 : get_bits1(gb);
962         mv_pred(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_TOP,      BLK_16X8, ref[0]);
963         mv_pred(h, MV_FWD_X2, MV_FWD_A1, MV_PRED_LEFT,     BLK_16X8, ref[2]);
964         break;
965     case P_8X16:
966         ref[0] = h->ref_flag ? 0 : get_bits1(gb);
967         ref[1] = h->ref_flag ? 0 : get_bits1(gb);
968         mv_pred(h, MV_FWD_X0, MV_FWD_B3, MV_PRED_LEFT,     BLK_8X16, ref[0]);
969         mv_pred(h, MV_FWD_X1, MV_FWD_C2, MV_PRED_TOPRIGHT, BLK_8X16, ref[1]);
970         break;
971     case P_8X8:
972         ref[0] = h->ref_flag ? 0 : get_bits1(gb);
973         ref[1] = h->ref_flag ? 0 : get_bits1(gb);
974         ref[2] = h->ref_flag ? 0 : get_bits1(gb);
975         ref[3] = h->ref_flag ? 0 : get_bits1(gb);
976         mv_pred(h, MV_FWD_X0, MV_FWD_B3, MV_PRED_MEDIAN,   BLK_8X8, ref[0]);
977         mv_pred(h, MV_FWD_X1, MV_FWD_C2, MV_PRED_MEDIAN,   BLK_8X8, ref[1]);
978         mv_pred(h, MV_FWD_X2, MV_FWD_X1, MV_PRED_MEDIAN,   BLK_8X8, ref[2]);
979         mv_pred(h, MV_FWD_X3, MV_FWD_X0, MV_PRED_MEDIAN,   BLK_8X8, ref[3]);
980     }
981     inter_pred(h, mb_type);
982     store_mvs(h);
983     if(mb_type != P_SKIP)
984         decode_residual_inter(h);
985     filter_mb(h,mb_type);
986     *h->col_type = mb_type;
987 }
988
989 static void decode_mb_b(AVSContext *h, enum mb_t mb_type) {
990     int block;
991     enum sub_mb_t sub_type[4];
992     int flags;
993
994     init_mb(h);
995
996     /* reset all MVs */
997     h->mv[MV_FWD_X0] = dir_mv;
998     set_mvs(&h->mv[MV_FWD_X0], BLK_16X16);
999     h->mv[MV_BWD_X0] = dir_mv;
1000     set_mvs(&h->mv[MV_BWD_X0], BLK_16X16);
1001     switch(mb_type) {
1002     case B_SKIP:
1003     case B_DIRECT:
1004         if(!(*h->col_type)) {
1005             /* intra MB at co-location, do in-plane prediction */
1006             mv_pred(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_BSKIP, BLK_16X16, 1);
1007             mv_pred(h, MV_BWD_X0, MV_BWD_C2, MV_PRED_BSKIP, BLK_16X16, 0);
1008         } else
1009             /* direct prediction from co-located P MB, block-wise */
1010             for(block=0;block<4;block++)
1011                 mv_pred_direct(h,&h->mv[mv_scan[block]],
1012                             &h->col_mv[(h->mby*h->mb_width+h->mbx)*4 + block]);
1013         break;
1014     case B_FWD_16X16:
1015         mv_pred(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_MEDIAN, BLK_16X16, 1);
1016         break;
1017     case B_SYM_16X16:
1018         mv_pred(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_MEDIAN, BLK_16X16, 1);
1019         mv_pred_sym(h, &h->mv[MV_FWD_X0], BLK_16X16);
1020         break;
1021     case B_BWD_16X16:
1022         mv_pred(h, MV_BWD_X0, MV_BWD_C2, MV_PRED_MEDIAN, BLK_16X16, 0);
1023         break;
1024     case B_8X8:
1025         for(block=0;block<4;block++)
1026             sub_type[block] = get_bits(&h->s.gb,2);
1027         for(block=0;block<4;block++) {
1028             switch(sub_type[block]) {
1029             case B_SUB_DIRECT:
1030                 if(!(*h->col_type)) {
1031                     /* intra MB at co-location, do in-plane prediction */
1032                     mv_pred(h, mv_scan[block], mv_scan[block]-3,
1033                             MV_PRED_BSKIP, BLK_8X8, 1);
1034                     mv_pred(h, mv_scan[block]+MV_BWD_OFFS,
1035                             mv_scan[block]-3+MV_BWD_OFFS,
1036                             MV_PRED_BSKIP, BLK_8X8, 0);
1037                 } else
1038                     mv_pred_direct(h,&h->mv[mv_scan[block]],
1039                                    &h->col_mv[(h->mby*h->mb_width + h->mbx)*4 + block]);
1040                 break;
1041             case B_SUB_FWD:
1042                 mv_pred(h, mv_scan[block], mv_scan[block]-3,
1043                         MV_PRED_MEDIAN, BLK_8X8, 1);
1044                 break;
1045             case B_SUB_SYM:
1046                 mv_pred(h, mv_scan[block], mv_scan[block]-3,
1047                         MV_PRED_MEDIAN, BLK_8X8, 1);
1048                 mv_pred_sym(h, &h->mv[mv_scan[block]], BLK_8X8);
1049                 break;
1050             }
1051         }
1052         for(block=0;block<4;block++) {
1053             if(sub_type[block] == B_SUB_BWD)
1054                 mv_pred(h, mv_scan[block]+MV_BWD_OFFS,
1055                         mv_scan[block]+MV_BWD_OFFS-3,
1056                         MV_PRED_MEDIAN, BLK_8X8, 0);
1057         }
1058         break;
1059     default:
1060         assert((mb_type > B_SYM_16X16) && (mb_type < B_8X8));
1061         flags = partition_flags[mb_type];
1062         if(mb_type & 1) { /* 16x8 macroblock types */
1063             if(flags & FWD0)
1064                 mv_pred(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_TOP,  BLK_16X8, 1);
1065             if(flags & SYM0) {
1066                 mv_pred(h, MV_FWD_X0, MV_FWD_C2, MV_PRED_TOP,  BLK_16X8, 1);
1067                 mv_pred_sym(h, &h->mv[MV_FWD_X0], BLK_16X8);
1068             }
1069             if(flags & FWD1)
1070                 mv_pred(h, MV_FWD_X2, MV_FWD_A1, MV_PRED_LEFT, BLK_16X8, 1);
1071             if(flags & SYM1) {
1072                 mv_pred(h, MV_FWD_X2, MV_FWD_A1, MV_PRED_LEFT, BLK_16X8, 1);
1073                 mv_pred_sym(h, &h->mv[9], BLK_16X8);
1074             }
1075             if(flags & BWD0)
1076                 mv_pred(h, MV_BWD_X0, MV_BWD_C2, MV_PRED_TOP,  BLK_16X8, 0);
1077             if(flags & BWD1)
1078                 mv_pred(h, MV_BWD_X2, MV_BWD_A1, MV_PRED_LEFT, BLK_16X8, 0);
1079         } else {          /* 8x16 macroblock types */
1080             if(flags & FWD0)
1081                 mv_pred(h, MV_FWD_X0, MV_FWD_B3, MV_PRED_LEFT, BLK_8X16, 1);
1082             if(flags & SYM0) {
1083                 mv_pred(h, MV_FWD_X0, MV_FWD_B3, MV_PRED_LEFT, BLK_8X16, 1);
1084                 mv_pred_sym(h, &h->mv[MV_FWD_X0], BLK_8X16);
1085             }
1086             if(flags & FWD1)
1087                 mv_pred(h, MV_FWD_X1, MV_FWD_C2, MV_PRED_TOPRIGHT,BLK_8X16, 1);
1088             if(flags & SYM1) {
1089                 mv_pred(h, MV_FWD_X1, MV_FWD_C2, MV_PRED_TOPRIGHT,BLK_8X16, 1);
1090                 mv_pred_sym(h, &h->mv[6], BLK_8X16);
1091             }
1092             if(flags & BWD0)
1093                 mv_pred(h, MV_BWD_X0, MV_BWD_B3, MV_PRED_LEFT, BLK_8X16, 0);
1094             if(flags & BWD1)
1095                 mv_pred(h, MV_BWD_X1, MV_BWD_C2, MV_PRED_TOPRIGHT,BLK_8X16, 0);
1096         }
1097     }
1098     inter_pred(h, mb_type);
1099     if(mb_type != B_SKIP)
1100         decode_residual_inter(h);
1101     filter_mb(h,mb_type);
1102 }
1103
1104 /*****************************************************************************
1105  *
1106  * slice level
1107  *
1108  ****************************************************************************/
1109
1110 static inline int decode_slice_header(AVSContext *h, GetBitContext *gb) {
1111     if(h->stc > 0xAF)
1112         av_log(h->s.avctx, AV_LOG_ERROR, "unexpected start code 0x%02x\n", h->stc);
1113     h->mby = h->stc;
1114     if((h->mby == 0) && (!h->qp_fixed)){
1115         h->qp_fixed = get_bits1(gb);
1116         h->qp = get_bits(gb,6);
1117     }
1118     /* inter frame or second slice can have weighting params */
1119     if((h->pic_type != FF_I_TYPE) || (!h->pic_structure && h->mby >= h->mb_width/2))
1120         if(get_bits1(gb)) { //slice_weighting_flag
1121             av_log(h->s.avctx, AV_LOG_ERROR,
1122                    "weighted prediction not yet supported\n");
1123         }
1124     return 0;
1125 }
1126
1127 static inline void check_for_slice(AVSContext *h) {
1128     GetBitContext *gb = &h->s.gb;
1129     int align;
1130     align = (-get_bits_count(gb)) & 7;
1131     if((show_bits_long(gb,24+align) & 0xFFFFFF) == 0x000001) {
1132         get_bits_long(gb,24+align);
1133         h->stc = get_bits(gb,8);
1134         decode_slice_header(h,gb);
1135     }
1136 }
1137
1138 /*****************************************************************************
1139  *
1140  * frame level
1141  *
1142  ****************************************************************************/
1143
1144 static void init_pic(AVSContext *h) {
1145     int i;
1146
1147     /* clear some predictors */
1148     for(i=0;i<=20;i+=4)
1149         h->mv[i] = un_mv;
1150     h->mv[MV_BWD_X0] = dir_mv;
1151     set_mvs(&h->mv[MV_BWD_X0], BLK_16X16);
1152     h->mv[MV_FWD_X0] = dir_mv;
1153     set_mvs(&h->mv[MV_FWD_X0], BLK_16X16);
1154     h->pred_mode_Y[3] = h->pred_mode_Y[6] = NOT_AVAIL;
1155     h->cy = h->picture.data[0];
1156     h->cu = h->picture.data[1];
1157     h->cv = h->picture.data[2];
1158     h->l_stride = h->picture.linesize[0];
1159     h->c_stride = h->picture.linesize[1];
1160     h->luma_scan[2] = 8*h->l_stride;
1161     h->luma_scan[3] = 8*h->l_stride+8;
1162     h->mbx = h->mby = 0;
1163     h->flags = 0;
1164 }
1165
1166 static int decode_pic(AVSContext *h) {
1167     MpegEncContext *s = &h->s;
1168     int skip_count;
1169     enum mb_t mb_type;
1170
1171     if (!s->context_initialized) {
1172         if (MPV_common_init(s) < 0)
1173             return -1;
1174     }
1175     get_bits(&s->gb,16);//bbv_dwlay
1176     if(h->stc == PIC_PB_START_CODE) {
1177         h->pic_type = get_bits(&s->gb,2) + FF_I_TYPE;
1178         /* make sure we have the reference frames we need */
1179         if(!h->DPB[0].data[0] ||
1180           (!h->DPB[1].data[0] && h->pic_type == FF_B_TYPE))
1181             return -1;
1182     } else {
1183         h->pic_type = FF_I_TYPE;
1184         if(get_bits1(&s->gb))
1185             get_bits(&s->gb,16);//time_code
1186     }
1187     /* release last B frame */
1188     if(h->picture.data[0])
1189         s->avctx->release_buffer(s->avctx, (AVFrame *)&h->picture);
1190
1191     s->avctx->get_buffer(s->avctx, (AVFrame *)&h->picture);
1192     init_pic(h);
1193     h->picture.poc = get_bits(&s->gb,8)*2;
1194
1195     /* get temporal distances and MV scaling factors */
1196     if(h->pic_type != FF_B_TYPE) {
1197         h->dist[0] = (h->picture.poc - h->DPB[0].poc  + 512) % 512;
1198     } else {
1199         h->dist[0] = (h->DPB[0].poc  - h->picture.poc + 512) % 512;
1200     }
1201     h->dist[1] = (h->picture.poc - h->DPB[1].poc  + 512) % 512;
1202     h->scale_den[0] = h->dist[0] ? 512/h->dist[0] : 0;
1203     h->scale_den[1] = h->dist[1] ? 512/h->dist[1] : 0;
1204     if(h->pic_type == FF_B_TYPE) {
1205         h->sym_factor = h->dist[0]*h->scale_den[1];
1206     } else {
1207         h->direct_den[0] = h->dist[0] ? 16384/h->dist[0] : 0;
1208         h->direct_den[1] = h->dist[1] ? 16384/h->dist[1] : 0;
1209     }
1210
1211     if(s->low_delay)
1212         get_ue_golomb(&s->gb); //bbv_check_times
1213     h->progressive             = get_bits1(&s->gb);
1214     if(h->progressive)
1215         h->pic_structure = 1;
1216     else if(!(h->pic_structure = get_bits1(&s->gb) && (h->stc == PIC_PB_START_CODE)) )
1217         get_bits1(&s->gb);     //advanced_pred_mode_disable
1218     skip_bits1(&s->gb);        //top_field_first
1219     skip_bits1(&s->gb);        //repeat_first_field
1220     h->qp_fixed                = get_bits1(&s->gb);
1221     h->qp                      = get_bits(&s->gb,6);
1222     if(h->pic_type == FF_I_TYPE) {
1223         if(!h->progressive && !h->pic_structure)
1224             skip_bits1(&s->gb);//what is this?
1225         skip_bits(&s->gb,4);   //reserved bits
1226     } else {
1227         if(!(h->pic_type == FF_B_TYPE && h->pic_structure == 1))
1228             h->ref_flag        = get_bits1(&s->gb);
1229         skip_bits(&s->gb,4);   //reserved bits
1230         h->skip_mode_flag      = get_bits1(&s->gb);
1231     }
1232     h->loop_filter_disable     = get_bits1(&s->gb);
1233     if(!h->loop_filter_disable && get_bits1(&s->gb)) {
1234         h->alpha_offset        = get_se_golomb(&s->gb);
1235         h->beta_offset         = get_se_golomb(&s->gb);
1236     } else {
1237         h->alpha_offset = h->beta_offset  = 0;
1238     }
1239     check_for_slice(h);
1240     if(h->pic_type == FF_I_TYPE) {
1241         do {
1242             decode_mb_i(h, 0);
1243         } while(next_mb(h));
1244     } else if(h->pic_type == FF_P_TYPE) {
1245         do {
1246             if(h->skip_mode_flag) {
1247                 skip_count = get_ue_golomb(&s->gb);
1248                 while(skip_count--) {
1249                     decode_mb_p(h,P_SKIP);
1250                     if(!next_mb(h))
1251                         goto done;
1252                 }
1253                 mb_type = get_ue_golomb(&s->gb) + P_16X16;
1254             } else
1255                 mb_type = get_ue_golomb(&s->gb) + P_SKIP;
1256             if(mb_type > P_8X8) {
1257                 decode_mb_i(h, mb_type - P_8X8 - 1);
1258             } else
1259                 decode_mb_p(h,mb_type);
1260         } while(next_mb(h));
1261     } else { /* FF_B_TYPE */
1262         do {
1263             if(h->skip_mode_flag) {
1264                 skip_count = get_ue_golomb(&s->gb);
1265                 while(skip_count--) {
1266                     decode_mb_b(h,B_SKIP);
1267                     if(!next_mb(h))
1268                         goto done;
1269                 }
1270                 mb_type = get_ue_golomb(&s->gb) + B_DIRECT;
1271             } else
1272                 mb_type = get_ue_golomb(&s->gb) + B_SKIP;
1273             if(mb_type > B_8X8) {
1274                 decode_mb_i(h, mb_type - B_8X8 - 1);
1275             } else
1276                 decode_mb_b(h,mb_type);
1277         } while(next_mb(h));
1278     }
1279  done:
1280     if(h->pic_type != FF_B_TYPE) {
1281         if(h->DPB[1].data[0])
1282             s->avctx->release_buffer(s->avctx, (AVFrame *)&h->DPB[1]);
1283         memcpy(&h->DPB[1], &h->DPB[0], sizeof(Picture));
1284         memcpy(&h->DPB[0], &h->picture, sizeof(Picture));
1285         memset(&h->picture,0,sizeof(Picture));
1286     }
1287     return 0;
1288 }
1289
1290 /*****************************************************************************
1291  *
1292  * headers and interface
1293  *
1294  ****************************************************************************/
1295
1296 /**
1297  * some predictions require data from the top-neighbouring macroblock.
1298  * this data has to be stored for one complete row of macroblocks
1299  * and this storage space is allocated here
1300  */
1301 static void init_top_lines(AVSContext *h) {
1302     /* alloc top line of predictors */
1303     h->top_qp       = av_malloc( h->mb_width);
1304     h->top_mv[0]    = av_malloc((h->mb_width*2+1)*sizeof(vector_t));
1305     h->top_mv[1]    = av_malloc((h->mb_width*2+1)*sizeof(vector_t));
1306     h->top_pred_Y   = av_malloc( h->mb_width*2*sizeof(*h->top_pred_Y));
1307     h->top_border_y = av_malloc((h->mb_width+1)*16);
1308     h->top_border_u = av_malloc((h->mb_width)*10);
1309     h->top_border_v = av_malloc((h->mb_width)*10);
1310
1311     /* alloc space for co-located MVs and types */
1312     h->col_mv       = av_malloc( h->mb_width*h->mb_height*4*sizeof(vector_t));
1313     h->col_type_base = av_malloc(h->mb_width*h->mb_height);
1314 }
1315
1316 static int decode_seq_header(AVSContext *h) {
1317     MpegEncContext *s = &h->s;
1318     extern const AVRational ff_frame_rate_tab[];
1319     int frame_rate_code;
1320
1321     h->profile =         get_bits(&s->gb,8);
1322     h->level =           get_bits(&s->gb,8);
1323     skip_bits1(&s->gb); //progressive sequence
1324     s->width =           get_bits(&s->gb,14);
1325     s->height =          get_bits(&s->gb,14);
1326     skip_bits(&s->gb,2); //chroma format
1327     skip_bits(&s->gb,3); //sample_precision
1328     h->aspect_ratio =    get_bits(&s->gb,4);
1329     frame_rate_code =    get_bits(&s->gb,4);
1330     skip_bits(&s->gb,18);//bit_rate_lower
1331     skip_bits1(&s->gb);  //marker_bit
1332     skip_bits(&s->gb,12);//bit_rate_upper
1333     s->low_delay =       get_bits1(&s->gb);
1334     h->mb_width  = (s->width  + 15) >> 4;
1335     h->mb_height = (s->height + 15) >> 4;
1336     h->s.avctx->time_base.den = ff_frame_rate_tab[frame_rate_code].num;
1337     h->s.avctx->time_base.num = ff_frame_rate_tab[frame_rate_code].den;
1338     h->s.avctx->width  = s->width;
1339     h->s.avctx->height = s->height;
1340     if(!h->top_qp)
1341         init_top_lines(h);
1342     return 0;
1343 }
1344
1345 /**
1346  * finds the end of the current frame in the bitstream.
1347  * @return the position of the first byte of the next frame, or -1
1348  */
1349 int ff_cavs_find_frame_end(ParseContext *pc, const uint8_t *buf, int buf_size) {
1350     int pic_found, i;
1351     uint32_t state;
1352
1353     pic_found= pc->frame_start_found;
1354     state= pc->state;
1355
1356     i=0;
1357     if(!pic_found){
1358         for(i=0; i<buf_size; i++){
1359             state= (state<<8) | buf[i];
1360             if(state == PIC_I_START_CODE || state == PIC_PB_START_CODE){
1361                 i++;
1362                 pic_found=1;
1363                 break;
1364             }
1365         }
1366     }
1367
1368     if(pic_found){
1369         /* EOF considered as end of frame */
1370         if (buf_size == 0)
1371             return 0;
1372         for(; i<buf_size; i++){
1373             state= (state<<8) | buf[i];
1374             if((state&0xFFFFFF00) == 0x100){
1375                 if(state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE){
1376                     pc->frame_start_found=0;
1377                     pc->state=-1;
1378                     return i-3;
1379                 }
1380             }
1381         }
1382     }
1383     pc->frame_start_found= pic_found;
1384     pc->state= state;
1385     return END_NOT_FOUND;
1386 }
1387
1388 void ff_cavs_flush(AVCodecContext * avctx) {
1389     AVSContext *h = avctx->priv_data;
1390     h->got_keyframe = 0;
1391 }
1392
1393 static int cavs_decode_frame(AVCodecContext * avctx,void *data, int *data_size,
1394                              uint8_t * buf, int buf_size) {
1395     AVSContext *h = avctx->priv_data;
1396     MpegEncContext *s = &h->s;
1397     int input_size;
1398     const uint8_t *buf_end;
1399     const uint8_t *buf_ptr;
1400     AVFrame *picture = data;
1401     uint32_t stc;
1402
1403     s->avctx = avctx;
1404
1405     if (buf_size == 0) {
1406         if(!s->low_delay && h->DPB[0].data[0]) {
1407             *data_size = sizeof(AVPicture);
1408             *picture = *(AVFrame *) &h->DPB[0];
1409         }
1410         return 0;
1411     }
1412
1413     buf_ptr = buf;
1414     buf_end = buf + buf_size;
1415     for(;;) {
1416         buf_ptr = ff_find_start_code(buf_ptr,buf_end, &stc);
1417         if(stc & 0xFFFFFE00)
1418             return FFMAX(0, buf_ptr - buf - s->parse_context.last_index);
1419         input_size = (buf_end - buf_ptr)*8;
1420         switch(stc) {
1421         case SEQ_START_CODE:
1422             init_get_bits(&s->gb, buf_ptr, input_size);
1423             decode_seq_header(h);
1424             break;
1425         case PIC_I_START_CODE:
1426             if(!h->got_keyframe) {
1427                 if(h->DPB[0].data[0])
1428                     avctx->release_buffer(avctx, (AVFrame *)&h->DPB[0]);
1429                 if(h->DPB[1].data[0])
1430                     avctx->release_buffer(avctx, (AVFrame *)&h->DPB[1]);
1431                 h->got_keyframe = 1;
1432             }
1433         case PIC_PB_START_CODE:
1434             *data_size = 0;
1435             if(!h->got_keyframe)
1436                 break;
1437             init_get_bits(&s->gb, buf_ptr, input_size);
1438             h->stc = stc;
1439             if(decode_pic(h))
1440                 break;
1441             *data_size = sizeof(AVPicture);
1442             if(h->pic_type != FF_B_TYPE) {
1443                 if(h->DPB[1].data[0]) {
1444                     *picture = *(AVFrame *) &h->DPB[1];
1445                 } else {
1446                     *data_size = 0;
1447                 }
1448             } else
1449                 *picture = *(AVFrame *) &h->picture;
1450             break;
1451         case EXT_START_CODE:
1452             //mpeg_decode_extension(avctx,buf_ptr, input_size);
1453             break;
1454         case USER_START_CODE:
1455             //mpeg_decode_user_data(avctx,buf_ptr, input_size);
1456             break;
1457         default:
1458             if (stc >= SLICE_MIN_START_CODE &&
1459                 stc <= SLICE_MAX_START_CODE) {
1460                 init_get_bits(&s->gb, buf_ptr, input_size);
1461                 decode_slice_header(h, &s->gb);
1462             }
1463             break;
1464         }
1465     }
1466 }
1467
1468 static int cavs_decode_init(AVCodecContext * avctx) {
1469     AVSContext *h = avctx->priv_data;
1470     MpegEncContext * const s = &h->s;
1471
1472     MPV_decode_defaults(s);
1473     s->avctx = avctx;
1474
1475     avctx->pix_fmt= PIX_FMT_YUV420P;
1476
1477     h->luma_scan[0] = 0;
1478     h->luma_scan[1] = 8;
1479     h->intra_pred_l[      INTRA_L_VERT] = intra_pred_vert;
1480     h->intra_pred_l[     INTRA_L_HORIZ] = intra_pred_horiz;
1481     h->intra_pred_l[        INTRA_L_LP] = intra_pred_lp;
1482     h->intra_pred_l[ INTRA_L_DOWN_LEFT] = intra_pred_down_left;
1483     h->intra_pred_l[INTRA_L_DOWN_RIGHT] = intra_pred_down_right;
1484     h->intra_pred_l[   INTRA_L_LP_LEFT] = intra_pred_lp_left;
1485     h->intra_pred_l[    INTRA_L_LP_TOP] = intra_pred_lp_top;
1486     h->intra_pred_l[    INTRA_L_DC_128] = intra_pred_dc_128;
1487     h->intra_pred_c[        INTRA_C_LP] = intra_pred_lp;
1488     h->intra_pred_c[     INTRA_C_HORIZ] = intra_pred_horiz;
1489     h->intra_pred_c[      INTRA_C_VERT] = intra_pred_vert;
1490     h->intra_pred_c[     INTRA_C_PLANE] = intra_pred_plane;
1491     h->intra_pred_c[   INTRA_C_LP_LEFT] = intra_pred_lp_left;
1492     h->intra_pred_c[    INTRA_C_LP_TOP] = intra_pred_lp_top;
1493     h->intra_pred_c[    INTRA_C_DC_128] = intra_pred_dc_128;
1494     h->mv[ 7] = un_mv;
1495     h->mv[19] = un_mv;
1496     return 0;
1497 }
1498
1499 static int cavs_decode_end(AVCodecContext * avctx) {
1500     AVSContext *h = avctx->priv_data;
1501
1502     av_free(h->top_qp);
1503     av_free(h->top_mv[0]);
1504     av_free(h->top_mv[1]);
1505     av_free(h->top_pred_Y);
1506     av_free(h->top_border_y);
1507     av_free(h->top_border_u);
1508     av_free(h->top_border_v);
1509     av_free(h->col_mv);
1510     av_free(h->col_type_base);
1511     return 0;
1512 }
1513
1514 AVCodec cavs_decoder = {
1515     "cavs",
1516     CODEC_TYPE_VIDEO,
1517     CODEC_ID_CAVS,
1518     sizeof(AVSContext),
1519     cavs_decode_init,
1520     NULL,
1521     cavs_decode_end,
1522     cavs_decode_frame,
1523     CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1524     .flush= ff_cavs_flush,
1525 };