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