GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/g2meet.c Lines: 781 910 85.8 %
Date: 2021-01-26 01:16:58 Branches: 476 606 78.5 %

Line Branch Exec Source
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/imgutils.h"
32
#include "libavutil/intreadwrite.h"
33
#include "libavutil/mem_internal.h"
34
35
#include "avcodec.h"
36
#include "blockdsp.h"
37
#include "bytestream.h"
38
#include "elsdec.h"
39
#include "get_bits.h"
40
#include "idctdsp.h"
41
#include "internal.h"
42
#include "jpegtables.h"
43
#include "mjpeg.h"
44
45
#define EPIC_PIX_STACK_SIZE 1024
46
#define EPIC_PIX_STACK_MAX  (EPIC_PIX_STACK_SIZE - 1)
47
48
enum ChunkType {
49
    DISPLAY_INFO = 0xC8,
50
    TILE_DATA,
51
    CURSOR_POS,
52
    CURSOR_SHAPE,
53
    CHUNK_CC,
54
    CHUNK_CD
55
};
56
57
enum Compression {
58
    COMPR_EPIC_J_B = 2,
59
    COMPR_KEMPF_J_B,
60
};
61
62
static const uint8_t luma_quant[64] = {
63
     8,  6,  5,  8, 12, 20, 26, 31,
64
     6,  6,  7, 10, 13, 29, 30, 28,
65
     7,  7,  8, 12, 20, 29, 35, 28,
66
     7,  9, 11, 15, 26, 44, 40, 31,
67
     9, 11, 19, 28, 34, 55, 52, 39,
68
    12, 18, 28, 32, 41, 52, 57, 46,
69
    25, 32, 39, 44, 52, 61, 60, 51,
70
    36, 46, 48, 49, 56, 50, 52, 50
71
};
72
73
static const uint8_t chroma_quant[64] = {
74
     9,  9, 12, 24, 50, 50, 50, 50,
75
     9, 11, 13, 33, 50, 50, 50, 50,
76
    12, 13, 28, 50, 50, 50, 50, 50,
77
    24, 33, 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
    50, 50, 50, 50, 50, 50, 50, 50,
81
    50, 50, 50, 50, 50, 50, 50, 50,
82
};
83
84
typedef struct ePICPixListElem {
85
    struct ePICPixListElem *next;
86
    uint32_t               pixel;
87
    uint8_t                rung;
88
} ePICPixListElem;
89
90
typedef struct ePICPixHashElem {
91
    uint32_t                pix_id;
92
    struct ePICPixListElem  *list;
93
} ePICPixHashElem;
94
95
#define EPIC_HASH_SIZE 256
96
typedef struct ePICPixHash {
97
    ePICPixHashElem *bucket[EPIC_HASH_SIZE];
98
    int              bucket_size[EPIC_HASH_SIZE];
99
    int              bucket_fill[EPIC_HASH_SIZE];
100
} ePICPixHash;
101
102
typedef struct ePICContext {
103
    ElsDecCtx        els_ctx;
104
    int              next_run_pos;
105
    ElsUnsignedRung  unsigned_rung;
106
    uint8_t          W_flag_rung;
107
    uint8_t          N_flag_rung;
108
    uint8_t          W_ctx_rung[256];
109
    uint8_t          N_ctx_rung[512];
110
    uint8_t          nw_pred_rung[256];
111
    uint8_t          ne_pred_rung[256];
112
    uint8_t          prev_row_rung[14];
113
    uint8_t          runlen_zeroes[14];
114
    uint8_t          runlen_one;
115
    int              stack_pos;
116
    uint32_t         stack[EPIC_PIX_STACK_SIZE];
117
    ePICPixHash      hash;
118
} ePICContext;
119
120
typedef struct JPGContext {
121
    BlockDSPContext bdsp;
122
    IDCTDSPContext idsp;
123
    ScanTable  scantable;
124
125
    VLC        dc_vlc[2], ac_vlc[2];
126
    int        prev_dc[3];
127
    DECLARE_ALIGNED(32, int16_t, block)[6][64];
128
129
    uint8_t    *buf;
130
} JPGContext;
131
132
typedef struct G2MContext {
133
    ePICContext ec;
134
    JPGContext jc;
135
136
    int        version;
137
138
    int        compression;
139
    int        width, height, bpp;
140
    int        orig_width, orig_height;
141
    int        tile_width, tile_height;
142
    int        tiles_x, tiles_y, tile_x, tile_y;
143
144
    int        got_header;
145
146
    uint8_t    *framebuf;
147
    int        framebuf_stride, old_width, old_height;
148
149
    uint8_t    *synth_tile, *jpeg_tile, *epic_buf, *epic_buf_base;
150
    int        tile_stride, epic_buf_stride, old_tile_w, old_tile_h;
151
    int        swapuv;
152
153
    uint8_t    *kempf_buf, *kempf_flags;
154
155
    uint8_t    *cursor;
156
    int        cursor_stride;
157
    int        cursor_fmt;
158
    int        cursor_w, cursor_h, cursor_x, cursor_y;
159
    int        cursor_hot_x, cursor_hot_y;
160
} G2MContext;
161
162
24
static av_cold int build_vlc(VLC *vlc, const uint8_t *bits_table,
163
                             const uint8_t *val_table, int nb_codes,
164
                             int is_ac)
165
{
166
24
    uint8_t  huff_size[256] = { 0 };
167
    uint16_t huff_code[256];
168
    uint16_t huff_sym[256];
169
    int i;
170
171
24
    ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
172
173
6168
    for (i = 0; i < 256; i++)
174
6144
        huff_sym[i] = i + 16 * is_ac;
175
176
24
    if (is_ac)
177
12
        huff_sym[0] = 16 * 256;
178
179
24
    return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
180
                              huff_code, 2, 2, huff_sym, 2, 2, 0);
181
}
182
183
6
static av_cold int jpg_init(AVCodecContext *avctx, JPGContext *c)
184
{
185
    int ret;
186
187
6
    ret = build_vlc(&c->dc_vlc[0], avpriv_mjpeg_bits_dc_luminance,
188
                    avpriv_mjpeg_val_dc, 12, 0);
189
6
    if (ret)
190
        return ret;
191
6
    ret = build_vlc(&c->dc_vlc[1], avpriv_mjpeg_bits_dc_chrominance,
192
                    avpriv_mjpeg_val_dc, 12, 0);
193
6
    if (ret)
194
        return ret;
195
6
    ret = build_vlc(&c->ac_vlc[0], avpriv_mjpeg_bits_ac_luminance,
196
                    avpriv_mjpeg_val_ac_luminance, 251, 1);
197
6
    if (ret)
198
        return ret;
199
6
    ret = build_vlc(&c->ac_vlc[1], avpriv_mjpeg_bits_ac_chrominance,
200
                    avpriv_mjpeg_val_ac_chrominance, 251, 1);
201
6
    if (ret)
202
        return ret;
203
204
6
    ff_blockdsp_init(&c->bdsp, avctx);
205
6
    ff_idctdsp_init(&c->idsp, avctx);
206
6
    ff_init_scantable(c->idsp.idct_permutation, &c->scantable,
207
                      ff_zigzag_direct);
208
209
6
    return 0;
210
}
211
212
6
static av_cold void jpg_free_context(JPGContext *ctx)
213
{
214
    int i;
215
216
18
    for (i = 0; i < 2; i++) {
217
12
        ff_free_vlc(&ctx->dc_vlc[i]);
218
12
        ff_free_vlc(&ctx->ac_vlc[i]);
219
    }
220
221
6
    av_freep(&ctx->buf);
222
6
}
223
224
159
static void jpg_unescape(const uint8_t *src, int src_size,
225
                         uint8_t *dst, int *dst_size)
226
{
227
159
    const uint8_t *src_end = src + src_size;
228
159
    uint8_t *dst_start = dst;
229
230
155218
    while (src < src_end) {
231
155059
        uint8_t x = *src++;
232
233
155059
        *dst++ = x;
234
235

155059
        if (x == 0xFF && !*src)
236
893
            src++;
237
    }
238
159
    *dst_size = dst - dst_start;
239
159
}
240
241
38284
static int jpg_decode_block(JPGContext *c, GetBitContext *gb,
242
                            int plane, int16_t *block)
