Debian Codegraph @

thirdparty/basis_universal/transcoder/basisu.h

raw symbols SCIP
1 // basisu.h
2 // Copyright (C) 2019-2024 Binomial LLC. All Rights Reserved.
3 // Important: If compiling with gcc, be sure strict aliasing is disabled: -fno-strict-aliasing
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 #pragma once
17
18 #ifdef _MSC_VER
19
20 #pragma warning (disable : 4201)
21 #pragma warning (disable : 4127) // warning C4127: conditional expression is constant
22 #pragma warning (disable : 4530) // C++ exception handler used, but unwind semantics are not enabled.
23
24 #endif // _MSC_VER
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <math.h>
29 #include <stdarg.h>
30 #include <string.h>
31 #include <memory.h>
32 #include <limits.h>
33 #include <stdint.h>
34
35 #include <algorithm>
36 #include <limits>
37 #include <functional>
38 #include <iterator>
39 #include <type_traits>
40 #include <assert.h>
41 #include <random>
42 #include <inttypes.h>
43
44 #include "basisu_containers.h"
45
46 #ifdef max
47 #undef max
48 #endif
49
50 #ifdef min
51 #undef min
52 #endif
53
54 #ifdef _WIN32
55 #define strcasecmp _stricmp
56 #endif
57
58 // Set to one to enable debug printf()'s when any errors occur, for development/debugging. Especially useful for WebGL development.
59 #ifndef BASISU_FORCE_DEVEL_MESSAGES
60 #define BASISU_FORCE_DEVEL_MESSAGES 0
61 #endif
62
63 #define BASISU_NOTE_UNUSED(x) (void)(x)
64 #define BASISU_ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
65 #define BASISU_NO_EQUALS_OR_COPY_CONSTRUCT(x) x(const x &) = delete; x& operator= (const x &) = delete;
66 #define BASISU_ASSUME(x) static_assert(x, #x);
67 #define BASISU_OFFSETOF(s, m) offsetof(s, m)
68 #define BASISU_STRINGIZE(x) #x
69 #define BASISU_STRINGIZE2(x) BASISU_STRINGIZE(x)
70
71 #if BASISU_FORCE_DEVEL_MESSAGES
72 #define BASISU_DEVEL_ERROR(...) do { basisu::debug_printf(__VA_ARGS__); } while(0)
73 #else
74 #define BASISU_DEVEL_ERROR(...)
75 #endif
76
77 namespace basisu
78 {
79 // Types/utilities
80
81 #ifdef _WIN32
82 const char BASISU_PATH_SEPERATOR_CHAR = '\\';
83 #else
84 const char BASISU_PATH_SEPERATOR_CHAR = '/';
85 #endif
86
87 typedef basisu::vector<uint8_t> uint8_vec;
88 typedef basisu::vector<int16_t> int16_vec;
89 typedef basisu::vector<uint16_t> uint16_vec;
90 typedef basisu::vector<uint32_t> uint_vec;
91 typedef basisu::vector<size_t> size_t_vec;
92 typedef basisu::vector<uint64_t> uint64_vec;
93 typedef basisu::vector<int> int_vec;
94 typedef basisu::vector<bool> bool_vec;
95 typedef basisu::vector<float> float_vec;
96
97 void enable_debug_printf(bool enabled);
98 void debug_printf(const char *pFmt, ...);
99 void debug_puts(const char* p);
100
101 template <typename... Args>
102 inline void fmt_debug_printf(const char* pFmt, Args&&... args)
103 {
104 std::string res;
105 if (!fmt_variants(res, pFmt, fmt_variant_vec{ fmt_variant(std::forward<Args>(args))... }))
106 return;
107 debug_puts(res.c_str());
108 }
109
110 template <typename T> inline void clear_obj(T& obj) { memset((void *)&obj, 0, sizeof(obj)); }
111
112 constexpr double cPiD = 3.14159265358979323846264338327950288;
113 constexpr float REALLY_SMALL_FLOAT_VAL = .000000125f;
114 constexpr float SMALL_FLOAT_VAL = .0000125f;
115 constexpr float BIG_FLOAT_VAL = 1e+30f;
116
117 template <typename T0, typename T1> inline T0 lerp(T0 a, T0 b, T1 c) { return a + (b - a) * c; }
118
119 inline float clampf(float value, float low, float high) { if (value < low) value = low; else if (value > high) value = high; return value; }
120 inline float saturate(float value) { return clampf(value, 0, 1.0f); }
121 inline uint8_t minimumub(uint8_t a, uint8_t b) { return (a < b) ? a : b; }
122 inline uint32_t minimumu(uint32_t a, uint32_t b) { return (a < b) ? a : b; }
123 inline int32_t minimumi(int32_t a, int32_t b) { return (a < b) ? a : b; }
124 inline float minimumf(float a, float b) { return (a < b) ? a : b; }
125 inline uint8_t maximumub(uint8_t a, uint8_t b) { return (a > b) ? a : b; }
126 inline uint32_t maximumu(uint32_t a, uint32_t b) { return (a > b) ? a : b; }
127 inline int32_t maximumi(int32_t a, int32_t b) { return (a > b) ? a : b; }
128 inline float maximumf(float a, float b) { return (a > b) ? a : b; }
129 inline int squarei(int i) { return i * i; }
130 inline float squaref(float i) { return i * i; }
131 inline double squared(double i) { return i * i; }
132 template<typename T> inline T square(T a) { return a * a; }
133 template<typename T> inline T sign(T a) { return (a < 0) ? (T)-1 : ((a == 0) ? (T)0 : (T)1); }
134
135 inline bool equal_tol(float a, float b, float t) { return fabsf(a - b) <= ((maximum(fabsf(a), fabsf(b)) + 1.0f) * t); }
136 inline bool equal_tol(double a, double b, double t) { return fabs(a - b) <= ((maximum(fabs(a), fabs(b)) + 1.0f) * t); }
137
138 template <class T>
139 inline T prev_wrap(T i, T n)
140 {
141 T temp = i - 1;
142 if (temp < 0)
143 temp = n - 1;
144 return temp;
145 }
146
147 template <class T>
148 inline T next_wrap(T i, T n)
149 {
150 T temp = i + 1;
151 if (temp >= n)
152 temp = 0;
153 return temp;
154 }
155
156 inline uint32_t iabs(int32_t i) { return (i < 0) ? static_cast<uint32_t>(-i) : static_cast<uint32_t>(i); }
157 inline uint64_t iabs64(int64_t i) { return (i < 0) ? static_cast<uint64_t>(-i) : static_cast<uint64_t>(i); }
158
159 template<typename T> inline void clear_vector(T &vec) { vec.erase(vec.begin(), vec.end()); }
160 template<typename T> inline typename T::value_type *enlarge_vector(T &vec, size_t n) { size_t cs = vec.size(); vec.resize(cs + n); return &vec[cs]; }
161
162 inline bool is_pow2(uint32_t x) { return x && ((x & (x - 1U)) == 0U); }
163 inline bool is_pow2(uint64_t x) { return x && ((x & (x - 1U)) == 0U); }
164
165 template<typename T> inline T open_range_check(T v, T minv, T maxv) { assert(v >= minv && v < maxv); BASISU_NOTE_UNUSED(minv); BASISU_NOTE_UNUSED(maxv); return v; }
166 template<typename T> inline T open_range_check(T v, T maxv) { assert(v < maxv); BASISU_NOTE_UNUSED(maxv); return v; }
167
168 // Open interval
169 inline bool in_bounds(int v, int l, int h)
170 {
171 return (v >= l) && (v < h);
172 }
173
174 // Closed interval
175 inline bool in_range(int v, int l, int h)
176 {
177 return (v >= l) && (v <= h);
178 }
179
180 inline uint32_t total_bits(uint32_t v) { uint32_t l = 0; for ( ; v > 0U; ++l) v >>= 1; return l; }
181
182 template<typename T> inline T saturate(T val) { return clamp(val, 0.0f, 1.0f); }
183
184 inline uint32_t get_bit(uint32_t src, int ndx)
185 {
186 assert(in_bounds(ndx, 0, 32));
187 return (src >> ndx) & 1;
188 }
189
190 inline bool is_bit_set(uint32_t src, int ndx)
191 {
192 return get_bit(src, ndx) != 0;
193 }
194
195 inline uint32_t get_bits(uint32_t val, int low, int high)
196 {
197 const int num_bits = (high - low) + 1;
198 assert(in_range(num_bits, 1, 32));
199
200 val >>= low;
201 if (num_bits != 32)
202 val &= ((1u << num_bits) - 1);
203
204 return val;
205 }
206
207 template<typename T, typename R> inline void append_vector(T &vec, const R *pObjs, size_t n)
208 {
209 if (n)
210 {
211 if (vec.size())
212 {
213 assert((pObjs + n) <= vec.begin() || (pObjs >= vec.end()));
214 }
215 const size_t cur_s = vec.size();
216 vec.resize(cur_s + n);
217 memcpy(&vec[cur_s], pObjs, sizeof(R) * n);
218 }
219 }
220
221 template<typename T> inline void append_vector(T &vec, const T &other_vec)
222 {
223 assert(&vec != &other_vec);
224 if (other_vec.size())
225 append_vector(vec, &other_vec[0], other_vec.size());
226 }
227
228 template<typename T> inline void vector_ensure_element_is_valid(T &vec, size_t idx)
229 {
230 if (idx >= vec.size())
231 vec.resize(idx + 1);
232 }
233
234 template<typename T> inline void vector_sort(T &vec)
235 {
236 if (vec.size())
237 std::sort(vec.begin(), vec.end());
238 }
239
240 template<typename T, typename U> inline bool unordered_set_contains(T& set, const U&obj)
241 {
242 return set.find(obj) != set.end();
243 }
244
245 template<typename T> int vector_find(const T &vec, const typename T::value_type &obj)
246 {
247 assert(vec.size() <= INT_MAX);
248 for (size_t i = 0; i < vec.size(); i++)
249 if (vec[i] == obj)
250 return static_cast<int>(i);
251 return -1;
252 }
253
254 template<typename T> void vector_set_all(T &vec, const typename T::value_type &obj)
255 {
256 for (size_t i = 0; i < vec.size(); i++)
257 vec[i] = obj;
258 }
259
260 inline uint64_t read_be64(const void *p)
261 {
262 uint64_t val = 0;
263 for (uint32_t i = 0; i < 8; i++)
264 val |= (static_cast<uint64_t>(static_cast<const uint8_t *>(p)[7 - i]) << (i * 8));
265 return val;
266 }
267
268 inline void write_be64(void *p, uint64_t x)
269 {
270 for (uint32_t i = 0; i < 8; i++)
271 static_cast<uint8_t *>(p)[7 - i] = static_cast<uint8_t>(x >> (i * 8));
272 }
273
274 static inline uint16_t byteswap16(uint16_t x) { return static_cast<uint16_t>((x << 8) | (x >> 8)); }
275 static inline uint32_t byteswap32(uint32_t x) { return ((x << 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x >> 24)); }
276
277 inline uint32_t floor_log2i(uint32_t v)
278 {
279 uint32_t b = 0;
280 for (; v > 1U; ++b)
281 v >>= 1;
282 return b;
283 }
284
285 inline uint32_t ceil_log2i(uint32_t v)
286 {
287 uint32_t b = floor_log2i(v);
288 if ((b != 32) && (v > (1U << b)))
289 ++b;
290 return b;
291 }
292
293 inline int posmod(int x, int y)
294 {
295 if (x >= 0)
296 return (x < y) ? x : (x % y);
297 int m = (-x) % y;
298 return (m != 0) ? (y - m) : m;
299 }
300
301 inline bool do_excl_ranges_overlap(int la, int ha, int lb, int hb)
302 {
303 assert(la < ha && lb < hb);
304 if ((ha <= lb) || (la >= hb)) return false;
305 return true;
306 }
307
308 static inline uint32_t read_le_word(const uint8_t* pBytes)
309 {
310 return (pBytes[1] << 8U) | (pBytes[0]);
311 }
312
313 static inline uint32_t read_le_dword(const uint8_t *pBytes)
314 {
315 return (pBytes[3] << 24U) | (pBytes[2] << 16U) | (pBytes[1] << 8U) | (pBytes[0]);
316 }
317
318 static inline void write_le_dword(uint8_t* pBytes, uint32_t val)
319 {
320 pBytes[0] = (uint8_t)val;
321 pBytes[1] = (uint8_t)(val >> 8U);
322 pBytes[2] = (uint8_t)(val >> 16U);
323 pBytes[3] = (uint8_t)(val >> 24U);
324 }
325
326 // Always little endian 1-8 byte unsigned int
327 template<uint32_t NumBytes>
328 struct packed_uint
329 {
330 uint8_t m_bytes[NumBytes];
331
332 inline packed_uint() { static_assert(NumBytes <= sizeof(uint64_t), "Invalid NumBytes"); }
333 inline packed_uint(uint64_t v) { *this = v; }
334 inline packed_uint(const packed_uint& other) { *this = other; }
335
336 inline packed_uint& operator= (uint64_t v)
337 {
338 // TODO: Add assert on truncation?
339 for (uint32_t i = 0; i < NumBytes; i++)
340 m_bytes[i] = static_cast<uint8_t>(v >> (i * 8));
341 return *this;
342 }
343
344 inline packed_uint& operator= (const packed_uint& rhs)
345 {
346 memcpy(m_bytes, rhs.m_bytes, sizeof(m_bytes));
347 return *this;
348 }
349
350 inline uint64_t get_uint64() const
351 {
352 // Some compilers may warn about this code. It clearly cannot access beyond the end of the m_bytes struct here.
353 if constexpr (NumBytes == 1)
354 {
355 return m_bytes[0];
356 }
357 else if constexpr (NumBytes == 2)
358 {
359 return (m_bytes[1] << 8U) | m_bytes[0];
360 }
361 else if constexpr (NumBytes == 3)
362 {
363 return (m_bytes[2] << 16U) | (m_bytes[1] << 8U) | m_bytes[0];
364 }
365 else if constexpr (NumBytes == 4)
366 {
367 return read_le_dword(m_bytes);
368 }
369 else if constexpr (NumBytes == 5)
370 {
371 uint32_t l = read_le_dword(m_bytes);
372 uint32_t h = m_bytes[4];
373 return static_cast<uint64_t>(l) | (static_cast<uint64_t>(h) << 32U);
374 }
375 else if constexpr (NumBytes == 6)
376 {
377 uint32_t l = read_le_dword(m_bytes);
378 uint32_t h = (m_bytes[5] << 8U) | m_bytes[4];
379 return static_cast<uint64_t>(l) | (static_cast<uint64_t>(h) << 32U);
380 }
381 else if constexpr (NumBytes == 7)
382 {
383 uint32_t l = read_le_dword(m_bytes);
384 uint32_t h = (m_bytes[6] << 16U) | (m_bytes[5] << 8U) | m_bytes[4];
385 return static_cast<uint64_t>(l) | (static_cast<uint64_t>(h) << 32U);
386 }
387 else if constexpr (NumBytes == 8)
388 {
389 uint32_t l = read_le_dword(m_bytes);
390 uint32_t h = read_le_dword(m_bytes + 4);
391 return static_cast<uint64_t>(l) | (static_cast<uint64_t>(h) << 32U);
392 }
393 else
394 {
395 static_assert(NumBytes <= 8, "Invalid NumBytes");
396 return 0;
397 }
398 }
399
400 inline uint32_t get_uint32() const
401 {
402 static_assert(NumBytes <= sizeof(uint32_t), "packed_uint too large to use get_uint32");
403 return static_cast<uint32_t>(get_uint64());
404 }
405
406 inline operator uint32_t() const
407 {
408 static_assert(NumBytes <= sizeof(uint32_t), "packed_uint too large to use operator uint32_t");
409 return static_cast<uint32_t>(get_uint64());
410 }
411 };
412
413 enum eZero { cZero };
414 enum eNoClamp { cNoClamp };
415
416 // Rice/Huffman entropy coding
417
418 // This is basically Deflate-style canonical Huffman, except we allow for a lot more symbols.
419 enum
420 {
421 cHuffmanMaxSupportedCodeSize = 16, cHuffmanMaxSupportedInternalCodeSize = 31,
422 cHuffmanFastLookupBits = 10,
423 cHuffmanMaxSymsLog2 = 14, cHuffmanMaxSyms = 1 << cHuffmanMaxSymsLog2,
424
425 // Small zero runs
426 cHuffmanSmallZeroRunSizeMin = 3, cHuffmanSmallZeroRunSizeMax = 10, cHuffmanSmallZeroRunExtraBits = 3,
427
428 // Big zero run
429 cHuffmanBigZeroRunSizeMin = 11, cHuffmanBigZeroRunSizeMax = 138, cHuffmanBigZeroRunExtraBits = 7,
430
431 // Small non-zero run
432 cHuffmanSmallRepeatSizeMin = 3, cHuffmanSmallRepeatSizeMax = 6, cHuffmanSmallRepeatExtraBits = 2,
433
434 // Big non-zero run
435 cHuffmanBigRepeatSizeMin = 7, cHuffmanBigRepeatSizeMax = 134, cHuffmanBigRepeatExtraBits = 7,
436
437 cHuffmanTotalCodelengthCodes = 21, cHuffmanSmallZeroRunCode = 17, cHuffmanBigZeroRunCode = 18, cHuffmanSmallRepeatCode = 19, cHuffmanBigRepeatCode = 20
438 };
439
440 static const uint8_t g_huffman_sorted_codelength_codes[] = { cHuffmanSmallZeroRunCode, cHuffmanBigZeroRunCode, cHuffmanSmallRepeatCode, cHuffmanBigRepeatCode, 0, 8, 7, 9, 6, 0xA, 5, 0xB, 4, 0xC, 3, 0xD, 2, 0xE, 1, 0xF, 0x10 };
441 const uint32_t cHuffmanTotalSortedCodelengthCodes = sizeof(g_huffman_sorted_codelength_codes) / sizeof(g_huffman_sorted_codelength_codes[0]);
442
443 // GPU texture formats and various uncompressed texture formats.
444
445 enum class texture_format
446 {
447 cInvalidTextureFormat = -1,
448
449 // Block-based formats
450 cETC1, // ETC1
451 cETC1S, // ETC1 (subset: diff colors only, no subblocks)
452 cETC2_RGB, // ETC2 color block (basisu doesn't support ETC2 planar/T/H modes - just basic ETC1)
453 cETC2_RGBA, // ETC2 EAC alpha block followed by ETC2 color block
454 cETC2_ALPHA, // ETC2 EAC alpha block
455 cBC1, // DXT1
456 cBC3, // DXT5 (BC4/DXT5A block followed by a BC1/DXT1 block)
457 cBC4, // DXT5A
458 cBC5, // 3DC/DXN (two BC4/DXT5A blocks)
459 cBC6HSigned, // HDR
460 cBC6HUnsigned, // HDR
461 cBC7,
462 cASTC_LDR_4x4, // ASTC 4x4 LDR only
463 cASTC_HDR_4x4, // ASTC 4x4 HDR only (but may use LDR ASTC blocks internally, although our encoders don't do this)
464 cASTC_HDR_6x6, // ASTC 6x6 HDR only (but may use LDR ASTC blocks internally, although our encoders don't do this)
465 cPVRTC1_4_RGB,
466 cPVRTC1_4_RGBA,
467 cATC_RGB,
468 cATC_RGBA_INTERPOLATED_ALPHA,
469 cFXT1_RGB,
470 cPVRTC2_4_RGBA,
471 cETC2_R11_EAC,
472 cETC2_RG11_EAC,
473 cUASTC4x4,
474 cUASTC_HDR_4x4,
475 cBC1_NV,
476 cBC1_AMD,
477
478 // Uncompressed/raw pixels
479 cRGBA32,
480 cRGB565,
481 cBGR565,
482 cRGBA4444,
483 cABGR4444,
484 cRGBA_HALF,
485 cRGB_HALF,
486 cRGB_9E5
487 };
488
489 inline bool is_uncompressed_texture_format(texture_format fmt)
490 {
491 switch (fmt)
492 {
493 case texture_format::cRGBA32:
494 case texture_format::cRGB565:
495 case texture_format::cBGR565:
496 case texture_format::cRGBA4444:
497 case texture_format::cABGR4444:
498 case texture_format::cRGBA_HALF:
499 case texture_format::cRGB_HALF:
500 case texture_format::cRGB_9E5:
501 return true;
502 default:
503 break;
504 }
505
506 return false;
507 }
508
509 inline bool is_block_based_texture_format(texture_format fmt)
510 {
511 return !is_uncompressed_texture_format(fmt);
512 }
513
514 // This is bytes per block for GPU formats, or bytes per texel for uncompressed formats.
515 inline uint32_t get_bytes_per_block_or_pixel(texture_format fmt)
516 {
517 switch (fmt)
518 {
519 case texture_format::cETC1:
520 case texture_format::cETC1S:
521 case texture_format::cETC2_RGB:
522 case texture_format::cETC2_ALPHA:
523 case texture_format::cBC1:
524 case texture_format::cBC1_NV:
525 case texture_format::cBC1_AMD:
526 case texture_format::cBC4:
527 case texture_format::cPVRTC1_4_RGB:
528 case texture_format::cPVRTC1_4_RGBA:
529 case texture_format::cATC_RGB:
530 case texture_format::cPVRTC2_4_RGBA:
531 case texture_format::cETC2_R11_EAC:
532 return 8;
533 case texture_format::cRGBA32:
534 case texture_format::cRGB_9E5:
535 return sizeof(uint32_t);
536 case texture_format::cRGB_HALF:
537 return sizeof(uint16_t) * 3;
538 case texture_format::cRGBA_HALF:
539 return sizeof(uint16_t) * 4;
540 case texture_format::cRGB565:
541 case texture_format::cBGR565:
542 case texture_format::cRGBA4444:
543 case texture_format::cABGR4444:
544 return sizeof(uint16_t);
545
546 default:
547 break;
548 }
549
550 // Everything else is 16 bytes/block.
551 return 16;
552 }
553
554 // This is qwords per block for GPU formats, or not valid for uncompressed formats.
555 inline uint32_t get_qwords_per_block(texture_format fmt)
556 {
557 assert(is_block_based_texture_format(fmt));
558
559 const uint32_t bytes_per_block = get_bytes_per_block_or_pixel(fmt);
560 return bytes_per_block >> 3;
561 }
562
563 inline uint32_t get_block_width(texture_format fmt)
564 {
565 assert(is_block_based_texture_format(fmt));
566
567 switch (fmt)
568 {
569 case texture_format::cFXT1_RGB:
570 return 8;
571 case texture_format::cASTC_HDR_6x6:
572 return 6;
573 default:
574 break;
575 }
576 return 4;
577 }
578
579 inline uint32_t get_block_height(texture_format fmt)
580 {
581 assert(is_block_based_texture_format(fmt));
582
583 switch (fmt)
584 {
585 case texture_format::cASTC_HDR_6x6:
586 return 6;
587 default:
588 break;
589 }
590 return 4;
591 }
592
593 inline bool is_hdr_texture_format(texture_format fmt)
594 {
595 switch (fmt)
596 {
597 case texture_format::cASTC_HDR_4x4:
598 case texture_format::cUASTC_HDR_4x4:
599 case texture_format::cASTC_HDR_6x6:
600 case texture_format::cBC6HSigned:
601 case texture_format::cBC6HUnsigned:
602 case texture_format::cRGBA_HALF:
603 case texture_format::cRGB_HALF:
604 case texture_format::cRGB_9E5:
605 return true;
606 default:
607 break;
608 }
609
610 return false;
611 }
612
613 inline bool is_ldr_texture_format(texture_format fmt)
614 {
615 return !is_hdr_texture_format(fmt);
616 }
617
618 } // namespace basisu
619