]> git.sesse.net Git - ffmpeg/blob - libavcodec/g2meet.c
g2meet: use an unsigned type for the djb hash
[ffmpeg] / libavcodec / g2meet.c
1 /*
2  * Go2Webinar / Go2Meeting decoder
3  * Copyright (c) 2012 Konstantin Shishkov
4  * Copyright (c) 2013 Maxim Poliakovski
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  * Go2Webinar / Go2Meeting decoder
26  */
27
28 #include <inttypes.h>
29 #include <zlib.h>
30
31 #include "libavutil/intreadwrite.h"
32
33 #include "avcodec.h"
34 #include "blockdsp.h"
35 #include "bytestream.h"
36 #include "elsdec.h"
37 #include "get_bits.h"
38 #include "idctdsp.h"
39 #include "internal.h"
40 #include "jpegtables.h"
41 #include "mjpeg.h"
42
43 #define EPIC_PIX_STACK_SIZE 1024
44 #define EPIC_PIX_STACK_MAX  (EPIC_PIX_STACK_SIZE - 1)
45
46 enum ChunkType {
47     DISPLAY_INFO = 0xC8,
48     TILE_DATA,
49     CURSOR_POS,
50     CURSOR_SHAPE,
51     CHUNK_CC,
52     CHUNK_CD
53 };
54
55 enum Compression {
56     COMPR_EPIC_J_B = 2,
57     COMPR_KEMPF_J_B,
58 };
59
60 static const uint8_t luma_quant[64] = {
61      8,  6,  5,  8, 12, 20, 26, 31,
62      6,  6,  7, 10, 13, 29, 30, 28,
63      7,  7,  8, 12, 20, 29, 35, 28,
64      7,  9, 11, 15, 26, 44, 40, 31,
65      9, 11, 19, 28, 34, 55, 52, 39,
66     12, 18, 28, 32, 41, 52, 57, 46,
67     25, 32, 39, 44, 52, 61, 60, 51,
68     36, 46, 48, 49, 56, 50, 52, 50
69 };
70
71 static const uint8_t chroma_quant[64] = {
72      9,  9, 12, 24, 50, 50, 50, 50,
73      9, 11, 13, 33, 50, 50, 50, 50,
74     12, 13, 28, 50, 50, 50, 50, 50,
75     24, 33, 50, 50, 50, 50, 50, 50,
76     50, 50, 50, 50, 50, 50, 50, 50,
77     50, 50, 50, 50, 50, 50, 50, 50,
78     50, 50, 50, 50, 50, 50, 50, 50,
79     50, 50, 50, 50, 50, 50, 50, 50,
80 };
81
82 typedef struct ePICPixListElem {
83     struct ePICPixListElem *next;
84     uint32_t               pixel;
85     uint8_t                rung;
86 } ePICPixListElem;
87
88 typedef struct ePICPixHashElem {
89     uint32_t                pix_id;
90     struct ePICPixListElem  *list;
91 } ePICPixHashElem;
92
93 #define EPIC_HASH_SIZE 256
94 typedef struct ePICPixHash {
95     ePICPixHashElem *bucket[EPIC_HASH_SIZE];
96     int              bucket_size[EPIC_HASH_SIZE];
97     int              bucket_fill[EPIC_HASH_SIZE];
98 } ePICPixHash;
99
100 typedef struct ePICContext {
101     ElsDecCtx        els_ctx;
102     int              next_run_pos;
103     ElsUnsignedRung  unsigned_rung;
104     uint8_t          W_flag_rung;
105     uint8_t          N_flag_rung;
106     uint8_t          W_ctx_rung[256];
107     uint8_t          N_ctx_rung[512];
108     uint8_t          nw_pred_rung[256];
109     uint8_t          ne_pred_rung[256];
110     uint8_t          prev_row_rung[14];
111     uint8_t          runlen_zeroes[14];
112     uint8_t          runlen_one;
113     int              stack_pos;
114     uint32_t         stack[EPIC_PIX_STACK_SIZE];
115     ePICPixHash      hash;
116 } ePICContext;
117
118 typedef struct JPGContext {
119     BlockDSPContext bdsp;
120     IDCTDSPContext idsp;
121     ScanTable  scantable;
122
123     VLC        dc_vlc[2], ac_vlc[2];
124     int        prev_dc[3];
125     DECLARE_ALIGNED(16, int16_t, block)[6][64];
126
127     uint8_t    *buf;
128 } JPGContext;
129
130 typedef struct G2MContext {
131     ePICContext ec;
132     JPGContext jc;
133
134     int        version;
135
136     int        compression;
137     int        width, height, bpp;
138     int        orig_width, orig_height;
139     int        tile_width, tile_height;
140     int        tiles_x, tiles_y, tile_x, tile_y;
141
142     int        got_header;
143
144     uint8_t    *framebuf;
145     int        framebuf_stride, old_width, old_height;
146
147     uint8_t    *synth_tile, *jpeg_tile, *epic_buf, *epic_buf_base;
148     int        tile_stride, epic_buf_stride, old_tile_w, old_tile_h;
149     int        swapuv;
150
151     uint8_t    *kempf_buf, *kempf_flags;
152
153     uint8_t    *cursor;
154     int        cursor_stride;
155     int        cursor_fmt;
156     int        cursor_w, cursor_h, cursor_x, cursor_y;
157     int        cursor_hot_x, cursor_hot_y;
158 } G2MContext;
159
160 static av_cold int build_vlc(VLC *vlc, const uint8_t *bits_table,
161                              const uint8_t *val_table, int nb_codes,
162                              int is_ac)
163 {
164     uint8_t  huff_size[256] = { 0 };
165     uint16_t huff_code[256];
166     uint16_t huff_sym[256];
167     int i;
168
169     ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
170
171     for (i = 0; i < 256; i++)
172         huff_sym[i] = i + 16 * is_ac;
173
174     if (is_ac)
175         huff_sym[0] = 16 * 256;
176
177     return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
178                               huff_code, 2, 2, huff_sym, 2, 2, 0);
179 }
180
181 static av_cold int jpg_init(AVCodecContext *avctx, JPGContext *c)
182 {
183     int ret;
184
185     ret = build_vlc(&c->dc_vlc[0], avpriv_mjpeg_bits_dc_luminance,
186                     avpriv_mjpeg_val_dc, 12, 0);
187     if (ret)
188         return ret;
189     ret = build_vlc(&c->dc_vlc[1], avpriv_mjpeg_bits_dc_chrominance,
190                     avpriv_mjpeg_val_dc, 12, 0);
191     if (ret)
192         return ret;
193     ret = build_vlc(&c->ac_vlc[0], avpriv_mjpeg_bits_ac_luminance,
194                     avpriv_mjpeg_val_ac_luminance, 251, 1);
195     if (ret)
196         return ret;
197     ret = build_vlc(&c->ac_vlc[1], avpriv_mjpeg_bits_ac_chrominance,
198                     avpriv_mjpeg_val_ac_chrominance, 251, 1);
199     if (ret)
200         return ret;
201
202     ff_blockdsp_init(&c->bdsp, avctx);
203     ff_idctdsp_init(&c->idsp, avctx);
204     ff_init_scantable(c->idsp.idct_permutation, &c->scantable,
205                       ff_zigzag_direct);
206
207     return 0;
208 }
209
210 static av_cold void jpg_free_context(JPGContext *ctx)
211 {
212     int i;
213
214     for (i = 0; i < 2; i++) {
215         ff_free_vlc(&ctx->dc_vlc[i]);
216         ff_free_vlc(&ctx->ac_vlc[i]);
217     }
218
219     av_freep(&ctx->buf);
220 }
221
222 static void jpg_unescape(const uint8_t *src, int src_size,
223                          uint8_t *dst, int *dst_size)
224 {
225     const uint8_t *src_end = src + src_size;
226     uint8_t *dst_start = dst;
227
228     while (src < src_end) {
229         uint8_t x = *src++;
230
231         *dst++ = x;
232
233         if (x == 0xFF && !*src)
234             src++;
235     }
236     *dst_size = dst - dst_start;
237 }
238
239 static int jpg_decode_block(JPGContext *c, GetBitContext *gb,
240                             int plane, int16_t *block)
241 {
242     int dc, val, pos;
243     const int is_chroma = !!plane;
244     const uint8_t *qmat = is_chroma ? chroma_quant : luma_quant;
245
246     c->bdsp.clear_block(block);
247     dc = get_vlc2(gb, c->dc_vlc[is_chroma].table, 9, 3);
248     if (dc < 0)
249         return AVERROR_INVALIDDATA;
250     if (dc)
251         dc = get_xbits(gb, dc);
252     dc                = dc * qmat[0] + c->prev_dc[plane];
253     block[0]          = dc;
254     c->prev_dc[plane] = dc;
255
256     pos = 0;
257     while (pos < 63) {
258         val = get_vlc2(gb, c->ac_vlc[is_chroma].table, 9, 3);
259         if (val < 0)
260             return AVERROR_INVALIDDATA;
261         pos += val >> 4;
262         val &= 0xF;
263         if (pos > 63)
264             return val ? AVERROR_INVALIDDATA : 0;
265         if (val) {
266             int nbits = val;
267
268             val                                 = get_xbits(gb, nbits);
269             val                                *= qmat[ff_zigzag_direct[pos]];
270             block[c->scantable.permutated[pos]] = val;
271         }
272     }
273     return 0;
274 }
275
276 static inline void yuv2rgb(uint8_t *out, int ridx, int Y, int U, int V)
277 {
278     out[ridx]     = av_clip_uint8(Y +              (91881 * V + 32768 >> 16));
279     out[1]        = av_clip_uint8(Y + (-22554 * U - 46802 * V + 32768 >> 16));
280     out[2 - ridx] = av_clip_uint8(Y + (116130 * U             + 32768 >> 16));
281 }
282
283 static int jpg_decode_data(JPGContext *c, int width, int height,
284                            const uint8_t *src, int src_size,
285                            uint8_t *dst, int dst_stride,
286                            const uint8_t *mask, int mask_stride, int num_mbs,
287                            int swapuv)
288 {
289     GetBitContext gb;
290     int mb_w, mb_h, mb_x, mb_y, i, j;
291     int bx, by;
292     int unesc_size;
293     int ret;
294     const int ridx = swapuv ? 2 : 0;
295
296     if ((ret = av_reallocp(&c->buf,
297                            src_size + FF_INPUT_BUFFER_PADDING_SIZE)) < 0)
298         return ret;
299     jpg_unescape(src, src_size, c->buf, &unesc_size);
300     memset(c->buf + unesc_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
301     init_get_bits(&gb, c->buf, unesc_size * 8);
302
303     width = FFALIGN(width, 16);
304     mb_w  =  width        >> 4;
305     mb_h  = (height + 15) >> 4;
306
307     if (!num_mbs)
308         num_mbs = mb_w * mb_h * 4;
309
310     for (i = 0; i < 3; i++)
311         c->prev_dc[i] = 1024;
312     bx =
313     by = 0;
314     c->bdsp.clear_blocks(c->block[0]);
315     for (mb_y = 0; mb_y < mb_h; mb_y++) {
316         for (mb_x = 0; mb_x < mb_w; mb_x++) {
317             if (mask && !mask[mb_x * 2] && !mask[mb_x * 2 + 1] &&
318                 !mask[mb_x * 2 +     mask_stride] &&
319                 !mask[mb_x * 2 + 1 + mask_stride]) {
320                 bx += 16;
321                 continue;
322             }
323             for (j = 0; j < 2; j++) {
324                 for (i = 0; i < 2; i++) {
325                     if (mask && !mask[mb_x * 2 + i + j * mask_stride])
326                         continue;
327                     num_mbs--;
328                     if ((ret = jpg_decode_block(c, &gb, 0,
329                                                 c->block[i + j * 2])) != 0)
330                         return ret;
331                     c->idsp.idct(c->block[i + j * 2]);
332                 }
333             }
334             for (i = 1; i < 3; i++) {
335                 if ((ret = jpg_decode_block(c, &gb, i, c->block[i + 3])) != 0)
336                     return ret;
337                 c->idsp.idct(c->block[i + 3]);
338             }
339
340             for (j = 0; j < 16; j++) {
341                 uint8_t *out = dst + bx * 3 + (by + j) * dst_stride;
342                 for (i = 0; i < 16; i++) {
343                     int Y, U, V;
344
345                     Y = c->block[(j >> 3) * 2 + (i >> 3)][(i & 7) + (j & 7) * 8];
346                     U = c->block[4][(i >> 1) + (j >> 1) * 8] - 128;
347                     V = c->block[5][(i >> 1) + (j >> 1) * 8] - 128;
348                     yuv2rgb(out + i * 3, ridx, Y, U, V);
349                 }
350             }
351
352             if (!num_mbs)
353                 return 0;
354             bx += 16;
355         }
356         bx  = 0;
357         by += 16;
358         if (mask)
359             mask += mask_stride * 2;
360     }
361
362     return 0;
363 }
364
365 #define LOAD_NEIGHBOURS(x)      \
366     W   = curr_row[(x)   - 1];  \
367     N   = above_row[(x)];       \
368     WW  = curr_row[(x)   - 2];  \
369     NW  = above_row[(x)  - 1];  \
370     NE  = above_row[(x)  + 1];  \
371     NN  = above2_row[(x)];      \
372     NNW = above2_row[(x) - 1];  \
373     NWW = above_row[(x)  - 2];  \
374     NNE = above2_row[(x) + 1]
375
376 #define UPDATE_NEIGHBOURS(x)    \
377     NNW = NN;                   \
378     NN  = NNE;                  \
379     NWW = NW;                   \
380     NW  = N;                    \
381     N   = NE;                   \
382     NE  = above_row[(x)  + 1];  \
383     NNE = above2_row[(x) + 1]
384
385 #define R_shift 16
386 #define G_shift  8
387 #define B_shift  0
388
389 static inline int log2_ceil(uint32_t x)
390 {
391     int c = 0;
392
393     for (--x; x > 0; x >>= 1)
394         c++;
395
396     return c;
397 }
398
399 /* improved djb2 hash from http://www.cse.yorku.ca/~oz/hash.html */
400 static int djb2_hash(uint32_t key)
401 {
402     uint32_t h = 5381;
403
404     h = (h * 33) ^ ((key >> 24) & 0xFF); // xxx: probably not needed at all
405     h = (h * 33) ^ ((key >> 16) & 0xFF);
406     h = (h * 33) ^ ((key >>  8) & 0xFF);
407     h = (h * 33) ^  (key        & 0xFF);
408
409     return h & (EPIC_HASH_SIZE - 1);
410 }
411
412 static void epic_hash_init(ePICPixHash *hash)
413 {
414     memset(hash, 0, sizeof(*hash));
415 }
416
417 static ePICPixHashElem *epic_hash_find(const ePICPixHash *hash, uint32_t key)
418 {
419     int i, idx = djb2_hash(key);
420     ePICPixHashElem *bucket = hash->bucket[idx];
421
422     for (i = 0; i < hash->bucket_fill[idx]; i++)
423         if (bucket[i].pix_id == key)
424             return &bucket[i];
425
426     return NULL;
427 }
428
429 static ePICPixHashElem *epic_hash_add(ePICPixHash *hash, uint32_t key)
430 {
431     ePICPixHashElem *bucket, *ret;
432     int idx = djb2_hash(key);
433
434     if (hash->bucket_size[idx] > INT_MAX / sizeof(**hash->bucket))
435         return NULL;
436
437     if (!(hash->bucket_fill[idx] < hash->bucket_size[idx])) {
438         int new_size = hash->bucket_size[idx] + 16;
439         bucket = av_realloc(hash->bucket[idx], new_size * sizeof(*bucket));
440         if (!bucket)
441             return NULL;
442         hash->bucket[idx]      = bucket;
443         hash->bucket_size[idx] = new_size;
444     }
445
446     ret = &hash->bucket[idx][hash->bucket_fill[idx]++];
447     memset(ret, 0, sizeof(*ret));
448     ret->pix_id = key;
449     return ret;
450 }
451
452 static int epic_add_pixel_to_cache(ePICPixHash *hash, uint32_t key, uint32_t pix)
453 {
454     ePICPixListElem *new_elem;
455     ePICPixHashElem *hash_elem = epic_hash_find(hash, key);
456
457     if (!hash_elem) {
458         if (!(hash_elem = epic_hash_add(hash, key)))
459             return AVERROR(ENOMEM);
460     }
461
462     new_elem = av_mallocz(sizeof(*new_elem));
463     if (!new_elem)
464         return AVERROR(ENOMEM);
465
466     new_elem->pixel = pix;
467     new_elem->next  = hash_elem->list;
468     hash_elem->list = new_elem;
469
470     return 0;
471 }
472
473 static inline int epic_cache_entries_for_pixel(const ePICPixHash *hash,
474                                                uint32_t pix)
475 {
476     ePICPixHashElem *hash_elem = epic_hash_find(hash, pix);
477
478     if (hash_elem != NULL && hash_elem->list != NULL)
479         return 1;
480
481     return 0;
482 }
483
484 static void epic_free_pixel_cache(ePICPixHash *hash)
485 {
486     int i, j;
487
488     for (i = 0; i < EPIC_HASH_SIZE; i++) {
489         for (j = 0; j < hash->bucket_fill[i]; j++) {
490             ePICPixListElem *list_elem = hash->bucket[i][j].list;
491             while (list_elem) {
492                 ePICPixListElem *tmp = list_elem->next;
493                 av_free(list_elem);
494                 list_elem = tmp;
495             }
496         }
497         av_freep(&hash->bucket[i]);
498         hash->bucket_size[i] =
499         hash->bucket_fill[i] = 0;
500     }
501 }
502
503 static inline int is_pixel_on_stack(const ePICContext *dc, uint32_t pix)
504 {
505     int i;
506
507     for (i = 0; i < dc->stack_pos; i++)
508         if (dc->stack[i] == pix)
509             break;
510
511     return i != dc->stack_pos;
512 }
513
514 #define TOSIGNED(val) (((val) >> 1) ^ -((val) & 1))
515
516 static inline int epic_decode_component_pred(ePICContext *dc,
517                                              int N, int W, int NW)
518 {
519     unsigned delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
520     return mid_pred(N, N + W - NW, W) - TOSIGNED(delta);
521 }
522
523 static uint32_t epic_decode_pixel_pred(ePICContext *dc, int x, int y,
524                                        const uint32_t *curr_row,
525                                        const uint32_t *above_row)
526 {
527     uint32_t N, W, NW, pred;
528     unsigned delta;
529     int GN, GW, GNW, R, G, B;
530
531     if (x && y) {
532         W  = curr_row[x  - 1];
533         N  = above_row[x];
534         NW = above_row[x - 1];
535
536         GN  = (N  >> G_shift) & 0xFF;
537         GW  = (W  >> G_shift) & 0xFF;
538         GNW = (NW >> G_shift) & 0xFF;
539
540         G = epic_decode_component_pred(dc, GN, GW, GNW);
541
542         R = G + epic_decode_component_pred(dc,
543                                            ((N  >> R_shift) & 0xFF) - GN,
544                                            ((W  >> R_shift) & 0xFF) - GW,
545                                            ((NW >> R_shift) & 0xFF) - GNW);
546
547         B = G + epic_decode_component_pred(dc,
548                                            ((N  >> B_shift) & 0xFF) - GN,
549                                            ((W  >> B_shift) & 0xFF) - GW,
550                                            ((NW >> B_shift) & 0xFF) - GNW);
551     } else {
552         if (x)
553             pred = curr_row[x - 1];
554         else
555             pred = above_row[x];
556
557         delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
558         R     = ((pred >> R_shift) & 0xFF) - TOSIGNED(delta);
559
560         delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
561         G     = ((pred >> G_shift) & 0xFF) - TOSIGNED(delta);
562
563         delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
564         B     = ((pred >> B_shift) & 0xFF) - TOSIGNED(delta);
565     }
566
567     return (R << R_shift) | (G << G_shift) | (B << B_shift);
568 }
569
570 static int epic_predict_pixel(ePICContext *dc, uint8_t *rung,
571                               uint32_t *pPix, uint32_t pix)
572 {
573     if (!ff_els_decode_bit(&dc->els_ctx, rung)) {
574         *pPix = pix;
575         return 1;
576     }
577     dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = pix;
578     return 0;
579 }
580
581 static int epic_handle_edges(ePICContext *dc, int x, int y,
582                              const uint32_t *curr_row,
583                              const uint32_t *above_row, uint32_t *pPix)
584 {
585     uint32_t pix;
586
587     if (!x && !y) { /* special case: top-left pixel */
588         /* the top-left pixel is coded independently with 3 unsigned numbers */
589         *pPix = (ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung) << R_shift) |
590                 (ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung) << G_shift) |
591                 (ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung) << B_shift);
592         return 1;
593     }
594
595     if (x) { /* predict from W first */
596         pix = curr_row[x - 1];
597         if (epic_predict_pixel(dc, &dc->W_flag_rung, pPix, pix))
598             return 1;
599     }
600
601     if (y) { /* then try to predict from N */
602         pix = above_row[x];
603         if (!dc->stack_pos || dc->stack[0] != pix) {
604             if (epic_predict_pixel(dc, &dc->N_flag_rung, pPix, pix))
605                 return 1;
606         }
607     }
608
609     return 0;
610 }
611
612 static int epic_decode_run_length(ePICContext *dc, int x, int y, int tile_width,
613                                   const uint32_t *curr_row,
614                                   const uint32_t *above_row,
615                                   const uint32_t *above2_row,
616                                   uint32_t *pPix, int *pRun)
617 {
618     int idx, got_pixel = 0, WWneW, old_WWneW = 0;
619     uint32_t W, WW, N, NN, NW, NE, NWW, NNW, NNE;
620
621     *pRun = 0;
622
623     LOAD_NEIGHBOURS(x);
624
625     if (dc->next_run_pos == x) {
626         /* can't reuse W for the new pixel in this case */
627         WWneW = 1;
628     } else {
629         idx = (WW  != W)  << 7 |
630               (NW  != W)  << 6 |
631               (N   != NE) << 5 |
632               (NW  != N)  << 4 |
633               (NWW != NW) << 3 |
634               (NNE != NE) << 2 |
635               (NN  != N)  << 1 |
636               (NNW != NW);
637         WWneW = ff_els_decode_bit(&dc->els_ctx, &dc->W_ctx_rung[idx]);
638     }
639
640     if (WWneW)
641         dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = W;
642     else {
643         *pPix     = W;
644         got_pixel = 1;
645     }
646
647     do {
648         int NWneW = 1;
649         if (got_pixel) // pixel value already known (derived from either W or N)
650             NWneW = *pPix != N;
651         else { // pixel value is unknown and will be decoded later
652             NWneW = *pRun ? NWneW : NW != W;
653
654             /* TODO: RFC this mess! */
655             switch (((NW != N) << 2) | (NWneW << 1) | WWneW) {
656             case 0:
657                 break; // do nothing here
658             case 3:
659             case 5:
660             case 6:
661             case 7:
662                 if (!is_pixel_on_stack(dc, N)) {
663                     idx = WWneW       << 8 |
664                           (*pRun ? old_WWneW : WW != W) << 7 |
665                           NWneW       << 6 |
666                           (N   != NE) << 5 |
667                           (NW  != N)  << 4 |
668                           (NWW != NW) << 3 |
669                           (NNE != NE) << 2 |
670                           (NN  != N)  << 1 |
671                           (NNW != NW);
672                     if (!ff_els_decode_bit(&dc->els_ctx, &dc->N_ctx_rung[idx])) {
673                         NWneW = 0;
674                         *pPix = N;
675                         got_pixel = 1;
676                         break;
677                     }
678                 }
679                 /* fall through */
680             default:
681                 NWneW = 1;
682                 old_WWneW = WWneW;
683                 if (!is_pixel_on_stack(dc, N))
684                     dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = N;
685             }
686         }
687
688         (*pRun)++;
689         if (x + *pRun >= tile_width - 1)
690             break;
691
692         UPDATE_NEIGHBOURS(x + *pRun);
693
694         if (!NWneW && NW == N && N == NE) {
695             int pos, run, rle;
696             int start_pos = x + *pRun;
697
698             /* scan for a run of pix in the line above */
699             uint32_t pix = above_row[start_pos + 1];
700             for (pos = start_pos + 2; pos < tile_width; pos++)
701                 if (!(above_row[pos] == pix))
702                     break;
703             run = pos - start_pos - 1;
704             idx = log2_ceil(run);
705             if (ff_els_decode_bit(&dc->els_ctx, &dc->prev_row_rung[idx]))
706                 *pRun += run;
707             else {
708                 int flag;
709                 /* run-length is coded as plain binary number of idx - 1 bits */
710                 for (pos = idx - 1, rle = 0, flag = 0; pos >= 0; pos--) {
711                     if ((1 << pos) + rle < run &&
712                         ff_els_decode_bit(&dc->els_ctx,
713                                           flag ? &dc->runlen_one
714                                                : &dc->runlen_zeroes[pos])) {
715                         flag = 1;
716                         rle |= 1 << pos;
717                     }
718                 }
719                 *pRun += rle;
720                 break; // return immediately
721             }
722             if (x + *pRun >= tile_width - 1)
723                 break;
724
725             LOAD_NEIGHBOURS(x + *pRun);
726             WWneW = 0;
727             NWneW = 0;
728         }
729
730         idx = WWneW       << 7 |
731               NWneW       << 6 |
732               (N   != NE) << 5 |
733               (NW  != N)  << 4 |
734               (NWW != NW) << 3 |
735               (NNE != NE) << 2 |
736               (NN  != N)  << 1 |
737               (NNW != NW);
738         WWneW = ff_els_decode_bit(&dc->els_ctx, &dc->W_ctx_rung[idx]);
739     } while (!WWneW);
740
741     dc->next_run_pos = x + *pRun;
742     return got_pixel;
743 }
744
745 static int epic_predict_pixel2(ePICContext *dc, uint8_t *rung,
746                                uint32_t *pPix, uint32_t pix)
747 {
748     if (ff_els_decode_bit(&dc->els_ctx, rung)) {
749         *pPix = pix;
750         return 1;
751     }
752     dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = pix;
753     return 0;
754 }
755
756 static int epic_predict_from_NW_NE(ePICContext *dc, int x, int y, int run,
757                                    int tile_width, const uint32_t *curr_row,
758                                    const uint32_t *above_row, uint32_t *pPix)
759 {
760     int pos;
761
762     /* try to reuse the NW pixel first */
763     if (x && y) {
764         uint32_t NW = above_row[x - 1];
765         if (NW != curr_row[x - 1] && NW != above_row[x] && !is_pixel_on_stack(dc, NW)) {
766             if (epic_predict_pixel2(dc, &dc->nw_pred_rung[NW & 0xFF], pPix, NW))
767                 return 1;
768         }
769     }
770
771     /* try to reuse the NE[x + run, y] pixel */
772     pos = x + run - 1;
773     if (pos < tile_width - 1 && y) {
774         uint32_t NE = above_row[pos + 1];
775         if (NE != above_row[pos] && !is_pixel_on_stack(dc, NE)) {
776             if (epic_predict_pixel2(dc, &dc->ne_pred_rung[NE & 0xFF], pPix, NE))
777                 return 1;
778         }
779     }
780
781     return 0;
782 }
783
784 static int epic_decode_from_cache(ePICContext *dc, uint32_t W, uint32_t *pPix)
785 {
786     ePICPixListElem *list, *prev = NULL;
787     ePICPixHashElem *hash_elem = epic_hash_find(&dc->hash, W);
788
789     if (!hash_elem || !hash_elem->list)
790         return 0;
791
792     list = hash_elem->list;
793     while (list) {
794         if (!is_pixel_on_stack(dc, list->pixel)) {
795             if (ff_els_decode_bit(&dc->els_ctx, &list->rung)) {
796                 *pPix = list->pixel;
797                 if (list != hash_elem->list) {
798                     prev->next      = list->next;
799                     list->next      = hash_elem->list;
800                     hash_elem->list = list;
801                 }
802                 return 1;
803             }
804             dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = list->pixel;
805         }
806         prev = list;
807         list = list->next;
808     }
809
810     return 0;
811 }
812
813 static int epic_decode_tile(ePICContext *dc, uint8_t *out, int tile_height,
814                             int tile_width, int stride)
815 {
816     int x, y;
817     uint32_t pix;
818     uint32_t *curr_row = NULL, *above_row = NULL, *above2_row;
819
820     for (y = 0; y < tile_height; y++, out += stride) {
821         above2_row = above_row;
822         above_row  = curr_row;
823         curr_row   = (uint32_t *) out;
824
825         for (x = 0, dc->next_run_pos = 0; x < tile_width;) {
826             if (dc->els_ctx.err)
827                 return AVERROR_INVALIDDATA; // bail out in the case of ELS overflow
828
829             pix = curr_row[x - 1]; // get W pixel
830
831             if (y >= 1 && x >= 2 &&
832                 pix != curr_row[x - 2]  && pix != above_row[x - 1] &&
833                 pix != above_row[x - 2] && pix != above_row[x] &&
834                 !epic_cache_entries_for_pixel(&dc->hash, pix)) {
835                 curr_row[x] = epic_decode_pixel_pred(dc, x, y, curr_row, above_row);
836                 x++;
837             } else {
838                 int got_pixel, run;
839                 dc->stack_pos = 0; // empty stack
840
841                 if (y < 2 || x < 2 || x == tile_width - 1) {
842                     run       = 1;
843                     got_pixel = epic_handle_edges(dc, x, y, curr_row, above_row, &pix);
844                 } else
845                     got_pixel = epic_decode_run_length(dc, x, y, tile_width,
846                                                        curr_row, above_row,
847                                                        above2_row, &pix, &run);
848
849                 if (!got_pixel && !epic_predict_from_NW_NE(dc, x, y, run,
850                                                            tile_width, curr_row,
851                                                            above_row, &pix)) {
852                     uint32_t ref_pix = curr_row[x - 1];
853                     if (!x || !epic_decode_from_cache(dc, ref_pix, &pix)) {
854                         pix = epic_decode_pixel_pred(dc, x, y, curr_row, above_row);
855                         if (x) {
856                             int ret = epic_add_pixel_to_cache(&dc->hash,
857                                                               ref_pix,
858                                                               pix);
859                             if (ret)
860                                 return ret;
861                         }
862                     }
863                 }
864                 for (; run > 0; x++, run--)
865                     curr_row[x] = pix;
866             }
867         }
868     }
869
870     return 0;
871 }
872
873 static int epic_jb_decode_tile(G2MContext *c, int tile_x, int tile_y,
874                                const uint8_t *src, size_t src_size,
875                                AVCodecContext *avctx)
876 {
877     uint8_t prefix, mask = 0x80;
878     int extrabytes, tile_width, tile_height, awidth, aheight;
879     size_t els_dsize;
880     uint8_t *dst;
881
882     if (!src_size)
883         return 0;
884
885     /* get data size of the ELS partition as unsigned variable-length integer */
886     prefix = *src++;
887     src_size--;
888     for (extrabytes = 0; (prefix & mask) && (extrabytes < 7); extrabytes++)
889         mask >>= 1;
890     if (extrabytes > 3 || src_size < extrabytes) {
891         av_log(avctx, AV_LOG_ERROR, "ePIC: invalid data size VLI\n");
892         return AVERROR_INVALIDDATA;
893     }
894
895     els_dsize = prefix & ((0x80 >> extrabytes) - 1); // mask out the length prefix
896     while (extrabytes-- > 0) {
897         els_dsize = (els_dsize << 8) | *src++;
898         src_size--;
899     }
900
901     if (src_size < els_dsize) {
902         av_log(avctx, AV_LOG_ERROR, "ePIC: data too short, needed %zu, got %zu\n",
903                els_dsize, src_size);
904         return AVERROR_INVALIDDATA;
905     }
906
907     tile_width  = FFMIN(c->width  - tile_x * c->tile_width,  c->tile_width);
908     tile_height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
909     awidth      = FFALIGN(tile_width,  16);
910     aheight     = FFALIGN(tile_height, 16);
911
912     if (els_dsize) {
913         int ret, i, j, k;
914         uint8_t tr_r, tr_g, tr_b, *buf;
915         uint32_t *in;
916         /* ELS decoder initializations */
917         memset(&c->ec, 0, sizeof(c->ec));
918         ff_els_decoder_init(&c->ec.els_ctx, src, els_dsize);
919         epic_hash_init(&c->ec.hash);
920
921         /* decode transparent pixel value */
922         tr_r = ff_els_decode_unsigned(&c->ec.els_ctx, &c->ec.unsigned_rung);
923         tr_g = ff_els_decode_unsigned(&c->ec.els_ctx, &c->ec.unsigned_rung);
924         tr_b = ff_els_decode_unsigned(&c->ec.els_ctx, &c->ec.unsigned_rung);
925         if (c->ec.els_ctx.err != 0) {
926             av_log(avctx, AV_LOG_ERROR,
927                    "ePIC: couldn't decode transparency pixel!\n");
928             return AVERROR_INVALIDDATA;
929         }
930
931         ret = epic_decode_tile(&c->ec, c->epic_buf, tile_height, tile_width,
932                                c->epic_buf_stride);
933
934         epic_free_pixel_cache(&c->ec.hash);
935         ff_els_decoder_uninit(&c->ec.unsigned_rung);
936
937         if (ret) {
938             av_log(avctx, AV_LOG_ERROR,
939                    "ePIC: tile decoding failed, frame=%d, tile_x=%d, tile_y=%d\n",
940                    avctx->frame_number, tile_x, tile_y);
941             return AVERROR_INVALIDDATA;
942         }
943
944         buf = c->epic_buf;
945         dst = c->framebuf + tile_x * c->tile_width * 3 +
946               tile_y * c->tile_height * c->framebuf_stride;
947
948         for (j = 0; j < tile_height; j++) {
949             uint8_t *out = dst;
950             in  = (uint32_t *) buf;
951             for (i = 0; i < tile_width; i++) {
952                 out[0] = (in[i] >> R_shift) & 0xFF;
953                 out[1] = (in[i] >> G_shift) & 0xFF;
954                 out[2] = (in[i] >> B_shift) & 0xFF;
955                 out   += 3;
956             }
957             buf += c->epic_buf_stride;
958             dst += c->framebuf_stride;
959         }
960
961         if (src_size > els_dsize) {
962             uint8_t *jpg;
963             uint32_t tr;
964             int bstride = FFALIGN(tile_width, 16) >> 3;
965             int nblocks = 0;
966             int estride = c->epic_buf_stride >> 2;
967
968             src      += els_dsize;
969             src_size -= els_dsize;
970
971             in = (uint32_t *) c->epic_buf;
972             tr = (tr_r << R_shift) | (tr_g << G_shift) | (tr_b << B_shift);
973
974             memset(c->kempf_flags, 0,
975                    (aheight >> 3) * bstride * sizeof(*c->kempf_flags));
976             for (j = 0; j < tile_height; j += 8) {
977                 for (i = 0; i < tile_width; i += 8) {
978                     c->kempf_flags[(i >> 3) + (j >> 3) * bstride] = 0;
979                     for (k = 0; k < 8 * 8; k++) {
980                         if (in[i + (k & 7) + (k >> 3) * estride] == tr) {
981                             c->kempf_flags[(i >> 3) + (j >> 3) * bstride] = 1;
982                             nblocks++;
983                             break;
984                         }
985                     }
986                 }
987                 in += 8 * estride;
988             }
989
990             memset(c->jpeg_tile, 0, c->tile_stride * aheight);
991             jpg_decode_data(&c->jc, awidth, aheight, src, src_size,
992                             c->jpeg_tile, c->tile_stride,
993                             c->kempf_flags, bstride, nblocks, c->swapuv);
994
995             in  = (uint32_t *) c->epic_buf;
996             dst = c->framebuf + tile_x * c->tile_width * 3 +
997                   tile_y * c->tile_height * c->framebuf_stride;
998             jpg = c->jpeg_tile;
999             for (j = 0; j < tile_height; j++) {
1000                 for (i = 0; i < tile_width; i++)
1001                     if (in[i] == tr)
1002                         memcpy(dst + i * 3, jpg + i * 3, 3);
1003                 in  += c->epic_buf_stride >> 2;
1004                 dst += c->framebuf_stride;
1005                 jpg += c->tile_stride;
1006             }
1007         }
1008     } else {
1009         dst = c->framebuf + tile_x * c->tile_width * 3 +
1010               tile_y * c->tile_height * c->framebuf_stride;
1011         return jpg_decode_data(&c->jc, tile_width, tile_height, src, src_size,
1012                                dst, c->framebuf_stride, NULL, 0, 0, c->swapuv);
1013     }
1014
1015     return 0;
1016 }
1017
1018 static void kempf_restore_buf(const uint8_t *src, int len,
1019                               uint8_t *dst, int stride,
1020                               const uint8_t *jpeg_tile, int tile_stride,
1021                               int width, int height,
1022                               const uint8_t *pal, int npal, int tidx)
1023 {
1024     GetBitContext gb;
1025     int i, j, nb, col;
1026     int align_width = FFALIGN(width, 16);
1027
1028     init_get_bits(&gb, src, len * 8);
1029
1030     if (npal <= 2)       nb = 1;
1031     else if (npal <= 4)  nb = 2;
1032     else if (npal <= 16) nb = 4;
1033     else                 nb = 8;
1034
1035     for (j = 0; j < height; j++, dst += stride, jpeg_tile += tile_stride) {
1036         if (get_bits(&gb, 8))
1037             continue;
1038         for (i = 0; i < width; i++) {
1039             col = get_bits(&gb, nb);
1040             if (col != tidx)
1041                 memcpy(dst + i * 3, pal + col * 3, 3);
1042             else
1043                 memcpy(dst + i * 3, jpeg_tile + i * 3, 3);
1044         }
1045         skip_bits_long(&gb, nb * (align_width - width));
1046     }
1047 }
1048
1049 static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,
1050                              const uint8_t *src, int src_size)
1051 {
1052     int width, height;
1053     int hdr, zsize, npal, tidx = -1, ret;
1054     int i, j;
1055     const uint8_t *src_end = src + src_size;
1056     uint8_t pal[768], transp[3];
1057     uLongf dlen = (c->tile_width + 1) * c->tile_height;
1058     int sub_type;
1059     int nblocks, cblocks, bstride;
1060     int bits, bitbuf, coded;
1061     uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +
1062                    tile_y * c->tile_height * c->framebuf_stride;
1063
1064     if (src_size < 2)
1065         return AVERROR_INVALIDDATA;
1066
1067     width  = FFMIN(c->width  - tile_x * c->tile_width,  c->tile_width);
1068     height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
1069
1070     hdr      = *src++;
1071     sub_type = hdr >> 5;
1072     if (sub_type == 0) {
1073         int j;
1074         memcpy(transp, src, 3);
1075         src += 3;
1076         for (j = 0; j < height; j++, dst += c->framebuf_stride)
1077             for (i = 0; i < width; i++)
1078                 memcpy(dst + i * 3, transp, 3);
1079         return 0;
1080     } else if (sub_type == 1) {
1081         return jpg_decode_data(&c->jc, width, height, src, src_end - src,
1082                                dst, c->framebuf_stride, NULL, 0, 0, 0);
1083     }
1084
1085     if (sub_type != 2) {
1086         memcpy(transp, src, 3);
1087         src += 3;
1088     }
1089     npal = *src++ + 1;
1090     memcpy(pal, src, npal * 3);
1091     src += npal * 3;
1092     if (sub_type != 2) {
1093         for (i = 0; i < npal; i++) {
1094             if (!memcmp(pal + i * 3, transp, 3)) {
1095                 tidx = i;
1096                 break;
1097             }
1098         }
1099     }
1100
1101     if (src_end - src < 2)
1102         return 0;
1103     zsize = (src[0] << 8) | src[1];
1104     src  += 2;
1105
1106     if (src_end - src < zsize)
1107         return AVERROR_INVALIDDATA;
1108
1109     ret = uncompress(c->kempf_buf, &dlen, src, zsize);
1110     if (ret)
1111         return AVERROR_INVALIDDATA;
1112     src += zsize;
1113
1114     if (sub_type == 2) {
1115         kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
1116                           NULL, 0, width, height, pal, npal, tidx);
1117         return 0;
1118     }
1119
1120     nblocks = *src++ + 1;
1121     cblocks = 0;
1122     bstride = FFALIGN(width, 16) >> 3;
1123     // blocks are coded LSB and we need normal bitreader for JPEG data
1124     bits = 0;
1125     for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {
1126         for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {
1127             if (!bits) {
1128                 bitbuf = *src++;
1129                 bits   = 8;
1130             }
1131             coded = bitbuf & 1;
1132             bits--;
1133             bitbuf >>= 1;
1134             cblocks += coded;
1135             if (cblocks > nblocks)
1136                 return AVERROR_INVALIDDATA;
1137             c->kempf_flags[j * 2 +      i * 2      * bstride] =
1138             c->kempf_flags[j * 2 + 1 +  i * 2      * bstride] =
1139             c->kempf_flags[j * 2 +     (i * 2 + 1) * bstride] =
1140             c->kempf_flags[j * 2 + 1 + (i * 2 + 1) * bstride] = coded;
1141         }
1142     }
1143
1144     memset(c->jpeg_tile, 0, c->tile_stride * height);
1145     jpg_decode_data(&c->jc, width, height, src, src_end - src,
1146                     c->jpeg_tile, c->tile_stride,
1147                     c->kempf_flags, bstride, nblocks * 4, 0);
1148
1149     kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
1150                       c->jpeg_tile, c->tile_stride,
1151                       width, height, pal, npal, tidx);
1152
1153     return 0;
1154 }
1155
1156 static int g2m_init_buffers(G2MContext *c)
1157 {
1158     int aligned_height;
1159
1160     if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
1161         c->framebuf_stride = FFALIGN(c->width * 3, 16);
1162         aligned_height     = FFALIGN(c->height,    16);
1163         av_free(c->framebuf);
1164         c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);
1165         if (!c->framebuf)
1166             return AVERROR(ENOMEM);
1167     }
1168     if (!c->synth_tile || !c->jpeg_tile ||
1169         (c->compression == 2 && !c->epic_buf_base) ||
1170         c->old_tile_w < c->tile_width ||
1171         c->old_tile_h < c->tile_height) {
1172         c->tile_stride     = FFALIGN(c->tile_width * 3, 16);
1173         c->epic_buf_stride = FFALIGN(c->tile_width * 4, 16);
1174         aligned_height     = FFALIGN(c->tile_height,    16);
1175         av_free(c->synth_tile);
1176         av_free(c->jpeg_tile);
1177         av_free(c->kempf_buf);
1178         av_free(c->kempf_flags);
1179         av_free(c->epic_buf_base);
1180         c->synth_tile  = av_mallocz(c->tile_stride      * aligned_height);
1181         c->jpeg_tile   = av_mallocz(c->tile_stride      * aligned_height);
1182         c->kempf_buf   = av_mallocz((c->tile_width + 1) * aligned_height +
1183                                     FF_INPUT_BUFFER_PADDING_SIZE);
1184         c->kempf_flags = av_mallocz(c->tile_width       * aligned_height);
1185         if (!c->synth_tile || !c->jpeg_tile ||
1186             !c->kempf_buf || !c->kempf_flags)
1187             return AVERROR(ENOMEM);
1188         if (c->compression == 2) {
1189             c->epic_buf_base = av_mallocz(c->epic_buf_stride * aligned_height + 4);
1190             if (!c->epic_buf_base)
1191                 return AVERROR(ENOMEM);
1192             c->epic_buf = c->epic_buf_base + 4;
1193         }
1194     }
1195
1196     return 0;
1197 }
1198
1199 static int g2m_load_cursor(AVCodecContext *avctx, G2MContext *c,
1200                            GetByteContext *gb)
1201 {
1202     int i, j, k;
1203     uint8_t *dst;
1204     uint32_t bits;
1205     uint32_t cur_size, cursor_w, cursor_h, cursor_stride;
1206     uint32_t cursor_hot_x, cursor_hot_y;
1207     int cursor_fmt, err;
1208
1209     cur_size     = bytestream2_get_be32(gb);
1210     cursor_w     = bytestream2_get_byte(gb);
1211     cursor_h     = bytestream2_get_byte(gb);
1212     cursor_hot_x = bytestream2_get_byte(gb);
1213     cursor_hot_y = bytestream2_get_byte(gb);
1214     cursor_fmt   = bytestream2_get_byte(gb);
1215
1216     cursor_stride = FFALIGN(cursor_w, 32) * 4;
1217
1218     if (cursor_w < 1 || cursor_w > 256 ||
1219         cursor_h < 1 || cursor_h > 256) {
1220         av_log(avctx, AV_LOG_ERROR, "Invalid cursor dimensions %"PRIu32"x%"PRIu32"\n",
1221                cursor_w, cursor_h);
1222         return AVERROR_INVALIDDATA;
1223     }
1224     if (cursor_hot_x > cursor_w || cursor_hot_y > cursor_h) {
1225         av_log(avctx, AV_LOG_WARNING, "Invalid hotspot position %"PRIu32",%"PRIu32"\n",
1226                cursor_hot_x, cursor_hot_y);
1227         cursor_hot_x = FFMIN(cursor_hot_x, cursor_w - 1);
1228         cursor_hot_y = FFMIN(cursor_hot_y, cursor_h - 1);
1229     }
1230     if (cur_size - 9 > bytestream2_get_bytes_left(gb) ||
1231         c->cursor_w * c->cursor_h / 4 > cur_size) {
1232         av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %"PRIu32"/%u\n",
1233                cur_size, bytestream2_get_bytes_left(gb));
1234         return AVERROR_INVALIDDATA;
1235     }
1236     if (cursor_fmt != 1 && cursor_fmt != 32) {
1237         avpriv_report_missing_feature(avctx, "Cursor format %d",
1238                                       cursor_fmt);
1239         return AVERROR_PATCHWELCOME;
1240     }
1241
1242     if ((err = av_reallocp(&c->cursor, cursor_stride * cursor_h)) < 0) {
1243         av_log(avctx, AV_LOG_ERROR, "Cannot allocate cursor buffer\n");
1244         return err;
1245     }
1246
1247     c->cursor_w      = cursor_w;
1248     c->cursor_h      = cursor_h;
1249     c->cursor_hot_x  = cursor_hot_x;
1250     c->cursor_hot_y  = cursor_hot_y;
1251     c->cursor_fmt    = cursor_fmt;
1252     c->cursor_stride = cursor_stride;
1253
1254     dst = c->cursor;
1255     switch (c->cursor_fmt) {
1256     case 1: // old monochrome
1257         for (j = 0; j < c->cursor_h; j++) {
1258             for (i = 0; i < c->cursor_w; i += 32) {
1259                 bits = bytestream2_get_be32(gb);
1260                 for (k = 0; k < 32; k++) {
1261                     dst[0] = !!(bits & 0x80000000);
1262                     dst   += 4;
1263                     bits <<= 1;
1264                 }
1265             }
1266             dst += c->cursor_stride - c->cursor_w * 4;
1267         }
1268
1269         dst = c->cursor;
1270         for (j = 0; j < c->cursor_h; j++) {
1271             for (i = 0; i < c->cursor_w; i += 32) {
1272                 bits = bytestream2_get_be32(gb);
1273                 for (k = 0; k < 32; k++) {
1274                     int mask_bit = !!(bits & 0x80000000);
1275                     switch (dst[0] * 2 + mask_bit) {
1276                     case 0:
1277                         dst[0] = 0xFF;
1278                         dst[1] = 0x00;
1279                         dst[2] = 0x00;
1280                         dst[3] = 0x00;
1281                         break;
1282                     case 1:
1283                         dst[0] = 0xFF;
1284                         dst[1] = 0xFF;
1285                         dst[2] = 0xFF;
1286                         dst[3] = 0xFF;
1287                         break;
1288                     default:
1289                         dst[0] = 0x00;
1290                         dst[1] = 0x00;
1291                         dst[2] = 0x00;
1292                         dst[3] = 0x00;
1293                     }
1294                     dst   += 4;
1295                     bits <<= 1;
1296                 }
1297             }
1298             dst += c->cursor_stride - c->cursor_w * 4;
1299         }
1300         break;
1301     case 32: // full colour
1302         /* skip monochrome version of the cursor and decode RGBA instead */
1303         bytestream2_skip(gb, c->cursor_h * (FFALIGN(c->cursor_w, 32) >> 3));
1304         for (j = 0; j < c->cursor_h; j++) {
1305             for (i = 0; i < c->cursor_w; i++) {
1306                 int val = bytestream2_get_be32(gb);
1307                 *dst++ = val >>  0;
1308                 *dst++ = val >>  8;
1309                 *dst++ = val >> 16;
1310                 *dst++ = val >> 24;
1311             }
1312             dst += c->cursor_stride - c->cursor_w * 4;
1313         }
1314         break;
1315     default:
1316         return AVERROR_PATCHWELCOME;
1317     }
1318     return 0;
1319 }
1320
1321 #define APPLY_ALPHA(src, new, alpha) \
1322     src = (src * (256 - alpha) + new * alpha) >> 8
1323
1324 static void g2m_paint_cursor(G2MContext *c, uint8_t *dst, int stride)
1325 {
1326     int i, j;
1327     int x, y, w, h;
1328     const uint8_t *cursor;
1329
1330     if (!c->cursor)
1331         return;
1332
1333     x = c->cursor_x - c->cursor_hot_x;
1334     y = c->cursor_y - c->cursor_hot_y;
1335
1336     cursor = c->cursor;
1337     w      = c->cursor_w;
1338     h      = c->cursor_h;
1339
1340     if (x + w > c->width)
1341         w = c->width - x;
1342     if (y + h > c->height)
1343         h = c->height - y;
1344     if (x < 0) {
1345         w      +=  x;
1346         cursor += -x * 4;
1347     } else {
1348         dst    +=  x * 3;
1349     }
1350     if (y < 0) {
1351         h      +=  y;
1352         cursor += -y * c->cursor_stride;
1353     } else {
1354         dst    +=  y * stride;
1355     }
1356     if (w < 0 || h < 0)
1357         return;
1358
1359     for (j = 0; j < h; j++) {
1360         for (i = 0; i < w; i++) {
1361             uint8_t alpha = cursor[i * 4];
1362             APPLY_ALPHA(dst[i * 3 + 0], cursor[i * 4 + 1], alpha);
1363             APPLY_ALPHA(dst[i * 3 + 1], cursor[i * 4 + 2], alpha);
1364             APPLY_ALPHA(dst[i * 3 + 2], cursor[i * 4 + 3], alpha);
1365         }
1366         dst    += stride;
1367         cursor += c->cursor_stride;
1368     }
1369 }
1370
1371 static int g2m_decode_frame(AVCodecContext *avctx, void *data,
1372                             int *got_picture_ptr, AVPacket *avpkt)
1373 {
1374     const uint8_t *buf = avpkt->data;
1375     int buf_size = avpkt->size;
1376     G2MContext *c = avctx->priv_data;
1377     AVFrame *pic = data;
1378     GetByteContext bc, tbc;
1379     int magic;
1380     int got_header = 0;
1381     uint32_t chunk_size, r_mask, g_mask, b_mask;
1382     int chunk_type, chunk_start;
1383     int i;
1384     int ret;
1385
1386     if (buf_size < 12) {
1387         av_log(avctx, AV_LOG_ERROR,
1388                "Frame should have at least 12 bytes, got %d instead\n",
1389                buf_size);
1390         return AVERROR_INVALIDDATA;
1391     }
1392
1393     bytestream2_init(&bc, buf, buf_size);
1394
1395     magic = bytestream2_get_be32(&bc);
1396     if ((magic & ~0xF) != MKBETAG('G', '2', 'M', '0') ||
1397         (magic & 0xF) < 2 || (magic & 0xF) > 5) {
1398         av_log(avctx, AV_LOG_ERROR, "Wrong magic %08X\n", magic);
1399         return AVERROR_INVALIDDATA;
1400     }
1401
1402     c->swapuv = magic == MKBETAG('G', '2', 'M', '2');
1403
1404     while (bytestream2_get_bytes_left(&bc) > 5) {
1405         chunk_size  = bytestream2_get_le32(&bc) - 1;
1406         chunk_type  = bytestream2_get_byte(&bc);
1407         chunk_start = bytestream2_tell(&bc);
1408         if (chunk_size > bytestream2_get_bytes_left(&bc)) {
1409             av_log(avctx, AV_LOG_ERROR, "Invalid chunk size %"PRIu32" type %02X\n",
1410                    chunk_size, chunk_type);
1411             break;
1412         }
1413         switch (chunk_type) {
1414         case DISPLAY_INFO:
1415             c->got_header = 0;
1416             if (chunk_size < 21) {
1417                 av_log(avctx, AV_LOG_ERROR, "Invalid display info size %"PRIu32"\n",
1418                        chunk_size);
1419                 break;
1420             }
1421             c->width  = bytestream2_get_be32(&bc);
1422             c->height = bytestream2_get_be32(&bc);
1423             if (c->width  < 16 || c->width  > c->orig_width ||
1424                 c->height < 16 || c->height > c->orig_height) {
1425                 av_log(avctx, AV_LOG_ERROR,
1426                        "Invalid frame dimensions %dx%d\n",
1427                        c->width, c->height);
1428                 ret = AVERROR_INVALIDDATA;
1429                 goto header_fail;
1430             }
1431             if (c->width != avctx->width || c->height != avctx->height) {
1432                 ret = ff_set_dimensions(avctx, c->width, c->height);
1433                 if (ret < 0)
1434                     return ret;
1435             }
1436             c->compression = bytestream2_get_be32(&bc);
1437             if (c->compression != 2 && c->compression != 3) {
1438                 av_log(avctx, AV_LOG_ERROR,
1439                        "Unknown compression method %d\n",
1440                        c->compression);
1441                 return AVERROR_PATCHWELCOME;
1442             }
1443             c->tile_width  = bytestream2_get_be32(&bc);
1444             c->tile_height = bytestream2_get_be32(&bc);
1445             if (!c->tile_width || !c->tile_height ||
1446                 ((c->tile_width | c->tile_height) & 0xF)) {
1447                 av_log(avctx, AV_LOG_ERROR,
1448                        "Invalid tile dimensions %dx%d\n",
1449                        c->tile_width, c->tile_height);
1450                 ret = AVERROR_INVALIDDATA;
1451                 goto header_fail;
1452             }
1453             c->tiles_x = (c->width  + c->tile_width  - 1) / c->tile_width;
1454             c->tiles_y = (c->height + c->tile_height - 1) / c->tile_height;
1455             c->bpp     = bytestream2_get_byte(&bc);
1456             if (c->bpp == 32) {
1457                 if (bytestream2_get_bytes_left(&bc) < 16 ||
1458                     (chunk_size - 21) < 16) {
1459                     av_log(avctx, AV_LOG_ERROR,
1460                            "Display info: missing bitmasks!\n");
1461                     return AVERROR_INVALIDDATA;
1462                 }
1463                 r_mask = bytestream2_get_be32(&bc);
1464                 g_mask = bytestream2_get_be32(&bc);
1465                 b_mask = bytestream2_get_be32(&bc);
1466                 if (r_mask != 0xFF0000 || g_mask != 0xFF00 || b_mask != 0xFF) {
1467                     av_log(avctx, AV_LOG_ERROR,
1468                            "Invalid or unsupported bitmasks: R=%"PRIX32", G=%"PRIX32", B=%"PRIX32"\n",
1469                            r_mask, g_mask, b_mask);
1470                     return AVERROR_PATCHWELCOME;
1471                 }
1472             } else {
1473                 avpriv_request_sample(avctx, "bpp=%d", c->bpp);
1474                 return AVERROR_PATCHWELCOME;
1475             }
1476             if (g2m_init_buffers(c)) {
1477                 ret = AVERROR(ENOMEM);
1478                 goto header_fail;
1479             }
1480             got_header = 1;
1481             break;
1482         case TILE_DATA:
1483             if (!c->tiles_x || !c->tiles_y) {
1484                 av_log(avctx, AV_LOG_WARNING,
1485                        "No display info - skipping tile\n");
1486                 break;
1487             }
1488             if (chunk_size < 2) {
1489                 av_log(avctx, AV_LOG_ERROR, "Invalid tile data size %"PRIu32"\n",
1490                        chunk_size);
1491                 break;
1492             }
1493             c->tile_x = bytestream2_get_byte(&bc);
1494             c->tile_y = bytestream2_get_byte(&bc);
1495             if (c->tile_x >= c->tiles_x || c->tile_y >= c->tiles_y) {
1496                 av_log(avctx, AV_LOG_ERROR,
1497                        "Invalid tile pos %d,%d (in %dx%d grid)\n",
1498                        c->tile_x, c->tile_y, c->tiles_x, c->tiles_y);
1499                 break;
1500             }
1501             ret = 0;
1502             switch (c->compression) {
1503             case COMPR_EPIC_J_B:
1504                 ret = epic_jb_decode_tile(c, c->tile_x, c->tile_y,
1505                                           buf + bytestream2_tell(&bc),
1506                                           chunk_size - 2, avctx);
1507                 break;
1508             case COMPR_KEMPF_J_B:
1509                 ret = kempf_decode_tile(c, c->tile_x, c->tile_y,
1510                                         buf + bytestream2_tell(&bc),
1511                                         chunk_size - 2);
1512                 break;
1513             }
1514             if (ret && c->framebuf)
1515                 av_log(avctx, AV_LOG_ERROR, "Error decoding tile %d,%d\n",
1516                        c->tile_x, c->tile_y);
1517             break;
1518         case CURSOR_POS:
1519             if (chunk_size < 5) {
1520                 av_log(avctx, AV_LOG_ERROR, "Invalid cursor pos size %"PRIu32"\n",
1521                        chunk_size);
1522                 break;
1523             }
1524             c->cursor_x = bytestream2_get_be16(&bc);
1525             c->cursor_y = bytestream2_get_be16(&bc);
1526             break;
1527         case CURSOR_SHAPE:
1528             if (chunk_size < 8) {
1529                 av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %"PRIu32"\n",
1530                        chunk_size);
1531                 break;
1532             }
1533             bytestream2_init(&tbc, buf + bytestream2_tell(&bc),
1534                              chunk_size - 4);
1535             g2m_load_cursor(avctx, c, &tbc);
1536             break;
1537         case CHUNK_CC:
1538         case CHUNK_CD:
1539             break;
1540         default:
1541             av_log(avctx, AV_LOG_WARNING, "Skipping chunk type %02d\n",
1542                    chunk_type);
1543         }
1544
1545         /* navigate to next chunk */
1546         bytestream2_skip(&bc, chunk_start + chunk_size - bytestream2_tell(&bc));
1547     }
1548     if (got_header)
1549         c->got_header = 1;
1550
1551     if (c->width && c->height) {
1552         if ((ret = ff_get_buffer(avctx, pic, 0)) < 0) {
1553             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1554             return ret;
1555         }
1556
1557         pic->key_frame = got_header;
1558         pic->pict_type = got_header ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
1559
1560         for (i = 0; i < avctx->height; i++)
1561             memcpy(pic->data[0] + i * pic->linesize[0],
1562                    c->framebuf + i * c->framebuf_stride,
1563                    c->width * 3);
1564         g2m_paint_cursor(c, pic->data[0], pic->linesize[0]);
1565
1566         *got_picture_ptr = 1;
1567     }
1568
1569     return buf_size;
1570
1571 header_fail:
1572     c->width   =
1573     c->height  = 0;
1574     c->tiles_x =
1575     c->tiles_y = 0;
1576     return ret;
1577 }
1578
1579 static av_cold int g2m_decode_init(AVCodecContext *avctx)
1580 {
1581     G2MContext *const c = avctx->priv_data;
1582     int ret;
1583
1584     if ((ret = jpg_init(avctx, &c->jc)) != 0) {
1585         av_log(avctx, AV_LOG_ERROR, "Cannot initialise VLCs\n");
1586         jpg_free_context(&c->jc);
1587         return AVERROR(ENOMEM);
1588     }
1589
1590     avctx->pix_fmt = AV_PIX_FMT_RGB24;
1591
1592     // store original sizes and check against those if resize happens
1593     c->orig_width  = avctx->width;
1594     c->orig_height = avctx->height;
1595
1596     return 0;
1597 }
1598
1599 static av_cold int g2m_decode_end(AVCodecContext *avctx)
1600 {
1601     G2MContext *const c = avctx->priv_data;
1602
1603     jpg_free_context(&c->jc);
1604
1605     av_freep(&c->epic_buf_base);
1606     av_freep(&c->kempf_buf);
1607     av_freep(&c->kempf_flags);
1608     av_freep(&c->synth_tile);
1609     av_freep(&c->jpeg_tile);
1610     av_freep(&c->cursor);
1611     av_freep(&c->framebuf);
1612
1613     return 0;
1614 }
1615
1616 AVCodec ff_g2m_decoder = {
1617     .name           = "g2m",
1618     .long_name      = NULL_IF_CONFIG_SMALL("Go2Meeting"),
1619     .type           = AVMEDIA_TYPE_VIDEO,
1620     .id             = AV_CODEC_ID_G2M,
1621     .priv_data_size = sizeof(G2MContext),
1622     .init           = g2m_decode_init,
1623     .close          = g2m_decode_end,
1624     .decode         = g2m_decode_frame,
1625     .capabilities   = CODEC_CAP_DR1,
1626     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
1627 };