243
{
244
    int dc, val, pos;
245
38284
    const int is_chroma = !!plane;
246
38284
    const uint8_t *qmat = is_chroma ? chroma_quant : luma_quant;
247
248
38284
    if (get_bits_left(gb) < 1)
249
        return AVERROR_INVALIDDATA;
250
251
38284
    c->bdsp.clear_block(block);
252
38284
    dc = get_vlc2(gb, c->dc_vlc[is_chroma].table, 9, 2);
253
38284
    if (dc < 0)
254
        return AVERROR_INVALIDDATA;
255
38284
    if (dc)
256
22214
        dc = get_xbits(gb, dc);
257
38284
    dc                = dc * qmat[0] + c->prev_dc[plane];
258
38284
    block[0]          = dc;
259
38284
    c->prev_dc[plane] = dc;
260
261
38284
    pos = 0;
262
225358
    while (pos < 63) {
263
224976
        val = get_vlc2(gb, c->ac_vlc[is_chroma].table, 9, 2);
264
224976
        if (val < 0)
265
            return AVERROR_INVALIDDATA;
266
224976
        pos += val >> 4;
267
224976
        val &= 0xF;
268
224976
        if (pos > 63)
269
37902
            return val ? AVERROR_INVALIDDATA : 0;
270
187074
        if (val) {
271
186680
            int nbits = val;
272
273
186680
            val                                 = get_xbits(gb, nbits);
274
186680
            val                                *= qmat[ff_zigzag_direct[pos]];
275
186680
            block[c->scantable.permutated[pos]] = val;
276
        }
277
    }
278
382
    return 0;
279
}
280
281
1684224
static inline void yuv2rgb(uint8_t *out, int ridx, int Y, int U, int V)
282
{
283
1684224
    out[ridx]     = av_clip_uint8(Y +              (91881 * V + 32768 >> 16));
284
1684224
    out[1]        = av_clip_uint8(Y + (-22554 * U - 46802 * V + 32768 >> 16));
285
1684224
    out[2 - ridx] = av_clip_uint8(Y + (116130 * U             + 32768 >> 16));
286
1684224
}
287
288
159
static int jpg_decode_data(JPGContext *c, int width, int height,
289
                           const uint8_t *src, int src_size,
290
                           uint8_t *dst, int dst_stride,
291
                           const uint8_t *mask, int mask_stride, int num_mbs,
292
                           int swapuv)
293
{
294
    GetBitContext gb;
295
    int mb_w, mb_h, mb_x, mb_y, i, j;
296
    int bx, by;
297
    int unesc_size;
298
    int ret;
299
159
    const int ridx = swapuv ? 2 : 0;
300
301
159
    if ((ret = av_reallocp(&c->buf,
302
159
                           src_size + AV_INPUT_BUFFER_PADDING_SIZE)) < 0)
303
        return ret;
304
159
    jpg_unescape(src, src_size, c->buf, &unesc_size);
305
159
    memset(c->buf + unesc_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
306
159
    if((ret = init_get_bits8(&gb, c->buf, unesc_size)) < 0)
307
        return ret;
308
309
159
    width = FFALIGN(width, 16);
310
159
    mb_w  =  width        >> 4;
311
159
    mb_h  = (height + 15) >> 4;
312
313
159
    if (!num_mbs)
314
        num_mbs = mb_w * mb_h * 4;
315
316
636
    for (i = 0; i < 3; i++)
317
477
        c->prev_dc[i] = 1024;
318
159
    bx =
319
159
    by = 0;
320
159
    c->bdsp.clear_blocks(c->block[0]);
321
1069
    for (mb_y = 0; mb_y < mb_h; mb_y++) {
322
11926
        for (mb_x = 0; mb_x < mb_w; mb_x++) {
323

11016
            if (mask && !mask[mb_x * 2] && !mask[mb_x * 2 + 1] &&
324
4574
                !mask[mb_x * 2 +     mask_stride] &&
325
4458
                !mask[mb_x * 2 + 1 + mask_stride]) {
326
4437
                bx += 16;
327
4437
                continue;
328
            }
329
19737
            for (j = 0; j < 2; j++) {
330
39474
                for (i = 0; i < 2; i++) {
331

26316
                    if (mask && !mask[mb_x * 2 + i + j * mask_stride])
332
1190
                        continue;
333
25126
                    num_mbs--;
334
25126
                    if ((ret = jpg_decode_block(c, &gb, 0,
335
25126
                                                c->block[i + j * 2])) != 0)
336
                        return ret;
337
25126
                    c->idsp.idct(c->block[i + j * 2]);
338
                }
339
            }
340
19737
            for (i = 1; i < 3; i++) {
341
13158
                if ((ret = jpg_decode_block(c, &gb, i, c->block[i + 3])) != 0)
342
                    return ret;
343
13158
                c->idsp.idct(c->block[i + 3]);
344
            }
345
346
111843
            for (j = 0; j < 16; j++) {
347
105264
                uint8_t *out = dst + bx * 3 + (by + j) * dst_stride;
348
1789488
                for (i = 0; i < 16; i++) {
349
                    int Y, U, V;
350
351
1684224
                    Y = c->block[(j >> 3) * 2 + (i >> 3)][(i & 7) + (j & 7) * 8];
352
1684224
                    U = c->block[4][(i >> 1) + (j >> 1) * 8] - 128;
353
1684224
                    V = c->block[5][(i >> 1) + (j >> 1) * 8] - 128;
354
1684224
                    yuv2rgb(out + i * 3, ridx, Y, U, V);
355
                }
356
            }
357
358
6579
            if (!num_mbs)
359
159
                return 0;
360
6420
            bx += 16;
361
        }
362
910
        bx  = 0;
363
910
        by += 16;
364
910
        if (mask)
365
910
            mask += mask_stride * 2;
366
    }
367
368
    return 0;
369
}
370
371
#define LOAD_NEIGHBOURS(x)      \
372
    W   = curr_row[(x)   - 1];  \
373
    N   = above_row[(x)];       \
374
    WW  = curr_row[(x)   - 2];  \
375
    NW  = above_row[(x)  - 1];  \
376
    NE  = above_row[(x)  + 1];  \
377
    NN  = above2_row[(x)];      \
378
    NNW = above2_row[(x) - 1];  \
379
    NWW = above_row[(x)  - 2];  \
380
    NNE = above2_row[(x) + 1]
381
382
#define UPDATE_NEIGHBOURS(x)    \
383
    NNW = NN;                   \
384
    NN  = NNE;                  \
385
    NWW = NW;                   \
386
    NW  = N;                    \
387
    N   = NE;                   \
388
    NE  = above_row[(x)  + 1];  \
389
    NNE = above2_row[(x) + 1]
390
391
#define R_shift 16
392
#define G_shift  8
393
#define B_shift  0
394
395
/* improved djb2 hash from http://www.cse.yorku.ca/~oz/hash.html */
396
97781
static int djb2_hash(uint32_t key)
397
{
398
97781
    uint32_t h = 5381;
399
400
97781
    h = (h * 33) ^ ((key >> 24) & 0xFF); // xxx: probably not needed at all
401
97781
    h = (h * 33) ^ ((key >> 16) & 0xFF);
402
97781
    h = (h * 33) ^ ((key >>  8) & 0xFF);
403
97781
    h = (h * 33) ^  (key        & 0xFF);
404
405
97781
    return h & (EPIC_HASH_SIZE - 1);
406
}
407
408
136
static void epic_hash_init(ePICPixHash *hash)
409
{
410
136
    memset(hash, 0, sizeof(*hash));
411
136
}
412
413
97247
static ePICPixHashElem *epic_hash_find(const ePICPixHash *hash, uint32_t key)
414
{
415
97247
    int i, idx = djb2_hash(key);
416
97247
    ePICPixHashElem *bucket = hash->bucket[idx];
417
418
97299
    for (i = 0; i < hash->bucket_fill[idx]; i++)
419
94232
        if (bucket[i].pix_id == key)
420
94180
            return &bucket[i];
421
422
3067
    return NULL;
423
}
424
425
534
static ePICPixHashElem *epic_hash_add(ePICPixHash *hash, uint32_t key)
426
{
427
    ePICPixHashElem *bucket, *ret;
428
534
    int idx = djb2_hash(key);
429
430
534
    if (hash->bucket_size[idx] > INT_MAX / sizeof(**hash->bucket))
431
        return NULL;
432
433
534
    if (!(hash->bucket_fill[idx] < hash->bucket_size[idx])) {
434
531
        int new_size = hash->bucket_size[idx] + 16;
435
531
        bucket = av_realloc(hash->bucket[idx], new_size * sizeof(*bucket));
436
531
        if (!bucket)
437
            return NULL;
438
531
        hash->bucket[idx]      = bucket;
439
531
        hash->bucket_size[idx] = new_size;
440
    }
441
442
534
    ret = &hash->bucket[idx][hash->bucket_fill[idx]++];
443
534
    memset(ret, 0, sizeof(*ret));
444
534
    ret->pix_id = key;
445
534
    return ret;
446
}
447
448
1658
static int epic_add_pixel_to_cache(ePICPixHash *hash, uint32_t key, uint32_t pix)
449
{
450
    ePICPixListElem *new_elem;
451
1658
    ePICPixHashElem *hash_elem = epic_hash_find(hash, key);
452
453
1658
    if (!hash_elem) {
454
534
        if (!(hash_elem = epic_hash_add(hash, key)))
455
            return AVERROR(ENOMEM);
456
    }
457
458
1658
    new_elem = av_mallocz(sizeof(*new_elem));
459
1658
    if (!new_elem)
460
        return AVERROR(ENOMEM);
461
462
1658
    new_elem->pixel = pix;
463
1658
    new_elem->next  = hash_elem->list;
464
1658
    hash_elem->list = new_elem;
465
466
1658
    return 0;
467
}
468
469
41955
static inline int epic_cache_entries_for_pixel(const ePICPixHash *hash,
470
                                               uint32_t pix)
471
{
472
41955
    ePICPixHashElem *hash_elem = epic_hash_find(hash, pix);
473
474

41955
    if (hash_elem != NULL && hash_elem->list != NULL)
475
39956
        return 1;
476
477
1999
    return 0;
478
}
479
480
136
static void epic_free_pixel_cache(ePICPixHash *hash)
481
{
482
    int i, j;
483
484
34952
    for (i = 0; i < EPIC_HASH_SIZE; i++) {
485
35350
        for (j = 0; j < hash->bucket_fill[i]; j++) {
486
534
            ePICPixListElem *list_elem = hash->bucket[i][j].list;
487
2192
            while (list_elem) {
488
1658
                ePICPixListElem *tmp = list_elem->next;
489
1658
                av_free(list_elem);
490
1658
                list_elem = tmp;
491
            }
492
        }
493
34816
        av_freep(&hash->bucket[i]);
494
34816
        hash->bucket_size[i] =
495
34816
        hash->bucket_fill[i] = 0;
496
    }
497
136
}
498
499
510904
static inline int is_pixel_on_stack(const ePICContext *dc, uint32_t pix)
500
{
501
    int i;
502
503
1163688
    for (i = 0; i < dc->stack_pos; i++)
504
806184
        if (dc->stack[i] == pix)
505
153400
            break;
506
507
510904
    return i != dc->stack_pos;
508
}
509
510
#define TOSIGNED(val) (((val) >> 1) ^ -((val) & 1))
511
512
9558
static inline int epic_decode_component_pred(ePICContext *dc,
513
                                             int N, int W, int NW)
514
{
515
9558
    unsigned delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
516
9558
    return mid_pred(N, N + W - NW, W) - TOSIGNED(delta);
517
}
518
519
4739
static uint32_t epic_decode_pixel_pred(ePICContext *dc, int x, int y,
520
                                       const uint32_t *curr_row,
521
                                       const uint32_t *above_row)
522
{
523
    uint32_t N, W, NW, pred;
524
    unsigned delta;
525
    int GN, GW, GNW, R, G, B;
526
527

4739
    if (x && y) {
528
3186
        W  = curr_row[x  - 1];
529
3186
        N  = above_row[x];
530
3186
        NW = above_row[x - 1];
531
532
3186
        GN  = (N  >> G_shift) & 0xFF;
533
3186
        GW  = (W  >> G_shift) & 0xFF;
534
3186
        GNW = (NW >> G_shift) & 0xFF;
535
536
3186
        G = epic_decode_component_pred(dc, GN, GW, GNW);
537
538
6372
        R = G + epic_decode_component_pred(dc,
539
3186
                                           ((N  >> R_shift) & 0xFF) - GN,
540
3186
                                           ((W  >> R_shift) & 0xFF) - GW,
541
3186
                                           ((NW >> R_shift) & 0xFF) - GNW);
542
543
3186
        B = G + epic_decode_component_pred(dc,
544
3186
                                           ((N  >> B_shift) & 0xFF) - GN,
545
3186
                                           ((W  >> B_shift) & 0xFF) - GW,
546
3186
                                           ((NW >> B_shift) & 0xFF) - GNW);
547
    } else {
548
1553
        if (x)
549
471
            pred = curr_row[x - 1];
550
        else
551
1082
            pred = above_row[x];
552
553
1553
        delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
554
1553
        R     = ((pred >> R_shift) & 0xFF) - TOSIGNED(delta);
555
556
1553
        delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
557
1553
        G     = ((pred >> G_shift) & 0xFF) - TOSIGNED(delta);
558
559
1553
        delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
560
1553
        B     = ((pred >> B_shift) & 0xFF) - TOSIGNED(delta);
561
    }
562
563



4739
    if (R<0 || G<0 || B<0 || R > 255 || G > 255 || B > 255) {
564
        avpriv_request_sample(NULL, "RGB %d %d %d (out of range)", R, G, B);
565
        return 0;
566
    }
567
568
4739
    return (R << R_shift) | (G << G_shift) | (B << B_shift);
569
}
570
571
99449
static int epic_predict_pixel(ePICContext *dc, uint8_t *rung,
572
                              uint32_t *pPix, uint32_t pix)
573
{
574
99449
    if (!ff_els_decode_bit(&dc->els_ctx, rung)) {
575
91084
        *pPix = pix;
576
91084
        return 1;
577
    }
578
8365
    dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = pix;
579
8365
    return 0;
580
}
581
582
95756
static int epic_handle_edges(ePICContext *dc, int x, int y,
583
                             const uint32_t *curr_row,
584
                             const uint32_t *above_row, uint32_t *pPix)
585
{
586
    uint32_t pix;
587
588

95756
    if (!x && !y) { /* special case: top-left pixel */
589
        /* the top-left pixel is coded independently with 3 unsigned numbers */
590
136
        *pPix = (ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung) << R_shift) |
591
136
                (ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung) << G_shift) |
592
136
                (ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung) << B_shift);
