Path: blob/master/thirdparty/basis_universal/transcoder/basisu.h
21152 views
// basisu.h1// Copyright (C) 2019-2024 Binomial LLC. All Rights Reserved.2// Important: If compiling with gcc, be sure strict aliasing is disabled: -fno-strict-aliasing3//4// Licensed under the Apache License, Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS,12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13// See the License for the specific language governing permissions and14// limitations under the License.15#pragma once1617#ifdef _MSC_VER1819#pragma warning (disable : 4201)20#pragma warning (disable : 4127) // warning C4127: conditional expression is constant21#pragma warning (disable : 4530) // C++ exception handler used, but unwind semantics are not enabled.2223#endif // _MSC_VER2425#include <stdlib.h>26#include <stdio.h>27#include <math.h>28#include <stdarg.h>29#include <string.h>30#include <memory.h>31#include <limits.h>32#include <stdint.h>3334#include <algorithm>35#include <limits>36#include <functional>37#include <iterator>38#include <type_traits>39#include <assert.h>40#include <random>41#include <inttypes.h>4243#include "basisu_containers.h"4445#ifdef max46#undef max47#endif4849#ifdef min50#undef min51#endif5253#ifdef _WIN3254#define strcasecmp _stricmp55#endif5657// Set to one to enable debug printf()'s when any errors occur, for development/debugging. Especially useful for WebGL development.58#ifndef BASISU_FORCE_DEVEL_MESSAGES59#define BASISU_FORCE_DEVEL_MESSAGES 060#endif6162#define BASISU_NOTE_UNUSED(x) (void)(x)63#define BASISU_ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))64#define BASISU_NO_EQUALS_OR_COPY_CONSTRUCT(x) x(const x &) = delete; x& operator= (const x &) = delete;65#define BASISU_ASSUME(x) static_assert(x, #x);66#define BASISU_OFFSETOF(s, m) offsetof(s, m)67#define BASISU_STRINGIZE(x) #x68#define BASISU_STRINGIZE2(x) BASISU_STRINGIZE(x)6970#if BASISU_FORCE_DEVEL_MESSAGES71#define BASISU_DEVEL_ERROR(...) do { basisu::debug_printf(__VA_ARGS__); } while(0)72#else73#define BASISU_DEVEL_ERROR(...)74#endif7576namespace basisu77{78// Types/utilities7980#ifdef _WIN3281const char BASISU_PATH_SEPERATOR_CHAR = '\\';82#else83const char BASISU_PATH_SEPERATOR_CHAR = '/';84#endif8586typedef basisu::vector<uint8_t> uint8_vec;87typedef basisu::vector<int16_t> int16_vec;88typedef basisu::vector<uint16_t> uint16_vec;89typedef basisu::vector<uint32_t> uint_vec;90typedef basisu::vector<size_t> size_t_vec;91typedef basisu::vector<uint64_t> uint64_vec;92typedef basisu::vector<int> int_vec;93typedef basisu::vector<bool> bool_vec;94typedef basisu::vector<float> float_vec;9596void enable_debug_printf(bool enabled);97void debug_printf(const char *pFmt, ...);98void debug_puts(const char* p);99100template <typename... Args>101inline void fmt_debug_printf(const char* pFmt, Args&&... args)102{103std::string res;104if (!fmt_variants(res, pFmt, fmt_variant_vec{ fmt_variant(std::forward<Args>(args))... }))105return;106debug_puts(res.c_str());107}108109template <typename T> inline void clear_obj(T& obj) { memset((void *)&obj, 0, sizeof(obj)); }110111constexpr double cPiD = 3.14159265358979323846264338327950288;112constexpr float REALLY_SMALL_FLOAT_VAL = .000000125f;113constexpr float SMALL_FLOAT_VAL = .0000125f;114constexpr float BIG_FLOAT_VAL = 1e+30f;115116template <typename T0, typename T1> inline T0 lerp(T0 a, T0 b, T1 c) { return a + (b - a) * c; }117118inline float clampf(float value, float low, float high) { if (value < low) value = low; else if (value > high) value = high; return value; }119inline float saturate(float value) { return clampf(value, 0, 1.0f); }120inline uint8_t minimumub(uint8_t a, uint8_t b) { return (a < b) ? a : b; }121inline uint32_t minimumu(uint32_t a, uint32_t b) { return (a < b) ? a : b; }122inline int32_t minimumi(int32_t a, int32_t b) { return (a < b) ? a : b; }123inline float minimumf(float a, float b) { return (a < b) ? a : b; }124inline uint8_t maximumub(uint8_t a, uint8_t b) { return (a > b) ? a : b; }125inline uint32_t maximumu(uint32_t a, uint32_t b) { return (a > b) ? a : b; }126inline int32_t maximumi(int32_t a, int32_t b) { return (a > b) ? a : b; }127inline float maximumf(float a, float b) { return (a > b) ? a : b; }128inline int squarei(int i) { return i * i; }129inline float squaref(float i) { return i * i; }130inline double squared(double i) { return i * i; }131template<typename T> inline T square(T a) { return a * a; }132template<typename T> inline T sign(T a) { return (a < 0) ? (T)-1 : ((a == 0) ? (T)0 : (T)1); }133134inline bool equal_tol(float a, float b, float t) { return fabsf(a - b) <= ((maximum(fabsf(a), fabsf(b)) + 1.0f) * t); }135inline bool equal_tol(double a, double b, double t) { return fabs(a - b) <= ((maximum(fabs(a), fabs(b)) + 1.0f) * t); }136137template <class T>138inline T prev_wrap(T i, T n)139{140T temp = i - 1;141if (temp < 0)142temp = n - 1;143return temp;144}145146template <class T>147inline T next_wrap(T i, T n)148{149T temp = i + 1;150if (temp >= n)151temp = 0;152return temp;153}154155inline uint32_t iabs(int32_t i) { return (i < 0) ? static_cast<uint32_t>(-i) : static_cast<uint32_t>(i); }156inline uint64_t iabs64(int64_t i) { return (i < 0) ? static_cast<uint64_t>(-i) : static_cast<uint64_t>(i); }157158template<typename T> inline void clear_vector(T &vec) { vec.erase(vec.begin(), vec.end()); }159template<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]; }160161inline bool is_pow2(uint32_t x) { return x && ((x & (x - 1U)) == 0U); }162inline bool is_pow2(uint64_t x) { return x && ((x & (x - 1U)) == 0U); }163164template<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; }165template<typename T> inline T open_range_check(T v, T maxv) { assert(v < maxv); BASISU_NOTE_UNUSED(maxv); return v; }166167// Open interval168inline bool in_bounds(int v, int l, int h)169{170return (v >= l) && (v < h);171}172173// Closed interval174inline bool in_range(int v, int l, int h)175{176return (v >= l) && (v <= h);177}178179inline uint32_t total_bits(uint32_t v) { uint32_t l = 0; for ( ; v > 0U; ++l) v >>= 1; return l; }180181template<typename T> inline T saturate(T val) { return clamp(val, 0.0f, 1.0f); }182183inline uint32_t get_bit(uint32_t src, int ndx)184{185assert(in_bounds(ndx, 0, 32));186return (src >> ndx) & 1;187}188189inline bool is_bit_set(uint32_t src, int ndx)190{191return get_bit(src, ndx) != 0;192}193194inline uint32_t get_bits(uint32_t val, int low, int high)195{196const int num_bits = (high - low) + 1;197assert(in_range(num_bits, 1, 32));198199val >>= low;200if (num_bits != 32)201val &= ((1u << num_bits) - 1);202203return val;204}205206template<typename T, typename R> inline void append_vector(T &vec, const R *pObjs, size_t n)207{208if (n)209{210if (vec.size())211{212assert((pObjs + n) <= vec.begin() || (pObjs >= vec.end()));213}214const size_t cur_s = vec.size();215vec.resize(cur_s + n);216memcpy(&vec[cur_s], pObjs, sizeof(R) * n);217}218}219220template<typename T> inline void append_vector(T &vec, const T &other_vec)221{222assert(&vec != &other_vec);223if (other_vec.size())224append_vector(vec, &other_vec[0], other_vec.size());225}226227template<typename T> inline void vector_ensure_element_is_valid(T &vec, size_t idx)228{229if (idx >= vec.size())230vec.resize(idx + 1);231}232233template<typename T> inline void vector_sort(T &vec)234{235if (vec.size())236std::sort(vec.begin(), vec.end());237}238239template<typename T, typename U> inline bool unordered_set_contains(T& set, const U&obj)240{241return set.find(obj) != set.end();242}243244template<typename T> int vector_find(const T &vec, const typename T::value_type &obj)245{246assert(vec.size() <= INT_MAX);247for (size_t i = 0; i < vec.size(); i++)248if (vec[i] == obj)249return static_cast<int>(i);250return -1;251}252253template<typename T> void vector_set_all(T &vec, const typename T::value_type &obj)254{255for (size_t i = 0; i < vec.size(); i++)256vec[i] = obj;257}258259inline uint64_t read_be64(const void *p)260{261uint64_t val = 0;262for (uint32_t i = 0; i < 8; i++)263val |= (static_cast<uint64_t>(static_cast<const uint8_t *>(p)[7 - i]) << (i * 8));264return val;265}266267inline void write_be64(void *p, uint64_t x)268{269for (uint32_t i = 0; i < 8; i++)270static_cast<uint8_t *>(p)[7 - i] = static_cast<uint8_t>(x >> (i * 8));271}272273static inline uint16_t byteswap16(uint16_t x) { return static_cast<uint16_t>((x << 8) | (x >> 8)); }274static inline uint32_t byteswap32(uint32_t x) { return ((x << 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x >> 24)); }275276inline uint32_t floor_log2i(uint32_t v)277{278uint32_t b = 0;279for (; v > 1U; ++b)280v >>= 1;281return b;282}283284inline uint32_t ceil_log2i(uint32_t v)285{286uint32_t b = floor_log2i(v);287if ((b != 32) && (v > (1U << b)))288++b;289return b;290}291292inline int posmod(int x, int y)293{294if (x >= 0)295return (x < y) ? x : (x % y);296int m = (-x) % y;297return (m != 0) ? (y - m) : m;298}299300inline bool do_excl_ranges_overlap(int la, int ha, int lb, int hb)301{302assert(la < ha && lb < hb);303if ((ha <= lb) || (la >= hb)) return false;304return true;305}306307static inline uint32_t read_le_word(const uint8_t* pBytes)308{309return (pBytes[1] << 8U) | (pBytes[0]);310}311312static inline uint32_t read_le_dword(const uint8_t *pBytes)313{314return (pBytes[3] << 24U) | (pBytes[2] << 16U) | (pBytes[1] << 8U) | (pBytes[0]);315}316317static inline void write_le_dword(uint8_t* pBytes, uint32_t val)318{319pBytes[0] = (uint8_t)val;320pBytes[1] = (uint8_t)(val >> 8U);321pBytes[2] = (uint8_t)(val >> 16U);322pBytes[3] = (uint8_t)(val >> 24U);323}324325// Always little endian 1-8 byte unsigned int326template<uint32_t NumBytes>327struct packed_uint328{329uint8_t m_bytes[NumBytes];330331inline packed_uint() { static_assert(NumBytes <= sizeof(uint64_t), "Invalid NumBytes"); }332inline packed_uint(uint64_t v) { *this = v; }333inline packed_uint(const packed_uint& other) { *this = other; }334335inline packed_uint& operator= (uint64_t v)336{337// TODO: Add assert on truncation?338for (uint32_t i = 0; i < NumBytes; i++)339m_bytes[i] = static_cast<uint8_t>(v >> (i * 8));340return *this;341}342343inline packed_uint& operator= (const packed_uint& rhs)344{345memcpy(m_bytes, rhs.m_bytes, sizeof(m_bytes));346return *this;347}348349inline uint64_t get_uint64() const350{351// Some compilers may warn about this code. It clearly cannot access beyond the end of the m_bytes struct here.352if constexpr (NumBytes == 1)353{354return m_bytes[0];355}356else if constexpr (NumBytes == 2)357{358return (m_bytes[1] << 8U) | m_bytes[0];359}360else if constexpr (NumBytes == 3)361{362return (m_bytes[2] << 16U) | (m_bytes[1] << 8U) | m_bytes[0];363}364else if constexpr (NumBytes == 4)365{366return read_le_dword(m_bytes);367}368else if constexpr (NumBytes == 5)369{370uint32_t l = read_le_dword(m_bytes);371uint32_t h = m_bytes[4];372return static_cast<uint64_t>(l) | (static_cast<uint64_t>(h) << 32U);373}374else if constexpr (NumBytes == 6)375{376uint32_t l = read_le_dword(m_bytes);377uint32_t h = (m_bytes[5] << 8U) | m_bytes[4];378return static_cast<uint64_t>(l) | (static_cast<uint64_t>(h) << 32U);379}380else if constexpr (NumBytes == 7)381{382uint32_t l = read_le_dword(m_bytes);383uint32_t h = (m_bytes[6] << 16U) | (m_bytes[5] << 8U) | m_bytes[4];384return static_cast<uint64_t>(l) | (static_cast<uint64_t>(h) << 32U);385}386else if constexpr (NumBytes == 8)387{388uint32_t l = read_le_dword(m_bytes);389uint32_t h = read_le_dword(m_bytes + 4);390return static_cast<uint64_t>(l) | (static_cast<uint64_t>(h) << 32U);391}392else393{394static_assert(NumBytes <= 8, "Invalid NumBytes");395return 0;396}397}398399inline uint32_t get_uint32() const400{401static_assert(NumBytes <= sizeof(uint32_t), "packed_uint too large to use get_uint32");402return static_cast<uint32_t>(get_uint64());403}404405inline operator uint32_t() const406{407static_assert(NumBytes <= sizeof(uint32_t), "packed_uint too large to use operator uint32_t");408return static_cast<uint32_t>(get_uint64());409}410};411412enum eZero { cZero };413enum eNoClamp { cNoClamp };414415// Rice/Huffman entropy coding416417// This is basically Deflate-style canonical Huffman, except we allow for a lot more symbols.418enum419{420cHuffmanMaxSupportedCodeSize = 16, cHuffmanMaxSupportedInternalCodeSize = 31,421cHuffmanFastLookupBits = 10,422cHuffmanMaxSymsLog2 = 14, cHuffmanMaxSyms = 1 << cHuffmanMaxSymsLog2,423424// Small zero runs425cHuffmanSmallZeroRunSizeMin = 3, cHuffmanSmallZeroRunSizeMax = 10, cHuffmanSmallZeroRunExtraBits = 3,426427// Big zero run428cHuffmanBigZeroRunSizeMin = 11, cHuffmanBigZeroRunSizeMax = 138, cHuffmanBigZeroRunExtraBits = 7,429430// Small non-zero run431cHuffmanSmallRepeatSizeMin = 3, cHuffmanSmallRepeatSizeMax = 6, cHuffmanSmallRepeatExtraBits = 2,432433// Big non-zero run434cHuffmanBigRepeatSizeMin = 7, cHuffmanBigRepeatSizeMax = 134, cHuffmanBigRepeatExtraBits = 7,435436cHuffmanTotalCodelengthCodes = 21, cHuffmanSmallZeroRunCode = 17, cHuffmanBigZeroRunCode = 18, cHuffmanSmallRepeatCode = 19, cHuffmanBigRepeatCode = 20437};438439static 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 };440const uint32_t cHuffmanTotalSortedCodelengthCodes = sizeof(g_huffman_sorted_codelength_codes) / sizeof(g_huffman_sorted_codelength_codes[0]);441442// GPU texture formats and various uncompressed texture formats.443444enum class texture_format445{446cInvalidTextureFormat = -1,447448// Block-based formats449cETC1, // ETC1450cETC1S, // ETC1 (subset: diff colors only, no subblocks)451cETC2_RGB, // ETC2 color block (basisu doesn't support ETC2 planar/T/H modes - just basic ETC1)452cETC2_RGBA, // ETC2 EAC alpha block followed by ETC2 color block453cETC2_ALPHA, // ETC2 EAC alpha block454cBC1, // DXT1455cBC3, // DXT5 (BC4/DXT5A block followed by a BC1/DXT1 block)456cBC4, // DXT5A457cBC5, // 3DC/DXN (two BC4/DXT5A blocks)458cBC6HSigned, // HDR459cBC6HUnsigned, // HDR460cBC7,461cASTC_LDR_4x4, // ASTC 4x4 LDR only462cASTC_HDR_4x4, // ASTC 4x4 HDR only (but may use LDR ASTC blocks internally, although our encoders don't do this)463cASTC_HDR_6x6, // ASTC 6x6 HDR only (but may use LDR ASTC blocks internally, although our encoders don't do this)464cPVRTC1_4_RGB,465cPVRTC1_4_RGBA,466cATC_RGB,467cATC_RGBA_INTERPOLATED_ALPHA,468cFXT1_RGB,469cPVRTC2_4_RGBA,470cETC2_R11_EAC,471cETC2_RG11_EAC,472cUASTC4x4,473cUASTC_HDR_4x4,474cBC1_NV,475cBC1_AMD,476477// Uncompressed/raw pixels478cRGBA32,479cRGB565,480cBGR565,481cRGBA4444,482cABGR4444,483cRGBA_HALF,484cRGB_HALF,485cRGB_9E5486};487488inline bool is_uncompressed_texture_format(texture_format fmt)489{490switch (fmt)491{492case texture_format::cRGBA32:493case texture_format::cRGB565:494case texture_format::cBGR565:495case texture_format::cRGBA4444:496case texture_format::cABGR4444:497case texture_format::cRGBA_HALF:498case texture_format::cRGB_HALF:499case texture_format::cRGB_9E5:500return true;501default:502break;503}504505return false;506}507508inline bool is_block_based_texture_format(texture_format fmt)509{510return !is_uncompressed_texture_format(fmt);511}512513// This is bytes per block for GPU formats, or bytes per texel for uncompressed formats.514inline uint32_t get_bytes_per_block_or_pixel(texture_format fmt)515{516switch (fmt)517{518case texture_format::cETC1:519case texture_format::cETC1S:520case texture_format::cETC2_RGB:521case texture_format::cETC2_ALPHA:522case texture_format::cBC1:523case texture_format::cBC1_NV:524case texture_format::cBC1_AMD:525case texture_format::cBC4:526case texture_format::cPVRTC1_4_RGB:527case texture_format::cPVRTC1_4_RGBA:528case texture_format::cATC_RGB:529case texture_format::cPVRTC2_4_RGBA:530case texture_format::cETC2_R11_EAC:531return 8;532case texture_format::cRGBA32:533case texture_format::cRGB_9E5:534return sizeof(uint32_t);535case texture_format::cRGB_HALF:536return sizeof(uint16_t) * 3;537case texture_format::cRGBA_HALF:538return sizeof(uint16_t) * 4;539case texture_format::cRGB565:540case texture_format::cBGR565:541case texture_format::cRGBA4444:542case texture_format::cABGR4444:543return sizeof(uint16_t);544545default:546break;547}548549// Everything else is 16 bytes/block.550return 16;551}552553// This is qwords per block for GPU formats, or not valid for uncompressed formats.554inline uint32_t get_qwords_per_block(texture_format fmt)555{556assert(is_block_based_texture_format(fmt));557558const uint32_t bytes_per_block = get_bytes_per_block_or_pixel(fmt);559return bytes_per_block >> 3;560}561562inline uint32_t get_block_width(texture_format fmt)563{564assert(is_block_based_texture_format(fmt));565566switch (fmt)567{568case texture_format::cFXT1_RGB:569return 8;570case texture_format::cASTC_HDR_6x6:571return 6;572default:573break;574}575return 4;576}577578inline uint32_t get_block_height(texture_format fmt)579{580assert(is_block_based_texture_format(fmt));581582switch (fmt)583{584case texture_format::cASTC_HDR_6x6:585return 6;586default:587break;588}589return 4;590}591592inline bool is_hdr_texture_format(texture_format fmt)593{594switch (fmt)595{596case texture_format::cASTC_HDR_4x4:597case texture_format::cUASTC_HDR_4x4:598case texture_format::cASTC_HDR_6x6:599case texture_format::cBC6HSigned:600case texture_format::cBC6HUnsigned:601case texture_format::cRGBA_HALF:602case texture_format::cRGB_HALF:603case texture_format::cRGB_9E5:604return true;605default:606break;607}608609return false;610}611612inline bool is_ldr_texture_format(texture_format fmt)613{614return !is_hdr_texture_format(fmt);615}616617} // namespace basisu618619620621