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

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

11016
            if (mask && !mask[mb_x * 2] && !mask[mb_x * 2 + 1] &&
304
4574
                !mask[mb_x * 2 +     mask_stride] &&
305
4458
                !mask[mb_x * 2 + 1 + mask_stride]) {
306
4437
                bx += 16;
307
4437
                continue;
308
            }
309
19737
            for (j = 0; j < 2; j++) {
310
39474
                for (i = 0; i < 2; i++) {
311

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

41955
    if (hash_elem != NULL && hash_elem->list != NULL)
455
39956
        return 1;
456
457
1999
    return 0;
458
}
459
460
136
static void epic_free_pixel_cache(ePICPixHash *hash)
461
{
462
    int i, j;
463
464
34952
    for (i = 0; i < EPIC_HASH_SIZE; i++) {
465
35350
        for (j = 0; j < hash->bucket_fill[i]; j++) {
466
534
            ePICPixListElem *list_elem = hash->bucket[i][j].list;
467
2192
            while (list_elem) {
468
1658
                ePICPixListElem *tmp = list_elem->next;
469
1658
                av_free(list_elem);
470
1658
                list_elem = tmp;
471
            }
472
        }
473
34816
        av_freep(&hash->bucket[i]);
474
34816
        hash->bucket_size[i] =
475
34816
        hash->bucket_fill[i] = 0;
476
    }
477
136
}
478
479
510904
static inline int is_pixel_on_stack(const ePICContext *dc, uint32_t pix)
480
{
481
    int i;
482
483
1163688
    for (i = 0; i < dc->stack_pos; i++)
484
806184
        if (dc->stack[i] == pix)
485
153400
            break;
486
487
510904
    return i != dc->stack_pos;
488
}
489
490
#define TOSIGNED(val) (((val) >> 1) ^ -((val) & 1))
491
492
9558
static inline int epic_decode_component_pred(ePICContext *dc,
493
                                             int N, int W, int NW)
494
{
495
9558
    unsigned delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
496
9558
    return mid_pred(N, N + W - NW, W) - TOSIGNED(delta);
497
}
498
499
4739
static uint32_t epic_decode_pixel_pred(ePICContext *dc, int x, int y,
500
                                       const uint32_t *curr_row,
501
                                       const uint32_t *above_row)
502
{
503
    uint32_t N, W, NW, pred;
504
    unsigned delta;
505
    int GN, GW, GNW, R, G, B;
506
507

4739
    if (x && y) {
508
3186
        W  = curr_row[x  - 1];
509
3186
        N  = above_row[x];
510
3186
        NW = above_row[x - 1];
511
512
3186
        GN  = (N  >> G_shift) & 0xFF;
513
3186
        GW  = (W  >> G_shift) & 0xFF;
514
3186
        GNW = (NW >> G_shift) & 0xFF;
515
516
3186
        G = epic_decode_component_pred(dc, GN, GW, GNW);
517
518
6372
        R = G + epic_decode_component_pred(dc,
519
3186
                                           ((N  >> R_shift) & 0xFF) - GN,
520
3186
                                           ((W  >> R_shift) & 0xFF) - GW,
521
3186
                                           ((NW >> R_shift) & 0xFF) - GNW);
522
523
3186
        B = G + epic_decode_component_pred(dc,
524
3186
                                           ((N  >> B_shift) & 0xFF) - GN,
525
3186
                                           ((W  >> B_shift) & 0xFF) - GW,
526
3186
                                           ((NW >> B_shift) & 0xFF) - GNW);
527
    } else {
528
1553
        if (x)
529
471
            pred = curr_row[x - 1];
530
        else
531
1082
            pred = above_row[x];
532
533
1553
        delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
534
1553
        R     = ((pred >> R_shift) & 0xFF) - TOSIGNED(delta);
535
536
1553
        delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
537
1553
        G     = ((pred >> G_shift) & 0xFF) - TOSIGNED(delta);
538
539
1553
        delta = ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung);
540
1553
        B     = ((pred >> B_shift) & 0xFF) - TOSIGNED(delta);
541
    }
542
543



4739
    if (R<0 || G<0 || B<0 || R > 255 || G > 255 || B > 255) {
544
        avpriv_request_sample(NULL, "RGB %d %d %d (out of range)", R, G, B);
545
        return 0;
546
    }
547
548
4739
    return (R << R_shift) | (G << G_shift) | (B << B_shift);
549
}
550
551
99449
static int epic_predict_pixel(ePICContext *dc, uint8_t *rung,
552
                              uint32_t *pPix, uint32_t pix)
553
{
554
99449
    if (!ff_els_decode_bit(&dc->els_ctx, rung)) {
555
91084
        *pPix = pix;
556
91084
        return 1;
557
    }
558
8365
    dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = pix;
559
8365
    return 0;
560
}
561
562
95756
static int epic_handle_edges(ePICContext *dc, int x, int y,
563
                             const uint32_t *curr_row,
564
                             const uint32_t *above_row, uint32_t *pPix)
565
{
566
    uint32_t pix;
567
568

95756
    if (!x && !y) { /* special case: top-left pixel */
569
        /* the top-left pixel is coded independently with 3 unsigned numbers */
570
136
        *pPix = (ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung) << R_shift) |
571
136
                (ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung) << G_shift) |
572
136
                (ff_els_decode_unsigned(&dc->els_ctx, &dc->unsigned_rung) << B_shift);
573
136
        return 1;
574
    }
575
576
95620
    if (x) { /* predict from W first */
577
78572
        pix = curr_row[x - 1];
578
78572
        if (epic_predict_pixel(dc, &dc->W_flag_rung, pPix, pix))
579
72049
            return 1;
580
    }