593
136
        return 1;
594
    }
595
596
95620
    if (x) { /* predict from W first */
597
78572
        pix = curr_row[x - 1];
598
78572
        if (epic_predict_pixel(dc, &dc->W_flag_rung, pPix, pix))
599
72049
            return 1;
600
    }
601
602
23571
    if (y) { /* then try to predict from N */
603
22080
        pix = above_row[x];
604

22080
        if (!dc->stack_pos || dc->stack[0] != pix) {
605
20877
            if (epic_predict_pixel(dc, &dc->N_flag_rung, pPix, pix))
606
19035
                return 1;
607
        }
608
    }
609
610
4536
    return 0;
611
}
612
613
218240
static int epic_decode_run_length(ePICContext *dc, int x, int y, int tile_width,
614
                                  const uint32_t *curr_row,
615
                                  const uint32_t *above_row,
616
                                  const uint32_t *above2_row,
617
                                  uint32_t *pPix, int *pRun)
618
{
619
218240
    int idx, got_pixel = 0, WWneW, old_WWneW = 0;
620
    uint32_t W, WW, N, NN, NW, NE, NWW, NNW, NNE;
621
622
218240
    *pRun = 0;
623
624
218240
    LOAD_NEIGHBOURS(x);
625
626
218240
    if (dc->next_run_pos == x) {
627
        /* can't reuse W for the new pixel in this case */
628
199455
        WWneW = 1;
629
    } else {
630
18785
        idx = (WW  != W)  << 7 |
631
18785
              (NW  != W)  << 6 |
632
18785
              (N   != NE) << 5 |
633
18785
              (NW  != N)  << 4 |
634
18785
              (NWW != NW) << 3 |
635
18785
              (NNE != NE) << 2 |
636
18785
              (NN  != N)  << 1 |
637
18785
              (NNW != NW);
638
18785
        WWneW = ff_els_decode_bit(&dc->els_ctx, &dc->W_ctx_rung[idx]);
639
18785
        if (WWneW < 0)
640
            return WWneW;
641
    }
642
643
218240
    if (WWneW)
644
201691
        dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = W;
645
    else {
646
16549
        *pPix     = W;
647
16549
        got_pixel = 1;
648
    }
649
650
    do {
651
503572
        int NWneW = 1;
652
503572
        if (got_pixel) // pixel value already known (derived from either W or N)
653
237740
            NWneW = *pPix != N;
654
        else { // pixel value is unknown and will be decoded later
655
265832
            NWneW = *pRun ? NWneW : NW != W;
656
657
            /* TODO: RFC this mess! */
658

265832
            switch (((NW != N) << 2) | (NWneW << 1) | WWneW) {
659
            case 0:
660
                break; // do nothing here
661
176548
            case 3:
662
            case 5:
663
            case 6:
664
            case 7:
665
176548
                if (!is_pixel_on_stack(dc, N)) {
666
457674
                    idx = WWneW       << 8 |
667

152558
                          (*pRun ? old_WWneW : WW != W) << 7 |
668
305116
                          NWneW       << 6 |
669
152558
                          (N   != NE) << 5 |
670
152558
                          (NW  != N)  << 4 |
671
152558
                          (NWW != NW) << 3 |
672
152558
                          (NNE != NE) << 2 |
673
152558
                          (NN  != N)  << 1 |
674
152558
                          (NNW != NW);
675
152558
                    if (!ff_els_decode_bit(&dc->els_ctx, &dc->N_ctx_rung[idx])) {
676
129319
                        NWneW = 0;
677
129319
                        *pPix = N;
678
129319
                        got_pixel = 1;
679
129319
                        break;
680
                    }
681
                }
682
                /* fall through */
683
            default:
684
136513
                NWneW = 1;
685
136513
                old_WWneW = WWneW;
686
136513
                if (!is_pixel_on_stack(dc, N))
687
23239
                    dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = N;
688
            }
689
        }
690
691
503572
        (*pRun)++;
692
503572
        if (x + *pRun >= tile_width - 1)
693
3378
            break;
694
695
500194
        UPDATE_NEIGHBOURS(x + *pRun);
696
697

500194
        if (!NWneW && NW == N && N == NE) {
698
            int pos, run, rle;
699
99184
            int start_pos = x + *pRun;
700
701
            /* scan for a run of pix in the line above */
702
99184
            uint32_t pix = above_row[start_pos + 1];
703
2511691
            for (pos = start_pos + 2; pos < tile_width; pos++)
704
2496269
                if (!(above_row[pos] == pix))
705
83762
                    break;
706
99184
            run = pos - start_pos - 1;
707
99184
            idx = av_ceil_log2(run);
708
99184
            if (ff_els_decode_bit(&dc->els_ctx, &dc->prev_row_rung[idx]))
709
66738
                *pRun += run;
710
            else {
711
                int flag;
712
                /* run-length is coded as plain binary number of idx - 1 bits */
713
131763
                for (pos = idx - 1, rle = 0, flag = 0; pos >= 0; pos--) {
714

193930
                    if ((1 << pos) + rle < run &&
715
94613
                        ff_els_decode_bit(&dc->els_ctx,
716
                                          flag ? &dc->runlen_one
717
                                               : &dc->runlen_zeroes[pos])) {
718
33844
                        flag = 1;
719
33844
                        rle |= 1 << pos;
720
                    }
721
                }
722
32446
                *pRun += rle;
723
32446
                break; // return immediately
724
            }
725
66738
            if (x + *pRun >= tile_width - 1)
726
13519
                break;
727
728
53219
            LOAD_NEIGHBOURS(x + *pRun);
729
53219
            WWneW = 0;
730
53219
            NWneW = 0;
731
        }
732
733
908458
        idx = WWneW       << 7 |
734
908458
              NWneW       << 6 |
735
454229
              (N   != NE) << 5 |
736
454229
              (NW  != N)  << 4 |
737
454229
              (NWW != NW) << 3 |
738
454229
              (NNE != NE) << 2 |
739
454229
              (NN  != N)  << 1 |
740
454229
              (NNW != NW);
741
454229
        WWneW = ff_els_decode_bit(&dc->els_ctx, &dc->W_ctx_rung[idx]);
742
454229
    } while (!WWneW);
743
744
218240
    dc->next_run_pos = x + *pRun;
745
218240
    return got_pixel;
746
}
747
748
36049
static int epic_predict_pixel2(ePICContext *dc, uint8_t *rung,
749
                               uint32_t *pPix, uint32_t pix)
