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