]> git.sesse.net Git - ffmpeg/blob - libavcodec/h261dec.c
Merge commit 'f34d3173fcfc7f3228095d509a64c4fa4b37b575'
[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 "avcodec.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     if (skip_1stop_8data_bits(&s->gb) < 0)
131         return AVERROR_INVALIDDATA;
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 | AV_EF_COMPLIANT))
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) {
383         av_log(s->avctx, AV_LOG_ERROR, "Invalid mtype index %d\n",
384                h->mtype);
385         return SLICE_ERROR;
386     }
387     av_assert0(h->mtype < FF_ARRAY_ELEMS(ff_h261_mtype_map));
388     h->mtype = ff_h261_mtype_map[h->mtype];
389
390     // Read mquant
391     if (IS_QUANT(h->mtype))
392         ff_set_qscale(s, get_bits(&s->gb, 5));
393
394     s->mb_intra = IS_INTRA4x4(h->mtype);
395
396     // Read mv
397     if (IS_16X16(h->mtype)) {
398         /* Motion vector data is included for all MC macroblocks. MVD is
399          * obtained from the macroblock vector by subtracting the vector
400          * of the preceding macroblock. For this calculation the vector
401          * of the preceding macroblock is regarded as zero in the
402          * following three situations:
403          * 1) evaluating MVD for macroblocks 1, 12 and 23;
404          * 2) evaluating MVD for macroblocks in which MBA does not represent a difference of 1;
405          * 3) MTYPE of the previous macroblock was not MC. */
406         if ((h->current_mba ==  1) || (h->current_mba == 12) ||
407             (h->current_mba == 23) || (h->mba_diff != 1)) {
408             h->current_mv_x = 0;
409             h->current_mv_y = 0;
410         }
411
412         h->current_mv_x = decode_mv_component(&s->gb, h->current_mv_x);
413         h->current_mv_y = decode_mv_component(&s->gb, h->current_mv_y);
414     } else {
415         h->current_mv_x = 0;
416         h->current_mv_y = 0;
417     }
418
419     // Read cbp
420     if (HAS_CBP(h->mtype))
421         cbp = get_vlc2(&s->gb, h261_cbp_vlc.table, H261_CBP_VLC_BITS, 2) + 1;
422
423     if (s->mb_intra) {
424         s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
425         goto intra;
426     }
427
428     //set motion vectors
429     s->mv_dir                      = MV_DIR_FORWARD;
430     s->mv_type                     = MV_TYPE_16X16;
431     s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
432     s->mv[0][0][0]                 = h->current_mv_x * 2; // gets divided by 2 in motion compensation
433     s->mv[0][0][1]                 = h->current_mv_y * 2;
434
435     if (s->current_picture.motion_val[0]) {
436         int b_stride = 2*s->mb_width + 1;
437         int b_xy     = 2 * s->mb_x + (2 * s->mb_y) * b_stride;
438         s->current_picture.motion_val[0][b_xy][0] = s->mv[0][0][0];
439         s->current_picture.motion_val[0][b_xy][1] = s->mv[0][0][1];
440     }
441
442 intra:
443     /* decode each block */
444     if (s->mb_intra || HAS_CBP(h->mtype)) {
445         s->dsp.clear_blocks(s->block[0]);
446         for (i = 0; i < 6; i++) {
447             if (h261_decode_block(h, s->block[i], i, cbp & 32) < 0)
448                 return SLICE_ERROR;
449             cbp += cbp;
450         }
451     } else {
452         for (i = 0; i < 6; i++)
453             s->block_last_index[i] = -1;
454     }
455
456     ff_MPV_decode_mb(s, s->block);
457
458     return SLICE_OK;
459 }
460
461 /**
462  * Decode the H.261 picture header.
463  * @return <0 if no startcode found
464  */
465 static int h261_decode_picture_header(H261Context *h)
466 {
467     MpegEncContext *const s = &h->s;
468     int format, i;
469     uint32_t startcode = 0;
470
471     for (i = get_bits_left(&s->gb); i > 24; i -= 1) {
472         startcode = ((startcode << 1) | get_bits(&s->gb, 1)) & 0x000FFFFF;
473
474         if (startcode == 0x10)
475             break;
476     }
477
478     if (startcode != 0x10) {
479         av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");
480         return -1;
481     }
482
483     /* temporal reference */
484     i = get_bits(&s->gb, 5); /* picture timestamp */
485     if (i < (s->picture_number & 31))
486         i += 32;
487     s->picture_number = (s->picture_number & ~31) + i;
488
489     s->avctx->time_base      = (AVRational) { 1001, 30000 };
490
491     /* PTYPE starts here */
492     skip_bits1(&s->gb); /* split screen off */
493     skip_bits1(&s->gb); /* camera  off */
494     skip_bits1(&s->gb); /* freeze picture release off */
495
496     format = get_bits1(&s->gb);
497
498     // only 2 formats possible
499     if (format == 0) { // QCIF
500         s->width     = 176;
501         s->height    = 144;
502         s->mb_width  = 11;
503         s->mb_height = 9;
504     } else { // CIF
505         s->width     = 352;
506         s->height    = 288;
507         s->mb_width  = 22;
508         s->mb_height = 18;
509     }
510
511     s->mb_num = s->mb_width * s->mb_height;
512
513     skip_bits1(&s->gb); /* still image mode off */
514     skip_bits1(&s->gb); /* Reserved */
515
516     /* PEI */
517     if (skip_1stop_8data_bits(&s->gb) < 0)
518         return AVERROR_INVALIDDATA;
519
520     /* H.261 has no I-frames, but if we pass AV_PICTURE_TYPE_I for the first
521      * frame, the codec crashes if it does not contain all I-blocks
522      * (e.g. when a packet is lost). */
523     s->pict_type = AV_PICTURE_TYPE_P;
524
525     h->gob_number = 0;
526     return 0;
527 }
528
529 static int h261_decode_gob(H261Context *h)
530 {
531     MpegEncContext *const s = &h->s;
532
533     ff_set_qscale(s, s->qscale);
534
535     /* decode mb's */
536     while (h->current_mba <= MBA_STUFFING) {
537         int ret;
538         /* DCT & quantize */
539         ret = h261_decode_mb(h);
540         if (ret < 0) {
541             if (ret == SLICE_END) {
542                 h261_decode_mb_skipped(h, h->current_mba, 33);
543                 return 0;
544             }
545             av_log(s->avctx, AV_LOG_ERROR, "Error at MB: %d\n",
546                    s->mb_x + s->mb_y * s->mb_stride);
547             return -1;
548         }
549
550         h261_decode_mb_skipped(h,
551                                h->current_mba - h->mba_diff,
552                                h->current_mba - 1);
553     }
554
555     return -1;
556 }
557
558 /**
559  * returns the number of bytes consumed for building the current frame
560  */
561 static int get_consumed_bytes(MpegEncContext *s, int buf_size)
562 {
563     int pos = get_bits_count(&s->gb) >> 3;
564     if (pos == 0)
565         pos = 1;      // avoid infinite loops (i doubt that is needed but ...)
566     if (pos + 10 > buf_size)
567         pos = buf_size;               // oops ;)
568
569     return pos;
570 }
571
572 static int h261_decode_frame(AVCodecContext *avctx, void *data,
573                              int *got_frame, AVPacket *avpkt)
574 {
575     const uint8_t *buf = avpkt->data;
576     int buf_size       = avpkt->size;
577     H261Context *h     = avctx->priv_data;
578     MpegEncContext *s  = &h->s;
579     int ret;
580     AVFrame *pict = data;
581
582     av_dlog(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);
583     av_dlog(avctx, "bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);
584     s->flags  = avctx->flags;
585     s->flags2 = avctx->flags2;
586
587     h->gob_start_code_skipped = 0;
588
589 retry:
590     init_get_bits(&s->gb, buf, buf_size * 8);
591
592     if (!s->context_initialized)
593         // we need the IDCT permutaton for reading a custom matrix
594         if (ff_MPV_common_init(s) < 0)
595             return -1;
596
597     ret = h261_decode_picture_header(h);
598
599     /* skip if the header was thrashed */
600     if (ret < 0) {
601         av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");
602         return -1;
603     }
604
605     if (s->width != avctx->coded_width || s->height != avctx->coded_height) {
606         ParseContext pc = s->parse_context; // FIXME move this demuxing hack to libavformat
607         s->parse_context.buffer = 0;
608         ff_MPV_common_end(s);
609         s->parse_context = pc;
610     }
611     if (!s->context_initialized) {
612         ret = ff_set_dimensions(avctx, s->width, s->height);
613         if (ret < 0)
614             return ret;
615
616         goto retry;
617     }
618
619     // for skipping the frame
620     s->current_picture.f->pict_type = s->pict_type;
621     s->current_picture.f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;
622
623     if ((avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B) ||
624         (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I) ||
625          avctx->skip_frame >= AVDISCARD_ALL)
626         return get_consumed_bytes(s, buf_size);
627
628     if (ff_MPV_frame_start(s, avctx) < 0)
629         return -1;
630
631     ff_mpeg_er_frame_start(s);
632
633     /* decode each macroblock */
634     s->mb_x = 0;
635     s->mb_y = 0;
636
637     while (h->gob_number < (s->mb_height == 18 ? 12 : 5)) {
638         if (h261_resync(h) < 0)
639             break;
640         h261_decode_gob(h);
641     }
642     ff_MPV_frame_end(s);
643
644     av_assert0(s->current_picture.f->pict_type == s->current_picture_ptr->f->pict_type);
645     av_assert0(s->current_picture.f->pict_type == s->pict_type);
646
647     if ((ret = av_frame_ref(pict, s->current_picture_ptr->f)) < 0)
648         return ret;
649     ff_print_debug_info(s, s->current_picture_ptr, pict);
650
651     *got_frame = 1;
652
653     return get_consumed_bytes(s, buf_size);
654 }
655
656 static av_cold int h261_decode_end(AVCodecContext *avctx)
657 {
658     H261Context *h    = avctx->priv_data;
659     MpegEncContext *s = &h->s;
660
661     ff_MPV_common_end(s);
662     return 0;
663 }
664
665 AVCodec ff_h261_decoder = {
666     .name           = "h261",
667     .long_name      = NULL_IF_CONFIG_SMALL("H.261"),
668     .type           = AVMEDIA_TYPE_VIDEO,
669     .id             = AV_CODEC_ID_H261,
670     .priv_data_size = sizeof(H261Context),
671     .init           = h261_decode_init,
672     .close          = h261_decode_end,
673     .decode         = h261_decode_frame,
674     .capabilities   = CODEC_CAP_DR1,
675     .max_lowres     = 3,
676 };