750
{
751
36049
    if (ff_els_decode_bit(&dc->els_ctx, rung)) {
752
22192
        *pPix = pix;
753
22192
        return 1;
754
    }
755
13857
    dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = pix;
756
13857
    return 0;
757
}
758
759
76908
static int epic_predict_from_NW_NE(ePICContext *dc, int x, int y, int run,
760
                                   int tile_width, const uint32_t *curr_row,
761
                                   const uint32_t *above_row, uint32_t *pPix)
762
{
763
    int pos;
764
765
    /* try to reuse the NW pixel first */
766

76908
    if (x && y) {
767
73974
        uint32_t NW = above_row[x - 1];
768

73974
        if (NW != curr_row[x - 1] && NW != above_row[x] && !is_pixel_on_stack(dc, NW)) {
769
20189
            if (epic_predict_pixel2(dc, &dc->nw_pred_rung[NW & 0xFF], pPix, NW))
770
12191
                return 1;
771
        }
772
    }
773
774
    /* try to reuse the NE[x + run, y] pixel */
775
64717
    pos = x + run - 1;
776

64717
    if (pos < tile_width - 1 && y) {
777
62826
        uint32_t NE = above_row[pos + 1];
778

62826
        if (NE != above_row[pos] && !is_pixel_on_stack(dc, NE)) {
779
15860
            if (epic_predict_pixel2(dc, &dc->ne_pred_rung[NE & 0xFF], pPix, NE))
780
10001
                return 1;
781
        }
782
    }
783
784
54716
    return 0;
785
}
786
787
53634
static int epic_decode_from_cache(ePICContext *dc, uint32_t W, uint32_t *pPix)
788
{
789
53634
    ePICPixListElem *list, *prev = NULL;
790
53634
    ePICPixHashElem *hash_elem = epic_hash_find(&dc->hash, W);
791
792

53634
    if (!hash_elem || !hash_elem->list)
793
534
        return 0;
794
795
53100
    list = hash_elem->list;
796
154706
    while (list) {
797
153582
        if (!is_pixel_on_stack(dc, list->pixel)) {
798
142918
            if (ff_els_decode_bit(&dc->els_ctx, &list->rung)) {
799
51976
                *pPix = list->pixel;
800
51976
                if (list != hash_elem->list) {
801
36609
                    prev->next      = list->next;
802
36609
                    list->next      = hash_elem->list;
803
36609
                    hash_elem->list = list;
804
                }
805
51976
                return 1;
806
            }
807
90942
            dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = list->pixel;
808
        }
809
101606
        prev = list;
810
101606
        list = list->next;
811
    }
812
813
1124
    return 0;
814
}
815
816
136
static int epic_decode_tile(ePICContext *dc, uint8_t *out, int tile_height,
817
                            int tile_width, int stride)
818
{
819
    int x, y;
820
    uint32_t pix;
821
136
    uint32_t *curr_row = NULL, *above_row = NULL, *above2_row;
822
823
17320
    for (y = 0; y < tile_height; y++, out += stride) {
824
17184
        above2_row = above_row;
825
17184
        above_row  = curr_row;
826
17184
        curr_row   = (uint32_t *) out;
827
828
333179
        for (x = 0, dc->next_run_pos = 0; x < tile_width;) {
829
315995
            if (dc->els_ctx.err)
830
                return AVERROR_INVALIDDATA; // bail out in the case of ELS overflow
831
832
315995
            pix = curr_row[x - 1]; // get W pixel
833
834

315995
            if (y >= 1 && x >= 2 &&
835

259371
                pix != curr_row[x - 2]  && pix != above_row[x - 1] &&
836

101123
                pix != above_row[x - 2] && pix != above_row[x] &&
837
41955
                !epic_cache_entries_for_pixel(&dc->hash, pix)) {
838
1999
                curr_row[x] = epic_decode_pixel_pred(dc, x, y, curr_row, above_row);
839
1999
                x++;
840
            } else {
841
                int got_pixel, run;
842
313996
                dc->stack_pos = 0; // empty stack
843
844

313996
                if (y < 2 || x < 2 || x == tile_width - 1) {
845
95756
                    run       = 1;
846
95756
                    got_pixel = epic_handle_edges(dc, x, y, curr_row, above_row, &pix);
847
                } else {
848
218240
                    got_pixel = epic_decode_run_length(dc, x, y, tile_width,
849
                                                       curr_row, above_row,
850
                                                       above2_row, &pix, &run);
851
218240
                    if (got_pixel < 0)
852
                        return got_pixel;
853
                }
854
855

313996
                if (!got_pixel && !epic_predict_from_NW_NE(dc, x, y, run,
856
                                                           tile_width, curr_row,
857
                                                           above_row, &pix)) {
858
54716
                    uint32_t ref_pix = curr_row[x - 1];
859

54716
                    if (!x || !epic_decode_from_cache(dc, ref_pix, &pix)) {
860
2740
                        pix = epic_decode_pixel_pred(dc, x, y, curr_row, above_row);
861
2740
                        if (is_pixel_on_stack(dc, pix))
862
                            return AVERROR_INVALIDDATA;
863
864
2740
                        if (x) {
865
1658
                            int ret = epic_add_pixel_to_cache(&dc->hash,
866
                                                              ref_pix,
867
                                                              pix);
868
1658
                            if (ret)
869
                                return ret;
870
                        }
871
                    }
872
                }
873
3159741
                for (; run > 0; x++, run--)
874
2845745
                    curr_row[x] = pix;
875
            }
876
        }
877
    }
878
879
136
    return 0;
880
}
881
882
136
static int epic_jb_decode_tile(G2MContext *c, int tile_x, int tile_y,
883
                               const uint8_t *src, size_t src_size,
884
                               AVCodecContext *avctx)
