Coverage Report

Created: 2026-09-14 07:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossless.cpp
Line
Count
Source
1
/*
2
 * Copyright (c) 2023, Nico Weber <thakis@chromium.org>
3
 *
4
 * SPDX-License-Identifier: BSD-2-Clause
5
 */
6
7
#include <AK/BitStream.h>
8
#include <AK/Debug.h>
9
#include <AK/Endian.h>
10
#include <AK/Format.h>
11
#include <AK/MemoryStream.h>
12
#include <AK/Vector.h>
13
#include <LibCompress/Deflate.h>
14
#include <LibGfx/ImageFormats/WebPLoaderLossless.h>
15
#include <LibGfx/ImageFormats/WebPSharedLossless.h>
16
17
// Lossless format: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification
18
19
namespace Gfx {
20
21
// https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
22
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#7_overall_structure_of_the_format
23
ErrorOr<VP8LHeader> decode_webp_chunk_VP8L_header(ReadonlyBytes vp8l_data)
24
0
{
25
    // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#3_riff_header
26
0
    if (vp8l_data.size() < 5)
27
0
        return Error::from_string_literal("WebPImageDecoderPlugin: VP8L chunk too small");
28
29
0
    FixedMemoryStream memory_stream { vp8l_data.trim(5) };
30
0
    LittleEndianInputBitStream bit_stream { MaybeOwned<Stream>(memory_stream), LittleEndianInputBitStream::UnsatisfiableReadBehavior::FillWithZero };
31
32
0
    u8 signature = TRY(bit_stream.read_bits(8));
33
0
    if (signature != 0x2f)
34
0
        return Error::from_string_literal("WebPImageDecoderPlugin: VP8L chunk invalid signature");
35
36
    // 14 bits width-1, 14 bits height-1, 1 bit alpha hint, 3 bit version_number.
37
0
    u16 width = TRY(bit_stream.read_bits(14)) + 1;
38
0
    u16 height = TRY(bit_stream.read_bits(14)) + 1;
39
0
    bool is_alpha_used = TRY(bit_stream.read_bits(1)) != 0;
40
0
    u8 version_number = TRY(bit_stream.read_bits(3));
41
0
    VERIFY(bit_stream.is_eof());
42
43
0
    dbgln_if(WEBP_DEBUG, "VP8L: width {}, height {}, is_alpha_used {}, version_number {}",
44
0
        width, height, is_alpha_used, version_number);
45
46
    // "The version_number is a 3 bit code that must be set to 0. Any other value should be treated as an error."
47
0
    if (version_number != 0)
48
0
        return Error::from_string_literal("WebPImageDecoderPlugin: VP8L chunk invalid version_number");
49
50
0
    return VP8LHeader { width, height, is_alpha_used, vp8l_data.slice(5) };
51
0
}
52
53
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#621_decoding_and_building_the_prefix_codes
54
static ErrorOr<CanonicalCode> decode_webp_chunk_VP8L_prefix_code(LittleEndianInputBitStream& bit_stream, size_t alphabet_size)
55
0
{
56
    // prefix-code           =  simple-prefix-code / normal-prefix-code
57
0
    bool is_simple_code_length_code = TRY(bit_stream.read_bits(1));
58
0
    dbgln_if(WEBP_DEBUG, "is_simple_code_length_code {}", is_simple_code_length_code);
59
60
0
    Vector<u8, 286> code_lengths;
61
62
0
    if (is_simple_code_length_code) {
63
0
        TRY(code_lengths.try_resize(alphabet_size));
64
65
0
        int num_symbols = TRY(bit_stream.read_bits(1)) + 1;
66
0
        int is_first_8bits = TRY(bit_stream.read_bits(1));
67
0
        u8 symbol0 = TRY(bit_stream.read_bits(1 + 7 * is_first_8bits));
68
0
        dbgln_if(WEBP_DEBUG, "  symbol0 {}", symbol0);
69
70
0
        if (symbol0 >= code_lengths.size())
71
0
            return Error::from_string_literal("symbol0 out of bounds");
72
0
        code_lengths[symbol0] = 1;
73
0
        if (num_symbols == 2) {
74
0
            u8 symbol1 = TRY(bit_stream.read_bits(8));
75
0
            dbgln_if(WEBP_DEBUG, "  symbol1 {}", symbol1);
76
77
0
            if (symbol1 >= code_lengths.size())
78
0
                return Error::from_string_literal("symbol1 out of bounds");
79
0
            code_lengths[symbol1] = 1;
80
0
        }
81
82
0
        return CanonicalCode::from_bytes(code_lengths);
83
0
    }
84
85
    // This has plenty in common with deflate (cf DeflateDecompressor::decode_codes() in Deflate.cpp in LibCompress)
86
    // Symbol 16 has different semantics, and kCodeLengthCodeOrder is different. Other than that, this is virtually deflate.
87
    // (...but webp uses 5 different prefix codes, while deflate doesn't.)
88
0
    int num_code_lengths = 4 + TRY(bit_stream.read_bits(4));
89
0
    dbgln_if(WEBP_DEBUG, "  num_code_lengths {}", num_code_lengths);
90
0
    VERIFY(num_code_lengths <= 19);
91
92
0
    u8 code_length_code_lengths[kCodeLengthCodeOrder.size()] = { 0 }; // "All zeros" [sic]
93
0
    for (int i = 0; i < num_code_lengths; ++i)
94
0
        code_length_code_lengths[kCodeLengthCodeOrder[i]] = TRY(bit_stream.read_bits(3));
95
96
    // "Next, if `ReadBits(1) == 0`, the maximum number of different read symbols
97
    //  (`max_symbol`) for each symbol type (A, R, G, B, and distance) is set to its
98
    //  alphabet size:"
99
0
    unsigned max_symbol;
100
0
    if (TRY(bit_stream.read_bits(1)) == 0) {
101
0
        max_symbol = alphabet_size;
102
0
    }
103
    // "Otherwise, it is defined as:"
104
0
    else {
105
        // "int length_nbits = 2 + 2 * ReadBits(3);"
106
0
        int length_nbits = 2 + 2 * TRY(bit_stream.read_bits(3));
107
        // "int max_symbol = 2 + ReadBits(length_nbits);"
108
0
        max_symbol = 2 + TRY(bit_stream.read_bits(length_nbits));
109
0
        dbgln_if(WEBP_DEBUG, "  extended, length_nbits {} max_symbol {}", length_nbits, max_symbol);
110
111
        // "If `max_symbol` is larger than the size of the alphabet for the symbol type, the bitstream is invalid."
112
0
        if (max_symbol > alphabet_size)
113
0
            return Error::from_string_literal("WebPImageDecoderPlugin: invalid max_symbol");
114
0
    }
115
116
    // "A prefix table is then built from code_length_code_lengths and used to read up to max_symbol code lengths."
117
0
    dbgln_if(WEBP_DEBUG, "  reading {} symbols from at most {} codes", alphabet_size, max_symbol);
118
0
    auto const code_length_code = TRY(CanonicalCode::from_bytes({ code_length_code_lengths, sizeof(code_length_code_lengths) }));
119
0
    u8 last_non_zero = 8; // "If code 16 is used before a non-zero value has been emitted, a value of 8 is repeated."
120
0
    while (code_lengths.size() < alphabet_size) {
121
0
        if (max_symbol == 0)
122
0
            break;
123
0
        --max_symbol;
124
125
0
        auto symbol = TRY(code_length_code.read_symbol(bit_stream));
126
127
0
        if (symbol < 16) {
128
            // "Code [0..15] indicates literal code lengths."
129
0
            code_lengths.append(static_cast<u8>(symbol));
130
0
            if (symbol != 0)
131
0
                last_non_zero = symbol;
132
0
        } else if (symbol == 16) {
133
            // "Code 16 repeats the previous non-zero value [3..6] times, i.e., 3 + ReadBits(2) times."
134
0
            auto nrepeat = 3 + TRY(bit_stream.read_bits(2));
135
136
            // This is different from deflate.
137
0
            for (size_t j = 0; j < nrepeat; ++j)
138
0
                code_lengths.append(last_non_zero);
139
0
        } else if (symbol == 17) {
140
            // "Code 17 emits a streak of zeros [3..10], i.e., 3 + ReadBits(3) times."
141
0
            auto nrepeat = 3 + TRY(bit_stream.read_bits(3));
142
0
            for (size_t j = 0; j < nrepeat; ++j)
143
0
                code_lengths.append(0);
144
0
        } else {
145
0
            VERIFY(symbol == 18);
146
            // "Code 18 emits a streak of zeros of length [11..138], i.e., 11 + ReadBits(7) times."
147
0
            auto nrepeat = 11 + TRY(bit_stream.read_bits(7));
148
0
            for (size_t j = 0; j < nrepeat; ++j)
149
0
                code_lengths.append(0);
150
0
        }
151
0
    }
152
153
0
    if (code_lengths.size() > alphabet_size)
154
0
        return Error::from_string_literal("Number of code lengths is larger than the alphabet size");
155
156
0
    return CanonicalCode::from_bytes(code_lengths);
157
0
}
158
159
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#622_decoding_of_meta_prefix_codes
160
// The description of prefix code groups is in "Decoding of Meta Prefix Codes", even though prefix code groups are used
161
// in regular images without meta prefix code as well ¯\_(ツ)_/¯.
162
static ErrorOr<PrefixCodeGroup> decode_webp_chunk_VP8L_prefix_code_group(u16 color_cache_size, LittleEndianInputBitStream& bit_stream)
163
0
{
164
    // prefix-code-group     =
165
    //     5prefix-code ; See "Interpretation of Meta Prefix Codes" to
166
    //                  ; understand what each of these five prefix
167
    //                  ; codes are for.
168
169
    // "Once code lengths are read, a prefix code for each symbol type (A, R, G, B, distance) is formed using their respective alphabet sizes."
170
    // ...
171
    // "* G channel: 256 + 24 + color_cache_size
172
    //  * other literals (A,R,B): 256
173
    //  * distance code: 40"
174
0
    Array<size_t, 5> const alphabet_sizes { 256 + 24 + static_cast<size_t>(color_cache_size), 256, 256, 256, 40 };
175
176
0
    PrefixCodeGroup group;
177
0
    for (size_t i = 0; i < alphabet_sizes.size(); ++i)
178
0
        group[i] = TRY(decode_webp_chunk_VP8L_prefix_code(bit_stream, alphabet_sizes[i]));
179
0
    return group;
180
0
}
181
182
static ErrorOr<NonnullRefPtr<Bitmap>> decode_webp_chunk_VP8L_image(ImageKind image_kind, BitmapFormat format, IntSize const& size, LittleEndianInputBitStream& bit_stream)
183
0
{
184
    // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#623_decoding_entropy-coded_image_data
185
    // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#523_color_cache_coding
186
    // spatially-coded-image =  color-cache-info meta-prefix data
187
    // entropy-coded-image   =  color-cache-info data
188
189
    // color-cache-info      =  %b0
190
    // color-cache-info      =/ (%b1 4BIT) ; 1 followed by color cache size
191
0
    bool has_color_cache_info = TRY(bit_stream.read_bits(1));
192
0
    u16 color_cache_size = 0;
193
0
    u8 color_cache_code_bits;
194
0
    dbgln_if(WEBP_DEBUG, "has_color_cache_info {}", has_color_cache_info);
195
0
    Vector<ARGB32, 32> color_cache;
196
0
    if (has_color_cache_info) {
197
0
        color_cache_code_bits = TRY(bit_stream.read_bits(4));
198
199
        // "The range of allowed values for color_cache_code_bits is [1..11]. Compliant decoders must indicate a corrupted bitstream for other values."
200
0
        if (color_cache_code_bits < 1 || color_cache_code_bits > 11)
201
0
            return Error::from_string_literal("WebPImageDecoderPlugin: VP8L invalid color_cache_code_bits");
202
203
0
        color_cache_size = 1 << color_cache_code_bits;
204
0
        dbgln_if(WEBP_DEBUG, "color_cache_size {}", color_cache_size);
205
206
0
        TRY(color_cache.try_resize(color_cache_size));
207
0
    }
208
209
0
    int num_prefix_groups = 1;
210
0
    RefPtr<Gfx::Bitmap> entropy_image;
211
0
    int prefix_bits = 0;
212
0
    if (image_kind == ImageKind::SpatiallyCoded) {
213
        // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#622_decoding_of_meta_prefix_codes
214
        // In particular, the "Entropy image" subsection.
215
        // "Meta prefix codes may be used only when the image is being used in the role of an ARGB image."
216
        // meta-prefix           =  %b0 / (%b1 entropy-image)
217
0
        bool has_meta_prefix = TRY(bit_stream.read_bits(1));
218
0
        dbgln_if(WEBP_DEBUG, "has_meta_prefix {}", has_meta_prefix);
219
0
        if (has_meta_prefix) {
220
0
            prefix_bits = TRY(bit_stream.read_bits(3)) + 2;
221
0
            dbgln_if(WEBP_DEBUG, "prefix_bits {}", prefix_bits);
222
0
            int block_size = 1 << prefix_bits;
223
0
            IntSize prefix_size { ceil_div(size.width(), block_size), ceil_div(size.height(), block_size) };
224
225
0
            entropy_image = TRY(decode_webp_chunk_VP8L_image(ImageKind::EntropyCoded, BitmapFormat::BGRx8888, prefix_size, bit_stream));
226
227
            // A "meta prefix image" or "entropy image" can tell the decoder to use different PrefixCodeGroup for
228
            // tiles of the main, spatially coded, image. It's a bit hidden in the spec:
229
            //      "The red and green components of a pixel define the meta prefix code used in a particular block of the ARGB image."
230
            //      ...
231
            //      "The number of prefix code groups in the ARGB image can be obtained by finding the largest meta prefix code from the entropy image"
232
            // That is, if a meta prefix image is present, the main image has more than one PrefixCodeGroup,
233
            // and the highest value in the meta prefix image determines how many exactly.
234
0
            u16 largest_meta_prefix_code = 0;
235
0
            for (ARGB32& pixel : *entropy_image) {
236
0
                u16 meta_prefix_code = (pixel >> 8) & 0xffff;
237
0
                if (meta_prefix_code > largest_meta_prefix_code)
238
0
                    largest_meta_prefix_code = meta_prefix_code;
239
0
            }
240
0
            dbgln_if(WEBP_DEBUG, "largest meta prefix code {}", largest_meta_prefix_code);
241
242
0
            num_prefix_groups = largest_meta_prefix_code + 1;
243
0
        }
244
0
    }
245
246
    // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#52_encoding_of_image_data
247
    // "The encoded image data consists of several parts:
248
    //    1. Decoding and building the prefix codes
249
    //    2. Meta prefix codes
250
    //    3. Entropy-coded image data"
251
    // data                  =  prefix-codes lz77-coded-image
252
    // prefix-codes          =  prefix-code-group *prefix-codes
253
254
0
    Vector<PrefixCodeGroup, 1> groups;
255
0
    for (int i = 0; i < num_prefix_groups; ++i)
256
0
        TRY(groups.try_append(TRY(decode_webp_chunk_VP8L_prefix_code_group(color_cache_size, bit_stream))));
257
258
0
    auto bitmap = TRY(Bitmap::create(format, size));
259
260
    // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#522_lz77_backward_reference
261
0
    struct Offset {
262
0
        i8 x, y;
263
0
    };
264
    // clang-format off
265
0
    Array<Offset, 120> distance_map { {
266
0
        {0, 1}, {1, 0},
267
0
        {1, 1}, {-1, 1}, {0, 2}, { 2, 0},
268
0
        {1, 2}, {-1, 2}, {2, 1}, {-2, 1},
269
0
        {2, 2}, {-2, 2}, {0, 3}, { 3, 0}, { 1, 3}, {-1, 3}, { 3, 1}, {-3, 1},
270
0
        {2, 3}, {-2, 3}, {3, 2}, {-3, 2}, { 0, 4}, { 4, 0}, { 1, 4}, {-1, 4}, { 4, 1}, {-4, 1},
271
0
        {3, 3}, {-3, 3}, {2, 4}, {-2, 4}, { 4, 2}, {-4, 2}, { 0, 5},
272
0
        {3, 4}, {-3, 4}, {4, 3}, {-4, 3}, { 5, 0}, { 1, 5}, {-1, 5}, { 5, 1}, {-5, 1}, { 2, 5}, {-2, 5}, { 5, 2}, {-5, 2},
273
0
        {4, 4}, {-4, 4}, {3, 5}, {-3, 5}, { 5, 3}, {-5, 3}, { 0, 6}, { 6, 0}, { 1, 6}, {-1, 6}, { 6, 1}, {-6, 1}, { 2, 6}, {-2, 6}, {6, 2}, {-6, 2},
274
0
        {4, 5}, {-4, 5}, {5, 4}, {-5, 4}, { 3, 6}, {-3, 6}, { 6, 3}, {-6, 3}, { 0, 7}, { 7, 0}, { 1, 7}, {-1, 7},
275
0
        {5, 5}, {-5, 5}, {7, 1}, {-7, 1}, { 4, 6}, {-4, 6}, { 6, 4}, {-6, 4}, { 2, 7}, {-2, 7}, { 7, 2}, {-7, 2}, { 3, 7}, {-3, 7}, {7, 3}, {-7, 3},
276
0
        {5, 6}, {-5, 6}, {6, 5}, {-6, 5}, { 8, 0}, { 4, 7}, {-4, 7}, { 7, 4}, {-7, 4}, { 8, 1}, { 8, 2},
277
0
        {6, 6}, {-6, 6}, {8, 3}, { 5, 7}, {-5, 7}, { 7, 5}, {-7, 5}, { 8, 4},
278
0
        {6, 7}, {-6, 7}, {7, 6}, {-7, 6}, { 8, 5},
279
0
        {7, 7}, {-7, 7}, {8, 6},
280
0
        {8, 7},
281
0
    } };
282
    // clang-format on
283
284
    // lz77-coded-image      =
285
    //     *((argb-pixel / lz77-copy / color-cache-code) lz77-coded-image)
286
    // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#623_decoding_entropy-coded_image_data
287
0
    ARGB32* begin = bitmap->begin();
288
0
    ARGB32* end = bitmap->end();
289
0
    ARGB32* pixel = begin;
290
291
0
    auto prefix_group = [prefix_bits, begin, &groups, size, &entropy_image](ARGB32* pixel) -> PrefixCodeGroup const& {
292
0
        if (!prefix_bits)
293
0
            return groups[0];
294
295
0
        size_t offset = pixel - begin;
296
0
        int x = offset % size.width();
297
0
        int y = offset / size.width();
298
299
0
        int meta_prefix_code = (entropy_image->scanline(y >> prefix_bits)[x >> prefix_bits] >> 8) & 0xffff;
300
0
        return groups[meta_prefix_code];
301
0
    };
302
303
0
    auto emit_pixel = [&pixel, &color_cache, color_cache_size, color_cache_code_bits](ARGB32 color) {
304
        // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#523_color_cache_coding
305
        // "The state of the color cache is maintained by inserting every pixel, be it produced by backward referencing or as literals, into the cache in the order they appear in the stream."
306
0
        *pixel++ = color;
307
0
        if (color_cache_size)
308
0
            color_cache[(0x1e35a7bd * color) >> (32 - color_cache_code_bits)] = color;
309
0
    };
310
311
0
    while (pixel < end) {
312
        // "For the current position (x, y) in the image, the decoder first identifies the corresponding prefix code group"
313
0
        auto const& group = prefix_group(pixel);
314
315
        // "Next, read the symbol S from the bitstream using prefix code #1.
316
        //  Note that S is any integer in the range 0 to (256 + 24 + color_cache_size - 1)."
317
0
        auto symbol = TRY(group[0].read_symbol(bit_stream));
318
0
        if (symbol >= 256u + 24u + color_cache_size)
319
0
            return Error::from_string_literal("WebPImageDecoderPlugin: Symbol out of bounds");
320
321
        // "1. if S < 256"
322
0
        if (symbol < 256u) {
323
            // "a. Use S as the green component."
324
0
            u8 g = symbol;
325
326
            // "b. Read red from the bitstream using prefix code #2."
327
0
            u8 r = TRY(group[1].read_symbol(bit_stream));
328
329
            // "c. Read blue from the bitstream using prefix code #3."
330
0
            u8 b = TRY(group[2].read_symbol(bit_stream));
331
332
            // "d. Read alpha from the bitstream using prefix code #4."
333
0
            u8 a = TRY(group[3].read_symbol(bit_stream));
334
335
0
            emit_pixel(Color(r, g, b, a).value());
336
0
        }
337
        // "2. if S >= 256 && S < 256 + 24"
338
0
        else if (symbol < 256u + 24u) {
339
0
            auto prefix_value = [&bit_stream](u8 prefix_code) -> ErrorOr<u32> {
340
                // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#522_lz77_backward_reference
341
0
                if (prefix_code < 4)
342
0
                    return prefix_code + 1;
343
0
                int extra_bits = (prefix_code - 2) >> 1;
344
0
                int offset = (2 + (prefix_code & 1)) << extra_bits;
345
0
                return offset + TRY(bit_stream.read_bits(extra_bits)) + 1;
346
0
            };
347
348
            // "a. Use S - 256 as a length prefix code."
349
0
            u8 length_prefix_code = symbol - 256;
350
351
            // "b. Read extra bits for length from the bitstream."
352
            // "c. Determine backward-reference length L from length prefix code and the extra bits read."
353
0
            u32 length = TRY(prefix_value(length_prefix_code));
354
355
            // "d. Read distance prefix code from the bitstream using prefix code #5."
356
0
            u8 distance_prefix_code = TRY(group[4].read_symbol(bit_stream));
357
358
            // "e. Read extra bits for distance from the bitstream."
359
            // "f. Determine backward-reference distance D from distance prefix code and the extra bits read."
360
0
            i32 distance = TRY(prefix_value(distance_prefix_code));
361
362
            // "g. Copy the L pixels (in scan-line order) from the sequence of pixels prior to them by D pixels."
363
364
            // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#522_lz77_backward_reference
365
            // "Distance codes larger than 120 denote the pixel-distance in scan-line order, offset by 120."
366
            // "The smallest distance codes [1..120] are special, and are reserved for a close neighborhood of the current pixel."
367
0
            if (distance <= 120) {
368
                // "The decoder can convert a distance code distance_code to a scan-line order distance dist as follows:"
369
0
                auto offset = distance_map[distance - 1];
370
0
                distance = offset.x + offset.y * bitmap->physical_width();
371
0
                if (distance < 1)
372
0
                    distance = 1;
373
0
            } else {
374
0
                distance = distance - 120;
375
0
            }
376
377
0
            if (pixel - begin < distance) {
378
0
                dbgln_if(WEBP_DEBUG, "invalid backref, {} < {}", pixel - begin, distance);
379
0
                return Error::from_string_literal("WebPImageDecoderPlugin: Backward reference distance out of bounds");
380
0
            }
381
382
0
            if (end - pixel < static_cast<ptrdiff_t>(length)) {
383
0
                dbgln_if(WEBP_DEBUG, "invalid length, {} < {}", end - pixel, length);
384
0
                return Error::from_string_literal("WebPImageDecoderPlugin: Backward reference length out of bounds");
385
0
            }
386
387
0
            ARGB32* src = pixel - distance;
388
0
            for (u32 i = 0; i < length; ++i)
389
0
                emit_pixel(src[i]);
390
0
        }
391
        // "3. if S >= 256 + 24"
392
0
        else {
393
            // "a. Use S - (256 + 24) as the index into the color cache."
394
0
            unsigned index = symbol - (256 + 24);
395
396
            // "b. Get ARGB color from the color cache at that index."
397
            // `symbol` is bounds-checked at the start of the loop.
398
0
            *pixel++ = color_cache[index];
399
0
        }
400
0
    }
401
402
0
    return bitmap;
403
0
}
404
405
namespace {
406
407
static ARGB32 add_argb32(ARGB32 a, ARGB32 b)
408
0
{
409
0
    auto a_color = Color::from_argb(a);
410
0
    auto b_color = Color::from_argb(b);
411
0
    return Color(a_color.red() + b_color.red(),
412
0
        a_color.green() + b_color.green(),
413
0
        a_color.blue() + b_color.blue(),
414
0
        a_color.alpha() + b_color.alpha())
415
0
        .value();
416
0
}
417
418
class Transform {
419
public:
420
    virtual ~Transform();
421
422
    // Could modify the input bitmap and return it, or could return a new bitmap.
423
    virtual ErrorOr<NonnullRefPtr<Bitmap>> transform(NonnullRefPtr<Bitmap>) = 0;
424
};
425
426
0
Transform::~Transform() = default;
427
428
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#41_predictor_transform
429
class PredictorTransform : public Transform {
430
public:
431
    static ErrorOr<NonnullOwnPtr<PredictorTransform>> read(LittleEndianInputBitStream&, IntSize const& image_size);
432
    virtual ErrorOr<NonnullRefPtr<Bitmap>> transform(NonnullRefPtr<Bitmap>) override;
433
434
private:
435
    PredictorTransform(int size_bits, NonnullRefPtr<Bitmap> predictor_bitmap)
436
0
        : m_size_bits(size_bits)
437
0
        , m_predictor_bitmap(move(predictor_bitmap))
438
0
    {
439
0
    }
440
441
    // These capitalized functions are all from the spec:
442
    static u8 Average2(u8 a, u8 b)
443
0
    {
444
0
        return (a + b) / 2;
445
0
    }
446
447
    static u32 Select(u32 L, u32 T, u32 TL)
448
0
    {
449
        // "L = left pixel, T = top pixel, TL = top left pixel."
450
451
0
#define ALPHA(x) ((x >> 24) & 0xff)
452
0
#define RED(x) ((x >> 16) & 0xff)
453
0
#define GREEN(x) ((x >> 8) & 0xff)
454
0
#define BLUE(x) (x & 0xff)
455
456
        // "ARGB component estimates for prediction."
457
0
        int pAlpha = ALPHA(L) + ALPHA(T) - ALPHA(TL);
458
0
        int pRed = RED(L) + RED(T) - RED(TL);
459
0
        int pGreen = GREEN(L) + GREEN(T) - GREEN(TL);
460
0
        int pBlue = BLUE(L) + BLUE(T) - BLUE(TL);
461
462
        // "Manhattan distances to estimates for left and top pixels."
463
0
        int pL = abs(pAlpha - (int)ALPHA(L)) + abs(pRed - (int)RED(L)) + abs(pGreen - (int)GREEN(L)) + abs(pBlue - (int)BLUE(L));
464
0
        int pT = abs(pAlpha - (int)ALPHA(T)) + abs(pRed - (int)RED(T)) + abs(pGreen - (int)GREEN(T)) + abs(pBlue - (int)BLUE(T));
465
466
        // "Return either left or top, the one closer to the prediction."
467
0
        if (pL < pT) {
468
0
            return L;
469
0
        } else {
470
0
            return T;
471
0
        }
472
473
0
#undef BLUE
474
0
#undef GREEN
475
0
#undef RED
476
0
#undef ALPHA
477
0
    }
478
479
    // "Clamp the input value between 0 and 255."
480
    static int Clamp(int a)
481
0
    {
482
0
        return clamp(a, 0, 255);
483
0
    }
484
485
    static int ClampAddSubtractFull(int a, int b, int c)
486
0
    {
487
0
        return Clamp(a + b - c);
488
0
    }
489
490
    static int ClampAddSubtractHalf(int a, int b)
491
0
    {
492
0
        return Clamp(a + (a - b) / 2);
493
0
    }
494
495
    // ...and we're back from the spec!
496
    static Color average2(Color a, Color b)
497
0
    {
498
0
        return Color(Average2(a.red(), b.red()),
499
0
            Average2(a.green(), b.green()),
500
0
            Average2(a.blue(), b.blue()),
501
0
            Average2(a.alpha(), b.alpha()));
502
0
    }
503
504
    static ARGB32 average2(ARGB32 a, ARGB32 b)
505
0
    {
506
0
        return average2(Color::from_argb(a), Color::from_argb(b)).value();
507
0
    }
508
509
    static ErrorOr<ARGB32> predict(u8 predictor, ARGB32 TL, ARGB32 T, ARGB32 TR, ARGB32 L);
510
511
    int m_size_bits;
512
    NonnullRefPtr<Bitmap> m_predictor_bitmap;
513
};
514
515
ErrorOr<NonnullOwnPtr<PredictorTransform>> PredictorTransform::read(LittleEndianInputBitStream& bit_stream, IntSize const& image_size)
516
0
{
517
    // predictor-image      =  3BIT ; sub-pixel code
518
    //                         entropy-coded-image
519
0
    int size_bits = TRY(bit_stream.read_bits(3)) + 2;
520
0
    dbgln_if(WEBP_DEBUG, "predictor size_bits {}", size_bits);
521
522
0
    int block_size = 1 << size_bits;
523
0
    IntSize predictor_image_size { ceil_div(image_size.width(), block_size), ceil_div(image_size.height(), block_size) };
524
525
0
    auto predictor_bitmap = TRY(decode_webp_chunk_VP8L_image(ImageKind::EntropyCoded, BitmapFormat::BGRx8888, predictor_image_size, bit_stream));
526
527
0
    return adopt_nonnull_own_or_enomem(new (nothrow) PredictorTransform(size_bits, move(predictor_bitmap)));
528
0
}
529
530
ErrorOr<NonnullRefPtr<Bitmap>> PredictorTransform::transform(NonnullRefPtr<Bitmap> bitmap_ref)
531
0
{
532
0
    Bitmap& bitmap = *bitmap_ref;
533
534
    // "There are special handling rules for some border pixels.
535
    //  If there is a prediction transform, regardless of the mode [0..13] for these pixels,
536
    //  the predicted value for the left-topmost pixel of the image is 0xff000000,
537
0
    bitmap.scanline(0)[0] = add_argb32(bitmap.scanline(0)[0], 0xff000000);
538
539
    //  L-pixel for all pixels on the top row,
540
0
    for (int x = 1; x < bitmap.width(); ++x)
541
0
        bitmap.scanline(0)[x] = add_argb32(bitmap.scanline(0)[x], bitmap.scanline(0)[x - 1]);
542
543
    //  and T-pixel for all pixels on the leftmost column."
544
0
    for (int y = 1; y < bitmap.height(); ++y)
545
0
        bitmap.scanline(y)[0] = add_argb32(bitmap.scanline(y)[0], bitmap.scanline(y - 1)[0]);
546
547
0
    ARGB32* bitmap_previous_scanline = bitmap.scanline(0);
548
0
    for (int y = 1; y < bitmap.height(); ++y) {
549
0
        ARGB32* bitmap_scanline = bitmap.scanline(y);
550
551
0
        ARGB32 TL = bitmap_previous_scanline[0];
552
0
        ARGB32 T = bitmap_previous_scanline[1];
553
0
        ARGB32 TR = 2 < bitmap.width() ? bitmap_previous_scanline[2] : bitmap_previous_scanline[0];
554
555
0
        ARGB32 L = bitmap_scanline[0];
556
557
0
        int predictor_y = y >> m_size_bits;
558
0
        ARGB32* predictor_scanline = m_predictor_bitmap->scanline(predictor_y);
559
560
0
        for (int x = 1; x < bitmap.width(); ++x) {
561
0
            int predictor_x = x >> m_size_bits;
562
563
            // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#51_roles_of_image_data
564
            // "The green component of a pixel defines which of the 14 predictors is used within a particular block of the ARGB image."
565
0
            u8 predictor = Color::from_argb(predictor_scanline[predictor_x]).green();
566
567
0
            ARGB32 predicted = TRY(predict(predictor, TL, T, TR, L));
568
569
            // "The final pixel value is obtained by adding each channel of the predicted value to the encoded residual value."
570
0
            bitmap_scanline[x] = add_argb32(bitmap_scanline[x], predicted);
571
572
0
            TL = T;
573
0
            T = TR;
574
575
            // "Addressing the TR-pixel for pixels on the rightmost column is exceptional.
576
            //  The pixels on the rightmost column are predicted by using the modes [0..13] just like pixels not on the border,
577
            //  but the leftmost pixel on the same row as the current pixel is instead used as the TR-pixel."
578
0
            TR = x + 2 < bitmap.width() ? bitmap_previous_scanline[x + 2] : bitmap_previous_scanline[0];
579
580
0
            L = bitmap_scanline[x];
581
0
        }
582
583
0
        bitmap_previous_scanline = bitmap_scanline;
584
0
    }
585
0
    return bitmap_ref;
586
0
}
587
588
ErrorOr<ARGB32> PredictorTransform::predict(u8 predictor, ARGB32 TL, ARGB32 T, ARGB32 TR, ARGB32 L)
589
0
{
590
0
    switch (predictor) {
591
0
    case 0:
592
        // "0xff000000 (represents solid black color in ARGB)"
593
0
        return 0xff000000;
594
0
    case 1:
595
        // "L"
596
0
        return L;
597
0
    case 2:
598
        // "T"
599
0
        return T;
600
0
    case 3:
601
        // "TR"
602
0
        return TR;
603
0
    case 4:
604
        // "TL"
605
0
        return TL;
606
0
    case 5:
607
        // "Average2(Average2(L, TR), T)"
608
0
        return average2(average2(L, TR), T);
609
0
    case 6:
610
        // "Average2(L, TL)"
611
0
        return average2(L, TL);
612
0
    case 7:
613
        // "Average2(L, T)"
614
0
        return average2(L, T);
615
0
    case 8:
616
        // "Average2(TL, T)"
617
0
        return average2(TL, T);
618
0
    case 9:
619
        // "Average2(T, TR)"
620
0
        return average2(T, TR);
621
0
    case 10:
622
        // "Average2(Average2(L, TL), Average2(T, TR))"
623
0
        return average2(average2(L, TL), average2(T, TR));
624
0
    case 11:
625
        // "Select(L, T, TL)"
626
0
        return Select(L, T, TL);
627
0
    case 12: {
628
        // "ClampAddSubtractFull(L, T, TL)"
629
0
        auto color_L = Color::from_argb(L);
630
0
        auto color_T = Color::from_argb(T);
631
0
        auto color_TL = Color::from_argb(TL);
632
0
        return Color(ClampAddSubtractFull(color_L.red(), color_T.red(), color_TL.red()),
633
0
            ClampAddSubtractFull(color_L.green(), color_T.green(), color_TL.green()),
634
0
            ClampAddSubtractFull(color_L.blue(), color_T.blue(), color_TL.blue()),
635
0
            ClampAddSubtractFull(color_L.alpha(), color_T.alpha(), color_TL.alpha()))
636
0
            .value();
637
0
    }
638
0
    case 13: {
639
        // "ClampAddSubtractHalf(Average2(L, T), TL)"
640
0
        auto color_L = Color::from_argb(L);
641
0
        auto color_T = Color::from_argb(T);
642
0
        auto color_TL = Color::from_argb(TL);
643
0
        return Color(ClampAddSubtractHalf(Average2(color_L.red(), color_T.red()), color_TL.red()),
644
0
            ClampAddSubtractHalf(Average2(color_L.green(), color_T.green()), color_TL.green()),
645
0
            ClampAddSubtractHalf(Average2(color_L.blue(), color_T.blue()), color_TL.blue()),
646
0
            ClampAddSubtractHalf(Average2(color_L.alpha(), color_T.alpha()), color_TL.alpha()))
647
0
            .value();
648
0
    }
649
0
    }
650
0
    return Error::from_string_literal("WebPImageDecoderPlugin: invalid predictor");
651
0
}
652
653
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#42_color_transform
654
class ColorTransform : public Transform {
655
public:
656
    static ErrorOr<NonnullOwnPtr<ColorTransform>> read(LittleEndianInputBitStream&, IntSize const& image_size);
657
    virtual ErrorOr<NonnullRefPtr<Bitmap>> transform(NonnullRefPtr<Bitmap>) override;
658
659
private:
660
    ColorTransform(int size_bits, NonnullRefPtr<Bitmap> color_bitmap)
661
0
        : m_size_bits(size_bits)
662
0
        , m_color_bitmap(move(color_bitmap))
663
0
    {
664
0
    }
665
666
    static i8 ColorTransformDelta(i8 transform, i8 color)
667
0
    {
668
0
        return (transform * color) >> 5;
669
0
    }
670
671
    static ARGB32 inverse_transform(ARGB32 pixel, ARGB32 transform);
672
673
    int m_size_bits;
674
    NonnullRefPtr<Bitmap> m_color_bitmap;
675
};
676
677
ErrorOr<NonnullOwnPtr<ColorTransform>> ColorTransform::read(LittleEndianInputBitStream& bit_stream, IntSize const& image_size)
678
0
{
679
    // color-image          =  3BIT ; sub-pixel code
680
    //                         entropy-coded-image
681
0
    int size_bits = TRY(bit_stream.read_bits(3)) + 2;
682
0
    dbgln_if(WEBP_DEBUG, "color size_bits {}", size_bits);
683
684
0
    int block_size = 1 << size_bits;
685
0
    IntSize color_image_size { ceil_div(image_size.width(), block_size), ceil_div(image_size.height(), block_size) };
686
687
0
    auto color_bitmap = TRY(decode_webp_chunk_VP8L_image(ImageKind::EntropyCoded, BitmapFormat::BGRx8888, color_image_size, bit_stream));
688
689
0
    return adopt_nonnull_own_or_enomem(new (nothrow) ColorTransform(size_bits, move(color_bitmap)));
690
0
}
691
692
ErrorOr<NonnullRefPtr<Bitmap>> ColorTransform::transform(NonnullRefPtr<Bitmap> bitmap_ref)
693
0
{
694
0
    Bitmap& bitmap = *bitmap_ref;
695
696
0
    for (int y = 0; y < bitmap.height(); ++y) {
697
0
        ARGB32* bitmap_scanline = bitmap.scanline(y);
698
699
0
        int color_y = y >> m_size_bits;
700
0
        ARGB32* color_scanline = m_color_bitmap->scanline(color_y);
701
702
0
        for (int x = 0; x < bitmap.width(); ++x) {
703
0
            int color_x = x >> m_size_bits;
704
0
            bitmap_scanline[x] = inverse_transform(bitmap_scanline[x], color_scanline[color_x]);
705
0
        }
706
0
    }
707
0
    return bitmap_ref;
708
0
}
709
710
ARGB32 ColorTransform::inverse_transform(ARGB32 pixel, ARGB32 transform)
711
0
{
712
    // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#51_roles_of_image_data
713
    // "Each ColorTransformElement 'cte' is treated as a pixel whose alpha component is 255,
714
    // red component is cte.red_to_blue, green component is cte.green_to_blue
715
    // and blue component is cte.green_to_red."
716
0
    auto transform_color = Color::from_argb(transform);
717
0
    i8 red_to_blue = static_cast<i8>(transform_color.red());
718
0
    i8 green_to_blue = static_cast<i8>(transform_color.green());
719
0
    i8 green_to_red = static_cast<i8>(transform_color.blue());
720
721
0
    auto pixel_color = Color::from_argb(pixel);
722
723
    // "Transformed values of red and blue components"
724
0
    int tmp_red = pixel_color.red();
725
0
    int green = pixel_color.green();
726
0
    int tmp_blue = pixel_color.blue();
727
728
    // "Applying the inverse transform is just adding the color transform deltas"
729
0
    tmp_red += ColorTransformDelta(green_to_red, green);
730
0
    tmp_blue += ColorTransformDelta(green_to_blue, green);
731
0
    tmp_blue += ColorTransformDelta(red_to_blue, tmp_red & 0xff);
732
733
0
    return Color(tmp_red & 0xff, green, tmp_blue & 0xff, pixel_color.alpha()).value();
734
0
}
735
736
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#43_subtract_green_transform
737
class SubtractGreenTransform : public Transform {
738
public:
739
    virtual ErrorOr<NonnullRefPtr<Bitmap>> transform(NonnullRefPtr<Bitmap>) override;
740
};
741
742
ErrorOr<NonnullRefPtr<Bitmap>> SubtractGreenTransform::transform(NonnullRefPtr<Bitmap> bitmap)
743
0
{
744
0
    for (ARGB32& pixel : *bitmap) {
745
0
        Color color = Color::from_argb(pixel);
746
0
        u8 red = (color.red() + color.green()) & 0xff;
747
0
        u8 blue = (color.blue() + color.green()) & 0xff;
748
0
        pixel = Color(red, color.green(), blue, color.alpha()).value();
749
0
    }
750
0
    return bitmap;
751
0
}
752
753
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#44_color_indexing_transform
754
class ColorIndexingTransform : public Transform {
755
public:
756
    static ErrorOr<NonnullOwnPtr<ColorIndexingTransform>> read(LittleEndianInputBitStream&, int original_width);
757
    virtual ErrorOr<NonnullRefPtr<Bitmap>> transform(NonnullRefPtr<Bitmap>) override;
758
759
    // For a color indexing transform, the green channel of the source image is used as the index into a palette to produce an output color.
760
    // If the palette is small enough, several output pixels are bundled into a single input pixel.
761
    // If the palette has just 2 colors, every index needs just a single bit, and the 8 bits of the green channel of one input pixel can encode 8 output pixels.
762
    // If the palette has 3 or 4 colors, every index needs 2 bits and every pixel can encode 4 output pixels.
763
    // If the palette has 5 to 16 colors, every index needs 4 bits and every pixel can encode 2 output pixels.
764
    // This returns how many output pixels one input pixel can encode after the color indexing transform.
765
    //
766
    // This affects all images after the color indexing transform:
767
    // If a webp file contains a 29x32 image and it contains a color indexing transform with a 4-color palette, then the in-memory size of all images
768
    // after the color indexing transform assume a bitmap size of ceil_div(29, 4)x32 = 8x32.
769
    // That is, the sizes of transforms after the color indexing transform are computed relative to the size 8x32,
770
    // the main image's meta prefix image's size (if present) is computed relative to the size 8x32,
771
    // the main image is 8x32, and only applying the color indexing transform resizes the image back to 29x32.
772
0
    int pixels_per_pixel() const { return m_pixels_per_pixel; }
773
774
private:
775
    ColorIndexingTransform(int pixels_per_pixel, int original_width, NonnullRefPtr<Bitmap> palette_bitmap)
776
0
        : m_pixels_per_pixel(pixels_per_pixel)
777
0
        , m_original_width(original_width)
778
0
        , m_palette_bitmap(palette_bitmap)
779
0
    {
780
0
    }
781
782
    int m_pixels_per_pixel;
783
    int m_original_width;
784
    NonnullRefPtr<Bitmap> m_palette_bitmap;
785
};
786
787
ErrorOr<NonnullOwnPtr<ColorIndexingTransform>> ColorIndexingTransform::read(LittleEndianInputBitStream& bit_stream, int original_width)
788
0
{
789
    // color-indexing-image =  8BIT ; color count
790
    //                         entropy-coded-image
791
0
    int color_table_size = TRY(bit_stream.read_bits(8)) + 1;
792
0
    dbgln_if(WEBP_DEBUG, "colorindexing color_table_size {}", color_table_size);
793
794
0
    IntSize palette_image_size { color_table_size, 1 };
795
0
    auto palette_bitmap = TRY(decode_webp_chunk_VP8L_image(ImageKind::EntropyCoded, BitmapFormat::BGRA8888, palette_image_size, bit_stream));
796
797
    // "When the color table is small (equal to or less than 16 colors), several pixels are bundled into a single pixel..."
798
0
    int width_bits;
799
0
    if (color_table_size <= 2)
800
0
        width_bits = 3;
801
0
    else if (color_table_size <= 4)
802
0
        width_bits = 2;
803
0
    else if (color_table_size <= 16)
804
0
        width_bits = 1;
805
0
    else
806
0
        width_bits = 0;
807
0
    int pixels_per_pixel = 1 << width_bits;
808
809
    // "The color table is always subtraction-coded to reduce image entropy. [...]  In decoding, every final color in the color table
810
    //  can be obtained by adding the previous color component values by each ARGB component separately,
811
    //  and storing the least significant 8 bits of the result."
812
0
    for (ARGB32* pixel = palette_bitmap->begin() + 1; pixel != palette_bitmap->end(); ++pixel)
813
0
        *pixel = add_argb32(*pixel, pixel[-1]);
814
815
0
    return adopt_nonnull_own_or_enomem(new (nothrow) ColorIndexingTransform(pixels_per_pixel, original_width, move(palette_bitmap)));
816
0
}
817
818
ErrorOr<NonnullRefPtr<Bitmap>> ColorIndexingTransform::transform(NonnullRefPtr<Bitmap> bitmap)
819
0
{
820
0
    if (pixels_per_pixel() == 1) {
821
0
        for (ARGB32& pixel : *bitmap) {
822
            // "The inverse transform for the image is simply replacing the pixel values (which are indices to the color table)
823
            //  with the actual color table values. The indexing is done based on the green component of the ARGB color. [...]
824
            //  If the index is equal or larger than color_table_size, the argb color value should be set to 0x00000000 (transparent black)."
825
0
            u8 index = Color::from_argb(pixel).green();
826
0
            pixel = index < m_palette_bitmap->width() ? m_palette_bitmap->scanline(0)[index] : 0;
827
0
        }
828
0
        return bitmap;
829
0
    }
830
831
    // Pixel bundling case.
832
0
    VERIFY(ceil_div(m_original_width, pixels_per_pixel()) == bitmap->size().width());
833
0
    IntSize unbundled_size = { m_original_width, bitmap->size().height() };
834
0
    auto new_bitmap = TRY(Bitmap::create(BitmapFormat::BGRA8888, unbundled_size));
835
836
0
    unsigned bits_per_pixel = 8 / pixels_per_pixel();
837
0
    unsigned pixel_mask = (1 << bits_per_pixel) - 1;
838
0
    for (int y = 0; y < bitmap->height(); ++y) {
839
0
        ARGB32* bitmap_scanline = bitmap->scanline(y);
840
0
        ARGB32* new_bitmap_scanline = new_bitmap->scanline(y);
841
842
0
        for (int x = 0, new_x = 0; x < bitmap->width(); ++x, new_x += pixels_per_pixel()) {
843
0
            u8 indexes = Color::from_argb(bitmap_scanline[x]).green();
844
845
0
            for (int i = 0; i < pixels_per_pixel() && new_x + i < new_bitmap->width(); ++i) {
846
0
                u8 index = indexes & pixel_mask;
847
0
                new_bitmap_scanline[new_x + i] = index < m_palette_bitmap->width() ? m_palette_bitmap->scanline(0)[index] : 0;
848
0
                indexes >>= bits_per_pixel;
849
0
            }
850
0
        }
851
0
    }
852
853
0
    return new_bitmap;
854
0
}
855
856
}
857
858
// https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
859
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#7_overall_structure_of_the_format
860
ErrorOr<NonnullRefPtr<Bitmap>> decode_webp_chunk_VP8L_contents(VP8LHeader const& vp8l_header)
861
0
{
862
0
    FixedMemoryStream memory_stream { vp8l_header.lossless_data };
863
0
    LittleEndianInputBitStream bit_stream { MaybeOwned<Stream>(memory_stream), LittleEndianInputBitStream::UnsatisfiableReadBehavior::FillWithZero };
864
865
    // image-stream = optional-transform spatially-coded-image
866
867
    // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#4_transformations
868
    // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#72_structure_of_transforms
869
870
0
    auto stored_size = IntSize { vp8l_header.width, vp8l_header.height };
871
872
    // optional-transform   =  (%b1 transform optional-transform) / %b0
873
0
    u8 seen_transforms = 0;
874
0
    Vector<NonnullOwnPtr<Transform>, 4> transforms;
875
0
    while (TRY(bit_stream.read_bits(1))) {
876
        // transform            =  predictor-tx / color-tx / subtract-green-tx
877
        // transform            =/ color-indexing-tx
878
879
0
        TransformType transform_type = static_cast<TransformType>(TRY(bit_stream.read_bits(2)));
880
0
        dbgln_if(WEBP_DEBUG, "transform type {}", (int)transform_type);
881
882
        // "Each transform is allowed to be used only once."
883
0
        u8 mask = 1 << (int)transform_type;
884
0
        if (seen_transforms & mask)
885
0
            return Error::from_string_literal("WebPImageDecoderPlugin: transform type used multiple times");
886
0
        seen_transforms |= mask;
887
888
        // "Transform data contains the information required to apply the inverse transform and depends on the transform type."
889
0
        switch (transform_type) {
890
0
        case PREDICTOR_TRANSFORM:
891
0
            TRY(transforms.try_append(TRY(PredictorTransform::read(bit_stream, stored_size))));
892
0
            break;
893
0
        case COLOR_TRANSFORM:
894
0
            TRY(transforms.try_append(TRY(ColorTransform::read(bit_stream, stored_size))));
895
0
            break;
896
0
        case SUBTRACT_GREEN_TRANSFORM:
897
0
            TRY(transforms.try_append(TRY(try_make<SubtractGreenTransform>())));
898
0
            break;
899
0
        case COLOR_INDEXING_TRANSFORM: {
900
0
            auto color_indexing_transform = TRY(ColorIndexingTransform::read(bit_stream, stored_size.width()));
901
902
            // "After reading this transform, image_width is subsampled by width_bits. This affects the size of subsequent transforms."
903
0
            stored_size.set_width(ceil_div(stored_size.width(), color_indexing_transform->pixels_per_pixel()));
904
905
0
            TRY(transforms.try_append(move(color_indexing_transform)));
906
0
            break;
907
0
        }
908
0
        }
909
0
    }
910
911
0
    auto format = vp8l_header.is_alpha_used ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888;
912
0
    auto bitmap = TRY(decode_webp_chunk_VP8L_image(ImageKind::SpatiallyCoded, format, stored_size, bit_stream));
913
914
    // "The inverse transforms are applied in the reverse order that they are read from the bitstream, that is, last one first."
915
0
    for (auto const& transform : transforms.in_reverse())
916
0
        bitmap = TRY(transform->transform(bitmap));
917
918
0
    if (!vp8l_header.is_alpha_used)
919
0
        bitmap->strip_alpha_channel();
920
921
0
    return bitmap;
922
0
}
923
924
}