]> git.sesse.net Git - ffmpeg/blob - libavcodec/h261dec.c
lavc: fix flac encoder and decoder dependencies
[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 "mpegvideo.h"
31 #include "h263.h"
32 #include "h261.h"
33 #include "internal.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 static VLC h261_mba_vlc;
44 static VLC h261_mtype_vlc;
45 static VLC h261_mv_vlc;
46 static VLC h261_cbp_vlc;
47
48 static av_cold void h261_decode_init_vlc(H261Context *h)
49 {
50     static int done = 0;
51
52     if (!done) {
53         done = 1;
54         INIT_VLC_STATIC(&h261_mba_vlc, H261_MBA_VLC_BITS, 35,
55                         ff_h261_mba_bits, 1, 1,
56                         ff_h261_mba_code, 1, 1, 662);
57         INIT_VLC_STATIC(&h261_mtype_vlc, H261_MTYPE_VLC_BITS, 10,
58                         ff_h261_mtype_bits, 1, 1,
59                         ff_h261_mtype_code, 1, 1, 80);
60         INIT_VLC_STATIC(&h261_mv_vlc, H261_MV_VLC_BITS, 17,
61                         &ff_h261_mv_tab[0][1], 2, 1,
62                         &ff_h261_mv_tab[0][0], 2, 1, 144);
63         INIT_VLC_STATIC(&h261_cbp_vlc, H261_CBP_VLC_BITS, 63,
64                         &ff_h261_cbp_tab[0][1], 2, 1,
65                         &ff_h261_cbp_tab[0][0], 2, 1, 512);
66         INIT_VLC_RL(ff_h261_rl_tcoeff, 552);
67     }
68 }
69
70 static av_cold int h261_decode_init(AVCodecContext *avctx)
71 {
72     H261Context *h          = avctx->priv_data;
73     MpegEncContext *const s = &h->s;
74
75     // set defaults
76     ff_MPV_decode_defaults(s);
77     s->avctx       = avctx;
78     s->width       = s->avctx->coded_width;
79     s->height      = s->avctx->coded_height;
80     s->codec_id    = s->avctx->codec->id;
81     s->out_format  = FMT_H261;
82     s->low_delay   = 1;
83     avctx->pix_fmt = AV_PIX_FMT_YUV420P;
84     s->codec_id    = avctx->codec->id;
85
86     ff_h261_common_init();
87     h261_decode_init_vlc(h);
88
89     h->gob_start_code_skipped = 0;
90
91     return 0;
92 }
93
94 /**
95  * Decode the group of blocks header or slice header.
96  * @return <0 if an error occurred
97  */
98 static int h261_decode_gob_header(H261Context *h)
99 {
100     unsigned int val;
101     MpegEncContext *const s = &h->s;
102
103     if (!h->gob_start_code_skipped) {
104         /* Check for GOB Start Code */
105         val = show_bits(&s->gb, 15);
106         if (val)
107             return -1;
108
109         /* We have a GBSC */
110         skip_bits(&s->gb, 16);
111     }
112
113     h->gob_start_code_skipped = 0;
114
115     h->gob_number = get_bits(&s->gb, 4); /* GN */
116     s->qscale     = get_bits(&s->gb, 5); /* GQUANT */
117
118     /* Check if gob_number is valid */
119     if (s->mb_height == 18) { // CIF
120         if ((h->gob_number <= 0) || (h->gob_number > 12))
121             return -1;
122     } else { // QCIF
123         if ((h->gob_number != 1) && (h->gob_number != 3) &&
124             (h->gob_number != 5))
125             return -1;
126     }
127
128     /* GEI */
129     if (skip_1stop_8data_bits(&s->gb) < 0)
130         return AVERROR_INVALIDDATA;
131
132     if (s->qscale == 0) {
133         av_log(s->avctx, AV_LOG_ERROR, "qscale has forbidden 0 value\n");
134         if (s->avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))
135             return -1;
136     }
137
138     /* For the first transmitted macroblock in a GOB, MBA is the absolute
139      * address. For subsequent macroblocks, MBA is the difference between
140      * the absolute addresses of the macroblock and the last transmitted
141      * macroblock. */
142     h->current_mba = 0;
143     h->mba_diff    = 0;
144
145     return 0;
146 }
147
148 /**
149  * Decode the group of blocks / video packet header.
150  * @return <0 if no resync found
151  */
152 static int h261_resync(H261Context *h)
153 {
154     MpegEncContext *const s = &h->s;
155     int left, ret;
156
157     if (h->gob_start_code_skipped) {
158         ret = h261_decode_gob_header(h);
159         if (ret >= 0)
160             return 0;
161     } else {
162         if (show_bits(&s->gb, 15) == 0) {
163             ret = h261_decode_gob_header(h);
164             if (ret >= 0)
165                 return 0;
166         }
167         // OK, it is not where it is supposed to be ...
168         s->gb = s->last_resync_gb;
169         align_get_bits(&s->gb);
170         left = get_bits_left(&s->gb);
171
172         for (; left > 15 + 1 + 4 + 5; left -= 8) {
173             if (show_bits(&s->gb, 15) == 0) {
174                 GetBitContext bak = s->gb;
175
176                 ret = h261_decode_gob_header(h);
177                 if (ret >= 0)
178                     return 0;
179
180                 s->gb = bak;
181             }
182             skip_bits(&s->gb, 8);
183         }
184     }
185
186     return -1;
187 }
188
189 /**
190  * Decode skipped macroblocks.
191  * @return 0
192  */
193 static int h261_decode_mb_skipped(H261Context *h, int mba1, int mba2)
194 {
195     MpegEncContext *const s = &h->s;
196     int i;
197
198     s->mb_intra = 0;
199
200     for (i = mba1; i < mba2; i++) {
201         int j, xy;
202
203         s->mb_x = ((h->gob_number - 1) % 2) * 11 + i % 11;
204         s->mb_y = ((h->gob_number - 1) / 2) * 3 + i / 11;
205         xy      = s->mb_x + s->mb_y * s->mb_stride;
206         ff_init_block_index(s);
207         ff_update_block_index(s);
208
209         for (j = 0; j < 6; j++)
210             s->block_last_index[j] = -1;
211
212         s->mv_dir                      = MV_DIR_FORWARD;
213         s->mv_type                     = MV_TYPE_16X16;
214         s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
215         s->mv[0][0][0]                 = 0;
216         s->mv[0][0][1]                 = 0;
217         s->mb_skipped                  = 1;
218         h->mtype                      &= ~MB_TYPE_H261_FIL;
219
220         ff_MPV_decode_mb(s, s->block);
221     }
222
223     return 0;
224 }
225
226 static const int mvmap[17] = {
227     0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16
228 };
229
230 static int decode_mv_component(GetBitContext *gb, int v)
231 {
232     int mv_diff = get_vlc2(gb, h261_mv_vlc.table, H261_MV_VLC_BITS, 2);
233
234     /* check if mv_diff is valid */
235     if (mv_diff < 0)
236         return v;
237
238     mv_diff = mvmap[mv_diff];
239
240     if (mv_diff && !get_bits1(gb))
241         mv_diff = -mv_diff;
242
243     v += mv_diff;
244     if (v <= -16)
245         v += 32;
246     else if (v >= 16)
247         v -= 32;
248
249     return v;
250 }
251
252 /**
253  * Decode a macroblock.
254  * @return <0 if an error occurred
255  */
256 static int h261_decode_block(H261Context *h, int16_t *block, int n, int coded)
257 {
258     MpegEncContext *const s = &h->s;
259     int code, level, i, j, run;
260     RLTable *rl = &ff_h261_rl_tcoeff;
261     const uint8_t *scan_table;
262
263     /* For the variable length encoding there are two code tables, one being
264      * used for the first transmitted LEVEL in INTER, INTER + MC and
265      * INTER + MC + FIL blocks, the second for all other LEVELs except the
266      * first one in INTRA blocks which is fixed length coded with 8 bits.
267      * NOTE: The two code tables only differ in one VLC so we handle that
268      * manually. */
269     scan_table = s->intra_scantable.permutated;
270     if (s->mb_intra) {
271         /* DC coef */
272         level = get_bits(&s->gb, 8);
273         // 0 (00000000b) and -128 (10000000b) are FORBIDDEN
274         if ((level & 0x7F) == 0) {
275             av_log(s->avctx, AV_LOG_ERROR, "illegal dc %d at %d %d\n",
276                    level, s->mb_x, s->mb_y);
277             return -1;
278         }
279         /* The code 1000 0000 is not used, the reconstruction level of 1024
280          * being coded as 1111 1111. */
281         if (level == 255)
282             level = 128;
283         block[0] = level;
284         i        = 1;
285     } else if (coded) {
286         // Run  Level   Code
287         // EOB          Not possible for first level when cbp is available (that's why the table is different)
288         // 0    1       1s
289         // *    *       0*
290         int check = show_bits(&s->gb, 2);
291         i = 0;
292         if (check & 0x2) {
293             skip_bits(&s->gb, 2);
294             block[0] = (check & 0x1) ? -1 : 1;
295             i        = 1;
296         }
297     } else {
298         i = 0;
299     }
300     if (!coded) {
301         s->block_last_index[n] = i - 1;
302         return 0;
303     }
304     for (;;) {
305         code = get_vlc2(&s->gb, rl->vlc.table, TCOEFF_VLC_BITS, 2);
306         if (code < 0) {
307             av_log(s->avctx, AV_LOG_ERROR, "illegal ac vlc code at %dx%d\n",
308                    s->mb_x, s->mb_y);
309             return -1;
310         }
311         if (code == rl->n) {
312             /* escape */
313             /* The remaining combinations of (run, level) are encoded with a
314              * 20-bit word consisting of 6 bits escape, 6 bits run and 8 bits
315              * level. */
316             run   = get_bits(&s->gb, 6);
317             level = get_sbits(&s->gb, 8);
318         } else if (code == 0) {
319             break;
320         } else {
321             run   = rl->table_run[code];
322             level = rl->table_level[code];
323             if (get_bits1(&s->gb))
324                 level = -level;
325         }
326         i += run;
327         if (i >= 64) {
328             av_log(s->avctx, AV_LOG_ERROR, "run overflow at %dx%d\n",
329                    s->mb_x, s->mb_y);
330             return -1;
331         }
332         j        = scan_table[i];
333         block[j] = level;
334         i++;
335     }
336     s->block_last_index[n] = i - 1;
337     return 0;
338 }
339
340 static int h261_decode_mb(H261Context *h)
341 {
342     MpegEncContext *const s = &h->s;
343     int i, cbp, xy;
344
345     cbp = 63;
346     // Read mba
347     do {
348         h->mba_diff = get_vlc2(&s->gb, h261_mba_vlc.table,
349                                H261_MBA_VLC_BITS, 2);
350
351         /* Check for slice end */
352         /* NOTE: GOB can be empty (no MB data) or exist only of MBA_stuffing */
353         if (h->mba_diff == MBA_STARTCODE) { // start code
354             h->gob_start_code_skipped = 1;
355             return SLICE_END;
356         }
357     } while (h->mba_diff == MBA_STUFFING); // stuffing
358
359     if (h->mba_diff < 0) {
360         if (get_bits_left(&s->gb) <= 7)
361             return SLICE_END;
362
363         av_log(s->avctx, AV_LOG_ERROR, "illegal mba at %d %d\n", s->mb_x, s->mb_y);
364         return SLICE_ERROR;
365     }
366
367     h->mba_diff    += 1;
368     h->current_mba += h->mba_diff;
369
370     if (h->current_mba > MBA_STUFFING)
371         return SLICE_ERROR;
372
373     s->mb_x = ((h->gob_number - 1) % 2) * 11 + ((h->current_mba - 1) % 11);
374     s->mb_y = ((h->gob_number - 1) / 2) * 3 + ((h->current_mba - 1) / 11);
375     xy      = s->mb_x + s->mb_y * s->mb_stride;
376     ff_init_block_index(s);
377     ff_update_block_index(s);
378
379     // Read mtype
380     h->mtype = get_vlc2(&s->gb, h261_mtype_vlc.table, H261_MTYPE_VLC_BITS, 2);
381     if (h->mtype < 0) {
382         av_log(s->avctx, AV_LOG_ERROR, "Invalid mtype index %d\n",
383                h->mtype);
384         return SLICE_ERROR;
385     }
386     av_assert0(h->mtype < FF_ARRAY_ELEMS(ff_h261_mtype_map));
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->dsp.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->time_base      = (AVRational) { 1001, 30000 };
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     if (skip_1stop_8data_bits(&s->gb) < 0)
510         return AVERROR_INVALIDDATA;
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     av_dlog(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);
575     av_dlog(avctx, "bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);
576     s->flags  = avctx->flags;
577     s->flags2 = avctx->flags2;
578
579     h->gob_start_code_skipped = 0;
580
581 retry:
582     init_get_bits(&s->gb, buf, buf_size * 8);
583
584     if (!s->context_initialized)
585         // we need the IDCT permutaton for reading a custom matrix
586         if (ff_MPV_common_init(s) < 0)
587             return -1;
588
589     ret = h261_decode_picture_header(h);
590
591     /* skip if the header was thrashed */
592     if (ret < 0) {
593         av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");
594         return -1;
595     }
596
597     if (s->width != avctx->coded_width || s->height != avctx->coded_height) {
598         ParseContext pc = s->parse_context; // FIXME move this demuxing hack to libavformat
599         s->parse_context.buffer = 0;
600         ff_MPV_common_end(s);
601         s->parse_context = pc;
602     }
603     if (!s->context_initialized) {
604         ret = ff_set_dimensions(avctx, s->width, s->height);
605         if (ret < 0)
606             return ret;
607
608         goto retry;
609     }
610
611     // for skipping the frame
612     s->current_picture.f.pict_type = s->pict_type;
613     s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
614
615     if ((avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B) ||
616         (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I) ||
617          avctx->skip_frame >= AVDISCARD_ALL)
618         return get_consumed_bytes(s, buf_size);
619
620     if (ff_MPV_frame_start(s, avctx) < 0)
621         return -1;
622
623     ff_mpeg_er_frame_start(s);
624
625     /* decode each macroblock */
626     s->mb_x = 0;
627     s->mb_y = 0;
628
629     while (h->gob_number < (s->mb_height == 18 ? 12 : 5)) {
630         if (h261_resync(h) < 0)
631             break;
632         h261_decode_gob(h);
633     }
634     ff_MPV_frame_end(s);
635
636     av_assert0(s->current_picture.f.pict_type == s->current_picture_ptr->f.pict_type);
637     av_assert0(s->current_picture.f.pict_type == s->pict_type);
638
639     if ((ret = av_frame_ref(pict, &s->current_picture_ptr->f)) < 0)
640         return ret;
641     ff_print_debug_info(s, s->current_picture_ptr, pict);
642
643     *got_frame = 1;
644
645     return get_consumed_bytes(s, buf_size);
646 }
647
648 static av_cold int h261_decode_end(AVCodecContext *avctx)
649 {
650     H261Context *h    = avctx->priv_data;
651     MpegEncContext *s = &h->s;
652
653     ff_MPV_common_end(s);
654     return 0;
655 }
656
657 AVCodec ff_h261_decoder = {
658     .name           = "h261",
659     .long_name      = NULL_IF_CONFIG_SMALL("H.261"),
660     .type           = AVMEDIA_TYPE_VIDEO,
661     .id             = AV_CODEC_ID_H261,
662     .priv_data_size = sizeof(H261Context),
663     .init           = h261_decode_init,
664     .close          = h261_decode_end,
665     .decode         = h261_decode_frame,
666     .capabilities   = CODEC_CAP_DR1,
667     .max_lowres     = 3,
668 };