885
{
886
136
    uint8_t prefix, mask = 0x80;
887
    int extrabytes, tile_width, tile_height, awidth, aheight;
888
    size_t els_dsize;
889
    uint8_t *dst;
890
891
136
    if (!src_size)
892
        return 0;
893
894
    /* get data size of the ELS partition as unsigned variable-length integer */
895
136
    prefix = *src++;
896
136
    src_size--;
897

224
    for (extrabytes = 0; (prefix & mask) && (extrabytes < 7); extrabytes++)
898
88
        mask >>= 1;
899

136
    if (extrabytes > 3 || src_size < extrabytes) {
900
        av_log(avctx, AV_LOG_ERROR, "ePIC: invalid data size VLI\n");
901
        return AVERROR_INVALIDDATA;
902
    }
903
904
136
    els_dsize = prefix & ((0x80 >> extrabytes) - 1); // mask out the length prefix
905
224
    while (extrabytes-- > 0) {
906
88
        els_dsize = (els_dsize << 8) | *src++;
907
88
        src_size--;
908
    }
909
910
136
    if (src_size < els_dsize) {
911
        av_log(avctx, AV_LOG_ERROR, "ePIC: data too short, needed %"SIZE_SPECIFIER", got %"SIZE_SPECIFIER"\n",
912
               els_dsize, src_size);
913
        return AVERROR_INVALIDDATA;
914
    }
915
916
136
    tile_width  = FFMIN(c->width  - tile_x * c->tile_width,  c->tile_width);
917
136
    tile_height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
918
136
    awidth      = FFALIGN(tile_width,  16);
919
136
    aheight     = FFALIGN(tile_height, 16);
920
921
136
    if (tile_width > (1 << FF_ARRAY_ELEMS(c->ec.prev_row_rung))) {
922
        avpriv_request_sample(avctx, "large tile width");
923
        return AVERROR_INVALIDDATA;
924
    }
925
926
136
    if (els_dsize) {
927
        int ret, i, j, k;
928
        uint8_t tr_r, tr_g, tr_b, *buf;
929
        uint32_t *in;
930
        /* ELS decoder initializations */
931
136
        memset(&c->ec, 0, sizeof(c->ec));
932
136
        ff_els_decoder_init(&c->ec.els_ctx, src, els_dsize);
933
136
        epic_hash_init(&c->ec.hash);
934
935
        /* decode transparent pixel value */
936
136
        tr_r = ff_els_decode_unsigned(&c->ec.els_ctx, &c->ec.unsigned_rung);
937
136
        tr_g = ff_els_decode_unsigned(&c->ec.els_ctx, &c->ec.unsigned_rung);
938
136
        tr_b = ff_els_decode_unsigned(&c->ec.els_ctx, &c->ec.unsigned_rung);
939
136
        if (c->ec.els_ctx.err != 0) {
940
            av_log(avctx, AV_LOG_ERROR,
941
                   "ePIC: couldn't decode transparency pixel!\n");
942
            ff_els_decoder_uninit(&c->ec.unsigned_rung);
943
            return AVERROR_INVALIDDATA;
944
        }
945
946
136
        ret = epic_decode_tile(&c->ec, c->epic_buf, tile_height, tile_width,
947
                               c->epic_buf_stride);
948
949
136
        epic_free_pixel_cache(&c->ec.hash);
950
136
        ff_els_decoder_uninit(&c->ec.unsigned_rung);
951
952
136
        if (ret) {
953
            av_log(avctx, AV_LOG_ERROR,
954
                   "ePIC: tile decoding failed, frame=%d, tile_x=%d, tile_y=%d\n",
955
                   avctx->frame_number, tile_x, tile_y);
956
            return AVERROR_INVALIDDATA;
957
        }
958
959
136
        buf = c->epic_buf;
960
136
        dst = c->framebuf + tile_x * c->tile_width * 3 +
961
136
              tile_y * c->tile_height * c->framebuf_stride;
962
963
17320
        for (j = 0; j < tile_height; j++) {
964
17184
            uint8_t *out = dst;
965
17184
            in  = (uint32_t *) buf;
966
2864928
            for (i = 0; i < tile_width; i++) {
967
2847744
                out[0] = (in[i] >> R_shift) & 0xFF;
968
2847744
                out[1] = (in[i] >> G_shift) & 0xFF;
969
2847744
                out[2] = (in[i] >> B_shift) & 0xFF;
970
2847744
                out   += 3;
971
            }
972
17184
            buf += c->epic_buf_stride;
973
17184
            dst += c->framebuf_stride;
974
        }
975
976
136
        if (src_size > els_dsize) {
977
            uint8_t *jpg;
978
            uint32_t tr;
979
92
            int bstride = FFALIGN(tile_width, 16) >> 3;
980
92
            int nblocks = 0;
981
92
            int estride = c->epic_buf_stride >> 2;
982
983
92
            src      += els_dsize;
984
92
            src_size -= els_dsize;
985
986
92
            in = (uint32_t *) c->epic_buf;
987
92
            tr = (tr_r << R_shift) | (tr_g << G_shift) | (tr_b << B_shift);
988
989
92
            memset(c->kempf_flags, 0,
990
92
                   (aheight >> 3) * bstride * sizeof(*c->kempf_flags));
991
1543
            for (j = 0; j < tile_height; j += 8) {
992
32605
                for (i = 0; i < tile_width; i += 8) {
993
31154
                    c->kempf_flags[(i >> 3) + (j >> 3) * bstride] = 0;
994
1113006
                    for (k = 0; k < 8 * 8; k++) {
995
1096594
                        if (in[i + (k & 7) + (k >> 3) * estride] == tr) {
996
14742
                            c->kempf_flags[(i >> 3) + (j >> 3) * bstride] = 1;
997
14742
                            nblocks++;
998
14742
                            break;
999
                        }
1000
                    }
1001
                }
1002
1451
                in += 8 * estride;
1003
            }
1004
1005
92
            memset(c->jpeg_tile, 0, c->tile_stride * aheight);
1006
92
            jpg_decode_data(&c->jc, awidth, aheight, src, src_size,
1007
                            c->jpeg_tile, c->tile_stride,
1008
92
                            c->kempf_flags, bstride, nblocks, c->swapuv);
1009
1010
92
            in  = (uint32_t *) c->epic_buf;
1011
92
            dst = c->framebuf + tile_x * c->tile_width * 3 +
1012
92
                  tile_y * c->tile_height * c->framebuf_stride;
1013
92
            jpg = c->jpeg_tile;
1014
11672
            for (j = 0; j < tile_height; j++) {
1015
2000508
                for (i = 0; i < tile_width; i++)
1016
1988928
                    if (in[i] == tr)
1017
717442
                        memcpy(dst + i * 3, jpg + i * 3, 3);
1018
11580
                in  += c->epic_buf_stride >> 2;
1019
11580
                dst += c->framebuf_stride;
1020
11580
                jpg += c->tile_stride;
1021
            }
1022
        }
1023
    } else {
1024
        dst = c->framebuf + tile_x * c->tile_width * 3 +
1025
              tile_y * c->tile_height * c->framebuf_stride;
1026
        return jpg_decode_data(&c->jc, tile_width, tile_height, src, src_size,
1027
                               dst, c->framebuf_stride, NULL, 0, 0, c->swapuv);
1028
    }
1029
1030
136
    return 0;
1031
}
1032
1033
81
static int kempf_restore_buf(const uint8_t *src, int len,
1034
                              uint8_t *dst, int stride,
1035
                              const uint8_t *jpeg_tile, int tile_stride,
1036
                              int width, int height,
1037
                              const uint8_t *pal, int npal, int tidx)
1038
{
1039
    GetBitContext gb;
1040
    int i, j, nb, col;
1041
    int ret;
1042
81
    int align_width = FFALIGN(width, 16);
1043
1044
81
    if ((ret = init_get_bits8(&gb, src, len)) < 0)
1045
        return ret;
1046
1047
81
    if (npal <= 2)       nb = 1;
1048
81
    else if (npal <= 4)  nb = 2;
1049
66
    else if (npal <= 16) nb = 4;
1050
29
    else                 nb = 8;
1051
1052
10449
    for (j = 0; j < height; j++, dst += stride, jpeg_tile += tile_stride) {
1053
10368
        if (get_bits(&gb, 8))
1054
            continue;
1055
1654912
        for (i = 0; i < width; i++) {
1056
1644544
            col = get_bits(&gb, nb);
1057
1644544
            if (col != tidx)
1058
1323579
                memcpy(dst + i * 3, pal + col * 3, 3);
1059
            else
1060
320965
                memcpy(dst + i * 3, jpeg_tile + i * 3, 3);
1061
        }
1062
10368
        skip_bits_long(&gb, nb * (align_width - width));
1063
    }
1064
1065
81
    return 0;
1066
}
1067
1068
101
static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,
1069
                             const uint8_t *src, int src_size)