581
582
23571
    if (y) { /* then try to predict from N */
583
22080
        pix = above_row[x];
584

22080
        if (!dc->stack_pos || dc->stack[0] != pix) {
585
20877
            if (epic_predict_pixel(dc, &dc->N_flag_rung, pPix, pix))
586
19035
                return 1;
587
        }
588
    }
589
590
4536
    return 0;
591
}
592
593
218240
static int epic_decode_run_length(ePICContext *dc, int x, int y, int tile_width,
594
                                  const uint32_t *curr_row,
595
                                  const uint32_t *above_row,
596
                                  const uint32_t *above2_row,
597
                                  uint32_t *pPix, int *pRun)
598
{
599
218240
    int idx, got_pixel = 0, WWneW, old_WWneW = 0;
600
    uint32_t W, WW, N, NN, NW, NE, NWW, NNW, NNE;
601
602
218240
    *pRun = 0;
603
604
218240
    LOAD_NEIGHBOURS(x);
605
606
218240
    if (dc->next_run_pos == x) {
607
        /* can't reuse W for the new pixel in this case */
608
199455
        WWneW = 1;
609
    } else {
610
18785
        idx = (WW  != W)  << 7 |
611
18785
              (NW  != W)  << 6 |
612
18785
              (N   != NE) << 5 |
613
18785
              (NW  != N)  << 4 |
614
18785
              (NWW != NW) << 3 |
615
18785
              (NNE != NE) << 2 |
616
18785
              (NN  != N)  << 1 |
617
18785
              (NNW != NW);
618
18785
        WWneW = ff_els_decode_bit(&dc->els_ctx, &dc->W_ctx_rung[idx]);
619
18785
        if (WWneW < 0)
620
            return WWneW;
621
    }
622
623
218240
    if (WWneW)
624
201691
        dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = W;
625
    else {
626
16549
        *pPix     = W;
627
16549
        got_pixel = 1;
628
    }
629
630
    do {
631
503572
        int NWneW = 1;
632
503572
        if (got_pixel) // pixel value already known (derived from either W or N)
633
237740
            NWneW = *pPix != N;
634
        else { // pixel value is unknown and will be decoded later
635
265832
            NWneW = *pRun ? NWneW : NW != W;
636
637
            /* TODO: RFC this mess! */
638

265832
            switch (((NW != N) << 2) | (NWneW << 1) | WWneW) {
639
            case 0:
640
                break; // do nothing here
641
176548
            case 3:
642
            case 5:
643
            case 6:
644
            case 7:
645
176548
                if (!is_pixel_on_stack(dc, N)) {
646
457674
                    idx = WWneW       << 8 |
647

152558
                          (*pRun ? old_WWneW : WW != W) << 7 |
648
305116
                          NWneW       << 6 |
649
152558
                          (N   != NE) << 5 |
650
152558
                          (NW  != N)  << 4 |
651
152558
                          (NWW != NW) << 3 |
652
152558
                          (NNE != NE) << 2 |
653
152558
                          (NN  != N)  << 1 |
654
152558
                          (NNW != NW);
655
152558
                    if (!ff_els_decode_bit(&dc->els_ctx, &dc->N_ctx_rung[idx])) {
656
129319
                        NWneW = 0;
657
129319
                        *pPix = N;
658
129319
                        got_pixel = 1;
659
129319
                        break;
660
                    }
661
                }
662
                /* fall through */
663
            default:
664
136513
                NWneW = 1;
665
136513
                old_WWneW = WWneW;
666
136513
                if (!is_pixel_on_stack(dc, N))
667
23239
                    dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = N;
668
            }
669
        }
670
671
503572
        (*pRun)++;
672
503572
        if (x + *pRun >= tile_width - 1)
673
3378
            break;
674
675
500194
        UPDATE_NEIGHBOURS(x + *pRun);
676
677

500194
        if (!NWneW && NW == N && N == NE) {
678
            int pos, run, rle;
679
99184
            int start_pos = x + *pRun;
680
681
            /* scan for a run of pix in the line above */
682
99184
            uint32_t pix = above_row[start_pos + 1];
683
2511691
            for (pos = start_pos + 2; pos < tile_width; pos++)
684
2496269
                if (!(above_row[pos] == pix))
685
83762
                    break;
686
99184
            run = pos - start_pos - 1;
687
99184
            idx = av_ceil_log2(run);
688
99184
            if (ff_els_decode_bit(&dc->els_ctx, &dc->prev_row_rung[idx]))
689
66738
                *pRun += run;
690
            else {
691
                int flag;
692
                /* run-length is coded as plain binary number of idx - 1 bits */
693
131763
                for (pos = idx - 1, rle = 0, flag = 0; pos >= 0; pos--) {
694

193930
                    if ((1 << pos) + rle < run &&
695
94613
                        ff_els_decode_bit(&dc->els_ctx,
696
                                          flag ? &dc->runlen_one
697
                                               : &dc->runlen_zeroes[pos])) {
698
33844
                        flag = 1;
699
33844
                        rle |= 1 << pos;
700
                    }
701
                }
702
32446
                *pRun += rle;
703
32446
                break; // return immediately
704
            }
705
66738
            if (x + *pRun >= tile_width - 1)
706
13519
                break;
707
708
53219
            LOAD_NEIGHBOURS(x + *pRun);
709
53219
            WWneW = 0;
710
53219
            NWneW = 0;
711
        }
712
713
908458
        idx = WWneW       << 7 |
714
908458
              NWneW       << 6 |
715
454229
              (N   != NE) << 5 |
716
454229
              (NW  != N)  << 4 |
717
454229
              (NWW != NW) << 3 |
718
454229
              (NNE != NE) << 2 |
719
454229
              (NN  != N)  << 1 |
720
454229
              (NNW != NW);
721
454229
        WWneW = ff_els_decode_bit(&dc->els_ctx, &dc->W_ctx_rung[idx]);
722
454229
    } while (!WWneW);
723
724
218240
    dc->next_run_pos = x + *pRun;
725
218240
    return got_pixel;
726
}
727
728
36049
static int epic_predict_pixel2(ePICContext *dc, uint8_t *rung,
729
                               uint32_t *pPix, uint32_t pix)
