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