1070
{
1071
    int width, height;
1072
101
    int hdr, zsize, npal, tidx = -1, ret;
1073
    int i, j;
1074
101
    const uint8_t *src_end = src + src_size;
1075
    uint8_t pal[768], transp[3];
1076
101
    uLongf dlen = (c->tile_width + 1) * c->tile_height;
1077
    int sub_type;
1078
    int nblocks, cblocks, bstride;
1079
    int bits, bitbuf, coded;
1080
101
    uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +
1081
101
                   tile_y * c->tile_height * c->framebuf_stride;
1082
1083
101
    if (src_size < 2)
1084
        return AVERROR_INVALIDDATA;
1085
1086
101
    width  = FFMIN(c->width  - tile_x * c->tile_width,  c->tile_width);
1087
101
    height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
1088
1089
101
    hdr      = *src++;
1090
101
    sub_type = hdr >> 5;
1091
101
    if (sub_type == 0) {
1092
        int j;
1093
20
        memcpy(transp, src, 3);
1094
20
        src += 3;
1095
2580
        for (j = 0; j < height; j++, dst += c->framebuf_stride)
1096
403968
            for (i = 0; i < width; i++)
1097
401408
                memcpy(dst + i * 3, transp, 3);
1098
20
        return 0;
1099
81
    } else if (sub_type == 1) {
1100
        return jpg_decode_data(&c->jc, width, height, src, src_end - src,
1101
                               dst, c->framebuf_stride, NULL, 0, 0, 0);
1102
    }
1103
1104
81
    if (sub_type != 2) {
1105
67
        memcpy(transp, src, 3);
1106
67
        src += 3;
1107
    }
1108
81
    npal = *src++ + 1;
1109
81
    if (src_end - src < npal * 3)
1110
        return AVERROR_INVALIDDATA;
1111
81
    memcpy(pal, src, npal * 3);
1112
81
    src += npal * 3;
1113
81
    if (sub_type != 2) {
1114
134
        for (i = 0; i < npal; i++) {
1115
134
            if (!memcmp(pal + i * 3, transp, 3)) {
1116
67
                tidx = i;
1117
67
                break;
1118
            }
1119
        }
1120
    }
1121
1122
81
    if (src_end - src < 2)
1123
        return 0;
1124
81
    zsize = (src[0] << 8) | src[1];
1125
81
    src  += 2;
1126
1127
81
    if (src_end - src < zsize + (sub_type != 2))
1128
        return AVERROR_INVALIDDATA;
1129
1130
81
    ret = uncompress(c->kempf_buf, &dlen, src, zsize);
1131
81
    if (ret)
1132
        return AVERROR_INVALIDDATA;
1133
81
    src += zsize;
1134
1135
81
    if (sub_type == 2) {
1136
14
        kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
1137
                          NULL, 0, width, height, pal, npal, tidx);
1138
14
        return 0;
1139
    }
1140
1141
67
    nblocks = *src++ + 1;
1142
67
    cblocks = 0;
1143
67
    bstride = FFALIGN(width, 16) >> 3;
1144
    // blocks are coded LSB and we need normal bitreader for JPEG data
1145
67
    bits = 0;
1146
603
    for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {
1147
5984
        for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {
1148
5448
            if (!bits) {
1149
681
                if (src >= src_end)
1150
                    return AVERROR_INVALIDDATA;
1151
681
                bitbuf = *src++;
1152
681
                bits   = 8;
1153
            }
1154
5448
            coded = bitbuf & 1;
1155
5448
            bits--;
1156
5448
            bitbuf >>= 1;
1157
5448
            cblocks += coded;
1158
5448
            if (cblocks > nblocks)
1159
                return AVERROR_INVALIDDATA;
1160
5448
            c->kempf_flags[j * 2 +      i * 2      * bstride] =
1161
5448
            c->kempf_flags[j * 2 + 1 +  i * 2      * bstride] =
1162
5448
            c->kempf_flags[j * 2 +     (i * 2 + 1) * bstride] =
1163
5448
            c->kempf_flags[j * 2 + 1 + (i * 2 + 1) * bstride] = coded;
1164
        }
1165
    }
1166
1167
67
    memset(c->jpeg_tile, 0, c->tile_stride * height);
1168
67
    jpg_decode_data(&c->jc, width, height, src, src_end - src,
1169
                    c->jpeg_tile, c->tile_stride,
1170
67
                    c->kempf_flags, bstride, nblocks * 4, 0);
1171
1172
67
    kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
1173
67
                      c->jpeg_tile, c->tile_stride,
1174
                      width, height, pal, npal, tidx);
1175
1176
67
    return 0;
1177
}
1178
1179
4
static int g2m_init_buffers(G2MContext *c)
1180
{
1181
    int aligned_height;
1182
1183

4
    if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
1184
4
        c->framebuf_stride = FFALIGN(c->width + 15, 16) * 3;
1185
4
        aligned_height     = c->height + 15;
1186
4
        av_free(c->framebuf);
1187
4
        c->framebuf = av_mallocz_array(c->framebuf_stride, aligned_height);
1188
4
        if (!c->framebuf)
1189
            return AVERROR(ENOMEM);
1190
    }
1191

4
    if (!c->synth_tile || !c->jpeg_tile ||
1192

1
        (c->compression == 2 && !c->epic_buf_base) ||
1193
1
        c->old_tile_w < c->tile_width ||
1194
        c->old_tile_h < c->tile_height) {
1195
4
        c->tile_stride     = FFALIGN(c->tile_width, 16) * 3;
1196
4
        c->epic_buf_stride = FFALIGN(c->tile_width * 4, 16);
1197
4
        aligned_height     = FFALIGN(c->tile_height,    16);
1198
4
        av_freep(&c->synth_tile);
1199
4
        av_freep(&c->jpeg_tile);
1200
4
        av_freep(&c->kempf_buf);
1201
4
        av_freep(&c->kempf_flags);
1202
4
        av_freep(&c->epic_buf_base);
1203
4
        c->epic_buf    = NULL;
1204
4
        c->synth_tile  = av_mallocz(c->tile_stride      * aligned_height);
1205
4
        c->jpeg_tile   = av_mallocz(c->tile_stride      * aligned_height);
1206
4
        c->kempf_buf   = av_mallocz((c->tile_width + 1) * aligned_height +
1207
                                    AV_INPUT_BUFFER_PADDING_SIZE);
1208
4
        c->kempf_flags = av_mallocz(c->tile_width       * aligned_height);
1209

4
        if (!c->synth_tile || !c->jpeg_tile ||
1210

4
            !c->kempf_buf || !c->kempf_flags)
1211
            return AVERROR(ENOMEM);
1212
4
        if (c->compression == 2) {
1213
3
            c->epic_buf_base = av_mallocz(c->epic_buf_stride * aligned_height + 4);
1214
3
            if (!c->epic_buf_base)
1215
                return AVERROR(ENOMEM);
1216
3
            c->epic_buf = c->epic_buf_base + 4;
1217
        }
1218
    }
1219
1220
4
    return 0;
1221
}
1222
1223
14
static int g2m_load_cursor(AVCodecContext *avctx, G2MContext *c,
1224
                           GetByteContext *gb)
1225
{
1226
    int i, j, k;
1227
    uint8_t *dst;
1228
    uint32_t bits;
1229
    uint32_t cur_size, cursor_w, cursor_h, cursor_stride;
1230
    uint32_t cursor_hot_x, cursor_hot_y;
1231
    int cursor_fmt, err;
1232
1233
14
    cur_size     = bytestream2_get_be32(gb);
1234
14
    cursor_w     = bytestream2_get_byte(gb);
1235
14
    cursor_h     = bytestream2_get_byte(gb);
1236
14
    cursor_hot_x = bytestream2_get_byte(gb);
1237
14
    cursor_hot_y = bytestream2_get_byte(gb);
1238
14
    cursor_fmt   = bytestream2_get_byte(gb);
1239
1240

14
    cursor_stride = FFALIGN(cursor_w, cursor_fmt==1 ? 32 : 1) * 4;
1241
1242

14
    if (cursor_w < 1 || cursor_w > 256 ||
1243
14
        cursor_h < 1 || cursor_h > 256) {
1244
        av_log(avctx, AV_LOG_ERROR, "Invalid cursor dimensions %"PRIu32"x%"PRIu32"\n",
1245
               cursor_w, cursor_h);
1246
        return AVERROR_INVALIDDATA;
1247
    }
1248

14
    if (cursor_hot_x > cursor_w || cursor_hot_y > cursor_h) {
1249
        av_log(avctx, AV_LOG_WARNING, "Invalid hotspot position %"PRIu32",%"PRIu32"\n",
1250
               cursor_hot_x, cursor_hot_y);
1251
        cursor_hot_x = FFMIN(cursor_hot_x, cursor_w - 1);
1252
        cursor_hot_y = FFMIN(cursor_hot_y, cursor_h - 1);
1253
    }
1254
14
    if (cur_size - 9 > bytestream2_get_bytes_left(gb) ||
1255
14
        c->cursor_w * c->cursor_h / 4 > cur_size) {
1256
        av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %"PRIu32"/%u\n",
1257
               cur_size, bytestream2_get_bytes_left(gb));
1258
        return AVERROR_INVALIDDATA;
1259
    }
1260

14
    if (cursor_fmt != 1 && cursor_fmt != 32) {
1261
        avpriv_report_missing_feature(avctx, "Cursor format %d",
1262
                                      cursor_fmt);
1263
        return AVERROR_PATCHWELCOME;
1264
    }