730
{
731
36049
    if (ff_els_decode_bit(&dc->els_ctx, rung)) {
732
22192
        *pPix = pix;
733
22192
        return 1;
734
    }
735
13857
    dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = pix;
736
13857
    return 0;
737
}
738
739
76908
static int epic_predict_from_NW_NE(ePICContext *dc, int x, int y, int run,
740
                                   int tile_width, const uint32_t *curr_row,
741
                                   const uint32_t *above_row, uint32_t *pPix)
742
{
743
    int pos;
744
745
    /* try to reuse the NW pixel first */
746

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

73974
        if (NW != curr_row[x - 1] && NW != above_row[x] && !is_pixel_on_stack(dc, NW)) {
749
20189
            if (epic_predict_pixel2(dc, &dc->nw_pred_rung[NW & 0xFF], pPix, NW))
750
12191
                return 1;
751
        }
752
    }
753
754
    /* try to reuse the NE[x + run, y] pixel */
755
64717
    pos = x + run - 1;
756

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

62826
        if (NE != above_row[pos] && !is_pixel_on_stack(dc, NE)) {
759
15860
            if (epic_predict_pixel2(dc, &dc->ne_pred_rung[NE & 0xFF], pPix, NE))
760
10001
                return 1;
761
        }
762
    }
763
764
54716
    return 0;
765
}
766
767
53634
static int epic_decode_from_cache(ePICContext *dc, uint32_t W, uint32_t *pPix)
768
{
769
53634
    ePICPixListElem *list, *prev = NULL;
770
53634
    ePICPixHashElem *hash_elem = epic_hash_find(&dc->hash, W);
771
772

53634
    if (!hash_elem || !hash_elem->list)
773
534
        return 0;
774
775
53100
    list = hash_elem->list;
776
154706
    while (list) {
777
153582
        if (!is_pixel_on_stack(dc, list->pixel)) {
778
142918
            if (ff_els_decode_bit(&dc->els_ctx, &list->rung)) {
779
51976
                *pPix = list->pixel;
780
51976
                if (list != hash_elem->list) {
781
36609
                    prev->next      = list->next;
782
36609
                    list->next      = hash_elem->list;
783
36609
                    hash_elem->list = list;
784
                }
785
51976
                return 1;
786
            }
787
90942
            dc->stack[dc->stack_pos++ & EPIC_PIX_STACK_MAX] = list->pixel;
788
        }
789
101606
        prev = list;
790
101606
        list = list->next;
791
    }
792
793
1124
    return 0;
794
}
795
796
136
static int epic_decode_tile(ePICContext *dc, uint8_t *out, int tile_height,
797
                            int tile_width, int stride)
798
{
799
    int x, y;
800
    uint32_t pix;
801
136
    uint32_t *curr_row = NULL, *above_row = NULL, *above2_row;
802
803
17320
    for (y = 0; y < tile_height; y++, out += stride) {
804
17184
        above2_row = above_row;
805
17184
        above_row  = curr_row;
806
17184
        curr_row   = (uint32_t *) out;
807
808
333179
        for (x = 0, dc->next_run_pos = 0; x < tile_width;) {
809
315995
            if (dc->els_ctx.err)
810
                return AVERROR_INVALIDDATA; // bail out in the case of ELS overflow
811
812
315995
            pix = curr_row[x - 1]; // get W pixel
813
814

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

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

101123
                pix != above_row[x - 2] && pix != above_row[x] &&
817
41955
                !epic_cache_entries_for_pixel(&dc->hash, pix)) {
818
1999
                curr_row[x] = epic_decode_pixel_pred(dc, x, y, curr_row, above_row);
819
1999
                x++;
820
            } else {
821
                int got_pixel, run;
822
313996
                dc->stack_pos = 0; // empty stack
823
824

313996
                if (y < 2 || x < 2 || x == tile_width - 1) {
825
95756
                    run       = 1;
826
95756
                    got_pixel = epic_handle_edges(dc, x, y, curr_row, above_row, &pix);
827
                } else {
828
218240
                    got_pixel = epic_decode_run_length(dc, x, y, tile_width,
829
                                                       curr_row, above_row,
830
                                                       above2_row, &pix, &run);
831
218240
                    if (got_pixel < 0)
832
                        return got_pixel;
833
                }
834
835

313996
                if (!got_pixel && !epic_predict_from_NW_NE(dc, x, y, run,
836
                                                           tile_width, curr_row,
837
                                                           above_row, &pix)) {
838
54716
                    uint32_t ref_pix = curr_row[x - 1];
839

54716
                    if (!x || !epic_decode_from_cache(dc, ref_pix, &pix)) {
840
2740
                        pix = epic_decode_pixel_pred(dc, x, y, curr_row, above_row);
841
2740
                        if (is_pixel_on_stack(dc, pix))
842
                            return AVERROR_INVALIDDATA;
843
844
2740
                        if (x) {
845
1658
                            int ret = epic_add_pixel_to_cache(&dc->hash,
846
                                                              ref_pix,
847
                                                              pix);
848
1658
                            if (ret)
849
                                return ret;
850
                        }
851
                    }
852
                }
853
3159741
                for (; run > 0; x++, run--)
854
2845745
                    curr_row[x] = pix;
855
            }
856
        }
857
    }
858
859
136
    return 0;
