astc.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707
  1. // Copyright 2016 The University of North Carolina at Chapel Hill
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // Please send all BUG REPORTS to <pavel@cs.unc.edu>.
  16. // <http://gamma.cs.unc.edu/FasTC/>
  17. #include <algorithm>
  18. #include <cassert>
  19. #include <cstring>
  20. #include <vector>
  21. #include <boost/container/static_vector.hpp>
  22. #include "common/common_types.h"
  23. #include "video_core/textures/astc.h"
  24. namespace {
  25. /// Count the number of bits set in a number.
  26. constexpr u32 Popcnt(u32 n) {
  27. u32 c = 0;
  28. for (; n; c++) {
  29. n &= n - 1;
  30. }
  31. return c;
  32. }
  33. } // Anonymous namespace
  34. class InputBitStream {
  35. public:
  36. constexpr explicit InputBitStream(const u8* ptr, std::size_t start_offset = 0)
  37. : cur_byte{ptr}, next_bit{start_offset % 8} {}
  38. constexpr std::size_t GetBitsRead() const {
  39. return bits_read;
  40. }
  41. constexpr bool ReadBit() {
  42. const bool bit = (*cur_byte >> next_bit++) & 1;
  43. while (next_bit >= 8) {
  44. next_bit -= 8;
  45. cur_byte++;
  46. }
  47. bits_read++;
  48. return bit;
  49. }
  50. constexpr u32 ReadBits(std::size_t nBits) {
  51. u32 ret = 0;
  52. for (std::size_t i = 0; i < nBits; ++i) {
  53. ret |= (ReadBit() & 1) << i;
  54. }
  55. return ret;
  56. }
  57. template <std::size_t nBits>
  58. constexpr u32 ReadBits() {
  59. u32 ret = 0;
  60. for (std::size_t i = 0; i < nBits; ++i) {
  61. ret |= (ReadBit() & 1) << i;
  62. }
  63. return ret;
  64. }
  65. private:
  66. const u8* cur_byte;
  67. std::size_t next_bit = 0;
  68. std::size_t bits_read = 0;
  69. };
  70. class OutputBitStream {
  71. public:
  72. constexpr explicit OutputBitStream(u8* ptr, std::size_t bits = 0, std::size_t start_offset = 0)
  73. : cur_byte{ptr}, num_bits{bits}, next_bit{start_offset % 8} {}
  74. constexpr std::size_t GetBitsWritten() const {
  75. return bits_written;
  76. }
  77. constexpr void WriteBitsR(u32 val, u32 nBits) {
  78. for (u32 i = 0; i < nBits; i++) {
  79. WriteBit((val >> (nBits - i - 1)) & 1);
  80. }
  81. }
  82. constexpr void WriteBits(u32 val, u32 nBits) {
  83. for (u32 i = 0; i < nBits; i++) {
  84. WriteBit((val >> i) & 1);
  85. }
  86. }
  87. private:
  88. constexpr void WriteBit(bool b) {
  89. if (bits_written >= num_bits) {
  90. return;
  91. }
  92. const u32 mask = 1 << next_bit++;
  93. // clear the bit
  94. *cur_byte &= static_cast<u8>(~mask);
  95. // Write the bit, if necessary
  96. if (b)
  97. *cur_byte |= static_cast<u8>(mask);
  98. // Next byte?
  99. if (next_bit >= 8) {
  100. cur_byte += 1;
  101. next_bit = 0;
  102. }
  103. }
  104. u8* cur_byte;
  105. std::size_t num_bits;
  106. std::size_t bits_written = 0;
  107. std::size_t next_bit = 0;
  108. };
  109. template <typename IntType>
  110. class Bits {
  111. public:
  112. explicit Bits(const IntType& v) : m_Bits(v) {}
  113. Bits(const Bits&) = delete;
  114. Bits& operator=(const Bits&) = delete;
  115. u8 operator[](u32 bitPos) const {
  116. return static_cast<u8>((m_Bits >> bitPos) & 1);
  117. }
  118. IntType operator()(u32 start, u32 end) const {
  119. if (start == end) {
  120. return (*this)[start];
  121. } else if (start > end) {
  122. u32 t = start;
  123. start = end;
  124. end = t;
  125. }
  126. u64 mask = (1 << (end - start + 1)) - 1;
  127. return (m_Bits >> start) & static_cast<IntType>(mask);
  128. }
  129. private:
  130. const IntType& m_Bits;
  131. };
  132. enum class IntegerEncoding { JustBits, Qus32, Trit };
  133. struct IntegerEncodedValue {
  134. constexpr IntegerEncodedValue() = default;
  135. constexpr IntegerEncodedValue(IntegerEncoding encoding_, u32 num_bits_)
  136. : encoding{encoding_}, num_bits{num_bits_} {}
  137. constexpr bool MatchesEncoding(const IntegerEncodedValue& other) const {
  138. return encoding == other.encoding && num_bits == other.num_bits;
  139. }
  140. // Returns the number of bits required to encode nVals values.
  141. u32 GetBitLength(u32 nVals) const {
  142. u32 totalBits = num_bits * nVals;
  143. if (encoding == IntegerEncoding::Trit) {
  144. totalBits += (nVals * 8 + 4) / 5;
  145. } else if (encoding == IntegerEncoding::Qus32) {
  146. totalBits += (nVals * 7 + 2) / 3;
  147. }
  148. return totalBits;
  149. }
  150. IntegerEncoding encoding{};
  151. u32 num_bits = 0;
  152. u32 bit_value = 0;
  153. union {
  154. u32 qus32_value = 0;
  155. u32 trit_value;
  156. };
  157. };
  158. using IntegerEncodedVector = boost::container::static_vector<
  159. IntegerEncodedValue, 64,
  160. boost::container::static_vector_options<
  161. boost::container::inplace_alignment<alignof(IntegerEncodedValue)>,
  162. boost::container::throw_on_overflow<false>>::type>;
  163. static void DecodeTritBlock(InputBitStream& bits, IntegerEncodedVector& result, u32 nBitsPerValue) {
  164. // Implement the algorithm in section C.2.12
  165. u32 m[5];
  166. u32 t[5];
  167. u32 T;
  168. // Read the trit encoded block according to
  169. // table C.2.14
  170. m[0] = bits.ReadBits(nBitsPerValue);
  171. T = bits.ReadBits<2>();
  172. m[1] = bits.ReadBits(nBitsPerValue);
  173. T |= bits.ReadBits<2>() << 2;
  174. m[2] = bits.ReadBits(nBitsPerValue);
  175. T |= bits.ReadBit() << 4;
  176. m[3] = bits.ReadBits(nBitsPerValue);
  177. T |= bits.ReadBits<2>() << 5;
  178. m[4] = bits.ReadBits(nBitsPerValue);
  179. T |= bits.ReadBit() << 7;
  180. u32 C = 0;
  181. Bits<u32> Tb(T);
  182. if (Tb(2, 4) == 7) {
  183. C = (Tb(5, 7) << 2) | Tb(0, 1);
  184. t[4] = t[3] = 2;
  185. } else {
  186. C = Tb(0, 4);
  187. if (Tb(5, 6) == 3) {
  188. t[4] = 2;
  189. t[3] = Tb[7];
  190. } else {
  191. t[4] = Tb[7];
  192. t[3] = Tb(5, 6);
  193. }
  194. }
  195. Bits<u32> Cb(C);
  196. if (Cb(0, 1) == 3) {
  197. t[2] = 2;
  198. t[1] = Cb[4];
  199. t[0] = (Cb[3] << 1) | (Cb[2] & ~Cb[3]);
  200. } else if (Cb(2, 3) == 3) {
  201. t[2] = 2;
  202. t[1] = 2;
  203. t[0] = Cb(0, 1);
  204. } else {
  205. t[2] = Cb[4];
  206. t[1] = Cb(2, 3);
  207. t[0] = (Cb[1] << 1) | (Cb[0] & ~Cb[1]);
  208. }
  209. for (std::size_t i = 0; i < 5; ++i) {
  210. IntegerEncodedValue& val = result.emplace_back(IntegerEncoding::Trit, nBitsPerValue);
  211. val.bit_value = m[i];
  212. val.trit_value = t[i];
  213. }
  214. }
  215. static void DecodeQus32Block(InputBitStream& bits, IntegerEncodedVector& result,
  216. u32 nBitsPerValue) {
  217. // Implement the algorithm in section C.2.12
  218. u32 m[3];
  219. u32 q[3];
  220. u32 Q;
  221. // Read the trit encoded block according to
  222. // table C.2.15
  223. m[0] = bits.ReadBits(nBitsPerValue);
  224. Q = bits.ReadBits<3>();
  225. m[1] = bits.ReadBits(nBitsPerValue);
  226. Q |= bits.ReadBits<2>() << 3;
  227. m[2] = bits.ReadBits(nBitsPerValue);
  228. Q |= bits.ReadBits<2>() << 5;
  229. Bits<u32> Qb(Q);
  230. if (Qb(1, 2) == 3 && Qb(5, 6) == 0) {
  231. q[0] = q[1] = 4;
  232. q[2] = (Qb[0] << 2) | ((Qb[4] & ~Qb[0]) << 1) | (Qb[3] & ~Qb[0]);
  233. } else {
  234. u32 C = 0;
  235. if (Qb(1, 2) == 3) {
  236. q[2] = 4;
  237. C = (Qb(3, 4) << 3) | ((~Qb(5, 6) & 3) << 1) | Qb[0];
  238. } else {
  239. q[2] = Qb(5, 6);
  240. C = Qb(0, 4);
  241. }
  242. Bits<u32> Cb(C);
  243. if (Cb(0, 2) == 5) {
  244. q[1] = 4;
  245. q[0] = Cb(3, 4);
  246. } else {
  247. q[1] = Cb(3, 4);
  248. q[0] = Cb(0, 2);
  249. }
  250. }
  251. for (std::size_t i = 0; i < 3; ++i) {
  252. IntegerEncodedValue& val = result.emplace_back(IntegerEncoding::Qus32, nBitsPerValue);
  253. val.bit_value = m[i];
  254. val.qus32_value = q[i];
  255. }
  256. }
  257. // Returns a new instance of this struct that corresponds to the
  258. // can take no more than maxval values
  259. static constexpr IntegerEncodedValue CreateEncoding(u32 maxVal) {
  260. while (maxVal > 0) {
  261. u32 check = maxVal + 1;
  262. // Is maxVal a power of two?
  263. if (!(check & (check - 1))) {
  264. return IntegerEncodedValue(IntegerEncoding::JustBits, Popcnt(maxVal));
  265. }
  266. // Is maxVal of the type 3*2^n - 1?
  267. if ((check % 3 == 0) && !((check / 3) & ((check / 3) - 1))) {
  268. return IntegerEncodedValue(IntegerEncoding::Trit, Popcnt(check / 3 - 1));
  269. }
  270. // Is maxVal of the type 5*2^n - 1?
  271. if ((check % 5 == 0) && !((check / 5) & ((check / 5) - 1))) {
  272. return IntegerEncodedValue(IntegerEncoding::Qus32, Popcnt(check / 5 - 1));
  273. }
  274. // Apparently it can't be represented with a bounded integer sequence...
  275. // just iterate.
  276. maxVal--;
  277. }
  278. return IntegerEncodedValue(IntegerEncoding::JustBits, 0);
  279. }
  280. static constexpr std::array<IntegerEncodedValue, 256> MakeEncodedValues() {
  281. std::array<IntegerEncodedValue, 256> encodings{};
  282. for (std::size_t i = 0; i < encodings.size(); ++i) {
  283. encodings[i] = CreateEncoding(static_cast<u32>(i));
  284. }
  285. return encodings;
  286. }
  287. static constexpr std::array EncodingsValues = MakeEncodedValues();
  288. // Fills result with the values that are encoded in the given
  289. // bitstream. We must know beforehand what the maximum possible
  290. // value is, and how many values we're decoding.
  291. static void DecodeIntegerSequence(IntegerEncodedVector& result, InputBitStream& bits, u32 maxRange,
  292. u32 nValues) {
  293. // Determine encoding parameters
  294. IntegerEncodedValue val = EncodingsValues[maxRange];
  295. // Start decoding
  296. u32 nValsDecoded = 0;
  297. while (nValsDecoded < nValues) {
  298. switch (val.encoding) {
  299. case IntegerEncoding::Qus32:
  300. DecodeQus32Block(bits, result, val.num_bits);
  301. nValsDecoded += 3;
  302. break;
  303. case IntegerEncoding::Trit:
  304. DecodeTritBlock(bits, result, val.num_bits);
  305. nValsDecoded += 5;
  306. break;
  307. case IntegerEncoding::JustBits:
  308. val.bit_value = bits.ReadBits(val.num_bits);
  309. result.push_back(val);
  310. nValsDecoded++;
  311. break;
  312. }
  313. }
  314. }
  315. namespace ASTCC {
  316. struct TexelWeightParams {
  317. u32 m_Width = 0;
  318. u32 m_Height = 0;
  319. bool m_bDualPlane = false;
  320. u32 m_MaxWeight = 0;
  321. bool m_bError = false;
  322. bool m_bVoidExtentLDR = false;
  323. bool m_bVoidExtentHDR = false;
  324. u32 GetPackedBitSize() const {
  325. // How many indices do we have?
  326. u32 nIdxs = m_Height * m_Width;
  327. if (m_bDualPlane) {
  328. nIdxs *= 2;
  329. }
  330. return EncodingsValues[m_MaxWeight].GetBitLength(nIdxs);
  331. }
  332. u32 GetNumWeightValues() const {
  333. u32 ret = m_Width * m_Height;
  334. if (m_bDualPlane) {
  335. ret *= 2;
  336. }
  337. return ret;
  338. }
  339. };
  340. static TexelWeightParams DecodeBlockInfo(InputBitStream& strm) {
  341. TexelWeightParams params;
  342. // Read the entire block mode all at once
  343. u16 modeBits = static_cast<u16>(strm.ReadBits<11>());
  344. // Does this match the void extent block mode?
  345. if ((modeBits & 0x01FF) == 0x1FC) {
  346. if (modeBits & 0x200) {
  347. params.m_bVoidExtentHDR = true;
  348. } else {
  349. params.m_bVoidExtentLDR = true;
  350. }
  351. // Next two bits must be one.
  352. if (!(modeBits & 0x400) || !strm.ReadBit()) {
  353. params.m_bError = true;
  354. }
  355. return params;
  356. }
  357. // First check if the last four bits are zero
  358. if ((modeBits & 0xF) == 0) {
  359. params.m_bError = true;
  360. return params;
  361. }
  362. // If the last two bits are zero, then if bits
  363. // [6-8] are all ones, this is also reserved.
  364. if ((modeBits & 0x3) == 0 && (modeBits & 0x1C0) == 0x1C0) {
  365. params.m_bError = true;
  366. return params;
  367. }
  368. // Otherwise, there is no error... Figure out the layout
  369. // of the block mode. Layout is determined by a number
  370. // between 0 and 9 corresponding to table C.2.8 of the
  371. // ASTC spec.
  372. u32 layout = 0;
  373. if ((modeBits & 0x1) || (modeBits & 0x2)) {
  374. // layout is in [0-4]
  375. if (modeBits & 0x8) {
  376. // layout is in [2-4]
  377. if (modeBits & 0x4) {
  378. // layout is in [3-4]
  379. if (modeBits & 0x100) {
  380. layout = 4;
  381. } else {
  382. layout = 3;
  383. }
  384. } else {
  385. layout = 2;
  386. }
  387. } else {
  388. // layout is in [0-1]
  389. if (modeBits & 0x4) {
  390. layout = 1;
  391. } else {
  392. layout = 0;
  393. }
  394. }
  395. } else {
  396. // layout is in [5-9]
  397. if (modeBits & 0x100) {
  398. // layout is in [7-9]
  399. if (modeBits & 0x80) {
  400. // layout is in [7-8]
  401. assert((modeBits & 0x40) == 0U);
  402. if (modeBits & 0x20) {
  403. layout = 8;
  404. } else {
  405. layout = 7;
  406. }
  407. } else {
  408. layout = 9;
  409. }
  410. } else {
  411. // layout is in [5-6]
  412. if (modeBits & 0x80) {
  413. layout = 6;
  414. } else {
  415. layout = 5;
  416. }
  417. }
  418. }
  419. assert(layout < 10);
  420. // Determine R
  421. u32 R = !!(modeBits & 0x10);
  422. if (layout < 5) {
  423. R |= (modeBits & 0x3) << 1;
  424. } else {
  425. R |= (modeBits & 0xC) >> 1;
  426. }
  427. assert(2 <= R && R <= 7);
  428. // Determine width & height
  429. switch (layout) {
  430. case 0: {
  431. u32 A = (modeBits >> 5) & 0x3;
  432. u32 B = (modeBits >> 7) & 0x3;
  433. params.m_Width = B + 4;
  434. params.m_Height = A + 2;
  435. break;
  436. }
  437. case 1: {
  438. u32 A = (modeBits >> 5) & 0x3;
  439. u32 B = (modeBits >> 7) & 0x3;
  440. params.m_Width = B + 8;
  441. params.m_Height = A + 2;
  442. break;
  443. }
  444. case 2: {
  445. u32 A = (modeBits >> 5) & 0x3;
  446. u32 B = (modeBits >> 7) & 0x3;
  447. params.m_Width = A + 2;
  448. params.m_Height = B + 8;
  449. break;
  450. }
  451. case 3: {
  452. u32 A = (modeBits >> 5) & 0x3;
  453. u32 B = (modeBits >> 7) & 0x1;
  454. params.m_Width = A + 2;
  455. params.m_Height = B + 6;
  456. break;
  457. }
  458. case 4: {
  459. u32 A = (modeBits >> 5) & 0x3;
  460. u32 B = (modeBits >> 7) & 0x1;
  461. params.m_Width = B + 2;
  462. params.m_Height = A + 2;
  463. break;
  464. }
  465. case 5: {
  466. u32 A = (modeBits >> 5) & 0x3;
  467. params.m_Width = 12;
  468. params.m_Height = A + 2;
  469. break;
  470. }
  471. case 6: {
  472. u32 A = (modeBits >> 5) & 0x3;
  473. params.m_Width = A + 2;
  474. params.m_Height = 12;
  475. break;
  476. }
  477. case 7: {
  478. params.m_Width = 6;
  479. params.m_Height = 10;
  480. break;
  481. }
  482. case 8: {
  483. params.m_Width = 10;
  484. params.m_Height = 6;
  485. break;
  486. }
  487. case 9: {
  488. u32 A = (modeBits >> 5) & 0x3;
  489. u32 B = (modeBits >> 9) & 0x3;
  490. params.m_Width = A + 6;
  491. params.m_Height = B + 6;
  492. break;
  493. }
  494. default:
  495. assert(false && "Don't know this layout...");
  496. params.m_bError = true;
  497. break;
  498. }
  499. // Determine whether or not we're using dual planes
  500. // and/or high precision layouts.
  501. bool D = (layout != 9) && (modeBits & 0x400);
  502. bool H = (layout != 9) && (modeBits & 0x200);
  503. if (H) {
  504. const u32 maxWeights[6] = {9, 11, 15, 19, 23, 31};
  505. params.m_MaxWeight = maxWeights[R - 2];
  506. } else {
  507. const u32 maxWeights[6] = {1, 2, 3, 4, 5, 7};
  508. params.m_MaxWeight = maxWeights[R - 2];
  509. }
  510. params.m_bDualPlane = D;
  511. return params;
  512. }
  513. static void FillVoidExtentLDR(InputBitStream& strm, u32* const outBuf, u32 blockWidth,
  514. u32 blockHeight) {
  515. // Don't actually care about the void extent, just read the bits...
  516. for (s32 i = 0; i < 4; ++i) {
  517. strm.ReadBits<13>();
  518. }
  519. // Decode the RGBA components and renormalize them to the range [0, 255]
  520. u16 r = static_cast<u16>(strm.ReadBits<16>());
  521. u16 g = static_cast<u16>(strm.ReadBits<16>());
  522. u16 b = static_cast<u16>(strm.ReadBits<16>());
  523. u16 a = static_cast<u16>(strm.ReadBits<16>());
  524. u32 rgba = (r >> 8) | (g & 0xFF00) | (static_cast<u32>(b) & 0xFF00) << 8 |
  525. (static_cast<u32>(a) & 0xFF00) << 16;
  526. for (u32 j = 0; j < blockHeight; j++) {
  527. for (u32 i = 0; i < blockWidth; i++) {
  528. outBuf[j * blockWidth + i] = rgba;
  529. }
  530. }
  531. }
  532. static void FillError(u32* outBuf, u32 blockWidth, u32 blockHeight) {
  533. for (u32 j = 0; j < blockHeight; j++) {
  534. for (u32 i = 0; i < blockWidth; i++) {
  535. outBuf[j * blockWidth + i] = 0xFFFF00FF;
  536. }
  537. }
  538. }
  539. // Replicates low numBits such that [(toBit - 1):(toBit - 1 - fromBit)]
  540. // is the same as [(numBits - 1):0] and repeats all the way down.
  541. template <typename IntType>
  542. static constexpr IntType Replicate(IntType val, u32 numBits, u32 toBit) {
  543. if (numBits == 0) {
  544. return 0;
  545. }
  546. if (toBit == 0) {
  547. return 0;
  548. }
  549. const IntType v = val & static_cast<IntType>((1 << numBits) - 1);
  550. IntType res = v;
  551. u32 reslen = numBits;
  552. while (reslen < toBit) {
  553. u32 comp = 0;
  554. if (numBits > toBit - reslen) {
  555. u32 newshift = toBit - reslen;
  556. comp = numBits - newshift;
  557. numBits = newshift;
  558. }
  559. res = static_cast<IntType>(res << numBits);
  560. res = static_cast<IntType>(res | (v >> comp));
  561. reslen += numBits;
  562. }
  563. return res;
  564. }
  565. static constexpr std::size_t NumReplicateEntries(u32 num_bits) {
  566. return std::size_t(1) << num_bits;
  567. }
  568. template <typename IntType, u32 num_bits, u32 to_bit>
  569. static constexpr auto MakeReplicateTable() {
  570. std::array<IntType, NumReplicateEntries(num_bits)> table{};
  571. for (IntType value = 0; value < static_cast<IntType>(std::size(table)); ++value) {
  572. table[value] = Replicate(value, num_bits, to_bit);
  573. }
  574. return table;
  575. }
  576. static constexpr auto REPLICATE_BYTE_TO_16_TABLE = MakeReplicateTable<u32, 8, 16>();
  577. static constexpr u32 ReplicateByteTo16(std::size_t value) {
  578. return REPLICATE_BYTE_TO_16_TABLE[value];
  579. }
  580. static constexpr auto REPLICATE_BIT_TO_7_TABLE = MakeReplicateTable<u32, 1, 7>();
  581. static constexpr u32 ReplicateBitTo7(std::size_t value) {
  582. return REPLICATE_BIT_TO_7_TABLE[value];
  583. }
  584. static constexpr auto REPLICATE_BIT_TO_9_TABLE = MakeReplicateTable<u32, 1, 9>();
  585. static constexpr u32 ReplicateBitTo9(std::size_t value) {
  586. return REPLICATE_BIT_TO_9_TABLE[value];
  587. }
  588. static constexpr auto REPLICATE_1_BIT_TO_8_TABLE = MakeReplicateTable<u32, 1, 8>();
  589. static constexpr auto REPLICATE_2_BIT_TO_8_TABLE = MakeReplicateTable<u32, 2, 8>();
  590. static constexpr auto REPLICATE_3_BIT_TO_8_TABLE = MakeReplicateTable<u32, 3, 8>();
  591. static constexpr auto REPLICATE_4_BIT_TO_8_TABLE = MakeReplicateTable<u32, 4, 8>();
  592. static constexpr auto REPLICATE_5_BIT_TO_8_TABLE = MakeReplicateTable<u32, 5, 8>();
  593. static constexpr auto REPLICATE_6_BIT_TO_8_TABLE = MakeReplicateTable<u32, 6, 8>();
  594. static constexpr auto REPLICATE_7_BIT_TO_8_TABLE = MakeReplicateTable<u32, 7, 8>();
  595. static constexpr auto REPLICATE_8_BIT_TO_8_TABLE = MakeReplicateTable<u32, 8, 8>();
  596. /// Use a precompiled table with the most common usages, if it's not in the expected range, fallback
  597. /// to the runtime implementation
  598. static constexpr u32 FastReplicateTo8(u32 value, u32 num_bits) {
  599. switch (num_bits) {
  600. case 1:
  601. return REPLICATE_1_BIT_TO_8_TABLE[value];
  602. case 2:
  603. return REPLICATE_2_BIT_TO_8_TABLE[value];
  604. case 3:
  605. return REPLICATE_3_BIT_TO_8_TABLE[value];
  606. case 4:
  607. return REPLICATE_4_BIT_TO_8_TABLE[value];
  608. case 5:
  609. return REPLICATE_5_BIT_TO_8_TABLE[value];
  610. case 6:
  611. return REPLICATE_6_BIT_TO_8_TABLE[value];
  612. case 7:
  613. return REPLICATE_7_BIT_TO_8_TABLE[value];
  614. case 8:
  615. return REPLICATE_8_BIT_TO_8_TABLE[value];
  616. default:
  617. return Replicate(value, num_bits, 8);
  618. }
  619. }
  620. static constexpr auto REPLICATE_1_BIT_TO_6_TABLE = MakeReplicateTable<u32, 1, 6>();
  621. static constexpr auto REPLICATE_2_BIT_TO_6_TABLE = MakeReplicateTable<u32, 2, 6>();
  622. static constexpr auto REPLICATE_3_BIT_TO_6_TABLE = MakeReplicateTable<u32, 3, 6>();
  623. static constexpr auto REPLICATE_4_BIT_TO_6_TABLE = MakeReplicateTable<u32, 4, 6>();
  624. static constexpr auto REPLICATE_5_BIT_TO_6_TABLE = MakeReplicateTable<u32, 5, 6>();
  625. static constexpr u32 FastReplicateTo6(u32 value, u32 num_bits) {
  626. switch (num_bits) {
  627. case 1:
  628. return REPLICATE_1_BIT_TO_6_TABLE[value];
  629. case 2:
  630. return REPLICATE_2_BIT_TO_6_TABLE[value];
  631. case 3:
  632. return REPLICATE_3_BIT_TO_6_TABLE[value];
  633. case 4:
  634. return REPLICATE_4_BIT_TO_6_TABLE[value];
  635. case 5:
  636. return REPLICATE_5_BIT_TO_6_TABLE[value];
  637. default:
  638. return Replicate(value, num_bits, 6);
  639. }
  640. }
  641. class Pixel {
  642. protected:
  643. using ChannelType = s16;
  644. u8 m_BitDepth[4] = {8, 8, 8, 8};
  645. s16 color[4] = {};
  646. public:
  647. Pixel() = default;
  648. Pixel(u32 a, u32 r, u32 g, u32 b, u32 bitDepth = 8)
  649. : m_BitDepth{u8(bitDepth), u8(bitDepth), u8(bitDepth), u8(bitDepth)},
  650. color{static_cast<ChannelType>(a), static_cast<ChannelType>(r),
  651. static_cast<ChannelType>(g), static_cast<ChannelType>(b)} {}
  652. // Changes the depth of each pixel. This scales the values to
  653. // the appropriate bit depth by either truncating the least
  654. // significant bits when going from larger to smaller bit depth
  655. // or by repeating the most significant bits when going from
  656. // smaller to larger bit depths.
  657. void ChangeBitDepth() {
  658. for (u32 i = 0; i < 4; i++) {
  659. Component(i) = ChangeBitDepth(Component(i), m_BitDepth[i]);
  660. m_BitDepth[i] = 8;
  661. }
  662. }
  663. template <typename IntType>
  664. static float ConvertChannelToFloat(IntType channel, u8 bitDepth) {
  665. float denominator = static_cast<float>((1 << bitDepth) - 1);
  666. return static_cast<float>(channel) / denominator;
  667. }
  668. // Changes the bit depth of a single component. See the comment
  669. // above for how we do this.
  670. static ChannelType ChangeBitDepth(Pixel::ChannelType val, u8 oldDepth) {
  671. assert(oldDepth <= 8);
  672. if (oldDepth == 8) {
  673. // Do nothing
  674. return val;
  675. } else if (oldDepth == 0) {
  676. return static_cast<ChannelType>((1 << 8) - 1);
  677. } else if (8 > oldDepth) {
  678. return static_cast<ChannelType>(FastReplicateTo8(static_cast<u32>(val), oldDepth));
  679. } else {
  680. // oldDepth > newDepth
  681. const u8 bitsWasted = static_cast<u8>(oldDepth - 8);
  682. u16 v = static_cast<u16>(val);
  683. v = static_cast<u16>((v + (1 << (bitsWasted - 1))) >> bitsWasted);
  684. v = ::std::min<u16>(::std::max<u16>(0, v), static_cast<u16>((1 << 8) - 1));
  685. return static_cast<u8>(v);
  686. }
  687. assert(false && "We shouldn't get here.");
  688. return 0;
  689. }
  690. const ChannelType& A() const {
  691. return color[0];
  692. }
  693. ChannelType& A() {
  694. return color[0];
  695. }
  696. const ChannelType& R() const {
  697. return color[1];
  698. }
  699. ChannelType& R() {
  700. return color[1];
  701. }
  702. const ChannelType& G() const {
  703. return color[2];
  704. }
  705. ChannelType& G() {
  706. return color[2];
  707. }
  708. const ChannelType& B() const {
  709. return color[3];
  710. }
  711. ChannelType& B() {
  712. return color[3];
  713. }
  714. const ChannelType& Component(u32 idx) const {
  715. return color[idx];
  716. }
  717. ChannelType& Component(u32 idx) {
  718. return color[idx];
  719. }
  720. void GetBitDepth(u8 (&outDepth)[4]) const {
  721. for (s32 i = 0; i < 4; i++) {
  722. outDepth[i] = m_BitDepth[i];
  723. }
  724. }
  725. // Take all of the components, transform them to their 8-bit variants,
  726. // and then pack each channel into an R8G8B8A8 32-bit integer. We assume
  727. // that the architecture is little-endian, so the alpha channel will end
  728. // up in the most-significant byte.
  729. u32 Pack() const {
  730. Pixel eightBit(*this);
  731. eightBit.ChangeBitDepth();
  732. u32 r = 0;
  733. r |= eightBit.A();
  734. r <<= 8;
  735. r |= eightBit.B();
  736. r <<= 8;
  737. r |= eightBit.G();
  738. r <<= 8;
  739. r |= eightBit.R();
  740. return r;
  741. }
  742. // Clamps the pixel to the range [0,255]
  743. void ClampByte() {
  744. for (u32 i = 0; i < 4; i++) {
  745. color[i] = (color[i] < 0) ? 0 : ((color[i] > 255) ? 255 : color[i]);
  746. }
  747. }
  748. void MakeOpaque() {
  749. A() = 255;
  750. }
  751. };
  752. static void DecodeColorValues(u32* out, u8* data, const u32* modes, const u32 nPartitions,
  753. const u32 nBitsForColorData) {
  754. // First figure out how many color values we have
  755. u32 nValues = 0;
  756. for (u32 i = 0; i < nPartitions; i++) {
  757. nValues += ((modes[i] >> 2) + 1) << 1;
  758. }
  759. // Then based on the number of values and the remaining number of bits,
  760. // figure out the max value for each of them...
  761. u32 range = 256;
  762. while (--range > 0) {
  763. IntegerEncodedValue val = EncodingsValues[range];
  764. u32 bitLength = val.GetBitLength(nValues);
  765. if (bitLength <= nBitsForColorData) {
  766. // Find the smallest possible range that matches the given encoding
  767. while (--range > 0) {
  768. IntegerEncodedValue newval = EncodingsValues[range];
  769. if (!newval.MatchesEncoding(val)) {
  770. break;
  771. }
  772. }
  773. // Return to last matching range.
  774. range++;
  775. break;
  776. }
  777. }
  778. // We now have enough to decode our integer sequence.
  779. IntegerEncodedVector decodedColorValues;
  780. InputBitStream colorStream(data);
  781. DecodeIntegerSequence(decodedColorValues, colorStream, range, nValues);
  782. // Once we have the decoded values, we need to dequantize them to the 0-255 range
  783. // This procedure is outlined in ASTC spec C.2.13
  784. u32 outIdx = 0;
  785. for (auto itr = decodedColorValues.begin(); itr != decodedColorValues.end(); ++itr) {
  786. // Have we already decoded all that we need?
  787. if (outIdx >= nValues) {
  788. break;
  789. }
  790. const IntegerEncodedValue& val = *itr;
  791. u32 bitlen = val.num_bits;
  792. u32 bitval = val.bit_value;
  793. assert(bitlen >= 1);
  794. u32 A = 0, B = 0, C = 0, D = 0;
  795. // A is just the lsb replicated 9 times.
  796. A = ReplicateBitTo9(bitval & 1);
  797. switch (val.encoding) {
  798. // Replicate bits
  799. case IntegerEncoding::JustBits:
  800. out[outIdx++] = FastReplicateTo8(bitval, bitlen);
  801. break;
  802. // Use algorithm in C.2.13
  803. case IntegerEncoding::Trit: {
  804. D = val.trit_value;
  805. switch (bitlen) {
  806. case 1: {
  807. C = 204;
  808. } break;
  809. case 2: {
  810. C = 93;
  811. // B = b000b0bb0
  812. u32 b = (bitval >> 1) & 1;
  813. B = (b << 8) | (b << 4) | (b << 2) | (b << 1);
  814. } break;
  815. case 3: {
  816. C = 44;
  817. // B = cb000cbcb
  818. u32 cb = (bitval >> 1) & 3;
  819. B = (cb << 7) | (cb << 2) | cb;
  820. } break;
  821. case 4: {
  822. C = 22;
  823. // B = dcb000dcb
  824. u32 dcb = (bitval >> 1) & 7;
  825. B = (dcb << 6) | dcb;
  826. } break;
  827. case 5: {
  828. C = 11;
  829. // B = edcb000ed
  830. u32 edcb = (bitval >> 1) & 0xF;
  831. B = (edcb << 5) | (edcb >> 2);
  832. } break;
  833. case 6: {
  834. C = 5;
  835. // B = fedcb000f
  836. u32 fedcb = (bitval >> 1) & 0x1F;
  837. B = (fedcb << 4) | (fedcb >> 4);
  838. } break;
  839. default:
  840. assert(false && "Unsupported trit encoding for color values!");
  841. break;
  842. } // switch(bitlen)
  843. } // case IntegerEncoding::Trit
  844. break;
  845. case IntegerEncoding::Qus32: {
  846. D = val.qus32_value;
  847. switch (bitlen) {
  848. case 1: {
  849. C = 113;
  850. } break;
  851. case 2: {
  852. C = 54;
  853. // B = b0000bb00
  854. u32 b = (bitval >> 1) & 1;
  855. B = (b << 8) | (b << 3) | (b << 2);
  856. } break;
  857. case 3: {
  858. C = 26;
  859. // B = cb0000cbc
  860. u32 cb = (bitval >> 1) & 3;
  861. B = (cb << 7) | (cb << 1) | (cb >> 1);
  862. } break;
  863. case 4: {
  864. C = 13;
  865. // B = dcb0000dc
  866. u32 dcb = (bitval >> 1) & 7;
  867. B = (dcb << 6) | (dcb >> 1);
  868. } break;
  869. case 5: {
  870. C = 6;
  871. // B = edcb0000e
  872. u32 edcb = (bitval >> 1) & 0xF;
  873. B = (edcb << 5) | (edcb >> 3);
  874. } break;
  875. default:
  876. assert(false && "Unsupported quint encoding for color values!");
  877. break;
  878. } // switch(bitlen)
  879. } // case IntegerEncoding::Qus32
  880. break;
  881. } // switch(val.encoding)
  882. if (val.encoding != IntegerEncoding::JustBits) {
  883. u32 T = D * C + B;
  884. T ^= A;
  885. T = (A & 0x80) | (T >> 2);
  886. out[outIdx++] = T;
  887. }
  888. }
  889. // Make sure that each of our values is in the proper range...
  890. for (u32 i = 0; i < nValues; i++) {
  891. assert(out[i] <= 255);
  892. }
  893. }
  894. static u32 UnquantizeTexelWeight(const IntegerEncodedValue& val) {
  895. u32 bitval = val.bit_value;
  896. u32 bitlen = val.num_bits;
  897. u32 A = ReplicateBitTo7(bitval & 1);
  898. u32 B = 0, C = 0, D = 0;
  899. u32 result = 0;
  900. switch (val.encoding) {
  901. case IntegerEncoding::JustBits:
  902. result = FastReplicateTo6(bitval, bitlen);
  903. break;
  904. case IntegerEncoding::Trit: {
  905. D = val.trit_value;
  906. assert(D < 3);
  907. switch (bitlen) {
  908. case 0: {
  909. u32 results[3] = {0, 32, 63};
  910. result = results[D];
  911. } break;
  912. case 1: {
  913. C = 50;
  914. } break;
  915. case 2: {
  916. C = 23;
  917. u32 b = (bitval >> 1) & 1;
  918. B = (b << 6) | (b << 2) | b;
  919. } break;
  920. case 3: {
  921. C = 11;
  922. u32 cb = (bitval >> 1) & 3;
  923. B = (cb << 5) | cb;
  924. } break;
  925. default:
  926. assert(false && "Invalid trit encoding for texel weight");
  927. break;
  928. }
  929. } break;
  930. case IntegerEncoding::Qus32: {
  931. D = val.qus32_value;
  932. assert(D < 5);
  933. switch (bitlen) {
  934. case 0: {
  935. u32 results[5] = {0, 16, 32, 47, 63};
  936. result = results[D];
  937. } break;
  938. case 1: {
  939. C = 28;
  940. } break;
  941. case 2: {
  942. C = 13;
  943. u32 b = (bitval >> 1) & 1;
  944. B = (b << 6) | (b << 1);
  945. } break;
  946. default:
  947. assert(false && "Invalid quint encoding for texel weight");
  948. break;
  949. }
  950. } break;
  951. }
  952. if (val.encoding != IntegerEncoding::JustBits && bitlen > 0) {
  953. // Decode the value...
  954. result = D * C + B;
  955. result ^= A;
  956. result = (A & 0x20) | (result >> 2);
  957. }
  958. assert(result < 64);
  959. // Change from [0,63] to [0,64]
  960. if (result > 32) {
  961. result += 1;
  962. }
  963. return result;
  964. }
  965. static void UnquantizeTexelWeights(u32 out[2][144], const IntegerEncodedVector& weights,
  966. const TexelWeightParams& params, const u32 blockWidth,
  967. const u32 blockHeight) {
  968. u32 weightIdx = 0;
  969. u32 unquantized[2][144];
  970. for (auto itr = weights.begin(); itr != weights.end(); ++itr) {
  971. unquantized[0][weightIdx] = UnquantizeTexelWeight(*itr);
  972. if (params.m_bDualPlane) {
  973. ++itr;
  974. unquantized[1][weightIdx] = UnquantizeTexelWeight(*itr);
  975. if (itr == weights.end()) {
  976. break;
  977. }
  978. }
  979. if (++weightIdx >= (params.m_Width * params.m_Height))
  980. break;
  981. }
  982. // Do infill if necessary (Section C.2.18) ...
  983. u32 Ds = (1024 + (blockWidth / 2)) / (blockWidth - 1);
  984. u32 Dt = (1024 + (blockHeight / 2)) / (blockHeight - 1);
  985. const u32 kPlaneScale = params.m_bDualPlane ? 2U : 1U;
  986. for (u32 plane = 0; plane < kPlaneScale; plane++)
  987. for (u32 t = 0; t < blockHeight; t++)
  988. for (u32 s = 0; s < blockWidth; s++) {
  989. u32 cs = Ds * s;
  990. u32 ct = Dt * t;
  991. u32 gs = (cs * (params.m_Width - 1) + 32) >> 6;
  992. u32 gt = (ct * (params.m_Height - 1) + 32) >> 6;
  993. u32 js = gs >> 4;
  994. u32 fs = gs & 0xF;
  995. u32 jt = gt >> 4;
  996. u32 ft = gt & 0x0F;
  997. u32 w11 = (fs * ft + 8) >> 4;
  998. u32 w10 = ft - w11;
  999. u32 w01 = fs - w11;
  1000. u32 w00 = 16 - fs - ft + w11;
  1001. u32 v0 = js + jt * params.m_Width;
  1002. #define FIND_TEXEL(tidx, bidx) \
  1003. u32 p##bidx = 0; \
  1004. do { \
  1005. if ((tidx) < (params.m_Width * params.m_Height)) { \
  1006. p##bidx = unquantized[plane][(tidx)]; \
  1007. } \
  1008. } while (0)
  1009. FIND_TEXEL(v0, 00);
  1010. FIND_TEXEL(v0 + 1, 01);
  1011. FIND_TEXEL(v0 + params.m_Width, 10);
  1012. FIND_TEXEL(v0 + params.m_Width + 1, 11);
  1013. #undef FIND_TEXEL
  1014. out[plane][t * blockWidth + s] =
  1015. (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4;
  1016. }
  1017. }
  1018. // Transfers a bit as described in C.2.14
  1019. static inline void BitTransferSigned(s32& a, s32& b) {
  1020. b >>= 1;
  1021. b |= a & 0x80;
  1022. a >>= 1;
  1023. a &= 0x3F;
  1024. if (a & 0x20)
  1025. a -= 0x40;
  1026. }
  1027. // Adds more precision to the blue channel as described
  1028. // in C.2.14
  1029. static inline Pixel BlueContract(s32 a, s32 r, s32 g, s32 b) {
  1030. return Pixel(static_cast<s16>(a), static_cast<s16>((r + b) >> 1),
  1031. static_cast<s16>((g + b) >> 1), static_cast<s16>(b));
  1032. }
  1033. // Partition selection functions as specified in
  1034. // C.2.21
  1035. static inline u32 hash52(u32 p) {
  1036. p ^= p >> 15;
  1037. p -= p << 17;
  1038. p += p << 7;
  1039. p += p << 4;
  1040. p ^= p >> 5;
  1041. p += p << 16;
  1042. p ^= p >> 7;
  1043. p ^= p >> 3;
  1044. p ^= p << 6;
  1045. p ^= p >> 17;
  1046. return p;
  1047. }
  1048. static u32 SelectPartition(s32 seed, s32 x, s32 y, s32 z, s32 partitionCount, s32 smallBlock) {
  1049. if (1 == partitionCount)
  1050. return 0;
  1051. if (smallBlock) {
  1052. x <<= 1;
  1053. y <<= 1;
  1054. z <<= 1;
  1055. }
  1056. seed += (partitionCount - 1) * 1024;
  1057. u32 rnum = hash52(static_cast<u32>(seed));
  1058. u8 seed1 = static_cast<u8>(rnum & 0xF);
  1059. u8 seed2 = static_cast<u8>((rnum >> 4) & 0xF);
  1060. u8 seed3 = static_cast<u8>((rnum >> 8) & 0xF);
  1061. u8 seed4 = static_cast<u8>((rnum >> 12) & 0xF);
  1062. u8 seed5 = static_cast<u8>((rnum >> 16) & 0xF);
  1063. u8 seed6 = static_cast<u8>((rnum >> 20) & 0xF);
  1064. u8 seed7 = static_cast<u8>((rnum >> 24) & 0xF);
  1065. u8 seed8 = static_cast<u8>((rnum >> 28) & 0xF);
  1066. u8 seed9 = static_cast<u8>((rnum >> 18) & 0xF);
  1067. u8 seed10 = static_cast<u8>((rnum >> 22) & 0xF);
  1068. u8 seed11 = static_cast<u8>((rnum >> 26) & 0xF);
  1069. u8 seed12 = static_cast<u8>(((rnum >> 30) | (rnum << 2)) & 0xF);
  1070. seed1 = static_cast<u8>(seed1 * seed1);
  1071. seed2 = static_cast<u8>(seed2 * seed2);
  1072. seed3 = static_cast<u8>(seed3 * seed3);
  1073. seed4 = static_cast<u8>(seed4 * seed4);
  1074. seed5 = static_cast<u8>(seed5 * seed5);
  1075. seed6 = static_cast<u8>(seed6 * seed6);
  1076. seed7 = static_cast<u8>(seed7 * seed7);
  1077. seed8 = static_cast<u8>(seed8 * seed8);
  1078. seed9 = static_cast<u8>(seed9 * seed9);
  1079. seed10 = static_cast<u8>(seed10 * seed10);
  1080. seed11 = static_cast<u8>(seed11 * seed11);
  1081. seed12 = static_cast<u8>(seed12 * seed12);
  1082. s32 sh1, sh2, sh3;
  1083. if (seed & 1) {
  1084. sh1 = (seed & 2) ? 4 : 5;
  1085. sh2 = (partitionCount == 3) ? 6 : 5;
  1086. } else {
  1087. sh1 = (partitionCount == 3) ? 6 : 5;
  1088. sh2 = (seed & 2) ? 4 : 5;
  1089. }
  1090. sh3 = (seed & 0x10) ? sh1 : sh2;
  1091. seed1 = static_cast<u8>(seed1 >> sh1);
  1092. seed2 = static_cast<u8>(seed2 >> sh2);
  1093. seed3 = static_cast<u8>(seed3 >> sh1);
  1094. seed4 = static_cast<u8>(seed4 >> sh2);
  1095. seed5 = static_cast<u8>(seed5 >> sh1);
  1096. seed6 = static_cast<u8>(seed6 >> sh2);
  1097. seed7 = static_cast<u8>(seed7 >> sh1);
  1098. seed8 = static_cast<u8>(seed8 >> sh2);
  1099. seed9 = static_cast<u8>(seed9 >> sh3);
  1100. seed10 = static_cast<u8>(seed10 >> sh3);
  1101. seed11 = static_cast<u8>(seed11 >> sh3);
  1102. seed12 = static_cast<u8>(seed12 >> sh3);
  1103. s32 a = seed1 * x + seed2 * y + seed11 * z + (rnum >> 14);
  1104. s32 b = seed3 * x + seed4 * y + seed12 * z + (rnum >> 10);
  1105. s32 c = seed5 * x + seed6 * y + seed9 * z + (rnum >> 6);
  1106. s32 d = seed7 * x + seed8 * y + seed10 * z + (rnum >> 2);
  1107. a &= 0x3F;
  1108. b &= 0x3F;
  1109. c &= 0x3F;
  1110. d &= 0x3F;
  1111. if (partitionCount < 4)
  1112. d = 0;
  1113. if (partitionCount < 3)
  1114. c = 0;
  1115. if (a >= b && a >= c && a >= d)
  1116. return 0;
  1117. else if (b >= c && b >= d)
  1118. return 1;
  1119. else if (c >= d)
  1120. return 2;
  1121. return 3;
  1122. }
  1123. static inline u32 Select2DPartition(s32 seed, s32 x, s32 y, s32 partitionCount, s32 smallBlock) {
  1124. return SelectPartition(seed, x, y, 0, partitionCount, smallBlock);
  1125. }
  1126. // Section C.2.14
  1127. static void ComputeEndpos32s(Pixel& ep1, Pixel& ep2, const u32*& colorValues,
  1128. u32 colorEndpos32Mode) {
  1129. #define READ_UINT_VALUES(N) \
  1130. u32 v[N]; \
  1131. for (u32 i = 0; i < N; i++) { \
  1132. v[i] = *(colorValues++); \
  1133. }
  1134. #define READ_INT_VALUES(N) \
  1135. s32 v[N]; \
  1136. for (u32 i = 0; i < N; i++) { \
  1137. v[i] = static_cast<s32>(*(colorValues++)); \
  1138. }
  1139. switch (colorEndpos32Mode) {
  1140. case 0: {
  1141. READ_UINT_VALUES(2)
  1142. ep1 = Pixel(0xFF, v[0], v[0], v[0]);
  1143. ep2 = Pixel(0xFF, v[1], v[1], v[1]);
  1144. } break;
  1145. case 1: {
  1146. READ_UINT_VALUES(2)
  1147. u32 L0 = (v[0] >> 2) | (v[1] & 0xC0);
  1148. u32 L1 = std::max(L0 + (v[1] & 0x3F), 0xFFU);
  1149. ep1 = Pixel(0xFF, L0, L0, L0);
  1150. ep2 = Pixel(0xFF, L1, L1, L1);
  1151. } break;
  1152. case 4: {
  1153. READ_UINT_VALUES(4)
  1154. ep1 = Pixel(v[2], v[0], v[0], v[0]);
  1155. ep2 = Pixel(v[3], v[1], v[1], v[1]);
  1156. } break;
  1157. case 5: {
  1158. READ_INT_VALUES(4)
  1159. BitTransferSigned(v[1], v[0]);
  1160. BitTransferSigned(v[3], v[2]);
  1161. ep1 = Pixel(v[2], v[0], v[0], v[0]);
  1162. ep2 = Pixel(v[2] + v[3], v[0] + v[1], v[0] + v[1], v[0] + v[1]);
  1163. ep1.ClampByte();
  1164. ep2.ClampByte();
  1165. } break;
  1166. case 6: {
  1167. READ_UINT_VALUES(4)
  1168. ep1 = Pixel(0xFF, v[0] * v[3] >> 8, v[1] * v[3] >> 8, v[2] * v[3] >> 8);
  1169. ep2 = Pixel(0xFF, v[0], v[1], v[2]);
  1170. } break;
  1171. case 8: {
  1172. READ_UINT_VALUES(6)
  1173. if (v[1] + v[3] + v[5] >= v[0] + v[2] + v[4]) {
  1174. ep1 = Pixel(0xFF, v[0], v[2], v[4]);
  1175. ep2 = Pixel(0xFF, v[1], v[3], v[5]);
  1176. } else {
  1177. ep1 = BlueContract(0xFF, v[1], v[3], v[5]);
  1178. ep2 = BlueContract(0xFF, v[0], v[2], v[4]);
  1179. }
  1180. } break;
  1181. case 9: {
  1182. READ_INT_VALUES(6)
  1183. BitTransferSigned(v[1], v[0]);
  1184. BitTransferSigned(v[3], v[2]);
  1185. BitTransferSigned(v[5], v[4]);
  1186. if (v[1] + v[3] + v[5] >= 0) {
  1187. ep1 = Pixel(0xFF, v[0], v[2], v[4]);
  1188. ep2 = Pixel(0xFF, v[0] + v[1], v[2] + v[3], v[4] + v[5]);
  1189. } else {
  1190. ep1 = BlueContract(0xFF, v[0] + v[1], v[2] + v[3], v[4] + v[5]);
  1191. ep2 = BlueContract(0xFF, v[0], v[2], v[4]);
  1192. }
  1193. ep1.ClampByte();
  1194. ep2.ClampByte();
  1195. } break;
  1196. case 10: {
  1197. READ_UINT_VALUES(6)
  1198. ep1 = Pixel(v[4], v[0] * v[3] >> 8, v[1] * v[3] >> 8, v[2] * v[3] >> 8);
  1199. ep2 = Pixel(v[5], v[0], v[1], v[2]);
  1200. } break;
  1201. case 12: {
  1202. READ_UINT_VALUES(8)
  1203. if (v[1] + v[3] + v[5] >= v[0] + v[2] + v[4]) {
  1204. ep1 = Pixel(v[6], v[0], v[2], v[4]);
  1205. ep2 = Pixel(v[7], v[1], v[3], v[5]);
  1206. } else {
  1207. ep1 = BlueContract(v[7], v[1], v[3], v[5]);
  1208. ep2 = BlueContract(v[6], v[0], v[2], v[4]);
  1209. }
  1210. } break;
  1211. case 13: {
  1212. READ_INT_VALUES(8)
  1213. BitTransferSigned(v[1], v[0]);
  1214. BitTransferSigned(v[3], v[2]);
  1215. BitTransferSigned(v[5], v[4]);
  1216. BitTransferSigned(v[7], v[6]);
  1217. if (v[1] + v[3] + v[5] >= 0) {
  1218. ep1 = Pixel(v[6], v[0], v[2], v[4]);
  1219. ep2 = Pixel(v[7] + v[6], v[0] + v[1], v[2] + v[3], v[4] + v[5]);
  1220. } else {
  1221. ep1 = BlueContract(v[6] + v[7], v[0] + v[1], v[2] + v[3], v[4] + v[5]);
  1222. ep2 = BlueContract(v[6], v[0], v[2], v[4]);
  1223. }
  1224. ep1.ClampByte();
  1225. ep2.ClampByte();
  1226. } break;
  1227. default:
  1228. assert(false && "Unsupported color endpoint mode (is it HDR?)");
  1229. break;
  1230. }
  1231. #undef READ_UINT_VALUES
  1232. #undef READ_INT_VALUES
  1233. }
  1234. static void DecompressBlock(const u8 inBuf[16], const u32 blockWidth, const u32 blockHeight,
  1235. u32* outBuf) {
  1236. InputBitStream strm(inBuf);
  1237. TexelWeightParams weightParams = DecodeBlockInfo(strm);
  1238. // Was there an error?
  1239. if (weightParams.m_bError) {
  1240. assert(false && "Invalid block mode");
  1241. FillError(outBuf, blockWidth, blockHeight);
  1242. return;
  1243. }
  1244. if (weightParams.m_bVoidExtentLDR) {
  1245. FillVoidExtentLDR(strm, outBuf, blockWidth, blockHeight);
  1246. return;
  1247. }
  1248. if (weightParams.m_bVoidExtentHDR) {
  1249. assert(false && "HDR void extent blocks are unsupported!");
  1250. FillError(outBuf, blockWidth, blockHeight);
  1251. return;
  1252. }
  1253. if (weightParams.m_Width > blockWidth) {
  1254. assert(false && "Texel weight grid width should be smaller than block width");
  1255. FillError(outBuf, blockWidth, blockHeight);
  1256. return;
  1257. }
  1258. if (weightParams.m_Height > blockHeight) {
  1259. assert(false && "Texel weight grid height should be smaller than block height");
  1260. FillError(outBuf, blockWidth, blockHeight);
  1261. return;
  1262. }
  1263. // Read num partitions
  1264. u32 nPartitions = strm.ReadBits<2>() + 1;
  1265. assert(nPartitions <= 4);
  1266. if (nPartitions == 4 && weightParams.m_bDualPlane) {
  1267. assert(false && "Dual plane mode is incompatible with four partition blocks");
  1268. FillError(outBuf, blockWidth, blockHeight);
  1269. return;
  1270. }
  1271. // Based on the number of partitions, read the color endpos32 mode for
  1272. // each partition.
  1273. // Determine partitions, partition index, and color endpos32 modes
  1274. s32 planeIdx = -1;
  1275. u32 partitionIndex;
  1276. u32 colorEndpos32Mode[4] = {0, 0, 0, 0};
  1277. // Define color data.
  1278. u8 colorEndpos32Data[16];
  1279. memset(colorEndpos32Data, 0, sizeof(colorEndpos32Data));
  1280. OutputBitStream colorEndpos32Stream(colorEndpos32Data, 16 * 8, 0);
  1281. // Read extra config data...
  1282. u32 baseCEM = 0;
  1283. if (nPartitions == 1) {
  1284. colorEndpos32Mode[0] = strm.ReadBits<4>();
  1285. partitionIndex = 0;
  1286. } else {
  1287. partitionIndex = strm.ReadBits<10>();
  1288. baseCEM = strm.ReadBits<6>();
  1289. }
  1290. u32 baseMode = (baseCEM & 3);
  1291. // Remaining bits are color endpos32 data...
  1292. u32 nWeightBits = weightParams.GetPackedBitSize();
  1293. s32 remainingBits = 128 - nWeightBits - static_cast<s32>(strm.GetBitsRead());
  1294. // Consider extra bits prior to texel data...
  1295. u32 extraCEMbits = 0;
  1296. if (baseMode) {
  1297. switch (nPartitions) {
  1298. case 2:
  1299. extraCEMbits += 2;
  1300. break;
  1301. case 3:
  1302. extraCEMbits += 5;
  1303. break;
  1304. case 4:
  1305. extraCEMbits += 8;
  1306. break;
  1307. default:
  1308. assert(false);
  1309. break;
  1310. }
  1311. }
  1312. remainingBits -= extraCEMbits;
  1313. // Do we have a dual plane situation?
  1314. u32 planeSelectorBits = 0;
  1315. if (weightParams.m_bDualPlane) {
  1316. planeSelectorBits = 2;
  1317. }
  1318. remainingBits -= planeSelectorBits;
  1319. // Read color data...
  1320. u32 colorDataBits = remainingBits;
  1321. while (remainingBits > 0) {
  1322. u32 nb = std::min(remainingBits, 8);
  1323. u32 b = strm.ReadBits(nb);
  1324. colorEndpos32Stream.WriteBits(b, nb);
  1325. remainingBits -= 8;
  1326. }
  1327. // Read the plane selection bits
  1328. planeIdx = strm.ReadBits(planeSelectorBits);
  1329. // Read the rest of the CEM
  1330. if (baseMode) {
  1331. u32 extraCEM = strm.ReadBits(extraCEMbits);
  1332. u32 CEM = (extraCEM << 6) | baseCEM;
  1333. CEM >>= 2;
  1334. bool C[4] = {0};
  1335. for (u32 i = 0; i < nPartitions; i++) {
  1336. C[i] = CEM & 1;
  1337. CEM >>= 1;
  1338. }
  1339. u8 M[4] = {0};
  1340. for (u32 i = 0; i < nPartitions; i++) {
  1341. M[i] = CEM & 3;
  1342. CEM >>= 2;
  1343. assert(M[i] <= 3);
  1344. }
  1345. for (u32 i = 0; i < nPartitions; i++) {
  1346. colorEndpos32Mode[i] = baseMode;
  1347. if (!(C[i]))
  1348. colorEndpos32Mode[i] -= 1;
  1349. colorEndpos32Mode[i] <<= 2;
  1350. colorEndpos32Mode[i] |= M[i];
  1351. }
  1352. } else if (nPartitions > 1) {
  1353. u32 CEM = baseCEM >> 2;
  1354. for (u32 i = 0; i < nPartitions; i++) {
  1355. colorEndpos32Mode[i] = CEM;
  1356. }
  1357. }
  1358. // Make sure everything up till here is sane.
  1359. for (u32 i = 0; i < nPartitions; i++) {
  1360. assert(colorEndpos32Mode[i] < 16);
  1361. }
  1362. assert(strm.GetBitsRead() + weightParams.GetPackedBitSize() == 128);
  1363. // Decode both color data and texel weight data
  1364. u32 colorValues[32]; // Four values, two endpos32s, four maximum paritions
  1365. DecodeColorValues(colorValues, colorEndpos32Data, colorEndpos32Mode, nPartitions,
  1366. colorDataBits);
  1367. Pixel endpos32s[4][2];
  1368. const u32* colorValuesPtr = colorValues;
  1369. for (u32 i = 0; i < nPartitions; i++) {
  1370. ComputeEndpos32s(endpos32s[i][0], endpos32s[i][1], colorValuesPtr, colorEndpos32Mode[i]);
  1371. }
  1372. // Read the texel weight data..
  1373. u8 texelWeightData[16];
  1374. memcpy(texelWeightData, inBuf, sizeof(texelWeightData));
  1375. // Reverse everything
  1376. for (u32 i = 0; i < 8; i++) {
  1377. // Taken from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits
  1378. #define REVERSE_BYTE(b) (((b)*0x80200802ULL) & 0x0884422110ULL) * 0x0101010101ULL >> 32
  1379. u8 a = static_cast<u8>(REVERSE_BYTE(texelWeightData[i]));
  1380. u8 b = static_cast<u8>(REVERSE_BYTE(texelWeightData[15 - i]));
  1381. #undef REVERSE_BYTE
  1382. texelWeightData[i] = b;
  1383. texelWeightData[15 - i] = a;
  1384. }
  1385. // Make sure that higher non-texel bits are set to zero
  1386. const u32 clearByteStart = (weightParams.GetPackedBitSize() >> 3) + 1;
  1387. texelWeightData[clearByteStart - 1] =
  1388. texelWeightData[clearByteStart - 1] &
  1389. static_cast<u8>((1 << (weightParams.GetPackedBitSize() % 8)) - 1);
  1390. memset(texelWeightData + clearByteStart, 0, 16 - clearByteStart);
  1391. IntegerEncodedVector texelWeightValues;
  1392. InputBitStream weightStream(texelWeightData);
  1393. DecodeIntegerSequence(texelWeightValues, weightStream, weightParams.m_MaxWeight,
  1394. weightParams.GetNumWeightValues());
  1395. // Blocks can be at most 12x12, so we can have as many as 144 weights
  1396. u32 weights[2][144];
  1397. UnquantizeTexelWeights(weights, texelWeightValues, weightParams, blockWidth, blockHeight);
  1398. // Now that we have endpos32s and weights, we can s32erpolate and generate
  1399. // the proper decoding...
  1400. for (u32 j = 0; j < blockHeight; j++)
  1401. for (u32 i = 0; i < blockWidth; i++) {
  1402. u32 partition = Select2DPartition(partitionIndex, i, j, nPartitions,
  1403. (blockHeight * blockWidth) < 32);
  1404. assert(partition < nPartitions);
  1405. Pixel p;
  1406. for (u32 c = 0; c < 4; c++) {
  1407. u32 C0 = endpos32s[partition][0].Component(c);
  1408. C0 = ReplicateByteTo16(C0);
  1409. u32 C1 = endpos32s[partition][1].Component(c);
  1410. C1 = ReplicateByteTo16(C1);
  1411. u32 plane = 0;
  1412. if (weightParams.m_bDualPlane && (((planeIdx + 1) & 3) == c)) {
  1413. plane = 1;
  1414. }
  1415. u32 weight = weights[plane][j * blockWidth + i];
  1416. u32 C = (C0 * (64 - weight) + C1 * weight + 32) / 64;
  1417. if (C == 65535) {
  1418. p.Component(c) = 255;
  1419. } else {
  1420. double Cf = static_cast<double>(C);
  1421. p.Component(c) = static_cast<u16>(255.0 * (Cf / 65536.0) + 0.5);
  1422. }
  1423. }
  1424. outBuf[j * blockWidth + i] = p.Pack();
  1425. }
  1426. }
  1427. } // namespace ASTCC
  1428. namespace Tegra::Texture::ASTC {
  1429. std::vector<u8> Decompress(const u8* data, u32 width, u32 height, u32 depth, u32 block_width,
  1430. u32 block_height) {
  1431. u32 blockIdx = 0;
  1432. std::size_t depth_offset = 0;
  1433. std::vector<u8> outData(height * width * depth * 4);
  1434. for (u32 k = 0; k < depth; k++) {
  1435. for (u32 j = 0; j < height; j += block_height) {
  1436. for (u32 i = 0; i < width; i += block_width) {
  1437. const u8* blockPtr = data + blockIdx * 16;
  1438. // Blocks can be at most 12x12
  1439. u32 uncompData[144];
  1440. ASTCC::DecompressBlock(blockPtr, block_width, block_height, uncompData);
  1441. u32 decompWidth = std::min(block_width, width - i);
  1442. u32 decompHeight = std::min(block_height, height - j);
  1443. u8* outRow = depth_offset + outData.data() + (j * width + i) * 4;
  1444. for (u32 jj = 0; jj < decompHeight; jj++) {
  1445. memcpy(outRow + jj * width * 4, uncompData + jj * block_width, decompWidth * 4);
  1446. }
  1447. blockIdx++;
  1448. }
  1449. }
  1450. depth_offset += height * width * 4;
  1451. }
  1452. return outData;
  1453. }
  1454. } // namespace Tegra::Texture::ASTC