1265
1266
14
    if ((err = av_reallocp(&c->cursor, cursor_stride * cursor_h)) < 0) {
1267
        av_log(avctx, AV_LOG_ERROR, "Cannot allocate cursor buffer\n");
1268
        return err;
1269
    }
1270
1271
14
    c->cursor_w      = cursor_w;
1272
14
    c->cursor_h      = cursor_h;
1273
14
    c->cursor_hot_x  = cursor_hot_x;
1274
14
    c->cursor_hot_y  = cursor_hot_y;
1275
14
    c->cursor_fmt    = cursor_fmt;
1276
14
    c->cursor_stride = cursor_stride;
1277
1278
14
    dst = c->cursor;
1279
14
    switch (c->cursor_fmt) {
1280
13
    case 1: // old monochrome
1281
429
        for (j = 0; j < c->cursor_h; j++) {
1282
832
            for (i = 0; i < c->cursor_w; i += 32) {
1283
416
                bits = bytestream2_get_be32(gb);
1284
13728
                for (k = 0; k < 32; k++) {
1285
13312
                    dst[0] = !!(bits & 0x80000000);
1286
13312
                    dst   += 4;
1287
13312
                    bits <<= 1;
1288
                }
1289
            }
1290
        }
1291
1292
13
        dst = c->cursor;
1293
429
        for (j = 0; j < c->cursor_h; j++) {
1294
832
            for (i = 0; i < c->cursor_w; i += 32) {
1295
416
                bits = bytestream2_get_be32(gb);
1296
13728
                for (k = 0; k < 32; k++) {
1297
13312
                    int mask_bit = !!(bits & 0x80000000);
1298
13312
                    switch (dst[0] * 2 + mask_bit) {
1299
824
                    case 0:
1300
824
                        dst[0] = 0xFF;
1301
824
                        dst[1] = 0x00;
1302
824
                        dst[2] = 0x00;
1303
824
                        dst[3] = 0x00;
1304
824
                        break;
1305
920
                    case 1:
1306
920
                        dst[0] = 0xFF;
1307
920
                        dst[1] = 0xFF;
1308
920
                        dst[2] = 0xFF;
1309
920
                        dst[3] = 0xFF;
1310
920
                        break;
1311
11568
                    default:
1312
11568
                        dst[0] = 0x00;
1313
11568
                        dst[1] = 0x00;
1314
11568
                        dst[2] = 0x00;
1315
11568
                        dst[3] = 0x00;
1316
                    }
1317
13312
                    dst   += 4;
1318
13312
                    bits <<= 1;
1319
                }
1320
            }
1321
        }
1322
13
        break;
1323
1
    case 32: // full colour
1324
        /* skip monochrome version of the cursor and decode RGBA instead */
1325
1
        bytestream2_skip(gb, c->cursor_h * (FFALIGN(c->cursor_w, 32) >> 3));
1326
33
        for (j = 0; j < c->cursor_h; j++) {
1327
1056
            for (i = 0; i < c->cursor_w; i++) {
1328
1024
                int val = bytestream2_get_be32(gb);
1329
1024
                *dst++ = val >>  0;
1330
1024
                *dst++ = val >>  8;
1331
1024
                *dst++ = val >> 16;
1332
1024
                *dst++ = val >> 24;
1333
            }
1334
        }
1335
1
        break;
1336
    default:
1337
        return AVERROR_PATCHWELCOME;
1338
    }
1339
14
    return 0;
1340
}
1341
1342
#define APPLY_ALPHA(src, new, alpha) \
1343
    src = (src * (256 - alpha) + new * alpha) >> 8
1344
1345
247
static void g2m_paint_cursor(G2MContext *c, uint8_t *dst, int stride)
1346
{
1347
    int i, j;
1348
    int x, y, w, h;
1349
    const uint8_t *cursor;
1350
1351
247
    if (!c->cursor)
1352
        return;
1353
1354
247
    x = c->cursor_x - c->cursor_hot_x;
1355
247
    y = c->cursor_y - c->cursor_hot_y;
1356
1357
247
    cursor = c->cursor;
1358
247
    w      = c->cursor_w;
1359
247
    h      = c->cursor_h;
1360
1361
247
    if (x + w > c->width)
1362
52
        w = c->width - x;
1363
247
    if (y + h > c->height)
1364
        h = c->height - y;
1365
247
    if (x < 0) {
1366
        w      +=  x;
1367
        cursor += -x * 4;
1368
    } else {
1369
247
        dst    +=  x * 3;
1370
    }
1371
1372
247
    if (y < 0)
1373
3
        h      +=  y;
1374

247
    if (w < 0 || h < 0)
1375
        return;
1376
247
    if (y < 0) {
1377
3
        cursor += -y * c->cursor_stride;
1378
    } else {
1379
244
        dst    +=  y * stride;
1380
    }
1381
1382
8133
    for (j = 0; j < h; j++) {
1383
236974
        for (i = 0; i < w; i++) {
1384
229088
            uint8_t alpha = cursor[i * 4];
1385
229088
            APPLY_ALPHA(dst[i * 3 + 0], cursor[i * 4 + 1], alpha);
1386
229088
            APPLY_ALPHA(dst[i * 3 + 1], cursor[i * 4 + 2], alpha);
1387
229088
            APPLY_ALPHA(dst[i * 3 + 2], cursor[i * 4 + 3], alpha);
1388
        }
1389
7886
        dst    += stride;
1390
7886
        cursor += c->cursor_stride;
1391
    }
1392
}
1393
1394
247
static int g2m_decode_frame(AVCodecContext *avctx, void *data,
1395
                            int *got_picture_ptr, AVPacket *avpkt)