860
}
861
862
136
static int epic_jb_decode_tile(G2MContext *c, int tile_x, int tile_y,
863
                               const uint8_t *src, size_t src_size,
864
                               AVCodecContext *avctx)
865
{
866
136
    uint8_t prefix, mask = 0x80;
867
    int extrabytes, tile_width, tile_height, awidth, aheight;
868
    size_t els_dsize;
869
    uint8_t *dst;
870
871
136
    if (!src_size)
872
        return 0;
873
874
    /* get data size of the ELS partition as unsigned variable-length integer */
875
136
    prefix = *src++;
876
136
    src_size--;
877

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

136
    if (extrabytes > 3 || src_size < extrabytes) {
880
        av_log(avctx, AV_LOG_ERROR, "ePIC: invalid data size VLI\n");
881
        return AVERROR_INVALIDDATA;
882
    }
883
884
136
    els_dsize = prefix & ((0x80 >> extrabytes) - 1); // mask out the length prefix
885
224
    while (extrabytes-- > 0) {
886
88
        els_dsize = (els_dsize << 8) | *src++;
887
88
        src_size--;
888
    }
889
890
136
    if (src_size < els_dsize) {
891
        av_log(avctx, AV_LOG_ERROR, "ePIC: data too short, needed %"SIZE_SPECIFIER", got %"SIZE_SPECIFIER"\n",
892
               els_dsize, src_size);
893
        return AVERROR_INVALIDDATA;
894
    }
895
896
136
    tile_width  = FFMIN(c->width  - tile_x * c->tile_width,  c->tile_width);
897
136
    tile_height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
898
136
    awidth      = FFALIGN(tile_width,  16);
899
136
    aheight     = FFALIGN(tile_height, 16);
900
901
136
    if (tile_width > (1 << FF_ARRAY_ELEMS(c->ec.prev_row_rung))) {
902
        avpriv_request_sample(avctx, "large tile width");
903
        return AVERROR_INVALIDDATA;
904
    }
905
906
136
    if (els_dsize) {
907
        int ret, i, j, k;
908
        uint8_t tr_r, tr_g, tr_b, *buf;
909
        uint32_t *in;
910
        /* ELS decoder initializations */
911
136
        memset(&c->ec, 0, sizeof(c->ec));
912
136
        ff_els_decoder_init(&c->ec.els_ctx, src, els_dsize);
913
136
        epic_hash_init(&c->ec.hash);
914
915
        /* decode transparent pixel value */
916
136
        tr_r = ff_els_decode_unsigned(&c->ec.els_ctx, &c->ec.unsigned_rung);
917
136
        tr_g = ff_els_decode_unsigned(&c->ec.els_ctx, &c->ec.unsigned_rung);
918
136
        tr_b = ff_els_decode_unsigned(&c->ec.els_ctx, &c->ec.unsigned_rung);
919
136
        if (c->ec.els_ctx.err != 0) {
920
            av_log(avctx, AV_LOG_ERROR,
921
                   "ePIC: couldn't decode transparency pixel!\n");
922
            ff_els_decoder_uninit(&c->ec.unsigned_rung);
923
            return AVERROR_INVALIDDATA;
924
        }
925
926
136
        ret = epic_decode_tile(&c->ec, c->epic_buf, tile_height, tile_width,
927
                               c->epic_buf_stride);
928
929
136
        epic_free_pixel_cache(&c->ec.hash);
930
136
        ff_els_decoder_uninit(&c->ec.unsigned_rung);
931
932
136
        if (ret) {
933
            av_log(avctx, AV_LOG_ERROR,
934
                   "ePIC: tile decoding failed, frame=%d, tile_x=%d, tile_y=%d\n",
935
                   avctx->frame_number, tile_x, tile_y);
936
            return AVERROR_INVALIDDATA;
937
        }
938
939
136
        buf = c->epic_buf;
940
136
        dst = c->framebuf + tile_x * c->tile_width * 3 +
941
136
              tile_y * c->tile_height * c->framebuf_stride;
942
943
17320
        for (j = 0; j < tile_height; j++) {
944
17184
            uint8_t *out = dst;
945
17184
            in  = (uint32_t *) buf;
946
2864928
            for (i = 0; i < tile_width; i++) {
947
2847744
                out[0] = (in[i] >> R_shift) & 0xFF;
948
2847744
                out[1] = (in[i] >> G_shift) & 0xFF;
949
2847744
                out[2] = (in[i] >> B_shift) & 0xFF;
950
2847744
                out   += 3;
951
            }
952
17184
            buf += c->epic_buf_stride;
953
17184
            dst += c->framebuf_stride;
954
        }
955
956
136
        if (src_size > els_dsize) {
957
            uint8_t *jpg;
958
            uint32_t tr;
959
92
            int bstride = FFALIGN(tile_width, 16) >> 3;
960
92
            int nblocks = 0;
961
92
            int estride = c->epic_buf_stride >> 2;
962
963
92
            src      += els_dsize;
964
92
            src_size -= els_dsize;
965
966
92
            in = (uint32_t *) c->epic_buf;
967
92
            tr = (tr_r << R_shift) | (tr_g << G_shift) | (tr_b << B_shift);
968
969
92
            memset(c->kempf_flags, 0,
970
92
                   (aheight >> 3) * bstride * sizeof(*c->kempf_flags));
971
1543
            for (j = 0; j < tile_height; j += 8) {
972
32605
                for (i = 0; i < tile_width; i += 8) {
973
31154
                    c->kempf_flags[(i >> 3) + (j >> 3) * bstride] = 0;
974
1113006
                    for (k = 0; k < 8 * 8; k++) {
975
1096594
                        if (in[i + (k & 7) + (k >> 3) * estride] == tr) {
976
14742
                            c->kempf_flags[(i >> 3) + (j >> 3) * bstride] = 1;
977
14742
                            nblocks++;
978
14742
                            break;
979
                        }
980
                    }
981
                }
982
1451
                in += 8 * estride;
983
            }
984
985
92
            memset(c->jpeg_tile, 0, c->tile_stride * aheight);
986
92
            jpg_decode_data(&c->jc, awidth, aheight, src, src_size,
987
                            c->jpeg_tile, c->tile_stride,
988
92
                            c->kempf_flags, bstride, nblocks, c->swapuv);
989
990
92
            in  = (uint32_t *) c->epic_buf;
991
92
            dst = c->framebuf + tile_x * c->tile_width * 3 +
992
92
                  tile_y * c->tile_height * c->framebuf_stride;
993
92
            jpg = c->jpeg_tile;
994
11672
            for (j = 0; j < tile_height; j++) {
995
2000508
                for (i = 0; i < tile_width; i++)
996
1988928
                    if (in[i] == tr)
997
717442
                        memcpy(dst + i * 3, jpg + i * 3, 3);
998
11580
                in  += c->epic_buf_stride >> 2;
999
11580
                dst += c->framebuf_stride;
1000
11580
                jpg += c->tile_stride;
1001
            }
1002
        }
1003
    } else {
1004
        dst = c->framebuf + tile_x * c->tile_width * 3 +
1005
              tile_y * c->tile_height * c->framebuf_stride;
1006
        return jpg_decode_data(&c->jc, tile_width, tile_height, src, src_size,
1007
                               dst, c->framebuf_stride, NULL, 0, 0, c->swapuv);
1008
    }
1009
1010
136
    return 0;
1011
}
1012
1013
81
static int kempf_restore_buf(const uint8_t *src, int len,
1014
                              uint8_t *dst, int stride,
1015
                              const uint8_t *jpeg_tile, int tile_stride,
1016
                              int width, int height,
1017
                              const uint8_t *pal, int npal, int tidx)
