]> git.sesse.net Git - ffmpeg/blob - libavcodec/h261dec.c
Merge commit '97bf7c03b1338a867da52c159a2afecbdedcfa88'
[ffmpeg] / libavcodec / h261dec.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
25  * H.261 decoder.
26  */
27
28 #include "libavutil/avassert.h"
29 #include "dsputil.h"
30 #include "avcodec.h"
31 #include "mpegvideo.h"
32 #include "h263.h"
33 #include "h261.h"
34 #include "h261data.h"
35
36 #define H261_MBA_VLC_BITS 9
37 #define H261_MTYPE_VLC_BITS 6
38 #define H261_MV_VLC_BITS 7
39 #define H261_CBP_VLC_BITS 9
40 #define TCOEFF_VLC_BITS 9
41 #define MBA_STUFFING 33
42 #define MBA_STARTCODE 34
43
44 extern uint8_t ff_h261_rl_table_store[2][2*MAX_RUN + MAX_LEVEL + 3];
45
46 static VLC h261_mba_vlc;
47 static VLC h261_mtype_vlc;
48 static VLC h261_mv_vlc;
49 static VLC h261_cbp_vlc;
50
51 static int h261_decode_block(H261Context * h, DCTELEM * block, int n, int coded);
52
53 static av_cold void h261_decode_init_vlc(H261Context *h){
54     static int done = 0;
55
56     if(!done){
57         done = 1;
58         INIT_VLC_STATIC(&h261_mba_vlc, H261_MBA_VLC_BITS, 35,
59                  ff_h261_mba_bits, 1, 1,
60                  ff_h261_mba_code, 1, 1, 662);
61         INIT_VLC_STATIC(&h261_mtype_vlc, H261_MTYPE_VLC_BITS, 10,
62                  ff_h261_mtype_bits, 1, 1,
63                  ff_h261_mtype_code, 1, 1, 80);
64         INIT_VLC_STATIC(&h261_mv_vlc, H261_MV_VLC_BITS, 17,
65                  &ff_h261_mv_tab[0][1], 2, 1,
66                  &ff_h261_mv_tab[0][0], 2, 1, 144);
67         INIT_VLC_STATIC(&h261_cbp_vlc, H261_CBP_VLC_BITS, 63,
68                  &ff_h261_cbp_tab[0][1], 2, 1,
69                  &ff_h261_cbp_tab[0][0], 2, 1, 512);
70         ff_init_rl(&ff_h261_rl_tcoeff, ff_h261_rl_table_store);
71         INIT_VLC_RL(ff_h261_rl_tcoeff, 552);
72     }
73 }
74
75 static av_cold int h261_decode_init(AVCodecContext *avctx){
76     H261Context *h= avctx->priv_data;
77     MpegEncContext * const s = &h->s;
78
79     // set defaults
80     ff_MPV_decode_defaults(s);
81     s->avctx = avctx;
82
83     s->width  = s->avctx->coded_width;
84     s->height = s->avctx->coded_height;
85     s->codec_id = s->avctx->codec->id;
86
87     s->out_format = FMT_H261;
88     s->low_delay= 1;
89     avctx->pix_fmt= AV_PIX_FMT_YUV420P;
90
91     s->codec_id= avctx->codec->id;
92
93     h261_decode_init_vlc(h);
94
95     h->gob_start_code_skipped = 0;
96
97     return 0;
98 }
99
100 /**
101  * Decode the group of blocks header or slice header.
102  * @return <0 if an error occurred
103  */
104 static int h261_decode_gob_header(H261Context *h){
105     unsigned int val;
106     MpegEncContext * const s = &h->s;
107
108     if ( !h->gob_start_code_skipped ){
109         /* Check for GOB Start Code */
110         val = show_bits(&s->gb, 15);
111         if(val)
112             return -1;
113
114         /* We have a GBSC */
115         skip_bits(&s->gb, 16);
116     }
117
118     h->gob_start_code_skipped = 0;
119
120     h->gob_number = get_bits(&s->gb, 4); /* GN */
121     s->qscale = get_bits(&s->gb, 5); /* GQUANT */
122
123     /* Check if gob_number is valid */
124     if (s->mb_height==18){ //cif
125         if ((h->gob_number<=0) || (h->gob_number>12))
126             return -1;
127     }
128     else{ //qcif
129         if ((h->gob_number!=1) && (h->gob_number!=3) && (h->gob_number!=5))
130             return -1;
131     }
132
133     /* GEI */
134     while (get_bits1(&s->gb) != 0) {
135         skip_bits(&s->gb, 8);
136     }
137
138     if(s->qscale==0) {
139         av_log(s->avctx, AV_LOG_ERROR, "qscale has forbidden 0 value\n");
140         if (s->avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))
141             return -1;
142     }
143
144     // For the first transmitted macroblock in a GOB, MBA is the absolute address. For
145     // subsequent macroblocks, MBA is the difference between the absolute addresses of
146     // the macroblock and the last transmitted macroblock.
147     h->current_mba = 0;
148     h->mba_diff = 0;
149
150     return 0;
151 }
152
153 /**
154  * Decode the group of blocks / video packet header.
155  * @return <0 if no resync found
156  */
157 static int ff_h261_resync(H261Context *h){
158     MpegEncContext * const s = &h->s;
159     int left, ret;
160
161     if ( h->gob_start_code_skipped ){
162         ret= h261_decode_gob_header(h);
163         if(ret>=0)
164             return 0;
165     }
166     else{
167         if(show_bits(&s->gb, 15)==0){
168             ret= h261_decode_gob_header(h);
169             if(ret>=0)
170                 return 0;
171         }
172         //OK, it is not where it is supposed to be ...
173         s->gb= s->last_resync_gb;
174         align_get_bits(&s->gb);
175         left= get_bits_left(&s->gb);
176
177         for(;left>15+1+4+5; left-=8){
178             if(show_bits(&s->gb, 15)==0){
179                 GetBitContext bak= s->gb;
180
181                 ret= h261_decode_gob_header(h);
182                 if(ret>=0)
183                     return 0;
184
185                 s->gb= bak;
186             }
187             skip_bits(&s->gb, 8);
188         }
189     }
190
191     return -1;
192 }
193
194 /**
195  * Decode skipped macroblocks.
196  * @return 0
197  */
198 static int h261_decode_mb_skipped(H261Context *h, int mba1, int mba2 )
199 {
200     MpegEncContext * const s = &h->s;
201     int i;
202
203     s->mb_intra = 0;
204
205     for(i=mba1; i<mba2; i++){
206         int j, xy;
207
208         s->mb_x= ((h->gob_number-1) % 2) * 11 + i % 11;
209         s->mb_y= ((h->gob_number-1) / 2) * 3 + i / 11;
210         xy = s->mb_x + s->mb_y * s->mb_stride;
211         ff_init_block_index(s);
212         ff_update_block_index(s);
213
214         for(j=0;j<6;j++)
215             s->block_last_index[j] = -1;
216
217         s->mv_dir = MV_DIR_FORWARD;
218         s->mv_type = MV_TYPE_16X16;
219         s->current_picture.f.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
220         s->mv[0][0][0] = 0;
221         s->mv[0][0][1] = 0;
222         s->mb_skipped = 1;
223         h->mtype &= ~MB_TYPE_H261_FIL;
224
225         ff_MPV_decode_mb(s, s->block);
226     }
227
228     return 0;
229 }
230
231 static int decode_mv_component(GetBitContext *gb, int v){
232     static const int mvmap[17] = {
233         0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16
234     };
235     int mv_diff = get_vlc2(gb, h261_mv_vlc.table, H261_MV_VLC_BITS, 2);
236
237     /* check if mv_diff is valid */
238     if ( mv_diff < 0 )
239         return v;
240
241     mv_diff = mvmap[mv_diff];
242
243     if(mv_diff && !get_bits1(gb))
244         mv_diff= -mv_diff;
245
246     v += mv_diff;
247     if     (v <=-16) v+= 32;
248     else if(v >= 16) v-= 32;
249
250     return v;
251 }
252
253 static int h261_decode_mb(H261Context *h){
254     MpegEncContext * const s = &h->s;
255     int i, cbp, xy;
256
257     cbp = 63;
258     // Read mba
259     do{
260         h->mba_diff = get_vlc2(&s->gb, h261_mba_vlc.table, H261_MBA_VLC_BITS, 2);
261
262         /* Check for slice end */
263         /* NOTE: GOB can be empty (no MB data) or exist only of MBA_stuffing */
264         if (h->mba_diff == MBA_STARTCODE){ // start code
265             h->gob_start_code_skipped = 1;
266             return SLICE_END;
267         }
268     }
269     while( h->mba_diff == MBA_STUFFING ); // stuffing
270
271     if ( h->mba_diff < 0 ){
272         if (get_bits_left(&s->gb) <= 7)
273             return SLICE_END;
274
275         av_log(s->avctx, AV_LOG_ERROR, "illegal mba at %d %d\n", s->mb_x, s->mb_y);
276         return SLICE_ERROR;
277     }
278
279     h->mba_diff += 1;
280     h->current_mba += h->mba_diff;
281
282     if ( h->current_mba > MBA_STUFFING )
283         return SLICE_ERROR;
284
285     s->mb_x= ((h->gob_number-1) % 2) * 11 + ((h->current_mba-1) % 11);
286     s->mb_y= ((h->gob_number-1) / 2) * 3 + ((h->current_mba-1) / 11);
287     xy = s->mb_x + s->mb_y * s->mb_stride;
288     ff_init_block_index(s);
289     ff_update_block_index(s);
290
291     // Read mtype
292     h->mtype = get_vlc2(&s->gb, h261_mtype_vlc.table, H261_MTYPE_VLC_BITS, 2);
293     if (h->mtype < 0) {
294         av_log(s->avctx, AV_LOG_ERROR, "illegal mtype %d\n", h->mtype);
295         return SLICE_ERROR;
296     }
297     h->mtype = ff_h261_mtype_map[h->mtype];
298
299     // Read mquant
300     if ( IS_QUANT ( h->mtype ) ){
301         ff_set_qscale(s, get_bits(&s->gb, 5));
302     }
303
304     s->mb_intra = IS_INTRA4x4(h->mtype);
305
306     // Read mv
307     if ( IS_16X16 ( h->mtype ) ){
308         // Motion vector data is included for all MC macroblocks. MVD is obtained from the macroblock vector by subtracting the
309         // vector of the preceding macroblock. For this calculation the vector of the preceding macroblock is regarded as zero in the
310         // following three situations:
311         // 1) evaluating MVD for macroblocks 1, 12 and 23;
312         // 2) evaluating MVD for macroblocks in which MBA does not represent a difference of 1;
313         // 3) MTYPE of the previous macroblock was not MC.
314         if ( ( h->current_mba == 1 ) || ( h->current_mba == 12 ) || ( h->current_mba == 23 ) ||
315              ( h->mba_diff != 1))
316         {
317             h->current_mv_x = 0;
318             h->current_mv_y = 0;
319         }
320
321         h->current_mv_x= decode_mv_component(&s->gb, h->current_mv_x);
322         h->current_mv_y= decode_mv_component(&s->gb, h->current_mv_y);
323     }else{
324         h->current_mv_x = 0;
325         h->current_mv_y = 0;
326     }
327
328     // Read cbp
329     if ( HAS_CBP( h->mtype ) ){
330         cbp = get_vlc2(&s->gb, h261_cbp_vlc.table, H261_CBP_VLC_BITS, 2) + 1;
331     }
332
333     if(s->mb_intra){
334         s->current_picture.f.mb_type[xy] = MB_TYPE_INTRA;
335         goto intra;
336     }
337
338     //set motion vectors
339     s->mv_dir = MV_DIR_FORWARD;
340     s->mv_type = MV_TYPE_16X16;
341     s->current_picture.f.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
342     s->mv[0][0][0] = h->current_mv_x * 2;//gets divided by 2 in motion compensation
343     s->mv[0][0][1] = h->current_mv_y * 2;
344
345 intra:
346     /* decode each block */
347     if(s->mb_intra || HAS_CBP(h->mtype)){
348         s->dsp.clear_blocks(s->block[0]);
349         for (i = 0; i < 6; i++) {
350             if (h261_decode_block(h, s->block[i], i, cbp&32) < 0){
351                 return SLICE_ERROR;
352             }
353             cbp+=cbp;
354         }
355     }else{
356         for (i = 0; i < 6; i++)
357             s->block_last_index[i]= -1;
358     }
359
360     ff_MPV_decode_mb(s, s->block);
361
362     return SLICE_OK;
363 }
364
365 /**
366  * Decode a macroblock.
367  * @return <0 if an error occurred
368  */
369 static int h261_decode_block(H261Context * h, DCTELEM * block,
370                              int n, int coded)
371 {
372     MpegEncContext * const s = &h->s;
373     int code, level, i, j, run;
374     RLTable *rl = &ff_h261_rl_tcoeff;
375     const uint8_t *scan_table;
376
377     // For the variable length encoding there are two code tables, one being used for
378     // the first transmitted LEVEL in INTER, INTER+MC and INTER+MC+FIL blocks, the second
379     // for all other LEVELs except the first one in INTRA blocks which is fixed length
380     // coded with 8 bits.
381     // NOTE: the two code tables only differ in one VLC so we handle that manually.
382     scan_table = s->intra_scantable.permutated;
383     if (s->mb_intra){
384         /* DC coef */
385         level = get_bits(&s->gb, 8);
386         // 0 (00000000b) and -128 (10000000b) are FORBIDDEN
387         if((level&0x7F) == 0){
388             av_log(s->avctx, AV_LOG_ERROR, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);
389             return -1;
390         }
391         // The code 1000 0000 is not used, the reconstruction level of 1024 being coded as 1111 1111.
392         if (level == 255)
393             level = 128;
394         block[0] = level;
395         i = 1;
396     }else if(coded){
397         // Run  Level   Code
398         // EOB                  Not possible for first level when cbp is available (that's why the table is different)
399         // 0    1               1s
400         // *    *               0*
401         int check = show_bits(&s->gb, 2);
402         i = 0;
403         if ( check & 0x2 ){
404             skip_bits(&s->gb, 2);
405             block[0] = ( check & 0x1 ) ? -1 : 1;
406             i = 1;
407         }
408     }else{
409         i = 0;
410     }
411     if(!coded){
412         s->block_last_index[n] = i - 1;
413         return 0;
414     }
415     for(;;){
416         code = get_vlc2(&s->gb, rl->vlc.table, TCOEFF_VLC_BITS, 2);
417         if (code < 0){
418             av_log(s->avctx, AV_LOG_ERROR, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
419             return -1;
420         }
421         if (code == rl->n) {
422             /* escape */
423             // 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.
424             run = get_bits(&s->gb, 6);
425             level = get_sbits(&s->gb, 8);
426         }else if(code == 0){
427             break;
428         }else{
429             run = rl->table_run[code];
430             level = rl->table_level[code];
431             if (get_bits1(&s->gb))
432                 level = -level;
433         }
434         i += run;
435         if (i >= 64){
436             av_log(s->avctx, AV_LOG_ERROR, "run overflow at %dx%d\n", s->mb_x, s->mb_y);
437             return -1;
438         }
439         j = scan_table[i];
440         block[j] = level;
441         i++;
442     }
443     s->block_last_index[n] = i-1;
444     return 0;
445 }
446
447 /**
448  * Decode the H.261 picture header.
449  * @return <0 if no startcode found
450  */
451 static int h261_decode_picture_header(H261Context *h){
452     MpegEncContext * const s = &h->s;
453     int format, i;
454     uint32_t startcode= 0;
455
456     for(i= get_bits_left(&s->gb); i>24; i-=1){
457         startcode = ((startcode << 1) | get_bits(&s->gb, 1)) & 0x000FFFFF;
458
459         if(startcode == 0x10)
460             break;
461     }
462
463     if (startcode != 0x10){
464         av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");
465         return -1;
466     }
467
468     /* temporal reference */
469     i= get_bits(&s->gb, 5); /* picture timestamp */
470     if(i < (s->picture_number&31))
471         i += 32;
472     s->picture_number = (s->picture_number&~31) + i;
473
474     s->avctx->time_base= (AVRational){1001, 30000};
475     s->current_picture.f.pts = s->picture_number;
476
477
478     /* PTYPE starts here */
479     skip_bits1(&s->gb); /* split screen off */
480     skip_bits1(&s->gb); /* camera  off */
481     skip_bits1(&s->gb); /* freeze picture release off */
482
483     format = get_bits1(&s->gb);
484
485     //only 2 formats possible
486     if (format == 0){//QCIF
487         s->width = 176;
488         s->height = 144;
489         s->mb_width = 11;
490         s->mb_height = 9;
491     }else{//CIF
492         s->width = 352;
493         s->height = 288;
494         s->mb_width = 22;
495         s->mb_height = 18;
496     }
497
498     s->mb_num = s->mb_width * s->mb_height;
499
500     skip_bits1(&s->gb); /* still image mode off */
501     skip_bits1(&s->gb); /* Reserved */
502
503     /* PEI */
504     while (get_bits1(&s->gb) != 0){
505         skip_bits(&s->gb, 8);
506     }
507
508     // h261 has no I-FRAMES, but if we pass AV_PICTURE_TYPE_I for the first frame, the codec crashes if it does
509     // not contain all I-blocks (e.g. when a packet is lost)
510     s->pict_type = AV_PICTURE_TYPE_P;
511
512     h->gob_number = 0;
513     return 0;
514 }
515
516 static int h261_decode_gob(H261Context *h){
517     MpegEncContext * const s = &h->s;
518
519     ff_set_qscale(s, s->qscale);
520
521     /* decode mb's */
522     while(h->current_mba <= MBA_STUFFING)
523     {
524         int ret;
525         /* DCT & quantize */
526         ret= h261_decode_mb(h);
527         if(ret<0){
528             if(ret==SLICE_END){
529                 h261_decode_mb_skipped(h, h->current_mba, 33);
530                 return 0;
531             }
532             av_log(s->avctx, AV_LOG_ERROR, "Error at MB: %d\n", s->mb_x + s->mb_y*s->mb_stride);
533             return -1;
534         }
535
536         h261_decode_mb_skipped(h, h->current_mba-h->mba_diff, h->current_mba-1);
537     }
538
539     return -1;
540 }
541
542 /**
543  * returns the number of bytes consumed for building the current frame
544  */
545 static int get_consumed_bytes(MpegEncContext *s, int buf_size){
546     int pos= get_bits_count(&s->gb)>>3;
547     if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
548     if(pos+10>buf_size) pos=buf_size; // oops ;)
549
550     return pos;
551 }
552
553 static int h261_decode_frame(AVCodecContext *avctx,
554                              void *data, int *data_size,
555                              AVPacket *avpkt)
556 {
557     const uint8_t *buf = avpkt->data;
558     int buf_size = avpkt->size;
559     H261Context *h= avctx->priv_data;
560     MpegEncContext *s = &h->s;
561     int ret;
562     AVFrame *pict = data;
563
564     av_dlog(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);
565     av_dlog(avctx, "bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);
566     s->flags= avctx->flags;
567     s->flags2= avctx->flags2;
568
569     h->gob_start_code_skipped=0;
570
571 retry:
572
573     init_get_bits(&s->gb, buf, buf_size*8);
574
575     if(!s->context_initialized){
576         if (ff_MPV_common_init(s) < 0) //we need the idct permutaton for reading a custom matrix
577             return -1;
578     }
579
580     //we need to set current_picture_ptr before reading the header, otherwise we cannot store anyting im there
581     if (s->current_picture_ptr == NULL || s->current_picture_ptr->f.data[0]) {
582         int i= ff_find_unused_picture(s, 0);
583         if (i < 0)
584             return i;
585         s->current_picture_ptr= &s->picture[i];
586     }
587
588     ret = h261_decode_picture_header(h);
589
590     /* skip if the header was thrashed */
591     if (ret < 0){
592         av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");
593         return -1;
594     }
595
596     if (s->width != avctx->coded_width || s->height != avctx->coded_height){
597         ParseContext pc= s->parse_context; //FIXME move this demuxing hack to libavformat
598         s->parse_context.buffer=0;
599         ff_MPV_common_end(s);
600         s->parse_context= pc;
601     }
602     if (!s->context_initialized) {
603         avcodec_set_dimensions(avctx, s->width, s->height);
604
605         goto retry;
606     }
607
608     // for skipping the frame
609     s->current_picture.f.pict_type = s->pict_type;
610     s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
611
612     if(  (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==AV_PICTURE_TYPE_B)
613        ||(avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=AV_PICTURE_TYPE_I)
614        || avctx->skip_frame >= AVDISCARD_ALL)
615         return get_consumed_bytes(s, buf_size);
616
617     if(ff_MPV_frame_start(s, avctx) < 0)
618         return -1;
619
620     ff_er_frame_start(s);
621
622     /* decode each macroblock */
623     s->mb_x=0;
624     s->mb_y=0;
625
626     while(h->gob_number < (s->mb_height==18 ? 12 : 5)){
627         if(ff_h261_resync(h)<0)
628             break;
629         h261_decode_gob(h);
630     }
631     ff_MPV_frame_end(s);
632
633     av_assert0(s->current_picture.f.pict_type == s->current_picture_ptr->f.pict_type);
634     av_assert0(s->current_picture.f.pict_type == s->pict_type);
635
636     *pict = s->current_picture_ptr->f;
637     ff_print_debug_info(s, pict);
638
639     *data_size = sizeof(AVFrame);
640
641     return get_consumed_bytes(s, buf_size);
642 }
643
644 static av_cold int h261_decode_end(AVCodecContext *avctx)
645 {
646     H261Context *h= avctx->priv_data;
647     MpegEncContext *s = &h->s;
648
649     ff_MPV_common_end(s);
650     return 0;
651 }
652
653 AVCodec ff_h261_decoder = {
654     .name           = "h261",
655     .type           = AVMEDIA_TYPE_VIDEO,
656     .id             = AV_CODEC_ID_H261,
657     .priv_data_size = sizeof(H261Context),
658     .init           = h261_decode_init,
659     .close          = h261_decode_end,
660     .decode         = h261_decode_frame,
661     .capabilities   = CODEC_CAP_DR1,
662     .max_lowres     = 3,
663     .long_name      = NULL_IF_CONFIG_SMALL("H.261"),
664 };