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