1018
{
1019
    GetBitContext gb;
1020
    int i, j, nb, col;
1021
    int ret;
1022
81
    int align_width = FFALIGN(width, 16);
1023
1024
81
    if ((ret = init_get_bits8(&gb, src, len)) < 0)
1025
        return ret;
1026
1027
81
    if (npal <= 2)       nb = 1;
1028
81
    else if (npal <= 4)  nb = 2;
1029
66
    else if (npal <= 16) nb = 4;
1030
29
    else                 nb = 8;
1031
1032

10449
    for (j = 0; j < height; j++, dst += stride, jpeg_tile = FF_PTR_ADD(jpeg_tile, tile_stride)) {
1033
10368
        if (get_bits(&gb, 8))
1034
            continue;
1035
1654912
        for (i = 0; i < width; i++) {
1036
1644544
            col = get_bits(&gb, nb);
1037
1644544
            if (col != tidx)
1038
1323579
                memcpy(dst + i * 3, pal + col * 3, 3);
1039
            else
1040
320965
                memcpy(dst + i * 3, jpeg_tile + i * 3, 3);
1041
        }
1042
10368
        skip_bits_long(&gb, nb * (align_width - width));
1043
    }
1044
1045
81
    return 0;
1046
}
1047
1048
101
static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,
1049
                             const uint8_t *src, int src_size)
1050
{
1051
    int width, height;
1052
101
    int hdr, zsize, npal, tidx = -1, ret;
1053
    int i, j;
1054
101
    const uint8_t *src_end = src + src_size;
1055
    uint8_t pal[768], transp[3];
1056
101
    uLongf dlen = (c->tile_width + 1) * c->tile_height;
1057
    int sub_type;
1058
    int nblocks, cblocks, bstride;
1059
    int bits, bitbuf, coded;
1060
101
    uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +
1061
101
                   tile_y * c->tile_height * c->framebuf_stride;
1062
1063
101
    if (src_size < 2)
1064
        return AVERROR_INVALIDDATA;
1065
1066
101
    width  = FFMIN(c->width  - tile_x * c->tile_width,  c->tile_width);
1067
101
    height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);
1068
1069
101
    hdr      = *src++;
1070
101
    sub_type = hdr >> 5;
1071
101
    if (sub_type == 0) {
1072
        int j;
1073
20
        memcpy(transp, src, 3);
1074
20
        src += 3;
1075
2580
        for (j = 0; j < height; j++, dst += c->framebuf_stride)
1076
403968
            for (i = 0; i < width; i++)
1077
401408
                memcpy(dst + i * 3, transp, 3);
1078
20
        return 0;
1079
81
    } else if (sub_type == 1) {
1080
        return jpg_decode_data(&c->jc, width, height, src, src_end - src,
1081
                               dst, c->framebuf_stride, NULL, 0, 0, 0);
1082
    }
1083
1084
81
    if (sub_type != 2) {
1085
67
        memcpy(transp, src, 3);
1086
67
        src += 3;
1087
    }
1088
81
    npal = *src++ + 1;
1089
81
    if (src_end - src < npal * 3)
1090
        return AVERROR_INVALIDDATA;
1091
81
    memcpy(pal, src, npal * 3);
1092
81
    src += npal * 3;
1093
81
    if (sub_type != 2) {
1094
134
        for (i = 0; i < npal; i++) {
1095
134
            if (!memcmp(pal + i * 3, transp, 3)) {
1096
67
                tidx = i;
1097
67
                break;
1098
            }
1099
        }
1100
    }
1101
1102
81
    if (src_end - src < 2)
1103
        return 0;
1104
81
    zsize = (src[0] << 8) | src[1];
1105
81
    src  += 2;
1106
1107
81
    if (src_end - src < zsize + (sub_type != 2))
