]> git.sesse.net Git - ffmpeg/blob - libavcodec/g2meet.c
Merge commit '3c47e7c4350f73fc77d8e76f0dd6d2946b13c5cc'
[ffmpeg] / libavcodec / g2meet.c
1 /*
2  * Go2Webinar decoder
3  * Copyright (c) 2012 Konstantin Shishkov
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Go2Webinar decoder
25  */
26
27 #include <inttypes.h>
28 #include <zlib.h>
29
30 #include "libavutil/intreadwrite.h"
31 #include "avcodec.h"
32 #include "blockdsp.h"
33 #include "bytestream.h"
34 #include "idctdsp.h"
35 #include "get_bits.h"
36 #include "internal.h"
37 #include "jpegtables.h"
38 #include "mjpeg.h"
39
40 enum ChunkType {
41     DISPLAY_INFO = 0xC8,
42     TILE_DATA,
43     CURSOR_POS,
44     CURSOR_SHAPE,
45     CHUNK_CC,
46     CHUNK_CD
47 };
48
49 enum Compression {
50     COMPR_EPIC_J_B = 2,
51     COMPR_KEMPF_J_B,
52 };
53
54 static const uint8_t luma_quant[64] = {
55      8,  6,  5,  8, 12, 20, 26, 31,
56      6,  6,  7, 10, 13, 29, 30, 28,
57      7,  7,  8, 12, 20, 29, 35, 28,
58      7,  9, 11, 15, 26, 44, 40, 31,
59      9, 11, 19, 28, 34, 55, 52, 39,
60     12, 18, 28, 32, 41, 52, 57, 46,
61     25, 32, 39, 44, 52, 61, 60, 51,
62     36, 46, 48, 49, 56, 50, 52, 50
63 };
64
65 static const uint8_t chroma_quant[64] = {
66      9,  9, 12, 24, 50, 50, 50, 50,
67      9, 11, 13, 33, 50, 50, 50, 50,
68     12, 13, 28, 50, 50, 50, 50, 50,
69     24, 33, 50, 50, 50, 50, 50, 50,
70     50, 50, 50, 50, 50, 50, 50, 50,
71     50, 50, 50, 50, 50, 50, 50, 50,
72     50, 50, 50, 50, 50, 50, 50, 50,
73     50, 50, 50, 50, 50, 50, 50, 50,
74 };
75
76 typedef struct JPGContext {
77     BlockDSPContext bdsp;
78     IDCTDSPContext idsp;
79     ScanTable  scantable;
80
81     VLC        dc_vlc[2], ac_vlc[2];
82     int        prev_dc[3];
83     DECLARE_ALIGNED(16, int16_t, block)[6][64];
84
85     uint8_t    *buf;
86 } JPGContext;
87
88 typedef struct G2MContext {
89     JPGContext jc;
90     int        version;
91
92     int        compression;
93     int        width, height, bpp;
94     int        orig_width, orig_height;
95     int        tile_width, tile_height;
96     int        tiles_x, tiles_y, tile_x, tile_y;
97
98     int        got_header;
99
100     uint8_t    *framebuf;
101     int        framebuf_stride, old_width, old_height;
102
103     uint8_t    *synth_tile, *jpeg_tile;
104     int        tile_stride, old_tile_w, old_tile_h;
105
106     uint8_t    *kempf_buf, *kempf_flags;
107
108     uint8_t    *cursor;
109     int        cursor_stride;
110     int        cursor_fmt;
111     int        cursor_w, cursor_h, cursor_x, cursor_y;
112     int        cursor_hot_x, cursor_hot_y;
113 } G2MContext;
114
115 static av_cold int build_vlc(VLC *vlc, const uint8_t *bits_table,
116                              const uint8_t *val_table, int nb_codes,
117                              int is_ac)
118 {
119     uint8_t  huff_size[256] = { 0 };
120     uint16_t huff_code[256];
121     uint16_t huff_sym[256];
122     int i;
123
124     ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
125
126     for (i = 0; i < 256; i++)
127         huff_sym[i] = i + 16 * is_ac;
128
129     if (is_ac)
130         huff_sym[0] = 16 * 256;
131
132     return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
133                               huff_code, 2, 2, huff_sym, 2, 2, 0);
134 }
135
136 static av_cold int jpg_init(AVCodecContext *avctx, JPGContext *c)
137 {
138     int ret;
139
140     ret = build_vlc(&c->dc_vlc[0], avpriv_mjpeg_bits_dc_luminance,
141                     avpriv_mjpeg_val_dc, 12, 0);
142     if (ret)
143         return ret;
144     ret = build_vlc(&c->dc_vlc[1], avpriv_mjpeg_bits_dc_chrominance,
145                     avpriv_mjpeg_val_dc, 12, 0);
146     if (ret)
147         return ret;
148     ret = build_vlc(&c->ac_vlc[0], avpriv_mjpeg_bits_ac_luminance,
149                     avpriv_mjpeg_val_ac_luminance, 251, 1);
150     if (ret)
151         return ret;
152     ret = build_vlc(&c->ac_vlc[1], avpriv_mjpeg_bits_ac_chrominance,
153                     avpriv_mjpeg_val_ac_chrominance, 251, 1);
154     if (ret)
155         return ret;
156
157     ff_blockdsp_init(&c->bdsp, avctx);
158     ff_idctdsp_init(&c->idsp, avctx);
159     ff_init_scantable(c->idsp.idct_permutation, &c->scantable,
160                       ff_zigzag_direct);
161
162     return 0;
163 }
164
165 static av_cold void jpg_free_context(JPGContext *ctx)
166 {
167     int i;
168
169     for (i = 0; i < 2; i++) {
170         ff_free_vlc(&ctx->dc_vlc[i]);
171         ff_free_vlc(&ctx->ac_vlc[i]);
172     }
173
174     av_freep(&ctx->buf);
175 }
176
177 static void jpg_unescape(const uint8_t *src, int src_size,
178                          uint8_t *dst, int *dst_size)
179 {
180     const uint8_t *src_end = src + src_size;
181     uint8_t *dst_start = dst;
182
183     while (src < src_end) {
184         uint8_t x = *src++;
185
186         *dst++ = x;
187
188         if (x == 0xFF && !*src)
189             src++;
190     }
191     *dst_size = dst - dst_start;
192 }
193
194 static int jpg_decode_block(JPGContext *c, GetBitContext *gb,
195                             int plane, int16_t *block)
196 {
197     int dc, val, pos;
198     const int is_chroma = !!plane;
199     const uint8_t *qmat = is_chroma ? chroma_quant : luma_quant;
200
201     c->bdsp.clear_block(block);
202     dc = get_vlc2(gb, c->dc_vlc[is_chroma].table, 9, 3);
203     if (dc < 0)
204         return AVERROR_INVALIDDATA;
205     if (dc)
206         dc = get_xbits(gb, dc);
207     dc                = dc * qmat[0] + c->prev_dc[plane];
208     block[0]          = dc;
209     c->prev_dc[plane] = dc;
210
211     pos = 0;
212     while (pos < 63) {
213         val = get_vlc2(gb, c->ac_vlc[is_chroma].table, 9, 3);
214         if (val < 0)
215             return AVERROR_INVALIDDATA;
216         pos += val >> 4;
217         val &= 0xF;
218         if (pos > 63)
219             return val ? AVERROR_INVALIDDATA : 0;
220         if (val) {
221             int nbits = val;
222
223             val                                 = get_xbits(gb, nbits);
224             val                                *= qmat[ff_zigzag_direct[pos]];
225             block[c->scantable.permutated[pos]] = val;
226         }
227     }
228     return 0;
229 }
230
231 static inline void yuv2rgb(uint8_t *out, int Y, int U, int V)
232 {
233     out[0] = av_clip_uint8(Y + (             91881 * V + 32768 >> 16));
234     out[1] = av_clip_uint8(Y + (-22554 * U - 46802 * V + 32768 >> 16));
235     out[2] = av_clip_uint8(Y + (116130 * U             + 32768 >> 16));
236 }
237
238 static int jpg_decode_data(JPGContext *c, int width, int height,
239                            const uint8_t *src, int src_size,
240                            uint8_t *dst, int dst_stride,
241                            const uint8_t *mask, int mask_stride, int num_mbs,
242                            int swapuv)
243 {
244     GetBitContext gb;
245     int mb_w, mb_h, mb_x, mb_y, i, j;
246     int bx, by;
247     int unesc_size;
248     int ret;
249
250     if ((ret = av_reallocp(&c->buf,
251                            src_size + FF_INPUT_BUFFER_PADDING_SIZE)) < 0)
252         return ret;
253     jpg_unescape(src, src_size, c->buf, &unesc_size);
254     memset(c->buf + unesc_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
255     init_get_bits(&gb, c->buf, unesc_size * 8);
256
257     width = FFALIGN(width, 16);
258     mb_w  =  width        >> 4;
259     mb_h  = (height + 15) >> 4;
260
261     if (!num_mbs)
262         num_mbs = mb_w * mb_h * 4;
263
264     for (i = 0; i < 3; i++)
265         c->prev_dc[i] = 1024;
266     bx = by = 0;
267     c->bdsp.clear_blocks(c->block[0]);
268     for (mb_y = 0; mb_y < mb_h; mb_y++) {
269         for (mb_x = 0; mb_x < mb_w; mb_x++) {
270             if (mask && !mask[mb_x * 2] && !mask[mb_x * 2 + 1] &&
271                 !mask[mb_x * 2 +     mask_stride] &&
272                 !mask[mb_x * 2 + 1 + mask_stride]) {
273                 bx += 16;
274                 continue;
275             }
276             for (j = 0; j < 2; j++) {
277                 for (i = 0; i < 2; i++) {
278                     if (mask && !mask[mb_x * 2 + i + j * mask_stride])
279                         continue;
280                     num_mbs--;
281                     if ((ret = jpg_decode_block(c, &gb, 0,
282                                                 c->block[i + j * 2])) != 0)
283                         return ret;
284                     c->idsp.idct(c->block[i + j * 2]);
285                 }
286             }
287             for (i = 1; i < 3; i++) {
288                 if ((ret = jpg_decode_block(c, &gb, i, c->block[i + 3])) != 0)
289                     return ret;
290                 c->idsp.idct(c->block[i + 3]);
291             }
292
293             for (j = 0; j < 16; j++) {
294                 uint8_t *out = dst + bx * 3 + (by + j) * dst_stride;
295                 for (i = 0; i < 16; i++) {
296                     int Y, U, V;
297
298                     Y = c->block[(j >> 3) * 2 + (i >> 3)][(i & 7) + (j & 7) * 8];
299                     U = c->block[4 ^ swapuv][(i >> 1) + (j >> 1) * 8] - 128;
300                     V = c->block[5 ^ swapuv][(i >> 1) + (j >> 1) * 8] - 128;
301                     yuv2rgb(out + i * 3, Y, U, V);
302                 }
303             }
304
305             if (!num_mbs)
306                 return 0;
307             bx += 16;
308         }
309         bx  = 0;
310         by += 16;
311         if (mask)
312             mask += mask_stride * 2;
313     }
314
315     return 0;
316 }
317
318 static void kempf_restore_buf(const uint8_t *src, int len,
319                               uint8_t *dst, int stride,
320                               const uint8_t *jpeg_tile, int tile_stride,
321                               int width, int height,
322                               const uint8_t *pal, int npal, int tidx)
323 {
324     GetBitContext gb;
325     int i, j, nb, col;
326
327     init_get_bits(&gb, src, len * 8);
328
329     if (npal <= 2)       nb = 1;
330     else if (npal <= 4)  nb = 2;
331     else if (npal <= 16) nb = 4;
332     else                 nb = 8;
333
334     for (j = 0; j < height; j++, dst += stride, jpeg_tile += tile_stride) {
335         if (get_bits(&gb, 8))
336             continue;
337         for (i = 0; i < width; i++) {
338             col = get_bits(&gb, nb);
339             if (col != tidx)
340                 memcpy(dst + i * 3, pal + col * 3, 3);
341             else
342                 memcpy(dst + i * 3, jpeg_tile + i * 3, 3);
343         }
344     }
345 }
346
347 static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,
348                              const uint8_t *src, int src_size)
349 {
350     int width, height;
351     int hdr, zsize, npal, tidx = -1, ret;
352     int i, j;
353     const uint8_t *src_end = src + src_size;
354     uint8_t pal[768], transp[3];
355     uLongf dlen = (c->tile_width + 1) * c->tile_height;
356     int sub_type;
357     int nblocks, cblocks, bstride;
358     int bits, bitbuf, coded;
359     uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +
360                    tile_y * c->tile_height * c->framebuf_stride;
361
362     if (src_size < 2)
363         return AVERROR_INVALIDDATA;
364
365     width  = FFMIN(c->width  - tile_x * c->tile_width,  c->tile_width);
366     height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
367
368     hdr      = *src++;
369     sub_type = hdr >> 5;
370     if (sub_type == 0) {
371         int j;
372         memcpy(transp, src, 3);
373         src += 3;
374         for (j = 0; j < height; j++, dst += c->framebuf_stride)
375             for (i = 0; i < width; i++)
376                 memcpy(dst + i * 3, transp, 3);
377         return 0;
378     } else if (sub_type == 1) {
379         return jpg_decode_data(&c->jc, width, height, src, src_end - src,
380                                dst, c->framebuf_stride, NULL, 0, 0, 0);
381     }
382
383     if (sub_type != 2) {
384         memcpy(transp, src, 3);
385         src += 3;
386     }
387     npal = *src++ + 1;
388     if (src_end - src < npal * 3)
389         return AVERROR_INVALIDDATA;
390     memcpy(pal, src, npal * 3);
391     src += npal * 3;
392     if (sub_type != 2) {
393         for (i = 0; i < npal; i++) {
394             if (!memcmp(pal + i * 3, transp, 3)) {
395                 tidx = i;
396                 break;
397             }
398         }
399     }
400
401     if (src_end - src < 2)
402         return 0;
403     zsize = (src[0] << 8) | src[1];
404     src  += 2;
405
406     if (src_end - src < zsize + (sub_type != 2))
407         return AVERROR_INVALIDDATA;
408
409     ret = uncompress(c->kempf_buf, &dlen, src, zsize);
410     if (ret)
411         return AVERROR_INVALIDDATA;
412     src += zsize;
413
414     if (sub_type == 2) {
415         kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
416                           NULL, 0, width, height, pal, npal, tidx);
417         return 0;
418     }
419
420     nblocks = *src++ + 1;
421     cblocks = 0;
422     bstride = FFALIGN(width, 16) >> 3;
423     // blocks are coded LSB and we need normal bitreader for JPEG data
424     bits = 0;
425     for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {
426         for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {
427             if (!bits) {
428                 if (src >= src_end)
429                     return AVERROR_INVALIDDATA;
430                 bitbuf = *src++;
431                 bits   = 8;
432             }
433             coded = bitbuf & 1;
434             bits--;
435             bitbuf >>= 1;
436             cblocks += coded;
437             if (cblocks > nblocks)
438                 return AVERROR_INVALIDDATA;
439             c->kempf_flags[j * 2 +      i * 2      * bstride] =
440             c->kempf_flags[j * 2 + 1 +  i * 2      * bstride] =
441             c->kempf_flags[j * 2 +     (i * 2 + 1) * bstride] =
442             c->kempf_flags[j * 2 + 1 + (i * 2 + 1) * bstride] = coded;
443         }
444     }
445
446     memset(c->jpeg_tile, 0, c->tile_stride * height);
447     jpg_decode_data(&c->jc, width, height, src, src_end - src,
448                     c->jpeg_tile, c->tile_stride,
449                     c->kempf_flags, bstride, nblocks * 4, 0);
450
451     kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
452                       c->jpeg_tile, c->tile_stride,
453                       width, height, pal, npal, tidx);
454
455     return 0;
456 }
457
458 static int g2m_init_buffers(G2MContext *c)
459 {
460     int aligned_height;
461
462     if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
463         c->framebuf_stride = FFALIGN(c->width + 15, 16) * 3;
464         aligned_height     = c->height + 15;
465         av_free(c->framebuf);
466         c->framebuf = av_mallocz_array(c->framebuf_stride, aligned_height);
467         if (!c->framebuf)
468             return AVERROR(ENOMEM);
469     }
470     if (!c->synth_tile || !c->jpeg_tile ||
471         c->old_tile_w < c->tile_width ||
472         c->old_tile_h < c->tile_height) {
473         c->tile_stride = FFALIGN(c->tile_width, 16) * 3;
474         aligned_height = FFALIGN(c->tile_height,    16);
475         av_free(c->synth_tile);
476         av_free(c->jpeg_tile);
477         av_free(c->kempf_buf);
478         av_free(c->kempf_flags);
479         c->synth_tile  = av_mallocz(c->tile_stride      * aligned_height);
480         c->jpeg_tile   = av_mallocz(c->tile_stride      * aligned_height);
481         c->kempf_buf   = av_mallocz((c->tile_width + 1) * aligned_height
482                                     + FF_INPUT_BUFFER_PADDING_SIZE);
483         c->kempf_flags = av_mallocz( c->tile_width      * aligned_height);
484         if (!c->synth_tile || !c->jpeg_tile ||
485             !c->kempf_buf || !c->kempf_flags)
486             return AVERROR(ENOMEM);
487     }
488
489     return 0;
490 }
491
492 static int g2m_load_cursor(AVCodecContext *avctx, G2MContext *c,
493                            GetByteContext *gb)
494 {
495     int i, j, k;
496     uint8_t *dst;
497     uint32_t bits;
498     uint32_t cur_size, cursor_w, cursor_h, cursor_stride;
499     uint32_t cursor_hot_x, cursor_hot_y;
500     int cursor_fmt, err;
501
502     cur_size     = bytestream2_get_be32(gb);
503     cursor_w     = bytestream2_get_byte(gb);
504     cursor_h     = bytestream2_get_byte(gb);
505     cursor_hot_x = bytestream2_get_byte(gb);
506     cursor_hot_y = bytestream2_get_byte(gb);
507     cursor_fmt   = bytestream2_get_byte(gb);
508
509     cursor_stride = FFALIGN(cursor_w, cursor_fmt==1 ? 32 : 1) * 4;
510
511     if (cursor_w < 1 || cursor_w > 256 ||
512         cursor_h < 1 || cursor_h > 256) {
513         av_log(avctx, AV_LOG_ERROR, "Invalid cursor dimensions %"PRIu32"x%"PRIu32"\n",
514                cursor_w, cursor_h);
515         return AVERROR_INVALIDDATA;
516     }
517     if (cursor_hot_x > cursor_w || cursor_hot_y > cursor_h) {
518         av_log(avctx, AV_LOG_WARNING, "Invalid hotspot position %"PRIu32",%"PRIu32"\n",
519                cursor_hot_x, cursor_hot_y);
520         cursor_hot_x = FFMIN(cursor_hot_x, cursor_w - 1);
521         cursor_hot_y = FFMIN(cursor_hot_y, cursor_h - 1);
522     }
523     if (cur_size - 9 > bytestream2_get_bytes_left(gb) ||
524         c->cursor_w * c->cursor_h / 4 > cur_size) {
525         av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %"PRIu32"/%u\n",
526                cur_size, bytestream2_get_bytes_left(gb));
527         return AVERROR_INVALIDDATA;
528     }
529     if (cursor_fmt != 1 && cursor_fmt != 32) {
530         avpriv_report_missing_feature(avctx, "Cursor format %d",
531                                       cursor_fmt);
532         return AVERROR_PATCHWELCOME;
533     }
534
535     if ((err = av_reallocp(&c->cursor, cursor_stride * cursor_h)) < 0) {
536         av_log(avctx, AV_LOG_ERROR, "Cannot allocate cursor buffer\n");
537         return err;
538     }
539
540     c->cursor_w      = cursor_w;
541     c->cursor_h      = cursor_h;
542     c->cursor_hot_x  = cursor_hot_x;
543     c->cursor_hot_y  = cursor_hot_y;
544     c->cursor_fmt    = cursor_fmt;
545     c->cursor_stride = cursor_stride;
546
547     dst = c->cursor;
548     switch (c->cursor_fmt) {
549     case 1: // old monochrome
550         for (j = 0; j < c->cursor_h; j++) {
551             for (i = 0; i < c->cursor_w; i += 32) {
552                 bits = bytestream2_get_be32(gb);
553                 for (k = 0; k < 32; k++) {
554                     dst[0] = !!(bits & 0x80000000);
555                     dst   += 4;
556                     bits <<= 1;
557                 }
558             }
559         }
560
561         dst = c->cursor;
562         for (j = 0; j < c->cursor_h; j++) {
563             for (i = 0; i < c->cursor_w; i += 32) {
564                 bits = bytestream2_get_be32(gb);
565                 for (k = 0; k < 32; k++) {
566                     int mask_bit = !!(bits & 0x80000000);
567                     switch (dst[0] * 2 + mask_bit) {
568                     case 0:
569                         dst[0] = 0xFF;
570                         dst[1] = 0x00;
571                         dst[2] = 0x00;
572                         dst[3] = 0x00;
573                         break;
574                     case 1:
575                         dst[0] = 0xFF;
576                         dst[1] = 0xFF;
577                         dst[2] = 0xFF;
578                         dst[3] = 0xFF;
579                         break;
580                     default:
581                         dst[0] = 0x00;
582                         dst[1] = 0x00;
583                         dst[2] = 0x00;
584                         dst[3] = 0x00;
585                     }
586                     dst   += 4;
587                     bits <<= 1;
588                 }
589             }
590         }
591         break;
592     case 32: // full colour
593         /* skip monochrome version of the cursor and decode RGBA instead */
594         bytestream2_skip(gb, c->cursor_h * (FFALIGN(c->cursor_w, 32) >> 3));
595         for (j = 0; j < c->cursor_h; j++) {
596             for (i = 0; i < c->cursor_w; i++) {
597                 int val = bytestream2_get_be32(gb);
598                 *dst++ = val >>  0;
599                 *dst++ = val >>  8;
600                 *dst++ = val >> 16;
601                 *dst++ = val >> 24;
602             }
603         }
604         break;
605     default:
606         return AVERROR_PATCHWELCOME;
607     }
608     return 0;
609 }
610
611 #define APPLY_ALPHA(src, new, alpha) \
612     src = (src * (256 - alpha) + new * alpha) >> 8
613
614 static void g2m_paint_cursor(G2MContext *c, uint8_t *dst, int stride)
615 {
616     int i, j;
617     int x, y, w, h;
618     const uint8_t *cursor;
619
620     if (!c->cursor)
621         return;
622
623     x = c->cursor_x - c->cursor_hot_x;
624     y = c->cursor_y - c->cursor_hot_y;
625
626     cursor = c->cursor;
627     w      = c->cursor_w;
628     h      = c->cursor_h;
629
630     if (x + w > c->width)
631         w = c->width - x;
632     if (y + h > c->height)
633         h = c->height - y;
634     if (x < 0) {
635         w      +=  x;
636         cursor += -x * 4;
637     } else {
638         dst    +=  x * 3;
639     }
640     if (y < 0) {
641         h      +=  y;
642         cursor += -y * c->cursor_stride;
643     } else {
644         dst    +=  y * stride;
645     }
646     if (w < 0 || h < 0)
647         return;
648
649     for (j = 0; j < h; j++) {
650         for (i = 0; i < w; i++) {
651             uint8_t alpha = cursor[i * 4];
652             APPLY_ALPHA(dst[i * 3 + 0], cursor[i * 4 + 1], alpha);
653             APPLY_ALPHA(dst[i * 3 + 1], cursor[i * 4 + 2], alpha);
654             APPLY_ALPHA(dst[i * 3 + 2], cursor[i * 4 + 3], alpha);
655         }
656         dst    += stride;
657         cursor += c->cursor_stride;
658     }
659 }
660
661 static int g2m_decode_frame(AVCodecContext *avctx, void *data,
662                             int *got_picture_ptr, AVPacket *avpkt)
663 {
664     const uint8_t *buf = avpkt->data;
665     int buf_size = avpkt->size;
666     G2MContext *c = avctx->priv_data;
667     AVFrame *pic = data;
668     GetByteContext bc, tbc;
669     int magic;
670     int got_header = 0;
671     uint32_t chunk_size, r_mask, g_mask, b_mask;
672     int chunk_type, chunk_start;
673     int i;
674     int ret;
675
676     if (buf_size < 12) {
677         av_log(avctx, AV_LOG_ERROR,
678                "Frame should have at least 12 bytes, got %d instead\n",
679                buf_size);
680         return AVERROR_INVALIDDATA;
681     }
682
683     bytestream2_init(&bc, buf, buf_size);
684
685     magic = bytestream2_get_be32(&bc);
686     if ((magic & ~0xF) != MKBETAG('G', '2', 'M', '0') ||
687         (magic & 0xF) < 2 || (magic & 0xF) > 5) {
688         av_log(avctx, AV_LOG_ERROR, "Wrong magic %08X\n", magic);
689         return AVERROR_INVALIDDATA;
690     }
691
692     if ((magic & 0xF) < 4) {
693         av_log(avctx, AV_LOG_ERROR, "G2M2 and G2M3 are not yet supported\n");
694         return AVERROR(ENOSYS);
695     }
696
697     while (bytestream2_get_bytes_left(&bc) > 5) {
698         chunk_size  = bytestream2_get_le32(&bc) - 1;
699         chunk_type  = bytestream2_get_byte(&bc);
700         chunk_start = bytestream2_tell(&bc);
701         if (chunk_size > bytestream2_get_bytes_left(&bc)) {
702             av_log(avctx, AV_LOG_ERROR, "Invalid chunk size %"PRIu32" type %02X\n",
703                    chunk_size, chunk_type);
704             break;
705         }
706         switch (chunk_type) {
707         case DISPLAY_INFO:
708             got_header =
709             c->got_header = 0;
710             if (chunk_size < 21) {
711                 av_log(avctx, AV_LOG_ERROR, "Invalid display info size %"PRIu32"\n",
712                        chunk_size);
713                 break;
714             }
715             c->width  = bytestream2_get_be32(&bc);
716             c->height = bytestream2_get_be32(&bc);
717             if (c->width  < 16 || c->width  > c->orig_width ||
718                 c->height < 16 || c->height > c->orig_height) {
719                 av_log(avctx, AV_LOG_ERROR,
720                        "Invalid frame dimensions %dx%d\n",
721                        c->width, c->height);
722                 ret = AVERROR_INVALIDDATA;
723                 goto header_fail;
724             }
725             if (c->width != avctx->width || c->height != avctx->height) {
726                 ret = ff_set_dimensions(avctx, c->width, c->height);
727                 if (ret < 0)
728                     goto header_fail;
729             }
730             c->compression = bytestream2_get_be32(&bc);
731             if (c->compression != 2 && c->compression != 3) {
732                 av_log(avctx, AV_LOG_ERROR,
733                        "Unknown compression method %d\n",
734                        c->compression);
735                 ret = AVERROR_PATCHWELCOME;
736                 goto header_fail;
737             }
738             c->tile_width  = bytestream2_get_be32(&bc);
739             c->tile_height = bytestream2_get_be32(&bc);
740             if (c->tile_width <= 0 || c->tile_height <= 0 ||
741                 ((c->tile_width | c->tile_height) & 0xF) ||
742                 c->tile_width * 4LL * c->tile_height >= INT_MAX
743             ) {
744                 av_log(avctx, AV_LOG_ERROR,
745                        "Invalid tile dimensions %dx%d\n",
746                        c->tile_width, c->tile_height);
747                 ret = AVERROR_INVALIDDATA;
748                 goto header_fail;
749             }
750             c->tiles_x = (c->width  + c->tile_width  - 1) / c->tile_width;
751             c->tiles_y = (c->height + c->tile_height - 1) / c->tile_height;
752             c->bpp     = bytestream2_get_byte(&bc);
753             if (c->bpp == 32) {
754                 if (bytestream2_get_bytes_left(&bc) < 16 ||
755                     (chunk_size - 21) < 16) {
756                     av_log(avctx, AV_LOG_ERROR,
757                            "Display info: missing bitmasks!\n");
758                     ret = AVERROR_INVALIDDATA;
759                     goto header_fail;
760                 }
761                 r_mask = bytestream2_get_be32(&bc);
762                 g_mask = bytestream2_get_be32(&bc);
763                 b_mask = bytestream2_get_be32(&bc);
764                 if (r_mask != 0xFF0000 || g_mask != 0xFF00 || b_mask != 0xFF) {
765                     av_log(avctx, AV_LOG_ERROR,
766                            "Invalid or unsupported bitmasks: R=%"PRIX32", G=%"PRIX32", B=%"PRIX32"\n",
767                            r_mask, g_mask, b_mask);
768                     ret = AVERROR_PATCHWELCOME;
769                     goto header_fail;
770                 }
771             } else {
772                 avpriv_request_sample(avctx, "bpp=%d", c->bpp);
773                 ret = AVERROR_PATCHWELCOME;
774                 goto header_fail;
775             }
776             if (g2m_init_buffers(c)) {
777                 ret = AVERROR(ENOMEM);
778                 goto header_fail;
779             }
780             got_header = 1;
781             break;
782         case TILE_DATA:
783             if (!c->tiles_x || !c->tiles_y) {
784                 av_log(avctx, AV_LOG_WARNING,
785                        "No display info - skipping tile\n");
786                 break;
787             }
788             if (chunk_size < 2) {
789                 av_log(avctx, AV_LOG_ERROR, "Invalid tile data size %"PRIu32"\n",
790                        chunk_size);
791                 break;
792             }
793             c->tile_x = bytestream2_get_byte(&bc);
794             c->tile_y = bytestream2_get_byte(&bc);
795             if (c->tile_x >= c->tiles_x || c->tile_y >= c->tiles_y) {
796                 av_log(avctx, AV_LOG_ERROR,
797                        "Invalid tile pos %d,%d (in %dx%d grid)\n",
798                        c->tile_x, c->tile_y, c->tiles_x, c->tiles_y);
799                 break;
800             }
801             ret = 0;
802             switch (c->compression) {
803             case COMPR_EPIC_J_B:
804                 av_log(avctx, AV_LOG_ERROR,
805                        "ePIC j-b compression is not implemented yet\n");
806                 return AVERROR(ENOSYS);
807             case COMPR_KEMPF_J_B:
808                 ret = kempf_decode_tile(c, c->tile_x, c->tile_y,
809                                         buf + bytestream2_tell(&bc),
810                                         chunk_size - 2);
811                 break;
812             }
813             if (ret && c->framebuf)
814                 av_log(avctx, AV_LOG_ERROR, "Error decoding tile %d,%d\n",
815                        c->tile_x, c->tile_y);
816             break;
817         case CURSOR_POS:
818             if (chunk_size < 5) {
819                 av_log(avctx, AV_LOG_ERROR, "Invalid cursor pos size %"PRIu32"\n",
820                        chunk_size);
821                 break;
822             }
823             c->cursor_x = bytestream2_get_be16(&bc);
824             c->cursor_y = bytestream2_get_be16(&bc);
825             break;
826         case CURSOR_SHAPE:
827             if (chunk_size < 8) {
828                 av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %"PRIu32"\n",
829                        chunk_size);
830                 break;
831             }
832             bytestream2_init(&tbc, buf + bytestream2_tell(&bc),
833                              chunk_size - 4);
834             g2m_load_cursor(avctx, c, &tbc);
835             break;
836         case CHUNK_CC:
837         case CHUNK_CD:
838             break;
839         default:
840             av_log(avctx, AV_LOG_WARNING, "Skipping chunk type %02d\n",
841                    chunk_type);
842         }
843
844         /* navigate to next chunk */
845         bytestream2_skip(&bc, chunk_start + chunk_size - bytestream2_tell(&bc));
846     }
847     if (got_header)
848         c->got_header = 1;
849
850     if (c->width && c->height && c->framebuf) {
851         if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)
852             return ret;
853
854         pic->key_frame = got_header;
855         pic->pict_type = got_header ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
856
857         for (i = 0; i < avctx->height; i++)
858             memcpy(pic->data[0] + i * pic->linesize[0],
859                    c->framebuf + i * c->framebuf_stride,
860                    c->width * 3);
861         g2m_paint_cursor(c, pic->data[0], pic->linesize[0]);
862
863         *got_picture_ptr = 1;
864     }
865
866     return buf_size;
867
868 header_fail:
869     c->width   =
870     c->height  = 0;
871     c->tiles_x =
872     c->tiles_y = 0;
873     return ret;
874 }
875
876 static av_cold int g2m_decode_init(AVCodecContext *avctx)
877 {
878     G2MContext *const c = avctx->priv_data;
879     int ret;
880
881     if ((ret = jpg_init(avctx, &c->jc)) != 0) {
882         av_log(avctx, AV_LOG_ERROR, "Cannot initialise VLCs\n");
883         jpg_free_context(&c->jc);
884         return AVERROR(ENOMEM);
885     }
886
887     avctx->pix_fmt = AV_PIX_FMT_RGB24;
888
889     // store original sizes and check against those if resize happens
890     c->orig_width  = avctx->width;
891     c->orig_height = avctx->height;
892
893     return 0;
894 }
895
896 static av_cold int g2m_decode_end(AVCodecContext *avctx)
897 {
898     G2MContext *const c = avctx->priv_data;
899
900     jpg_free_context(&c->jc);
901
902     av_freep(&c->kempf_buf);
903     av_freep(&c->kempf_flags);
904     av_freep(&c->synth_tile);
905     av_freep(&c->jpeg_tile);
906     av_freep(&c->cursor);
907     av_freep(&c->framebuf);
908
909     return 0;
910 }
911
912 AVCodec ff_g2m_decoder = {
913     .name           = "g2m",
914     .long_name      = NULL_IF_CONFIG_SMALL("Go2Meeting"),
915     .type           = AVMEDIA_TYPE_VIDEO,
916     .id             = AV_CODEC_ID_G2M,
917     .priv_data_size = sizeof(G2MContext),
918     .init           = g2m_decode_init,
919     .close          = g2m_decode_end,
920     .decode         = g2m_decode_frame,
921     .capabilities   = CODEC_CAP_DR1,
922 };