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