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