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