1108
        return AVERROR_INVALIDDATA;
1109
1110
81
    ret = uncompress(c->kempf_buf, &dlen, src, zsize);
1111
81
    if (ret)
1112
        return AVERROR_INVALIDDATA;
1113
81
    src += zsize;
1114
1115
81
    if (sub_type == 2) {
1116
14
        kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
1117
                          NULL, 0, width, height, pal, npal, tidx);
1118
14
        return 0;
1119
    }
1120
1121
67
    nblocks = *src++ + 1;
1122
67
    cblocks = 0;
1123
67
    bstride = FFALIGN(width, 16) >> 3;
1124
    // blocks are coded LSB and we need normal bitreader for JPEG data
1125
67
    bits = 0;
1126
603
    for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {
1127
5984
        for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {
1128
5448
            if (!bits) {
1129
681
                if (src >= src_end)
1130
                    return AVERROR_INVALIDDATA;
1131
681
                bitbuf = *src++;
1132
681
                bits   = 8;
1133
            }
1134
5448
            coded = bitbuf & 1;
1135
5448
            bits--;
1136
5448
            bitbuf >>= 1;
1137
5448
            cblocks += coded;
1138
5448
            if (cblocks > nblocks)
1139
                return AVERROR_INVALIDDATA;
1140
5448
            c->kempf_flags[j * 2 +      i * 2      * bstride] =
1141
5448
            c->kempf_flags[j * 2 + 1 +  i * 2      * bstride] =
1142
5448
            c->kempf_flags[j * 2 +     (i * 2 + 1) * bstride] =
1143
5448
            c->kempf_flags[j * 2 + 1 + (i * 2 + 1) * bstride] = coded;
1144
        }
1145
    }
1146
1147
67
    memset(c->jpeg_tile, 0, c->tile_stride * height);
1148
67
    jpg_decode_data(&c->jc, width, height, src, src_end - src,
1149
                    c->jpeg_tile, c->tile_stride,
1150
67
                    c->kempf_flags, bstride, nblocks * 4, 0);
1151
1152
67
    kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,
1153
67
                      c->jpeg_tile, c->tile_stride,
1154
                      width, height, pal, npal, tidx);
1155
1156
67
    return 0;
1157
}
1158
1159
4
static int g2m_init_buffers(G2MContext *c)
1160
{
1161
    int aligned_height;
1162
1163

4
    if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
1164
4
        c->framebuf_stride = FFALIGN(c->width + 15, 16) * 3;
1165
4
        aligned_height     = c->height + 15;
1166
4
        av_free(c->framebuf);
1167
4
        c->framebuf = av_mallocz_array(c->framebuf_stride, aligned_height);
1168
4
        if (!c->framebuf)
1169
            return AVERROR(ENOMEM);
1170
    }
1171

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

1
        (c->compression == 2 && !c->epic_buf_base) ||
1173
1
        c->old_tile_w < c->tile_width ||
1174
        c->old_tile_h < c->tile_height) {
1175
4
        c->tile_stride     = FFALIGN(c->tile_width, 16) * 3;
1176
4
        c->epic_buf_stride = FFALIGN(c->tile_width * 4, 16);
1177
4
        aligned_height     = FFALIGN(c->tile_height,    16);
1178
4
        av_freep(&c->synth_tile);
1179
4
        av_freep(&c->jpeg_tile);
1180
4
        av_freep(&c->kempf_buf);
1181
4
        av_freep(&c->kempf_flags);
1182
4
        av_freep(&c->epic_buf_base);
1183
4
        c->epic_buf    = NULL;
1184
4
        c->synth_tile  = av_mallocz(c->tile_stride      * aligned_height);
1185
4
        c->jpeg_tile   = av_mallocz(c->tile_stride      * aligned_height);
1186
4
        c->kempf_buf   = av_mallocz((c->tile_width + 1) * aligned_height +
1187
                                    AV_INPUT_BUFFER_PADDING_SIZE);
1188
4
        c->kempf_flags = av_mallocz(c->tile_width       * aligned_height);
1189

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

4
            !c->kempf_buf || !c->kempf_flags)
1191
            return AVERROR(ENOMEM);
1192
4
        if (c->compression == 2) {
1193
3
            c->epic_buf_base = av_mallocz(c->epic_buf_stride * aligned_height + 4);
1194
3
            if (!c->epic_buf_base)
1195
                return AVERROR(ENOMEM);
1196
3
            c->epic_buf = c->epic_buf_base + 4;
1197
        }
1198
    }
1199
1200
4
    return 0;
1201
}
1202
1203
14
static int g2m_load_cursor(AVCodecContext *avctx, G2MContext *c,
1204
                           GetByteContext *gb)
1205
{
1206
    int i, j, k;
1207
    uint8_t *dst;
1208
    uint32_t bits;
1209
    uint32_t cur_size, cursor_w, cursor_h, cursor_stride;
1210
    uint32_t cursor_hot_x, cursor_hot_y;
1211
    int cursor_fmt, err;
1212
1213
14
    cur_size     = bytestream2_get_be32(gb);
1214
14
    cursor_w     = bytestream2_get_byte(gb);
1215
14
    cursor_h     = bytestream2_get_byte(gb);
1216
14
    cursor_hot_x = bytestream2_get_byte(gb);
1217
14
    cursor_hot_y = bytestream2_get_byte(gb);
1218
14
    cursor_fmt   = bytestream2_get_byte(gb);
1219
1220

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

14
    if (cursor_w < 1 || cursor_w > 256 ||
1223
14
        cursor_h < 1 || cursor_h > 256) {
1224
        av_log(avctx, AV_LOG_ERROR, "Invalid cursor dimensions %"PRIu32"x%"PRIu32"\n",
1225
               cursor_w, cursor_h);
1226
        return AVERROR_INVALIDDATA;
1227
    }
1228

14
    if (cursor_hot_x > cursor_w || cursor_hot_y > cursor_h) {
1229
        av_log(avctx, AV_LOG_WARNING, "Invalid hotspot position %"PRIu32",%"PRIu32"\n",
1230
               cursor_hot_x, cursor_hot_y);
1231
        cursor_hot_x = FFMIN(cursor_hot_x, cursor_w - 1);
1232
        cursor_hot_y = FFMIN(cursor_hot_y, cursor_h - 1);
1233
    }
1234
14
    if (cur_size - 9 > bytestream2_get_bytes_left(gb) ||
1235
14
        c->cursor_w * c->cursor_h / 4 > cur_size) {
1236
        av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %"PRIu32"/%u\n",
1237
               cur_size, bytestream2_get_bytes_left(gb));
1238
        return AVERROR_INVALIDDATA;
1239
    }
