Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

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