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