1240

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

247
    if (w < 0 || h < 0)
1355
        return;
1356
247
    if (y < 0) {
1357
3
        cursor += -y * c->cursor_stride;
1358
    } else {
1359
244
        dst    +=  y * stride;
1360
    }
1361
1362
8133
    for (j = 0; j < h; j++) {
1363
236974
        for (i = 0; i < w; i++) {
1364
229088
            uint8_t alpha = cursor[i * 4];
1365
229088
            APPLY_ALPHA(dst[i * 3 + 0], cursor[i * 4 + 1], alpha);
1366
229088
            APPLY_ALPHA(dst[i * 3 + 1], cursor[i * 4 + 2], alpha);
1367
229088
            APPLY_ALPHA(dst[i * 3 + 2], cursor[i * 4 + 3], alpha);
1368
        }
1369
7886
        dst    += stride;
1370
7886
        cursor += c->cursor_stride;
1371
    }
1372
}
1373
1374
247
static int g2m_decode_frame(AVCodecContext *avctx, void *data,
1375
                            int *got_picture_ptr, AVPacket *avpkt)
1376
{
1377
247
    const uint8_t *buf = avpkt->data;
1378
247
    int buf_size = avpkt->size;
1379
247
    G2MContext *c = avctx->priv_data;
1380
247
    AVFrame *pic = data;
1381
    GetByteContext bc, tbc;
1382
    int magic;
1383
247
    int got_header = 0;
1384
    uint32_t chunk_size, r_mask, g_mask, b_mask;
1385
    int chunk_type, chunk_start;
1386
    int i;
1387
    int ret;
1388
1389
247
    if (buf_size < 12) {
1390
        av_log(avctx, AV_LOG_ERROR,
1391
               "Frame should have at least 12 bytes, got %d instead\n",
1392
               buf_size);
1393
        return AVERROR_INVALIDDATA;
1394
    }
1395
1396
247
    bytestream2_init(&bc, buf, buf_size);
1397
1398
247
    magic = bytestream2_get_be32(&bc);
1399
247
    if ((magic & ~0xF) != MKBETAG('G', '2', 'M', '0') ||
1400

247
        (magic & 0xF) < 2 || (magic & 0xF) > 5) {
1401
        av_log(avctx, AV_LOG_ERROR, "Wrong magic %08X\n", magic);
1402
        return AVERROR_INVALIDDATA;
1403
    }
1404
1405
247
    c->swapuv = magic == MKBETAG('G', '2', 'M', '2');
1406
1407
761
    while (bytestream2_get_bytes_left(&bc) > 5) {
1408
514
        chunk_size  = bytestream2_get_le32(&bc) - 1;
1409
514
        chunk_type  = bytestream2_get_byte(&bc);
1410
514
        chunk_start = bytestream2_tell(&bc);
1411
514
        if (chunk_size > bytestream2_get_bytes_left(&bc)) {
1412
            av_log(avctx, AV_LOG_ERROR, "Invalid chunk size %"PRIu32" type %02X\n",
1413
                   chunk_size, chunk_type);
1414
            break;
1415
        }
1416

514
        switch (chunk_type) {
1417
4
        case DISPLAY_INFO:
1418
4
            got_header =
1419
4
            c->got_header = 0;
1420
4
            if (chunk_size < 21) {
1421
                av_log(avctx, AV_LOG_ERROR, "Invalid display info size %"PRIu32"\n",
1422
                       chunk_size);
1423
                break;
1424
            }
1425
4
            c->width  = bytestream2_get_be32(&bc);
1426
4
            c->height = bytestream2_get_be32(&bc);
1427

4
            if (c->width < 16 || c->height < 16) {
1428
                av_log(avctx, AV_LOG_ERROR,
1429
                       "Invalid frame dimensions %dx%d\n",
1430
                       c->width, c->height);
1431
                ret = AVERROR_INVALIDDATA;
1432
                goto header_fail;
1433
            }
1434

4
            if (c->width != avctx->width || c->height != avctx->height) {
1435
                ret = ff_set_dimensions(avctx, c->width, c->height);
1436
                if (ret < 0)
1437
                    goto header_fail;
1438
            }
1439
4
            c->compression = bytestream2_get_be32(&bc);
1440

4
            if (c->compression != 2 && c->compression != 3) {
1441
                avpriv_report_missing_feature(avctx, "Compression method %d",
1442
                                              c->compression);
1443
                ret = AVERROR_PATCHWELCOME;
1444
                goto header_fail;
1445
            }
1446
4
            c->tile_width  = bytestream2_get_be32(&bc);
1447
4
            c->tile_height = bytestream2_get_be32(&bc);
1448

4
            if (c->tile_width <= 0 || c->tile_height <= 0 ||
1449
4
                ((c->tile_width | c->tile_height) & 0xF) ||
1450

8
                c->tile_width * (uint64_t)c->tile_height >= INT_MAX / 4 ||
1451
4
                av_image_check_size2(c->tile_width, c->tile_height, avctx->max_pixels, avctx->pix_fmt, 0, avctx) < 0
1452
            ) {
1453
                av_log(avctx, AV_LOG_ERROR,
1454
                       "Invalid tile dimensions %dx%d\n",
1455
                       c->tile_width, c->tile_height);
1456
                ret = AVERROR_INVALIDDATA;
1457
                goto header_fail;
1458
            }
1459
4
            c->tiles_x = (c->width  + c->tile_width  - 1) / c->tile_width;
1460
4
            c->tiles_y = (c->height + c->tile_height - 1) / c->tile_height;
1461
4
            c->bpp     = bytestream2_get_byte(&bc);
1462
4
            if (c->bpp == 32) {
1463
4
                if (bytestream2_get_bytes_left(&bc) < 16 ||
1464
4
                    (chunk_size - 21) < 16) {
1465
                    av_log(avctx, AV_LOG_ERROR,
1466
                           "Display info: missing bitmasks!\n");
1467
                    ret = AVERROR_INVALIDDATA;
1468
                    goto header_fail;
1469
                }
1470
4
                r_mask = bytestream2_get_be32(&bc);
1471
4
                g_mask = bytestream2_get_be32(&bc);
1472
4
                b_mask = bytestream2_get_be32(&bc);
1473

4
                if (r_mask != 0xFF0000 || g_mask != 0xFF00 || b_mask != 0xFF) {
1474
                    avpriv_report_missing_feature(avctx,
1475
                                                  "Bitmasks: R=%"PRIX32", G=%"PRIX32", B=%"PRIX32,
1476
                                                  r_mask, g_mask, b_mask);
1477
                    ret = AVERROR_PATCHWELCOME;
1478
                    goto header_fail;
1479
                }
1480
            } else {
1481
                avpriv_request_sample(avctx, "bpp=%d", c->bpp);
1482
                ret = AVERROR_PATCHWELCOME;
1483
                goto header_fail;
1484
            }
1485
4
            if (g2m_init_buffers(c)) {
1486
                ret = AVERROR(ENOMEM);
1487
                goto header_fail;
1488
            }
1489
4
            got_header = 1;
1490
4
            break;
1491
237
        case TILE_DATA:
1492

237
            if (!c->tiles_x || !c->tiles_y) {
1493
                av_log(avctx, AV_LOG_WARNING,
1494
                       "No display info - skipping tile\n");
1495
                break;
1496
            }
1497
237
            if (chunk_size < 2) {
1498
                av_log(avctx, AV_LOG_ERROR, "Invalid tile data size %"PRIu32"\n",
1499
                       chunk_size);
1500
                break;
1501
            }
1502
237
            c->tile_x = bytestream2_get_byte(&bc);
1503
237
            c->tile_y = bytestream2_get_byte(&bc);
1504

237
            if (c->tile_x >= c->tiles_x || c->tile_y >= c->tiles_y) {
1505
                av_log(avctx, AV_LOG_ERROR,
1506
                       "Invalid tile pos %d,%d (in %dx%d grid)\n",
1507
                       c->tile_x, c->tile_y, c->tiles_x, c->tiles_y);
1508
                break;
1509
            }
1510
237
            ret = 0;
1511
237
            switch (c->compression) {
1512
136
            case COMPR_EPIC_J_B:
1513
272
                ret = epic_jb_decode_tile(c, c->tile_x, c->tile_y,
1514
136
                                          buf + bytestream2_tell(&bc),
1515
136
                                          chunk_size - 2, avctx);
1516
136
                break;
1517
101
            case COMPR_KEMPF_J_B:
1518
202
                ret = kempf_decode_tile(c, c->tile_x, c->tile_y,
1519
101
                                        buf + bytestream2_tell(&bc),
1520
101
                                        chunk_size - 2);
1521
101
                break;
1522
            }
1523

237
            if (ret && c->framebuf)
1524
                av_log(avctx, AV_LOG_ERROR, "Error decoding tile %d,%d\n",
1525
                       c->tile_x, c->tile_y);
1526
237
            break;
1527
245
        case CURSOR_POS:
1528
245
            if (chunk_size < 5) {
1529
                av_log(avctx, AV_LOG_ERROR, "Invalid cursor pos size %"PRIu32"\n",
1530
                       chunk_size);
1531
                break;
1532
            }
1533
245
            c->cursor_x = bytestream2_get_be16(&bc);
1534
245
            c->cursor_y = bytestream2_get_be16(&bc);
1535
245
            break;
1536
14
        case CURSOR_SHAPE:
1537
14
            if (chunk_size < 8) {
1538
                av_log(avctx, AV_LOG_ERROR, "Invalid cursor data size %"PRIu32"\n",
1539
                       chunk_size);
1540
                break;
1541
            }
1542
14
            bytestream2_init(&tbc, buf + bytestream2_tell(&bc),
1543
14
                             chunk_size - 4);
1544
14
            g2m_load_cursor(avctx, c, &tbc);
1545
14
            break;
1546
14
        case CHUNK_CC:
1547
        case CHUNK_CD:
1548
14
            break;
1549
        default:
1550
            av_log(avctx, AV_LOG_WARNING, "Skipping chunk type %02d\n",
1551
                   chunk_type);
1552
        }
1553
1554
        /* navigate to next chunk */
1555
514
        bytestream2_skip(&bc, chunk_start + chunk_size - bytestream2_tell(&bc));
1556
    }
1557
247
    if (got_header)
1558
4
        c->got_header = 1;
1559
1560

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