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