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