1/*
2 * Copyright 2020 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/core/SkCompressedDataUtils.h"
9
10#include "include/core/SkBitmap.h"
11#include "include/core/SkColorPriv.h"
12#include "include/core/SkData.h"
13#include "include/private/SkColorData.h"
14#include "include/private/SkTPin.h"
15#include "src/core/SkMathPriv.h"
16#include "src/core/SkMipmap.h"
17
18struct ETC1Block {
19    uint32_t fHigh;
20    uint32_t fLow;
21};
22
23constexpr uint32_t kFlipBit = 0x1; // set -> T/B sub-blocks; not-set -> L/R sub-blocks
24constexpr uint32_t kDiffBit = 0x2; // set -> differential; not-set -> individual
25
26static inline int extend_4To8bits(int b) {
27    int c = b & 0xf;
28    return (c << 4) | c;
29}
30
31static inline int extend_5To8bits(int b) {
32    int c = b & 0x1f;
33    return (c << 3) | (c >> 2);
34}
35
36static inline int extend_5plus3To8Bits(int base, int diff) {
37    static const int kLookup[8] = { 0, 1, 2, 3, -4, -3, -2, -1 };
38
39    return extend_5To8bits((0x1f & base) + kLookup[0x7 & diff]);
40}
41
42static const int kNumETC1ModifierTables = 8;
43static const int kNumETC1PixelIndices = 4;
44
45// The index of each row in this table is the ETC1 table codeword
46// The index of each column in this table is the ETC1 pixel index value
47static const int kETC1ModifierTables[kNumETC1ModifierTables][kNumETC1PixelIndices] = {
48    /* 0 */ { 2,    8,  -2,   -8 },
49    /* 1 */ { 5,   17,  -5,  -17 },
50    /* 2 */ { 9,   29,  -9,  -29 },
51    /* 3 */ { 13,  42, -13,  -42 },
52    /* 4 */ { 18,  60, -18,  -60 },
53    /* 5 */ { 24,  80, -24,  -80 },
54    /* 6 */ { 33, 106, -33, -106 },
55    /* 7 */ { 47, 183, -47, -183 }
56};
57
58static int num_4x4_blocks(int size) {
59    return ((size + 3) & ~3) >> 2;
60}
61
62// Return which sub-block a given x,y location in the overall 4x4 block belongs to
63static int xy_to_subblock_index(int x, int y, bool flip) {
64    SkASSERT(x >= 0 && x < 4);
65    SkASSERT(y >= 0 && y < 4);
66
67    if (flip) {
68        return y < 2 ? 0 : 1; // sub-block 1 is on top of sub-block 2
69    } else {
70        return x < 2 ? 0 : 1; // sub-block 1 is to the left of sub-block 2
71    }
72}
73
74struct IColor {
75    int fR, fG, fB;
76};
77
78static SkPMColor add_delta_and_clamp(const IColor& col, int delta) {
79    int r8 = SkTPin(col.fR + delta, 0, 255);
80    int g8 = SkTPin(col.fG + delta, 0, 255);
81    int b8 = SkTPin(col.fB + delta, 0, 255);
82
83    return SkPackARGB32(0xFF, r8, g8, b8);
84}
85
86static bool decompress_etc1(SkISize dimensions, const uint8_t* srcData, SkBitmap* dst) {
87    const ETC1Block* srcBlocks = reinterpret_cast<const ETC1Block*>(srcData);
88
89    int numXBlocks = num_4x4_blocks(dimensions.width());
90    int numYBlocks = num_4x4_blocks(dimensions.height());
91
92    for (int y = 0; y < numYBlocks; ++y) {
93        for (int x = 0; x < numXBlocks; ++x) {
94            const ETC1Block* curBlock1 = &srcBlocks[y * numXBlocks + x];
95            uint32_t high = SkBSwap32(curBlock1->fHigh);
96            uint32_t low = SkBSwap32(curBlock1->fLow);
97
98            bool flipped = SkToBool(high & kFlipBit);
99            bool differential = SkToBool(high & kDiffBit);
100
101            IColor colors[2];
102
103            if (differential) {
104                colors[0].fR = extend_5To8bits(high >> 27);
105                colors[1].fR = extend_5plus3To8Bits(high >> 27, high >> 24);
106                colors[0].fG = extend_5To8bits(high >> 19);
107                colors[1].fG = extend_5plus3To8Bits(high >> 19, high >> 16);
108                colors[0].fB = extend_5To8bits(high >> 11);
109                colors[1].fB = extend_5plus3To8Bits(high >> 11, high >> 8);
110            } else {
111                colors[0].fR = extend_4To8bits(high >> 28);
112                colors[1].fR = extend_4To8bits(high >> 24);
113                colors[0].fG = extend_4To8bits(high >> 20);
114                colors[1].fG = extend_4To8bits(high >> 16);
115                colors[0].fB = extend_4To8bits(high >> 12);
116                colors[1].fB = extend_4To8bits(high >> 8);
117            }
118
119            int tableIndex0 = (high >> 5) & 0x7;
120            int tableIndex1 = (high >> 2) & 0x7;
121            const int* tables[2] = {
122                kETC1ModifierTables[tableIndex0],
123                kETC1ModifierTables[tableIndex1]
124            };
125
126            int baseShift = 0;
127            int offsetX = 4 * x, offsetY = 4 * y;
128            for (int i = 0; i < 4; ++i, ++baseShift) {
129                for (int j = 0; j < 4; ++j) {
130                    if (offsetX + j >= dst->width() || offsetY + i >= dst->height()) {
131                        // This can happen for the topmost levels of a mipmap and for
132                        // non-multiple of 4 textures
133                        continue;
134                    }
135
136                    int subBlockIndex = xy_to_subblock_index(j, i, flipped);
137                    int pixelIndex = ((low >> (baseShift+(j*4))) & 0x1) |
138                                     (low >> (baseShift+(j*4)+15) & 0x2);
139
140                    SkASSERT(subBlockIndex == 0 || subBlockIndex == 1);
141                    SkASSERT(pixelIndex >= 0 && pixelIndex < 4);
142
143                    int delta = tables[subBlockIndex][pixelIndex];
144                    *dst->getAddr32(offsetX + j, offsetY + i) =
145                                                add_delta_and_clamp(colors[subBlockIndex], delta);
146                }
147            }
148        }
149    }
150
151    return true;
152}
153
154//------------------------------------------------------------------------------------------------
155struct BC1Block {
156    uint16_t fColor0;
157    uint16_t fColor1;
158    uint32_t fIndices;
159};
160
161static SkPMColor from565(uint16_t rgb565) {
162    uint8_t r8 = SkR16ToR32((rgb565 >> 11) & 0x1F);
163    uint8_t g8 = SkG16ToG32((rgb565 >> 5) & 0x3F);
164    uint8_t b8 = SkB16ToB32(rgb565 & 0x1F);
165
166    return SkPackARGB32(0xFF, r8, g8, b8);
167}
168
169// return t*col0 + (1-t)*col1
170static SkPMColor lerp(float t, SkPMColor col0, SkPMColor col1) {
171    SkASSERT(SkGetPackedA32(col0) == 0xFF && SkGetPackedA32(col1) == 0xFF);
172
173    // TODO: given 't' is only either 1/3 or 2/3 this could be done faster
174    uint8_t r8 = SkScalarRoundToInt(t * SkGetPackedR32(col0) + (1.0f - t) * SkGetPackedR32(col1));
175    uint8_t g8 = SkScalarRoundToInt(t * SkGetPackedG32(col0) + (1.0f - t) * SkGetPackedG32(col1));
176    uint8_t b8 = SkScalarRoundToInt(t * SkGetPackedB32(col0) + (1.0f - t) * SkGetPackedB32(col1));
177    return SkPackARGB32(0xFF, r8, g8, b8);
178}
179
180static bool decompress_bc1(SkISize dimensions, const uint8_t* srcData,
181                           bool isOpaque, SkBitmap* dst) {
182    const BC1Block* srcBlocks = reinterpret_cast<const BC1Block*>(srcData);
183
184    int numXBlocks = num_4x4_blocks(dimensions.width());
185    int numYBlocks = num_4x4_blocks(dimensions.height());
186
187    SkPMColor colors[4];
188
189    for (int y = 0; y < numYBlocks; ++y) {
190        for (int x = 0; x < numXBlocks; ++x) {
191            const BC1Block* curBlock = &srcBlocks[y * numXBlocks + x];
192
193            colors[0] = from565(curBlock->fColor0);
194            colors[1] = from565(curBlock->fColor1);
195            if (curBlock->fColor0 <= curBlock->fColor1) {        // signal for a transparent block
196                colors[2] = SkPackARGB32(
197                    0xFF,
198                    (SkGetPackedR32(colors[0]) + SkGetPackedR32(colors[1])) >> 1,
199                    (SkGetPackedG32(colors[0]) + SkGetPackedG32(colors[1])) >> 1,
200                    (SkGetPackedB32(colors[0]) + SkGetPackedB32(colors[1])) >> 1);
201                // The opacity of the overall texture trumps the per-block transparency
202                colors[3] = SkPackARGB32(isOpaque ? 0xFF : 0, 0, 0, 0);
203            } else {
204                colors[2] = lerp(2.0f/3.0f, colors[0], colors[1]);
205                colors[3] = lerp(1.0f/3.0f, colors[0], colors[1]);
206            }
207
208            int shift = 0;
209            int offsetX = 4 * x, offsetY = 4 * y;
210            for (int i = 0; i < 4; ++i) {
211                for (int j = 0; j < 4; ++j, shift += 2) {
212                    if (offsetX + j >= dst->width() || offsetY + i >= dst->height()) {
213                        // This can happen for the topmost levels of a mipmap and for
214                        // non-multiple of 4 textures
215                        continue;
216                    }
217
218                    int index = (curBlock->fIndices >> shift) & 0x3;
219                    *dst->getAddr32(offsetX + j, offsetY + i) = colors[index];
220                }
221            }
222        }
223    }
224
225    return true;
226}
227
228bool SkDecompress(sk_sp<SkData> data,
229                  SkISize dimensions,
230                  SkImage::CompressionType compressionType,
231                  SkBitmap* dst) {
232    using Type = SkImage::CompressionType;
233
234    const uint8_t* bytes = data->bytes();
235    switch (compressionType) {
236        case Type::kNone:             return false;
237        case Type::kETC2_RGB8_UNORM:  return decompress_etc1(dimensions, bytes, dst);
238        case Type::kBC1_RGB8_UNORM:   return decompress_bc1(dimensions, bytes, true, dst);
239        case Type::kBC1_RGBA8_UNORM:  return decompress_bc1(dimensions, bytes, false, dst);
240        case Type::kASTC_RGBA8_4x4: return true;
241        case Type::kASTC_RGBA8_6x6: return true;
242        case Type::kASTC_RGBA8_8x8: return true;
243    }
244
245    SkUNREACHABLE;
246    return false;
247}
248
249size_t SkCompressedDataSize(SkImage::CompressionType type, SkISize dimensions,
250                            SkTArray<size_t>* individualMipOffsets, bool mipMapped) {
251    SkASSERT(!individualMipOffsets || !individualMipOffsets->count());
252
253    int numMipLevels = 1;
254    if (mipMapped) {
255        numMipLevels = SkMipmap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1;
256    }
257
258    size_t totalSize = 0;
259    switch (type) {
260        case SkImage::CompressionType::kNone:
261            break;
262        case SkImage::CompressionType::kETC2_RGB8_UNORM:
263        case SkImage::CompressionType::kBC1_RGB8_UNORM:
264        case SkImage::CompressionType::kBC1_RGBA8_UNORM: {
265            for (int i = 0; i < numMipLevels; ++i) {
266                int numBlocks = num_4x4_blocks(dimensions.width()) *
267                                num_4x4_blocks(dimensions.height());
268
269                if (individualMipOffsets) {
270                    individualMipOffsets->push_back(totalSize);
271                }
272
273                static_assert(sizeof(ETC1Block) == sizeof(BC1Block));
274                totalSize += numBlocks * sizeof(ETC1Block);
275
276                dimensions = {std::max(1, dimensions.width()/2), std::max(1, dimensions.height()/2)};
277            }
278            break;
279        }
280        case SkImage::CompressionType::kASTC_RGBA8_4x4: {
281            // The evil number 16 here is the size of each ASTC block, which is constant for the ASTC 4x4 format,
282            // while the ASTC 4x4 format also explain the evil number 4.0f above
283            totalSize = std::ceil(dimensions.width() / 4.0f) * std::ceil(dimensions.height() / 4.0f) * 16;
284            if (individualMipOffsets) {
285                individualMipOffsets->push_back(0);
286            }
287            break;
288        }
289        case SkImage::CompressionType::kASTC_RGBA8_6x6: {
290            // The evil number 16 here is the size of each ASTC block, which is constant for the ASTC 4x4 format,
291            // while the ASTC 6x6 format also explain the evil number 6.0f above
292            totalSize = std::ceil(dimensions.width() / 6.0f) * std::ceil(dimensions.height() / 6.0f) * 16;
293            if (individualMipOffsets) {
294                individualMipOffsets->push_back(0);
295            }
296            break;
297        }
298        case SkImage::CompressionType::kASTC_RGBA8_8x8: {
299            // The evil number 16 here is the size of each ASTC block, which is constant for the ASTC 4x4 format,
300            // while the ASTC 8x8 format also explain the evil number 8.0f above
301            totalSize = std::ceil(dimensions.width() / 8.0f) * std::ceil(dimensions.height() / 8.0f) * 16;
302            if (individualMipOffsets) {
303                individualMipOffsets->push_back(0);
304            }
305            break;
306        }
307    }
308
309    return totalSize;
310}
311
312size_t SkCompressedBlockSize(SkImage::CompressionType type) {
313    switch (type) {
314        case SkImage::CompressionType::kNone:
315            return 0;
316        case SkImage::CompressionType::kETC2_RGB8_UNORM:
317            return sizeof(ETC1Block);
318        case SkImage::CompressionType::kBC1_RGB8_UNORM:
319        case SkImage::CompressionType::kBC1_RGBA8_UNORM:
320            return sizeof(BC1Block);
321        case SkImage::CompressionType::kASTC_RGBA8_4x4:
322        case SkImage::CompressionType::kASTC_RGBA8_6x6:
323        case SkImage::CompressionType::kASTC_RGBA8_8x8:
324            // The evil number 16 here is the constant size of ASTC format
325            return 16;
326    }
327    SkUNREACHABLE;
328}
329
330size_t SkCompressedFormatDataSize(SkImage::CompressionType compressionType,
331                                  SkISize dimensions, bool mipMapped) {
332    return SkCompressedDataSize(compressionType, dimensions, nullptr, mipMapped);
333}
334