]> git.sesse.net Git - ffmpeg/blob - libavcodec/h261.c
cleanup
[ffmpeg] / libavcodec / h261.c
1 /*
2  * H261 decoder
3  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
4  * Copyright (c) 2004 Maarten Daniels
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /**
22  * @file h261.c
23  * h261codec.
24  */
25
26 #include "common.h"
27 #include "dsputil.h"
28 #include "avcodec.h"
29 #include "mpegvideo.h"
30 #include "h261data.h"
31
32
33 #define H261_MBA_VLC_BITS 9
34 #define H261_MTYPE_VLC_BITS 6
35 #define H261_MV_VLC_BITS 7
36 #define H261_CBP_VLC_BITS 9
37 #define TCOEFF_VLC_BITS 9
38
39 #define MBA_STUFFING 33
40 #define MBA_STARTCODE 34
41 #define IS_FIL(a)    ((a)&MB_TYPE_H261_FIL)
42
43 /**
44  * H261Context
45  */
46 typedef struct H261Context{
47     MpegEncContext s;
48
49     int current_mba;
50     int previous_mba;
51     int mba_diff;
52     int mtype;
53     int current_mv_x;
54     int current_mv_y;
55     int gob_number;
56     int bits_left; //8 - nr of bits left of the following frame in the last byte in this frame
57     int last_bits; //bits left of the following frame in the last byte in this frame
58     int gob_start_code_skipped; // 1 if gob start code is already read before gob header is read
59 }H261Context;
60
61 void ff_h261_loop_filter(MpegEncContext *s){
62     H261Context * h= (H261Context*)s;
63     const int linesize  = s->linesize;
64     const int uvlinesize= s->uvlinesize;
65     uint8_t *dest_y = s->dest[0];
66     uint8_t *dest_cb= s->dest[1];
67     uint8_t *dest_cr= s->dest[2];
68
69     if(!(IS_FIL (h->mtype)))
70         return;
71
72     s->dsp.h261_loop_filter(dest_y                   , linesize);
73     s->dsp.h261_loop_filter(dest_y                + 8, linesize);
74     s->dsp.h261_loop_filter(dest_y + 8 * linesize    , linesize);
75     s->dsp.h261_loop_filter(dest_y + 8 * linesize + 8, linesize);
76     s->dsp.h261_loop_filter(dest_cb, uvlinesize);
77     s->dsp.h261_loop_filter(dest_cr, uvlinesize);
78 }
79
80 static int ff_h261_get_picture_format(int width, int height){
81     // QCIF
82     if (width == 176 && height == 144)
83         return 0;
84     // CIF
85     else if (width == 352 && height == 288)
86         return 1;
87     // ERROR
88     else
89         return -1;
90 }
91
92 static void h261_encode_block(H261Context * h, DCTELEM * block,
93                               int n);
94 static int h261_decode_block(H261Context *h, DCTELEM *block,
95                              int n, int coded);
96
97 void ff_h261_encode_picture_header(MpegEncContext * s, int picture_number){
98     H261Context * h = (H261Context *) s;
99     int format, temp_ref;
100
101     align_put_bits(&s->pb);
102
103     /* Update the pointer to last GOB */
104     s->ptr_lastgob = pbBufPtr(&s->pb);
105
106     put_bits(&s->pb, 20, 0x10); /* PSC */
107
108     temp_ref= s->picture_number * (int64_t)30000 * s->avctx->frame_rate_base / 
109                          (1001 * (int64_t)s->avctx->frame_rate);
110     put_bits(&s->pb, 5, temp_ref & 0x1f); /* TemporalReference */
111
112     put_bits(&s->pb, 1, 0); /* split screen off */
113     put_bits(&s->pb, 1, 0); /* camera  off */
114     put_bits(&s->pb, 1, 0); /* freeze picture release off */
115     
116     format = ff_h261_get_picture_format(s->width, s->height);
117     
118     put_bits(&s->pb, 1, format); /* 0 == QCIF, 1 == CIF */
119
120     put_bits(&s->pb, 1, 0); /* still image mode */
121     put_bits(&s->pb, 1, 0); /* reserved */
122
123     put_bits(&s->pb, 1, 0); /* no PEI */    
124     if(format == 0)
125         h->gob_number = -1;
126     else
127         h->gob_number = 0;
128     h->current_mba = 0;
129 }
130
131 /**
132  * Encodes a group of blocks header.
133  */
134 static void h261_encode_gob_header(MpegEncContext * s, int mb_line){
135     H261Context * h = (H261Context *)s;
136     if(ff_h261_get_picture_format(s->width, s->height) == 0){
137         h->gob_number+=2; // QCIF
138     }
139     else{
140         h->gob_number++; // CIF
141     }
142     put_bits(&s->pb, 16, 1); /* GBSC */
143     put_bits(&s->pb, 4, h->gob_number); /* GN */
144     put_bits(&s->pb, 5, s->qscale); /* GQUANT */
145     put_bits(&s->pb, 1, 0); /* no GEI */
146     h->current_mba = 0;
147     h->previous_mba = 0;
148     h->current_mv_x=0;
149     h->current_mv_y=0;
150 }
151
152 void ff_h261_reorder_mb_index(MpegEncContext* s){
153     /* for CIF the GOB's are fragmented in the middle of a scanline
154        that's why we need to adjust the x and y index of the macroblocks */
155     if(ff_h261_get_picture_format(s->width,s->height) == 1){ // CIF
156         if((s->mb_x == 0 && (s->mb_y % 3 == 0) ) || (s->mb_x == 11 && ((s->mb_y -1 )% 3 == 0) ))
157             h261_encode_gob_header(s,0);
158         if(s->mb_x < 11 ){
159             if((s->mb_y % 3) == 1 ){
160                 s->mb_x += 0;
161                 s->mb_y += 1;
162             }
163             else if( (s->mb_y % 3) == 2 ){
164                 s->mb_x += 11;
165                 s->mb_y -= 1;
166             }
167         }
168         else{
169             if((s->mb_y % 3) == 1 ){
170                 s->mb_x += 0;
171                 s->mb_y -= 1;
172             }
173             else if( (s->mb_y % 3) == 0 ){
174                 s->mb_x -= 11;
175                 s->mb_y += 1;
176             }
177         }
178         ff_init_block_index(s);
179         ff_update_block_index(s);
180     /* for QCIF we don't need to reorder MB's
181        there the GOB's aren't fragmented in the middle of a scanline */
182     }else if(ff_h261_get_picture_format(s->width,s->height) == 0){ // QCIF
183         if(s->mb_y % 3 == 0 && s->mb_x == 0)
184             h261_encode_gob_header(s,0);
185     }
186 }
187
188 static void h261_encode_motion(H261Context * h, int val){
189     MpegEncContext * const s = &h->s;
190     int sign, code;
191     if(val==0){
192         code = 0;
193         put_bits(&s->pb,h261_mv_tab[code][1],h261_mv_tab[code][0]);
194     } 
195     else{
196         if(val > 16)
197             val -=32;
198         if(val < -16)
199             val+=32;
200         sign = val < 0;
201         code = sign ? -val : val; 
202         put_bits(&s->pb,h261_mv_tab[code][1],h261_mv_tab[code][0]);
203         put_bits(&s->pb,1,sign);
204     }
205 }
206
207 static inline int get_cbp(MpegEncContext * s,
208                       DCTELEM block[6][64])
209 {
210     int i, cbp;
211     cbp= 0;
212     for (i = 0; i < 6; i++) {
213         if (s->block_last_index[i] >= 0)
214             cbp |= 1 << (5 - i);
215     }
216     return cbp;
217 }
218 void ff_h261_encode_mb(MpegEncContext * s,
219          DCTELEM block[6][64],
220          int motion_x, int motion_y)
221 {
222     H261Context * h = (H261Context *)s;
223     int old_mtype, mvd, mv_diff_x, mv_diff_y, i, cbp;
224     cbp = 63; // avoid warning
225     mvd = 0;
226  
227     h->current_mba++;
228     old_mtype = h->mtype;
229     h->mtype = 0;
230  
231     if (!s->mb_intra){
232         /* compute cbp */
233         cbp= get_cbp(s, block);
234    
235         /* mvd indicates if this block is motion compensated */
236         if(((motion_x >> 1) - h->current_mv_x != 0) || ((motion_y >> 1 ) - h->current_mv_y) != 0){
237             mvd = 1;
238         }
239         else if((motion_x >> 1 == 0) && (motion_y >> 1 == 0)){
240             mvd = 0;
241         }
242         else
243             mvd = 1;
244         if((cbp | mvd | s->dquant ) == 0) {
245             /* skip macroblock */
246             s->skip_count++;
247             h->current_mv_x=0;
248             h->current_mv_y=0;
249             return;
250         }
251     }
252
253     /* MB is not skipped, encode MBA */
254     put_bits(&s->pb, h261_mba_bits[(h->current_mba-h->previous_mba)-1], h261_mba_code[(h->current_mba-h->previous_mba)-1]);
255  
256     /* calculate MTYPE */
257     if(!s->mb_intra){
258         h->mtype+=2;
259     if(mvd == 1){   
260         h->mtype+=2;
261         if(cbp!=0)
262             h->mtype+=1;
263         if(s->loop_filter)
264             h->mtype+=3;
265         }
266     }
267
268     if(s->dquant) 
269         h->mtype++;
270
271     put_bits(&s->pb, h261_mtype_bits[h->mtype], h261_mtype_code[h->mtype]);
272  
273     h->mtype = h261_mtype_map[h->mtype];
274  
275     if(IS_QUANT(h->mtype)){
276         ff_set_qscale(s,s->qscale+s->dquant);
277         put_bits(&s->pb, 5, s->qscale);
278     }
279  
280     if(IS_16X16(h->mtype)){
281         mv_diff_x = (motion_x >> 1) - h->current_mv_x;
282         mv_diff_y = (motion_y >> 1) - h->current_mv_y;
283         h->current_mv_x = (motion_x >> 1);
284         h->current_mv_y = (motion_y >> 1);
285         h261_encode_motion(h,mv_diff_x);
286         h261_encode_motion(h,mv_diff_y);
287     }
288  
289     h->previous_mba = h->current_mba;
290  
291     if(HAS_CBP(h->mtype)){
292         put_bits(&s->pb,h261_cbp_tab[cbp-1][1],h261_cbp_tab[cbp-1][0]); 
293     }
294     for(i=0; i<6; i++) {
295         /* encode each block */
296         h261_encode_block(h, block[i], i);
297     }
298
299     if ( ( h->current_mba == 11 ) || ( h->current_mba == 22 ) || ( h->current_mba == 33 ) || ( !IS_16X16 ( h->mtype ) )){
300         h->current_mv_x=0;
301         h->current_mv_y=0;
302     }
303 }
304
305 void ff_h261_encode_init(MpegEncContext *s){
306     static int done = 0;
307     
308     if (!done) {
309         done = 1;
310         init_rl(&h261_rl_tcoeff);
311     }
312
313     s->min_qcoeff= -127;
314     s->max_qcoeff=  127;
315     s->y_dc_scale_table=
316     s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
317 }
318
319
320 /**
321  * encodes a 8x8 block.
322  * @param block the 8x8 block
323  * @param n block index (0-3 are luma, 4-5 are chroma)
324  */
325 static void h261_encode_block(H261Context * h, DCTELEM * block, int n){
326     MpegEncContext * const s = &h->s;
327     int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
328     RLTable *rl;
329
330     rl = &h261_rl_tcoeff;
331     if (s->mb_intra) {
332         /* DC coef */
333         level = block[0];
334         /* 255 cannot be represented, so we clamp */
335         if (level > 254) {
336             level = 254;
337             block[0] = 254;
338         }
339         /* 0 cannot be represented also */
340         else if (level < 1) {
341             level = 1;
342             block[0] = 1;
343         }
344         if (level == 128)
345             put_bits(&s->pb, 8, 0xff);
346         else
347             put_bits(&s->pb, 8, level);
348         i = 1;
349     } else if((block[0]==1 || block[0] == -1) && (s->block_last_index[n] > -1)){
350         //special case
351         put_bits(&s->pb,1,1);
352         put_bits(&s->pb,1,block[0]>0 ? 0 : 1 );
353         i = 1;
354     } else {
355         i = 0;
356     }
357    
358     /* AC coefs */
359     last_index = s->block_last_index[n];
360     last_non_zero = i - 1;
361     for (; i <= last_index; i++) {
362         j = s->intra_scantable.permutated[i];
363         level = block[j];
364         if (level) {
365             run = i - last_non_zero - 1;
366             last = (i == last_index);
367             sign = 0;
368             slevel = level;
369             if (level < 0) {
370                 sign = 1;
371                 level = -level;
372             }
373             code = get_rl_index(rl, 0 /*no last in H.261, EOB is used*/, run, level);
374             if(run==0 && level < 16)
375             code+=1;
376             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
377             if (code == rl->n) {
378                 put_bits(&s->pb, 6, run);
379                 assert(slevel != 0);
380                 if(slevel < -127){
381                     slevel = -127;
382                 }
383                 else if(slevel > 127){
384                     slevel = 127;
385                 }
386                 put_bits(&s->pb, 8, slevel & 0xff);
387             } else {
388                 put_bits(&s->pb, 1, sign);
389             }
390             last_non_zero = i;
391         }
392     }
393     if(last_index > -1){
394         put_bits(&s->pb, rl->table_vlc[0][1], rl->table_vlc[0][0]);// END OF BLOCK
395     }
396 }
397
398 /***********************************************/
399 /* decoding */
400
401 static VLC h261_mba_vlc;
402 static VLC h261_mtype_vlc;
403 static VLC h261_mv_vlc;
404 static VLC h261_cbp_vlc;
405
406 void init_vlc_rl(RLTable *rl);
407
408 static void h261_decode_init_vlc(H261Context *h){
409     static int done = 0;
410
411     if(!done){
412         done = 1;
413         init_vlc(&h261_mba_vlc, H261_MBA_VLC_BITS, 35,
414                  h261_mba_bits, 1, 1,
415                  h261_mba_code, 1, 1);
416         init_vlc(&h261_mtype_vlc, H261_MTYPE_VLC_BITS, 10,
417                  h261_mtype_bits, 1, 1,
418                  h261_mtype_code, 1, 1);
419         init_vlc(&h261_mv_vlc, H261_MV_VLC_BITS, 17,
420                  &h261_mv_tab[0][1], 2, 1,
421                  &h261_mv_tab[0][0], 2, 1);
422         init_vlc(&h261_cbp_vlc, H261_CBP_VLC_BITS, 63,
423                  &h261_cbp_tab[0][1], 2, 1,
424                  &h261_cbp_tab[0][0], 2, 1);
425         init_rl(&h261_rl_tcoeff);
426         init_vlc_rl(&h261_rl_tcoeff);
427     }
428 }
429
430 static int h261_decode_init(AVCodecContext *avctx){
431     H261Context *h= avctx->priv_data;
432     MpegEncContext * const s = &h->s;
433
434     // set defaults
435     MPV_decode_defaults(s);
436     s->avctx = avctx;
437
438     s->width  = s->avctx->coded_width;
439     s->height = s->avctx->coded_height;
440     s->codec_id = s->avctx->codec->id;
441
442     s->out_format = FMT_H261;
443     s->low_delay= 1;
444     avctx->pix_fmt= PIX_FMT_YUV420P;
445
446     s->codec_id= avctx->codec->id;
447
448     h261_decode_init_vlc(h);
449
450     h->gob_start_code_skipped = 0;
451     
452     return 0;
453 }
454
455 /**
456  * decodes the group of blocks header or slice header.
457  * @return <0 if an error occured
458  */
459 static int h261_decode_gob_header(H261Context *h){
460     unsigned int val;
461     MpegEncContext * const s = &h->s;
462     
463     if ( !h->gob_start_code_skipped ){
464         /* Check for GOB Start Code */
465         val = show_bits(&s->gb, 15);
466         if(val)
467             return -1;
468
469         /* We have a GBSC */
470         skip_bits(&s->gb, 16);
471     }
472
473     h->gob_start_code_skipped = 0;
474
475     h->gob_number = get_bits(&s->gb, 4); /* GN */
476     s->qscale = get_bits(&s->gb, 5); /* GQUANT */
477
478     /* Check if gob_number is valid */
479     if (s->mb_height==18){ //cif
480         if ((h->gob_number<=0) || (h->gob_number>12))
481             return -1;
482     }
483     else{ //qcif
484         if ((h->gob_number!=1) && (h->gob_number!=3) && (h->gob_number!=5))
485             return -1;
486     }
487
488     /* GEI */
489     while (get_bits1(&s->gb) != 0) {
490         skip_bits(&s->gb, 8);
491     }
492
493     if(s->qscale==0)
494         return -1;
495
496     // For the first transmitted macroblock in a GOB, MBA is the absolute address. For
497     // subsequent macroblocks, MBA is the difference between the absolute addresses of
498     // the macroblock and the last transmitted macroblock.
499     h->current_mba = 0;
500     h->mba_diff = 0;
501
502     return 0;
503 }
504
505 /**
506  * decodes the group of blocks / video packet header.
507  * @return <0 if no resync found
508  */
509 static int ff_h261_resync(H261Context *h){
510     MpegEncContext * const s = &h->s;
511     int left, ret;
512
513     if ( h->gob_start_code_skipped ){
514         ret= h261_decode_gob_header(h);
515         if(ret>=0)
516             return 0;
517     }
518     else{
519         if(show_bits(&s->gb, 15)==0){
520             ret= h261_decode_gob_header(h);
521             if(ret>=0)
522                 return 0;
523         }
524         //ok, its not where its supposed to be ...
525         s->gb= s->last_resync_gb;
526         align_get_bits(&s->gb);
527         left= s->gb.size_in_bits - get_bits_count(&s->gb);
528
529         for(;left>15+1+4+5; left-=8){
530             if(show_bits(&s->gb, 15)==0){
531                 GetBitContext bak= s->gb;
532
533                 ret= h261_decode_gob_header(h);
534                 if(ret>=0)
535                     return 0;
536
537                 s->gb= bak;
538             }
539             skip_bits(&s->gb, 8);
540         }
541     }
542
543     return -1;
544 }
545
546 /**
547  * decodes skipped macroblocks
548  * @return 0
549  */
550 static int h261_decode_mb_skipped(H261Context *h, int mba1, int mba2 )
551 {
552     MpegEncContext * const s = &h->s;
553     int i;
554     
555     s->mb_intra = 0;
556
557     for(i=mba1; i<mba2; i++){
558         int j, xy;
559
560         s->mb_x= ((h->gob_number-1) % 2) * 11 + i % 11;
561         s->mb_y= ((h->gob_number-1) / 2) * 3 + i / 11;
562         xy = s->mb_x + s->mb_y * s->mb_stride;
563         ff_init_block_index(s);
564         ff_update_block_index(s);
565         s->dsp.clear_blocks(s->block[0]);
566
567         for(j=0;j<6;j++)
568             s->block_last_index[j] = -1;
569
570         s->mv_dir = MV_DIR_FORWARD;
571         s->mv_type = MV_TYPE_16X16;
572         s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
573         s->mv[0][0][0] = 0;
574         s->mv[0][0][1] = 0;
575         s->mb_skiped = 1;
576         h->mtype &= ~MB_TYPE_H261_FIL;
577
578         MPV_decode_mb(s, s->block);
579     }
580
581     return 0;
582 }
583
584 static int decode_mv_component(GetBitContext *gb, int v){
585     int mv_diff = get_vlc2(gb, h261_mv_vlc.table, H261_MV_VLC_BITS, 2);
586
587     /* check if mv_diff is valid */
588     if ( mv_diff < 0 )
589         return v;
590
591     mv_diff = mvmap[mv_diff];
592
593     if(mv_diff && !get_bits1(gb))
594         mv_diff= -mv_diff;
595     
596     v += mv_diff;
597     if     (v <=-16) v+= 32;
598     else if(v >= 16) v-= 32;
599
600     return v;
601 }
602
603 static int h261_decode_mb(H261Context *h){
604     MpegEncContext * const s = &h->s;
605     int i, cbp, xy, old_mtype;
606
607     cbp = 63;
608     // Read mba
609     do{
610         h->mba_diff = get_vlc2(&s->gb, h261_mba_vlc.table, H261_MBA_VLC_BITS, 2);
611
612         /* Check for slice end */
613         /* NOTE: GOB can be empty (no MB data) or exist only of MBA_stuffing */
614         if (h->mba_diff == MBA_STARTCODE){ // start code
615             h->gob_start_code_skipped = 1;
616             return SLICE_END;
617         }
618     }
619     while( h->mba_diff == MBA_STUFFING ); // stuffing
620
621     if ( h->mba_diff < 0 ){
622         if ( get_bits_count(&s->gb) + 7 >= s->gb.size_in_bits )
623             return SLICE_END;
624
625         av_log(s->avctx, AV_LOG_ERROR, "illegal mba at %d %d\n", s->mb_x, s->mb_y);
626         return SLICE_ERROR;
627     }
628
629     h->mba_diff += 1;
630     h->current_mba += h->mba_diff;
631
632     if ( h->current_mba > MBA_STUFFING )
633         return SLICE_ERROR;
634     
635     s->mb_x= ((h->gob_number-1) % 2) * 11 + ((h->current_mba-1) % 11);
636     s->mb_y= ((h->gob_number-1) / 2) * 3 + ((h->current_mba-1) / 11);
637     xy = s->mb_x + s->mb_y * s->mb_stride;
638     ff_init_block_index(s);
639     ff_update_block_index(s);
640     s->dsp.clear_blocks(s->block[0]);
641
642     // Read mtype
643     old_mtype = h->mtype;
644     h->mtype = get_vlc2(&s->gb, h261_mtype_vlc.table, H261_MTYPE_VLC_BITS, 2);
645     h->mtype = h261_mtype_map[h->mtype];
646
647     // Read mquant
648     if ( IS_QUANT ( h->mtype ) ){
649         ff_set_qscale(s, get_bits(&s->gb, 5));
650     }
651
652     s->mb_intra = IS_INTRA4x4(h->mtype);
653
654     // Read mv
655     if ( IS_16X16 ( h->mtype ) ){
656         // Motion vector data is included for all MC macroblocks. MVD is obtained from the macroblock vector by subtracting the
657         // vector of the preceding macroblock. For this calculation the vector of the preceding macroblock is regarded as zero in the
658         // following three situations:
659         // 1) evaluating MVD for macroblocks 1, 12 and 23;
660         // 2) evaluating MVD for macroblocks in which MBA does not represent a difference of 1;
661         // 3) MTYPE of the previous macroblock was not MC.
662         if ( ( h->current_mba == 1 ) || ( h->current_mba == 12 ) || ( h->current_mba == 23 ) ||
663              ( h->mba_diff != 1) || ( !IS_16X16 ( old_mtype ) ))
664         {
665             h->current_mv_x = 0;
666             h->current_mv_y = 0;
667         }
668
669         h->current_mv_x= decode_mv_component(&s->gb, h->current_mv_x);
670         h->current_mv_y= decode_mv_component(&s->gb, h->current_mv_y);
671     }
672
673     // Read cbp
674     if ( HAS_CBP( h->mtype ) ){
675         cbp = get_vlc2(&s->gb, h261_cbp_vlc.table, H261_CBP_VLC_BITS, 2) + 1;
676     }
677
678     if(s->mb_intra){
679         s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
680         goto intra;
681     }
682
683     //set motion vectors
684     s->mv_dir = MV_DIR_FORWARD;
685     s->mv_type = MV_TYPE_16X16;
686     s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
687     if(IS_16X16 ( h->mtype )){
688         s->mv[0][0][0] = h->current_mv_x * 2;//gets divided by 2 in motion compensation
689         s->mv[0][0][1] = h->current_mv_y * 2;
690     }
691     else{
692         h->current_mv_x = s->mv[0][0][0] = 0;
693         h->current_mv_x = s->mv[0][0][1] = 0;
694     }
695
696 intra:
697     /* decode each block */
698     if(s->mb_intra || HAS_CBP(h->mtype)){
699         for (i = 0; i < 6; i++) {
700             if (h261_decode_block(h, s->block[i], i, cbp&32) < 0){
701                 return SLICE_ERROR;
702             }
703             cbp+=cbp;
704         }
705     }
706
707     MPV_decode_mb(s, s->block);
708
709     return SLICE_OK;
710 }
711
712 /**
713  * decodes a macroblock
714  * @return <0 if an error occured
715  */
716 static int h261_decode_block(H261Context * h, DCTELEM * block,
717                              int n, int coded)
718 {
719     MpegEncContext * const s = &h->s;
720     int code, level, i, j, run;
721     RLTable *rl = &h261_rl_tcoeff;
722     const uint8_t *scan_table;
723     
724     // For the variable length encoding there are two code tables, one being used for
725     // the first transmitted LEVEL in INTER, INTER+MC and INTER+MC+FIL blocks, the second
726     // for all other LEVELs except the first one in INTRA blocks which is fixed length
727     // coded with 8 bits.
728     // NOTE: the two code tables only differ in one VLC so we handle that manually.
729     scan_table = s->intra_scantable.permutated;
730     if (s->mb_intra){
731         /* DC coef */
732         level = get_bits(&s->gb, 8);
733         // 0 (00000000b) and -128 (10000000b) are FORBIDDEN
734         if((level&0x7F) == 0){
735             av_log(s->avctx, AV_LOG_ERROR, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);
736             return -1;
737         }
738         // The code 1000 0000 is not used, the reconstruction level of 1024 being coded as 1111 1111.
739         if (level == 255)
740             level = 128;
741         block[0] = level;
742         i = 1;
743     }else if(coded){
744         // Run  Level   Code
745         // EOB                  Not possible for first level when cbp is available (that's why the table is different)
746         // 0    1               1s
747         // *    *               0*
748         int check = show_bits(&s->gb, 2);
749         i = 0;
750         if ( check & 0x2 ){
751             skip_bits(&s->gb, 2);
752             block[0] = ( check & 0x1 ) ? -1 : 1;
753             i = 1;
754         }
755     }else{
756         i = 0;
757     }
758     if(!coded){
759         s->block_last_index[n] = i - 1;
760         return 0;
761     }
762     for(;;){
763         code = get_vlc2(&s->gb, rl->vlc.table, TCOEFF_VLC_BITS, 2);
764         if (code < 0){
765             av_log(s->avctx, AV_LOG_ERROR, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
766             return -1;
767         }
768         if (code == rl->n) {
769             /* escape */
770             // The remaining combinations of (run, level) are encoded with a 20-bit word consisting of 6 bits escape, 6 bits run and 8 bits level.
771             run = get_bits(&s->gb, 6);
772             level = (int8_t)get_bits(&s->gb, 8);
773         }else if(code == 0){
774             break;
775         }else{
776             run = rl->table_run[code];
777             level = rl->table_level[code];
778             if (get_bits1(&s->gb))
779                 level = -level;
780         }
781         i += run;
782         if (i >= 64){
783             av_log(s->avctx, AV_LOG_ERROR, "run overflow at %dx%d\n", s->mb_x, s->mb_y);
784             return -1;
785         }
786         j = scan_table[i];
787         block[j] = level;
788         i++;
789     }
790     s->block_last_index[n] = i-1;
791     return 0;
792 }
793
794 /**
795  * decodes the H261 picture header.
796  * @return <0 if no startcode found
797  */
798 int h261_decode_picture_header(H261Context *h){
799     MpegEncContext * const s = &h->s;
800     int format, i;
801     uint32_t startcode= 0;
802
803     for(i= s->gb.size_in_bits - get_bits_count(&s->gb); i>24; i-=1){
804         startcode = ((startcode << 1) | get_bits(&s->gb, 1)) & 0x000FFFFF;
805
806         if(startcode == 0x10)
807             break;
808     }
809
810     if (startcode != 0x10){
811         av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");
812         return -1;
813     }
814
815     /* temporal reference */
816     s->picture_number = get_bits(&s->gb, 5); /* picture timestamp */
817
818     /* PTYPE starts here */
819     skip_bits1(&s->gb); /* split screen off */
820     skip_bits1(&s->gb); /* camera  off */
821     skip_bits1(&s->gb); /* freeze picture release off */
822
823     format = get_bits1(&s->gb);
824
825     //only 2 formats possible
826     if (format == 0){//QCIF
827         s->width = 176;
828         s->height = 144;
829         s->mb_width = 11;
830         s->mb_height = 9;
831     }else{//CIF
832         s->width = 352;
833         s->height = 288;
834         s->mb_width = 22;
835         s->mb_height = 18;
836     }
837
838     s->mb_num = s->mb_width * s->mb_height;
839
840     skip_bits1(&s->gb); /* still image mode off */
841     skip_bits1(&s->gb); /* Reserved */
842
843     /* PEI */
844     while (get_bits1(&s->gb) != 0){
845         skip_bits(&s->gb, 8);
846     }
847
848     // h261 has no I-FRAMES, but if we pass I_TYPE for the first frame, the codec crashes if it does 
849     // not contain all I-blocks (e.g. when a packet is lost)
850     s->pict_type = P_TYPE;
851
852     h->gob_number = 0;
853     return 0;
854 }
855
856 static int h261_decode_gob(H261Context *h){
857     MpegEncContext * const s = &h->s;
858     
859     ff_set_qscale(s, s->qscale);
860
861     /* decode mb's */
862     while(h->current_mba <= MBA_STUFFING)
863     {
864         int ret;
865         /* DCT & quantize */
866         ret= h261_decode_mb(h);
867         if(ret<0){
868             if(ret==SLICE_END){
869                 h261_decode_mb_skipped(h, h->current_mba, 33);                
870                 return 0;
871             }
872             av_log(s->avctx, AV_LOG_ERROR, "Error at MB: %d\n", s->mb_x + s->mb_y*s->mb_stride);
873             return -1;
874         }
875         
876         h261_decode_mb_skipped(h, h->current_mba-h->mba_diff, h->current_mba-1);
877     }
878     
879     return -1;
880 }
881
882 static int h261_find_frame_end(ParseContext *pc, AVCodecContext* avctx, const uint8_t *buf, int buf_size){
883     int vop_found, i, j, bits_left, last_bits;
884     uint32_t state;
885
886     H261Context *h = avctx->priv_data;
887
888     if(h){
889         bits_left = h->bits_left;
890         last_bits = h->last_bits;
891     }
892     else{
893         bits_left = 0;
894         last_bits = 0;
895     }
896
897     vop_found= pc->frame_start_found;
898     state= pc->state;
899     if(bits_left!=0 && !vop_found)
900         state = state << (8-bits_left) | last_bits;
901     i=0;
902     if(!vop_found){
903         for(i=0; i<buf_size; i++){
904             state= (state<<8) | buf[i];
905             for(j=0; j<8; j++){
906                 if(( (  (state<<j)  |  (buf[i]>>(8-j))  )>>(32-20) == 0x10 )&&(((state >> (17-j)) & 0x4000) == 0x0)){
907                     i++;
908                     vop_found=1;
909                     break;
910                 }
911             }
912             if(vop_found)
913                     break;    
914         }
915     }
916     if(vop_found){
917         for(; i<buf_size; i++){
918             if(avctx->flags & CODEC_FLAG_TRUNCATED)//XXX ffplay workaround, someone a better solution?
919                 state= (state<<8) | buf[i];
920             for(j=0; j<8; j++){
921                 if(( (  (state<<j)  |  (buf[i]>>(8-j))  )>>(32-20) == 0x10 )&&(((state >> (17-j)) & 0x4000) == 0x0)){
922                     pc->frame_start_found=0;
923                     pc->state=-1;
924                     return i-3;
925                 }
926             }
927         }
928     }
929
930     pc->frame_start_found= vop_found;
931     pc->state= state;
932     return END_NOT_FOUND;
933 }
934
935 static int h261_parse(AVCodecParserContext *s,
936                       AVCodecContext *avctx,
937                       uint8_t **poutbuf, int *poutbuf_size, 
938                       const uint8_t *buf, int buf_size)
939 {
940     ParseContext *pc = s->priv_data;
941     int next;
942     
943     next= h261_find_frame_end(pc,avctx, buf, buf_size);
944     if (ff_combine_frame(pc, next, (uint8_t **)&buf, &buf_size) < 0) {
945         *poutbuf = NULL;
946         *poutbuf_size = 0;
947         return buf_size;
948     }
949     *poutbuf = (uint8_t *)buf;
950     *poutbuf_size = buf_size;
951     return next;
952 }
953
954 /**
955  * returns the number of bytes consumed for building the current frame
956  */
957 static int get_consumed_bytes(MpegEncContext *s, int buf_size){
958     if(s->flags&CODEC_FLAG_TRUNCATED){
959         int pos= (get_bits_count(&s->gb)+7)>>3;
960         pos -= s->parse_context.last_index;
961         if(pos<0) pos=0;// padding is not really read so this might be -1
962         return pos;
963     }else{
964         int pos= get_bits_count(&s->gb)>>3;
965         if(pos==0) pos=1; //avoid infinite loops (i doubt thats needed but ...)
966         if(pos+10>buf_size) pos=buf_size; // oops ;)
967
968         return pos;
969     }
970 }
971
972 static int h261_decode_frame(AVCodecContext *avctx,
973                              void *data, int *data_size,
974                              uint8_t *buf, int buf_size)
975 {
976     H261Context *h= avctx->priv_data;
977     MpegEncContext *s = &h->s;
978     int ret;
979     AVFrame *pict = data;
980
981 #ifdef DEBUG
982     printf("*****frame %d size=%d\n", avctx->frame_number, buf_size);
983     printf("bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);
984 #endif
985     s->flags= avctx->flags;
986     s->flags2= avctx->flags2;
987
988     /* no supplementary picture */
989     if (buf_size == 0) {
990         return 0;
991     }
992
993     if(s->flags&CODEC_FLAG_TRUNCATED){
994         int next;
995
996         next= h261_find_frame_end(&s->parse_context,avctx, buf, buf_size);
997
998         if( ff_combine_frame(&s->parse_context, next, &buf, &buf_size) < 0 )
999             return buf_size;
1000     }
1001
1002
1003 retry:
1004
1005     init_get_bits(&s->gb, buf, buf_size*8);
1006
1007     if(!s->context_initialized){
1008         if (MPV_common_init(s) < 0) //we need the idct permutaton for reading a custom matrix
1009             return -1;
1010     }
1011
1012     //we need to set current_picture_ptr before reading the header, otherwise we cant store anyting im there
1013     if(s->current_picture_ptr==NULL || s->current_picture_ptr->data[0]){
1014         int i= ff_find_unused_picture(s, 0);
1015         s->current_picture_ptr= &s->picture[i];
1016     }
1017
1018     ret = h261_decode_picture_header(h);
1019
1020     /* skip if the header was thrashed */
1021     if (ret < 0){
1022         av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");
1023         return -1;
1024     }
1025
1026     if (s->width != avctx->coded_width || s->height != avctx->coded_height){
1027         ParseContext pc= s->parse_context; //FIXME move these demuxng hack to avformat
1028         s->parse_context.buffer=0;
1029         MPV_common_end(s);
1030         s->parse_context= pc;
1031     }
1032     if (!s->context_initialized) {
1033         avcodec_set_dimensions(avctx, s->width, s->height);
1034
1035         goto retry;
1036     }
1037
1038     // for hurry_up==5
1039     s->current_picture.pict_type= s->pict_type;
1040     s->current_picture.key_frame= s->pict_type == I_TYPE;
1041
1042     /* skip everything if we are in a hurry>=5 */
1043     if(avctx->hurry_up>=5) return get_consumed_bytes(s, buf_size);
1044
1045     if(MPV_frame_start(s, avctx) < 0)
1046         return -1;
1047
1048     ff_er_frame_start(s);
1049
1050     /* decode each macroblock */
1051     s->mb_x=0;
1052     s->mb_y=0;
1053
1054     while(h->gob_number < (s->mb_height==18 ? 12 : 5)){
1055         if(ff_h261_resync(h)<0)
1056             break;
1057         h261_decode_gob(h);
1058     }
1059     MPV_frame_end(s);
1060
1061 assert(s->current_picture.pict_type == s->current_picture_ptr->pict_type);
1062 assert(s->current_picture.pict_type == s->pict_type);
1063     *pict= *(AVFrame*)&s->current_picture;
1064     ff_print_debug_info(s, pict);
1065
1066     /* Return the Picture timestamp as the frame number */
1067     /* we substract 1 because it is added on utils.c    */
1068     avctx->frame_number = s->picture_number - 1;
1069
1070     *data_size = sizeof(AVFrame);
1071
1072     return get_consumed_bytes(s, buf_size);
1073 }
1074
1075 static int h261_decode_end(AVCodecContext *avctx)
1076 {
1077     H261Context *h= avctx->priv_data;
1078     MpegEncContext *s = &h->s;
1079
1080     MPV_common_end(s);
1081     return 0;
1082 }
1083
1084 AVCodec h261_encoder = {
1085     "h261",
1086     CODEC_TYPE_VIDEO,
1087     CODEC_ID_H261,
1088     sizeof(H261Context),
1089     MPV_encode_init,
1090     MPV_encode_picture,
1091     MPV_encode_end,
1092 };
1093
1094 AVCodec h261_decoder = {
1095     "h261",
1096     CODEC_TYPE_VIDEO,
1097     CODEC_ID_H261,
1098     sizeof(H261Context),
1099     h261_decode_init,
1100     NULL,
1101     h261_decode_end,
1102     h261_decode_frame,
1103     CODEC_CAP_TRUNCATED,
1104 };
1105
1106 AVCodecParser h261_parser = {
1107     { CODEC_ID_H261 },
1108     sizeof(ParseContext),
1109     NULL,
1110     h261_parse,
1111     ff_parse_close,
1112 };