1396
{
1397
247
    const uint8_t *buf = avpkt->data;
1398
247
    int buf_size = avpkt->size;
1399
247
    G2MContext *c = avctx->priv_data;
1400
247
    AVFrame *pic = data;
1401
    GetByteContext bc, tbc;
1402
    int magic;
1403
247
    int got_header = 0;
1404
    uint32_t chunk_size, r_mask, g_mask, b_mask;
1405
    int chunk_type, chunk_start;
1406
    int i;
1407
    int ret;
1408
1409
247
    if (buf_size < 12) {
1410
        av_log(avctx, AV_LOG_ERROR,
1411
               "Frame should have at least 12 bytes, got %d instead\n",
1412
               buf_size);
1413
        return AVERROR_INVALIDDATA;
1414
    }
1415
1416
247
    bytestream2_init(&bc, buf, buf_size);
1417
1418
247
    magic = bytestream2_get_be32(&bc);
1419
247
    if ((magic & ~0xF) != MKBETAG('G', '2', 'M', '0') ||
1420

247
        (magic & 0xF) < 2 || (magic & 0xF) > 5) {
1421
        av_log(avctx, AV_LOG_ERROR, "Wrong magic %08X\n", magic);
1422
        return AVERROR_INVALIDDATA;
1423
    }
1424
1425
247
    c->swapuv = magic == MKBETAG('G', '2', 'M', '2');
1426
1427
761
    while (bytestream2_get_bytes_left(&bc) > 5) {
1428
514
        chunk_size  = bytestream2_get_le32(&bc) - 1;
1429
514
        chunk_type  = bytestream2_get_byte(&bc);
1430
514
        chunk_start = bytestream2_tell(&bc);
1431
514
        if (chunk_size > bytestream2_get_bytes_left(&bc)) {
1432
            av_log(avctx, AV_LOG_ERROR, "Invalid chunk size %"PRIu32" type %02X\n",
1433
                   chunk_size, chunk_type);
1434
            break;
1435
        }
1436

514
        switch (chunk_type) {
1437
4
        case DISPLAY_INFO:
1438
4
            got_header =
1439
4
            c->got_header = 0;
1440
4
            if (chunk_size < 21) {
1441
                av_log(avctx, AV_LOG_ERROR, "Invalid display info size %"PRIu32"\n",
1442
                       chunk_size);
1443
                break;
1444
            }
1445
4
            c->width  = bytestream2_get_be32(&bc);
1446
4
            c->height = bytestream2_get_be32(&bc);
1447

4
            if (c->width < 16 || c->height < 16) {
1448
                av_log(avctx, AV_LOG_ERROR,
1449
                       "Invalid frame dimensions %dx%d\n",
1450
                       c->width, c->height);
1451
                ret = AVERROR_INVALIDDATA;
1452
                goto header_fail;
1453
            }
1454

4
            if (c->width != avctx->width || c->height != avctx->height) {
1455
                ret = ff_set_dimensions(avctx, c->width, c->height);
1456
                if (ret < 0)
1457
                    goto header_fail;
1458
            }
1459
4
            c->compression = bytestream2_get_be32(&bc);
1460

4
            if (c->compression != 2 && c->compression != 3) {
1461
                avpriv_report_missing_feature(avctx, "Compression method %d",
1462
                                              c->compression);
1463
                ret = AVERROR_PATCHWELCOME;
1464
                goto header_fail;
1465
            }
1466
4
            c->tile_width  = bytestream2_get_be32(&bc);
1467
4
            c->tile_height = bytestream2_get_be32(&bc);
1468

4
            if (c->tile_width <= 0 || c->tile_height <= 0 ||
1469
4
                ((c->tile_width | c->tile_height) & 0xF) ||
1470

8
                c->tile_width * (uint64_t)c->tile_height >= INT_MAX / 4 ||
1471
4
                av_image_check_size2(c->tile_width, c->tile_height, avctx->max_pixels, avctx->pix_fmt, 0, avctx) < 0
1472
            ) {
1473
                av_log(avctx, AV_LOG_ERROR,
1474
                       "Invalid tile dimensions %dx%d\n",
1475
                       c->tile_width, c->tile_height);
1476
                ret = AVERROR_INVALIDDATA;
1477
                goto header_fail;
1478
            }
1479
4
            c->tiles_x = (c->width  + c->tile_width  - 1) / c->tile_width;
1480
4
            c->tiles_y = (c->height + c->tile_height - 1) / c->tile_height;
1481
4
            c->bpp     = bytestream2_get_byte(&bc);
1482
4
            if (c->bpp == 32) {
1483
4
                if (bytestream2_get_bytes_left(&bc) < 16 ||
1484
4
                    (chunk_size - 21) < 16) {
1485
                    av_log(avctx, AV_LOG_ERROR,
1486
                           "Display info: missing bitmasks!\n");
1487
                    ret = AVERROR_INVALIDDATA;
1488
                    goto header_fail;
1489
                }
1490
4
                r_mask = bytestream2_get_be32(&bc);
1491
4
                g_mask = bytestream2_get_be32(&bc);
1492
4
                b_mask = bytestream2_get_be32(&bc);
1493

4
                if (r_mask != 0xFF0000 || g_mask != 0xFF00 || b_mask != 0xFF) {
1494
                    avpriv_report_missing_feature(avctx,
1495
                                                  "Bitmasks: R=%"PRIX32", G=%"PRIX32", B=%"PRIX32,
1496
                                                  r_mask, g_mask, b_mask);
1497
                    ret = AVERROR_PATCHWELCOME;
1498
                    goto header_fail;
1499
                }
1500
            } else {
1501
                avpriv_request_sample(avctx, "bpp=%d", c->bpp);
1502
                ret = AVERROR_PATCHWELCOME;
1503
                goto header_fail;
1504
            }
1505
4
            if (g2m_init_buffers(c)) {
1506
                ret = AVERROR(ENOMEM);
1507
                goto header_fail;
1508
            }
1509
4
            got_header = 1;
1510
4
            break;
1511
237
        case TILE_DATA:
1512

237
            if (!c->tiles_x || !c->tiles_y) {
1513
                av_log(avctx, AV_LOG_WARNING,
1514
                       "No display info - skipping tile\n");
1515
                break;
1516
            }
1517
237
            if (chunk_size < 2) {
1518
                av_log(avctx, AV_LOG_ERROR, "Invalid tile data size %"PRIu32"\n",
1519
                       chunk_size);
1520
                break;
1521
            }
1522
237
            c->tile_x = bytestream2_get_byte(&bc);
1523
237
            c->tile_y = bytestream2_get_byte(&bc);
1524

237
            if (c->tile_x >= c->tiles_x || c->tile_y >= c->tiles_y) {
1525
                av_log(avctx, AV_LOG_ERROR,
1526
                       "Invalid tile pos %d,%d (in %dx%d grid)\n",
1527
                       c->tile_x, c->tile_y, c->tiles_x, c->tiles_y);
1528
                break;
1529
            }
1530
237
            ret = 0;
1531
237
            switch (c->compression) {
1532
136
            case COMPR_EPIC_J_B:
1533
272
                ret = epic_jb_decode_tile(c, c->tile_x, c->tile_y,
1534
136
                                          buf + bytestream2_tell(&bc),
1535
136
                                          chunk_size - 2, avctx);
1536
136
                break;
1537
101
            case COMPR_KEMPF_J_B:
1538
202
                ret = kempf_decode_tile(c, c->tile_x, c->tile_y,
1539
101
                                        buf + bytestream2_tell(&bc),
1540
101
                                        chunk_size - 2);
1541
101
                break;
1542
            }
1543

237
            if (ret && c->framebuf)
1544
                av_log(avctx, AV_LOG_ERROR, "Error decoding tile %d,%d\n",
1545
                       c->tile_x, c->tile_y);
1546
237
            break;
1547
245
        case CURSOR_POS:
1548
245
            if (chunk_size < 5) {
1549
                av_log(avctx, AV_LOG_ERROR, "Invalid cursor pos size %"PRIu32"\n",
1550
                       chunk_size);
1551
                break;
1552
            }
1553
245
            c->cursor_x = bytestream2_get_be16(&bc);
1554
245
            c->cursor_y = bytestream2_get_be16(&bc);
1555
245
            break;
1556
14
        case CURSOR_SHAPE:
1557
14
            if (chunk_size < 8) {
1558
                av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %"PRIu32"\n",
1559
                       chunk_size);
1560
                break;
1561
            }
1562
14
            bytestream2_init(&tbc, buf + bytestream2_tell(&bc),
1563
14
                             chunk_size - 4);
1564
14
            g2m_load_cursor(avctx, c, &tbc);
1565
14
            break;
1566
14
        case CHUNK_CC:
1567
        case CHUNK_CD:
1568
14
            break;
1569
        default:
1570
            av_log(avctx, AV_LOG_WARNING, "Skipping chunk type %02d\n",
1571
                   chunk_type);
1572
        }
1573
1574
        /* navigate to next chunk */
1575
514
        bytestream2_skip(&bc, chunk_start + chunk_size - bytestream2_tell(&bc));
1576
    }
1577
247
    if (got_header)
1578
4
        c->got_header = 1;
1579
1580

247
    if (c->width && c->height && c->framebuf) {
1581
247
        if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)
1582
            return ret;
1583
1584
247
        pic->key_frame = got_header;
1585
247
        pic->pict_type = got_header ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
1586
1587
210563
        for (i = 0; i < avctx->height; i++)
1588
210316
            memcpy(pic->data[0] + i * pic->linesize[0],
1589
210316
                   c->framebuf + i * c->framebuf_stride,
1590
210316
                   c->width * 3);
1591
247
        g2m_paint_cursor(c, pic->data[0], pic->linesize[0]);
1592
1593
247
        *got_picture_ptr = 1;
1594
    }
1595
1596
247
    return buf_size;
1597
1598
header_fail:
1599
    c->width   =
1600
    c->height  = 0;
1601
    c->tiles_x =
1602
    c->tiles_y = 0;
1603
    c->tile_width =
1604
    c->tile_height = 0;
1605
    return ret;
1606
}
1607
1608
6
static av_cold int g2m_decode_init(AVCodecContext *avctx)
1609
{
1610
6
    G2MContext *const c = avctx->priv_data;
1611
    int ret;
1612
1613
6
    if ((ret = jpg_init(avctx, &c->jc)) != 0) {
1614
        av_log(avctx, AV_LOG_ERROR, "Cannot initialise VLCs\n");
1615
        jpg_free_context(&c->jc);
1616
        return AVERROR(ENOMEM);
1617
    }
1618
1619
6
    avctx->pix_fmt = AV_PIX_FMT_RGB24;
1620
1621
    // store original sizes and check against those if resize happens
1622
6
    c->orig_width  = avctx->width;
1623
6
    c->orig_height = avctx->height;
1624
1625
6
    return 0;
1626
}
1627
1628
6
static av_cold int g2m_decode_end(AVCodecContext *avctx)
1629
{
1630
6
    G2MContext *const c = avctx->priv_data;
1631
1632
6
    jpg_free_context(&c->jc);
1633
1634
6
    av_freep(&c->epic_buf_base);
1635
6
    c->epic_buf = NULL;
1636
6
    av_freep(&c->kempf_buf);
1637
6
    av_freep(&c->kempf_flags);
1638
6
    av_freep(&c->synth_tile);
1639
6
    av_freep(&c->jpeg_tile);
1640
6
    av_freep(&c->cursor);
1641
6
    av_freep(&c->framebuf);
1642
1643
6
    return 0;
1644
}
1645
1646
AVCodec ff_g2m_decoder = {
1647
    .name           = "g2m",
1648
    .long_name      = NULL_IF_CONFIG_SMALL("Go2Meeting"),
1649
    .type           = AVMEDIA_TYPE_VIDEO,
1650
    .id             = AV_CODEC_ID_G2M,
1651
    .priv_data_size = sizeof(G2MContext),
1652
    .init           = g2m_decode_init,
1653
    .close          = g2m_decode_end,
1654
    .decode         = g2m_decode_frame,
1655
    .capabilities   = AV_CODEC_CAP_DR1,
1656
    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
1657
};