AstcDecoder.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. namespace Ryujinx.Graphics.Texture.Astc
  7. {
  8. // https://github.com/GammaUNC/FasTC/blob/master/ASTCEncoder/src/Decompressor.cpp
  9. public static class AstcDecoder
  10. {
  11. struct TexelWeightParams
  12. {
  13. public int Width;
  14. public int Height;
  15. public bool DualPlane;
  16. public int MaxWeight;
  17. public bool Error;
  18. public bool VoidExtentLdr;
  19. public bool VoidExtentHdr;
  20. public int GetPackedBitSize()
  21. {
  22. // How many indices do we have?
  23. int indices = Height * Width;
  24. if (DualPlane)
  25. {
  26. indices *= 2;
  27. }
  28. IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(MaxWeight);
  29. return intEncoded.GetBitLength(indices);
  30. }
  31. public int GetNumWeightValues()
  32. {
  33. int ret = Width * Height;
  34. if (DualPlane)
  35. {
  36. ret *= 2;
  37. }
  38. return ret;
  39. }
  40. }
  41. public static bool TryDecodeToRgba8(
  42. Span<byte> data,
  43. int blockWidth,
  44. int blockHeight,
  45. int width,
  46. int height,
  47. int depth,
  48. int levels,
  49. out Span<byte> decoded)
  50. {
  51. bool success = true;
  52. using (MemoryStream inputStream = new MemoryStream(data.ToArray()))
  53. {
  54. BinaryReader binReader = new BinaryReader(inputStream);
  55. using (MemoryStream outputStream = new MemoryStream())
  56. {
  57. int blockIndex = 0;
  58. int mipOffset = 0;
  59. for (int l = 0; l < levels; l++)
  60. {
  61. int sliceSize = width * height * 4;
  62. for (int k = 0; k < depth; k++)
  63. for (int j = 0; j < height; j += blockHeight)
  64. for (int i = 0; i < width; i += blockWidth)
  65. {
  66. int[] decompressedData = new int[144];
  67. try
  68. {
  69. DecompressBlock(binReader.ReadBytes(0x10), decompressedData, blockWidth, blockHeight);
  70. }
  71. catch (Exception)
  72. {
  73. success = false;
  74. }
  75. int decompressedWidth = Math.Min(blockWidth, width - i);
  76. int decompressedHeight = Math.Min(blockHeight, height - j);
  77. int baseOffset = mipOffset + k * sliceSize + (j * width + i) * 4;
  78. for (int jj = 0; jj < decompressedHeight; jj++)
  79. {
  80. outputStream.Seek(baseOffset + jj * width * 4, SeekOrigin.Begin);
  81. byte[] outputBuffer = new byte[decompressedData.Length * sizeof(int)];
  82. Buffer.BlockCopy(decompressedData, 0, outputBuffer, 0, outputBuffer.Length);
  83. outputStream.Write(outputBuffer, jj * blockWidth * 4, decompressedWidth * 4);
  84. }
  85. blockIndex++;
  86. }
  87. mipOffset += sliceSize * depth;
  88. width = Math.Max(1, width >> 1);
  89. height = Math.Max(1, height >> 1);
  90. depth = Math.Max(1, depth >> 1);
  91. }
  92. decoded = outputStream.ToArray();
  93. }
  94. }
  95. return success;
  96. }
  97. public static bool DecompressBlock(
  98. byte[] inputBuffer,
  99. int[] outputBuffer,
  100. int blockWidth,
  101. int blockHeight)
  102. {
  103. BitArrayStream bitStream = new BitArrayStream(new BitArray(inputBuffer));
  104. TexelWeightParams texelParams = DecodeBlockInfo(bitStream);
  105. if (texelParams.Error)
  106. {
  107. throw new AstcDecoderException("Invalid block mode.");
  108. }
  109. if (texelParams.VoidExtentLdr)
  110. {
  111. FillVoidExtentLdr(bitStream, outputBuffer, blockWidth, blockHeight);
  112. return true;
  113. }
  114. if (texelParams.VoidExtentHdr)
  115. {
  116. throw new AstcDecoderException("HDR void extent blocks are not supported.");
  117. }
  118. if (texelParams.Width > blockWidth)
  119. {
  120. throw new AstcDecoderException("Texel weight grid width should be smaller than block width.");
  121. }
  122. if (texelParams.Height > blockHeight)
  123. {
  124. throw new AstcDecoderException("Texel weight grid height should be smaller than block height.");
  125. }
  126. // Read num partitions
  127. int numberPartitions = bitStream.ReadBits(2) + 1;
  128. Debug.Assert(numberPartitions <= 4);
  129. if (numberPartitions == 4 && texelParams.DualPlane)
  130. {
  131. throw new AstcDecoderException("Dual plane mode is incompatible with four partition blocks.");
  132. }
  133. // Based on the number of partitions, read the color endpoint mode for
  134. // each partition.
  135. // Determine partitions, partition index, and color endpoint modes
  136. int planeIndices = -1;
  137. int partitionIndex;
  138. uint[] colorEndpointMode = { 0, 0, 0, 0 };
  139. BitArrayStream colorEndpointStream = new BitArrayStream(new BitArray(16 * 8));
  140. // Read extra config data...
  141. uint baseColorEndpointMode = 0;
  142. if (numberPartitions == 1)
  143. {
  144. colorEndpointMode[0] = (uint)bitStream.ReadBits(4);
  145. partitionIndex = 0;
  146. }
  147. else
  148. {
  149. partitionIndex = bitStream.ReadBits(10);
  150. baseColorEndpointMode = (uint)bitStream.ReadBits(6);
  151. }
  152. uint baseMode = (baseColorEndpointMode & 3);
  153. // Remaining bits are color endpoint data...
  154. int numberWeightBits = texelParams.GetPackedBitSize();
  155. int remainingBits = 128 - numberWeightBits - bitStream.Position;
  156. // Consider extra bits prior to texel data...
  157. uint extraColorEndpointModeBits = 0;
  158. if (baseMode != 0)
  159. {
  160. switch (numberPartitions)
  161. {
  162. case 2: extraColorEndpointModeBits += 2; break;
  163. case 3: extraColorEndpointModeBits += 5; break;
  164. case 4: extraColorEndpointModeBits += 8; break;
  165. default: Debug.Assert(false); break;
  166. }
  167. }
  168. remainingBits -= (int)extraColorEndpointModeBits;
  169. // Do we have a dual plane situation?
  170. int planeSelectorBits = 0;
  171. if (texelParams.DualPlane)
  172. {
  173. planeSelectorBits = 2;
  174. }
  175. remainingBits -= planeSelectorBits;
  176. // Read color data...
  177. int colorDataBits = remainingBits;
  178. while (remainingBits > 0)
  179. {
  180. int numberBits = Math.Min(remainingBits, 8);
  181. int bits = bitStream.ReadBits(numberBits);
  182. colorEndpointStream.WriteBits(bits, numberBits);
  183. remainingBits -= 8;
  184. }
  185. // Read the plane selection bits
  186. planeIndices = bitStream.ReadBits(planeSelectorBits);
  187. // Read the rest of the CEM
  188. if (baseMode != 0)
  189. {
  190. uint extraColorEndpointMode = (uint)bitStream.ReadBits((int)extraColorEndpointModeBits);
  191. uint tempColorEndpointMode = (extraColorEndpointMode << 6) | baseColorEndpointMode;
  192. tempColorEndpointMode >>= 2;
  193. bool[] c = new bool[4];
  194. for (int i = 0; i < numberPartitions; i++)
  195. {
  196. c[i] = (tempColorEndpointMode & 1) != 0;
  197. tempColorEndpointMode >>= 1;
  198. }
  199. byte[] m = new byte[4];
  200. for (int i = 0; i < numberPartitions; i++)
  201. {
  202. m[i] = (byte)(tempColorEndpointMode & 3);
  203. tempColorEndpointMode >>= 2;
  204. Debug.Assert(m[i] <= 3);
  205. }
  206. for (int i = 0; i < numberPartitions; i++)
  207. {
  208. colorEndpointMode[i] = baseMode;
  209. if (!(c[i])) colorEndpointMode[i] -= 1;
  210. colorEndpointMode[i] <<= 2;
  211. colorEndpointMode[i] |= m[i];
  212. }
  213. }
  214. else if (numberPartitions > 1)
  215. {
  216. uint tempColorEndpointMode = baseColorEndpointMode >> 2;
  217. for (uint i = 0; i < numberPartitions; i++)
  218. {
  219. colorEndpointMode[i] = tempColorEndpointMode;
  220. }
  221. }
  222. // Make sure everything up till here is sane.
  223. for (int i = 0; i < numberPartitions; i++)
  224. {
  225. Debug.Assert(colorEndpointMode[i] < 16);
  226. }
  227. Debug.Assert(bitStream.Position + texelParams.GetPackedBitSize() == 128);
  228. // Decode both color data and texel weight data
  229. int[] colorValues = new int[32]; // Four values * two endpoints * four maximum partitions
  230. DecodeColorValues(colorValues, colorEndpointStream.ToByteArray(), colorEndpointMode, numberPartitions, colorDataBits);
  231. AstcPixel[][] endPoints = new AstcPixel[4][];
  232. endPoints[0] = new AstcPixel[2];
  233. endPoints[1] = new AstcPixel[2];
  234. endPoints[2] = new AstcPixel[2];
  235. endPoints[3] = new AstcPixel[2];
  236. int colorValuesPosition = 0;
  237. for (int i = 0; i < numberPartitions; i++)
  238. {
  239. ComputeEndpoints(endPoints[i], colorValues, colorEndpointMode[i], ref colorValuesPosition);
  240. }
  241. // Read the texel weight data.
  242. byte[] texelWeightData = (byte[])inputBuffer.Clone();
  243. // Reverse everything
  244. for (int i = 0; i < 8; i++)
  245. {
  246. byte a = ReverseByte(texelWeightData[i]);
  247. byte b = ReverseByte(texelWeightData[15 - i]);
  248. texelWeightData[i] = b;
  249. texelWeightData[15 - i] = a;
  250. }
  251. // Make sure that higher non-texel bits are set to zero
  252. int clearByteStart = (texelParams.GetPackedBitSize() >> 3) + 1;
  253. texelWeightData[clearByteStart - 1] &= (byte)((1 << (texelParams.GetPackedBitSize() % 8)) - 1);
  254. int cLen = 16 - clearByteStart;
  255. for (int i = clearByteStart; i < clearByteStart + cLen; i++) texelWeightData[i] = 0;
  256. List<IntegerEncoded> texelWeightValues = new List<IntegerEncoded>();
  257. BitArrayStream weightBitStream = new BitArrayStream(new BitArray(texelWeightData));
  258. IntegerEncoded.DecodeIntegerSequence(texelWeightValues, weightBitStream, texelParams.MaxWeight, texelParams.GetNumWeightValues());
  259. // Blocks can be at most 12x12, so we can have as many as 144 weights
  260. int[][] weights = new int[2][];
  261. weights[0] = new int[144];
  262. weights[1] = new int[144];
  263. UnquantizeTexelWeights(weights, texelWeightValues, texelParams, blockWidth, blockHeight);
  264. // Now that we have endpoints and weights, we can interpolate and generate
  265. // the proper decoding...
  266. for (int j = 0; j < blockHeight; j++)
  267. {
  268. for (int i = 0; i < blockWidth; i++)
  269. {
  270. int partition = Select2dPartition(partitionIndex, i, j, numberPartitions, ((blockHeight * blockWidth) < 32));
  271. Debug.Assert(partition < numberPartitions);
  272. AstcPixel pixel = new AstcPixel(0, 0, 0, 0);
  273. for (int component = 0; component < 4; component++)
  274. {
  275. int component0 = endPoints[partition][0].GetComponent(component);
  276. component0 = BitArrayStream.Replicate(component0, 8, 16);
  277. int component1 = endPoints[partition][1].GetComponent(component);
  278. component1 = BitArrayStream.Replicate(component1, 8, 16);
  279. int plane = 0;
  280. if (texelParams.DualPlane && (((planeIndices + 1) & 3) == component))
  281. {
  282. plane = 1;
  283. }
  284. int weight = weights[plane][j * blockWidth + i];
  285. int finalComponent = (component0 * (64 - weight) + component1 * weight + 32) / 64;
  286. if (finalComponent == 65535)
  287. {
  288. pixel.SetComponent(component, 255);
  289. }
  290. else
  291. {
  292. double finalComponentFloat = finalComponent;
  293. pixel.SetComponent(component, (int)(255.0 * (finalComponentFloat / 65536.0) + 0.5));
  294. }
  295. }
  296. outputBuffer[j * blockWidth + i] = pixel.Pack();
  297. }
  298. }
  299. return true;
  300. }
  301. private static int Select2dPartition(int seed, int x, int y, int partitionCount, bool isSmallBlock)
  302. {
  303. return SelectPartition(seed, x, y, 0, partitionCount, isSmallBlock);
  304. }
  305. private static int SelectPartition(int seed, int x, int y, int z, int partitionCount, bool isSmallBlock)
  306. {
  307. if (partitionCount == 1)
  308. {
  309. return 0;
  310. }
  311. if (isSmallBlock)
  312. {
  313. x <<= 1;
  314. y <<= 1;
  315. z <<= 1;
  316. }
  317. seed += (partitionCount - 1) * 1024;
  318. int rightNum = Hash52((uint)seed);
  319. byte seed01 = (byte)(rightNum & 0xF);
  320. byte seed02 = (byte)((rightNum >> 4) & 0xF);
  321. byte seed03 = (byte)((rightNum >> 8) & 0xF);
  322. byte seed04 = (byte)((rightNum >> 12) & 0xF);
  323. byte seed05 = (byte)((rightNum >> 16) & 0xF);
  324. byte seed06 = (byte)((rightNum >> 20) & 0xF);
  325. byte seed07 = (byte)((rightNum >> 24) & 0xF);
  326. byte seed08 = (byte)((rightNum >> 28) & 0xF);
  327. byte seed09 = (byte)((rightNum >> 18) & 0xF);
  328. byte seed10 = (byte)((rightNum >> 22) & 0xF);
  329. byte seed11 = (byte)((rightNum >> 26) & 0xF);
  330. byte seed12 = (byte)(((rightNum >> 30) | (rightNum << 2)) & 0xF);
  331. seed01 *= seed01; seed02 *= seed02;
  332. seed03 *= seed03; seed04 *= seed04;
  333. seed05 *= seed05; seed06 *= seed06;
  334. seed07 *= seed07; seed08 *= seed08;
  335. seed09 *= seed09; seed10 *= seed10;
  336. seed11 *= seed11; seed12 *= seed12;
  337. int seedHash1, seedHash2, seedHash3;
  338. if ((seed & 1) != 0)
  339. {
  340. seedHash1 = (seed & 2) != 0 ? 4 : 5;
  341. seedHash2 = (partitionCount == 3) ? 6 : 5;
  342. }
  343. else
  344. {
  345. seedHash1 = (partitionCount == 3) ? 6 : 5;
  346. seedHash2 = (seed & 2) != 0 ? 4 : 5;
  347. }
  348. seedHash3 = (seed & 0x10) != 0 ? seedHash1 : seedHash2;
  349. seed01 >>= seedHash1; seed02 >>= seedHash2; seed03 >>= seedHash1; seed04 >>= seedHash2;
  350. seed05 >>= seedHash1; seed06 >>= seedHash2; seed07 >>= seedHash1; seed08 >>= seedHash2;
  351. seed09 >>= seedHash3; seed10 >>= seedHash3; seed11 >>= seedHash3; seed12 >>= seedHash3;
  352. int a = seed01 * x + seed02 * y + seed11 * z + (rightNum >> 14);
  353. int b = seed03 * x + seed04 * y + seed12 * z + (rightNum >> 10);
  354. int c = seed05 * x + seed06 * y + seed09 * z + (rightNum >> 6);
  355. int d = seed07 * x + seed08 * y + seed10 * z + (rightNum >> 2);
  356. a &= 0x3F; b &= 0x3F; c &= 0x3F; d &= 0x3F;
  357. if (partitionCount < 4) d = 0;
  358. if (partitionCount < 3) c = 0;
  359. if (a >= b && a >= c && a >= d) return 0;
  360. else if (b >= c && b >= d) return 1;
  361. else if (c >= d) return 2;
  362. return 3;
  363. }
  364. static int Hash52(uint val)
  365. {
  366. val ^= val >> 15; val -= val << 17; val += val << 7; val += val << 4;
  367. val ^= val >> 5; val += val << 16; val ^= val >> 7; val ^= val >> 3;
  368. val ^= val << 6; val ^= val >> 17;
  369. return (int)val;
  370. }
  371. static void UnquantizeTexelWeights(
  372. int[][] outputBuffer,
  373. List<IntegerEncoded> weights,
  374. TexelWeightParams texelParams,
  375. int blockWidth,
  376. int blockHeight)
  377. {
  378. int weightIndices = 0;
  379. int[][] unquantized = new int[2][];
  380. unquantized[0] = new int[144];
  381. unquantized[1] = new int[144];
  382. for (int i = 0; i < weights.Count; i++)
  383. {
  384. unquantized[0][weightIndices] = UnquantizeTexelWeight(weights[i]);
  385. if (texelParams.DualPlane)
  386. {
  387. i++;
  388. unquantized[1][weightIndices] = UnquantizeTexelWeight(weights[i]);
  389. if (i == weights.Count)
  390. {
  391. break;
  392. }
  393. }
  394. if (++weightIndices >= (texelParams.Width * texelParams.Height)) break;
  395. }
  396. // Do infill if necessary (Section C.2.18) ...
  397. int ds = (1024 + (blockWidth / 2)) / (blockWidth - 1);
  398. int dt = (1024 + (blockHeight / 2)) / (blockHeight - 1);
  399. int planeScale = texelParams.DualPlane ? 2 : 1;
  400. for (int plane = 0; plane < planeScale; plane++)
  401. {
  402. for (int t = 0; t < blockHeight; t++)
  403. {
  404. for (int s = 0; s < blockWidth; s++)
  405. {
  406. int cs = ds * s;
  407. int ct = dt * t;
  408. int gs = (cs * (texelParams.Width - 1) + 32) >> 6;
  409. int gt = (ct * (texelParams.Height - 1) + 32) >> 6;
  410. int js = gs >> 4;
  411. int fs = gs & 0xF;
  412. int jt = gt >> 4;
  413. int ft = gt & 0x0F;
  414. int w11 = (fs * ft + 8) >> 4;
  415. int w10 = ft - w11;
  416. int w01 = fs - w11;
  417. int w00 = 16 - fs - ft + w11;
  418. int v0 = js + jt * texelParams.Width;
  419. int p00 = 0;
  420. int p01 = 0;
  421. int p10 = 0;
  422. int p11 = 0;
  423. if (v0 < (texelParams.Width * texelParams.Height))
  424. {
  425. p00 = unquantized[plane][v0];
  426. }
  427. if (v0 + 1 < (texelParams.Width * texelParams.Height))
  428. {
  429. p01 = unquantized[plane][v0 + 1];
  430. }
  431. if (v0 + texelParams.Width < (texelParams.Width * texelParams.Height))
  432. {
  433. p10 = unquantized[plane][v0 + texelParams.Width];
  434. }
  435. if (v0 + texelParams.Width + 1 < (texelParams.Width * texelParams.Height))
  436. {
  437. p11 = unquantized[plane][v0 + texelParams.Width + 1];
  438. }
  439. outputBuffer[plane][t * blockWidth + s] = (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4;
  440. }
  441. }
  442. }
  443. }
  444. static int UnquantizeTexelWeight(IntegerEncoded intEncoded)
  445. {
  446. int bitValue = intEncoded.BitValue;
  447. int bitLength = intEncoded.NumberBits;
  448. int a = BitArrayStream.Replicate(bitValue & 1, 1, 7);
  449. int b = 0, c = 0, d = 0;
  450. int result = 0;
  451. switch (intEncoded.GetEncoding())
  452. {
  453. case IntegerEncoded.EIntegerEncoding.JustBits:
  454. result = BitArrayStream.Replicate(bitValue, bitLength, 6);
  455. break;
  456. case IntegerEncoded.EIntegerEncoding.Trit:
  457. {
  458. d = intEncoded.TritValue;
  459. Debug.Assert(d < 3);
  460. switch (bitLength)
  461. {
  462. case 0:
  463. {
  464. int[] results = { 0, 32, 63 };
  465. result = results[d];
  466. break;
  467. }
  468. case 1:
  469. {
  470. c = 50;
  471. break;
  472. }
  473. case 2:
  474. {
  475. c = 23;
  476. int b2 = (bitValue >> 1) & 1;
  477. b = (b2 << 6) | (b2 << 2) | b2;
  478. break;
  479. }
  480. case 3:
  481. {
  482. c = 11;
  483. int cb = (bitValue >> 1) & 3;
  484. b = (cb << 5) | cb;
  485. break;
  486. }
  487. default:
  488. throw new AstcDecoderException("Invalid trit encoding for texel weight.");
  489. }
  490. break;
  491. }
  492. case IntegerEncoded.EIntegerEncoding.Quint:
  493. {
  494. d = intEncoded.QuintValue;
  495. Debug.Assert(d < 5);
  496. switch (bitLength)
  497. {
  498. case 0:
  499. {
  500. int[] results = { 0, 16, 32, 47, 63 };
  501. result = results[d];
  502. break;
  503. }
  504. case 1:
  505. {
  506. c = 28;
  507. break;
  508. }
  509. case 2:
  510. {
  511. c = 13;
  512. int b2 = (bitValue >> 1) & 1;
  513. b = (b2 << 6) | (b2 << 1);
  514. break;
  515. }
  516. default:
  517. throw new AstcDecoderException("Invalid quint encoding for texel weight.");
  518. }
  519. break;
  520. }
  521. }
  522. if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits && bitLength > 0)
  523. {
  524. // Decode the value...
  525. result = d * c + b;
  526. result ^= a;
  527. result = (a & 0x20) | (result >> 2);
  528. }
  529. Debug.Assert(result < 64);
  530. // Change from [0,63] to [0,64]
  531. if (result > 32)
  532. {
  533. result += 1;
  534. }
  535. return result;
  536. }
  537. static byte ReverseByte(byte b)
  538. {
  539. // Taken from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits
  540. return (byte)((((b) * 0x80200802L) & 0x0884422110L) * 0x0101010101L >> 32);
  541. }
  542. static uint[] ReadUintColorValues(int number, int[] colorValues, ref int colorValuesPosition)
  543. {
  544. uint[] ret = new uint[number];
  545. for (int i = 0; i < number; i++)
  546. {
  547. ret[i] = (uint)colorValues[colorValuesPosition++];
  548. }
  549. return ret;
  550. }
  551. static int[] ReadIntColorValues(int number, int[] colorValues, ref int colorValuesPosition)
  552. {
  553. int[] ret = new int[number];
  554. for (int i = 0; i < number; i++)
  555. {
  556. ret[i] = colorValues[colorValuesPosition++];
  557. }
  558. return ret;
  559. }
  560. static void ComputeEndpoints(
  561. AstcPixel[] endPoints,
  562. int[] colorValues,
  563. uint colorEndpointMode,
  564. ref int colorValuesPosition)
  565. {
  566. switch (colorEndpointMode)
  567. {
  568. case 0:
  569. {
  570. uint[] val = ReadUintColorValues(2, colorValues, ref colorValuesPosition);
  571. endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[0], (short)val[0]);
  572. endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[1], (short)val[1]);
  573. break;
  574. }
  575. case 1:
  576. {
  577. uint[] val = ReadUintColorValues(2, colorValues, ref colorValuesPosition);
  578. int l0 = (int)((val[0] >> 2) | (val[1] & 0xC0));
  579. int l1 = (int)Math.Max(l0 + (val[1] & 0x3F), 0xFFU);
  580. endPoints[0] = new AstcPixel(0xFF, (short)l0, (short)l0, (short)l0);
  581. endPoints[1] = new AstcPixel(0xFF, (short)l1, (short)l1, (short)l1);
  582. break;
  583. }
  584. case 4:
  585. {
  586. uint[] val = ReadUintColorValues(4, colorValues, ref colorValuesPosition);
  587. endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]);
  588. endPoints[1] = new AstcPixel((short)val[3], (short)val[1], (short)val[1], (short)val[1]);
  589. break;
  590. }
  591. case 5:
  592. {
  593. int[] val = ReadIntColorValues(4, colorValues, ref colorValuesPosition);
  594. BitArrayStream.BitTransferSigned(ref val[1], ref val[0]);
  595. BitArrayStream.BitTransferSigned(ref val[3], ref val[2]);
  596. endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]);
  597. endPoints[1] = new AstcPixel((short)(val[2] + val[3]), (short)(val[0] + val[1]), (short)(val[0] + val[1]), (short)(val[0] + val[1]));
  598. endPoints[0].ClampByte();
  599. endPoints[1].ClampByte();
  600. break;
  601. }
  602. case 6:
  603. {
  604. uint[] val = ReadUintColorValues(4, colorValues, ref colorValuesPosition);
  605. endPoints[0] = new AstcPixel(0xFF, (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8));
  606. endPoints[1] = new AstcPixel(0xFF, (short)val[0], (short)val[1], (short)val[2]);
  607. break;
  608. }
  609. case 8:
  610. {
  611. uint[] val = ReadUintColorValues(6, colorValues, ref colorValuesPosition);
  612. if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4])
  613. {
  614. endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]);
  615. endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[3], (short)val[5]);
  616. }
  617. else
  618. {
  619. endPoints[0] = AstcPixel.BlueContract(0xFF, (short)val[1], (short)val[3], (short)val[5]);
  620. endPoints[1] = AstcPixel.BlueContract(0xFF, (short)val[0], (short)val[2], (short)val[4]);
  621. }
  622. break;
  623. }
  624. case 9:
  625. {
  626. int[] val = ReadIntColorValues(6, colorValues, ref colorValuesPosition);
  627. BitArrayStream.BitTransferSigned(ref val[1], ref val[0]);
  628. BitArrayStream.BitTransferSigned(ref val[3], ref val[2]);
  629. BitArrayStream.BitTransferSigned(ref val[5], ref val[4]);
  630. if (val[1] + val[3] + val[5] >= 0)
  631. {
  632. endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]);
  633. endPoints[1] = new AstcPixel(0xFF, (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5]));
  634. }
  635. else
  636. {
  637. endPoints[0] = AstcPixel.BlueContract(0xFF, val[0] + val[1], val[2] + val[3], val[4] + val[5]);
  638. endPoints[1] = AstcPixel.BlueContract(0xFF, val[0], val[2], val[4]);
  639. }
  640. endPoints[0].ClampByte();
  641. endPoints[1].ClampByte();
  642. break;
  643. }
  644. case 10:
  645. {
  646. uint[] val = ReadUintColorValues(6, colorValues, ref colorValuesPosition);
  647. endPoints[0] = new AstcPixel((short)val[4], (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8));
  648. endPoints[1] = new AstcPixel((short)val[5], (short)val[0], (short)val[1], (short)val[2]);
  649. break;
  650. }
  651. case 12:
  652. {
  653. uint[] val = ReadUintColorValues(8, colorValues, ref colorValuesPosition);
  654. if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4])
  655. {
  656. endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
  657. endPoints[1] = new AstcPixel((short)val[7], (short)val[1], (short)val[3], (short)val[5]);
  658. }
  659. else
  660. {
  661. endPoints[0] = AstcPixel.BlueContract((short)val[7], (short)val[1], (short)val[3], (short)val[5]);
  662. endPoints[1] = AstcPixel.BlueContract((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
  663. }
  664. break;
  665. }
  666. case 13:
  667. {
  668. int[] val = ReadIntColorValues(8, colorValues, ref colorValuesPosition);
  669. BitArrayStream.BitTransferSigned(ref val[1], ref val[0]);
  670. BitArrayStream.BitTransferSigned(ref val[3], ref val[2]);
  671. BitArrayStream.BitTransferSigned(ref val[5], ref val[4]);
  672. BitArrayStream.BitTransferSigned(ref val[7], ref val[6]);
  673. if (val[1] + val[3] + val[5] >= 0)
  674. {
  675. endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
  676. endPoints[1] = new AstcPixel((short)(val[7] + val[6]), (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5]));
  677. }
  678. else
  679. {
  680. endPoints[0] = AstcPixel.BlueContract(val[6] + val[7], val[0] + val[1], val[2] + val[3], val[4] + val[5]);
  681. endPoints[1] = AstcPixel.BlueContract(val[6], val[0], val[2], val[4]);
  682. }
  683. endPoints[0].ClampByte();
  684. endPoints[1].ClampByte();
  685. break;
  686. }
  687. default:
  688. throw new AstcDecoderException("Unsupported color endpoint mode (is it HDR?)");
  689. }
  690. }
  691. static void DecodeColorValues(
  692. int[] outputValues,
  693. byte[] inputData,
  694. uint[] modes,
  695. int numberPartitions,
  696. int numberBitsForColorData)
  697. {
  698. // First figure out how many color values we have
  699. int numberValues = 0;
  700. for (int i = 0; i < numberPartitions; i++)
  701. {
  702. numberValues += (int)((modes[i] >> 2) + 1) << 1;
  703. }
  704. // Then based on the number of values and the remaining number of bits,
  705. // figure out the max value for each of them...
  706. int range = 256;
  707. while (--range > 0)
  708. {
  709. IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(range);
  710. int bitLength = intEncoded.GetBitLength(numberValues);
  711. if (bitLength <= numberBitsForColorData)
  712. {
  713. // Find the smallest possible range that matches the given encoding
  714. while (--range > 0)
  715. {
  716. IntegerEncoded newIntEncoded = IntegerEncoded.CreateEncoding(range);
  717. if (!newIntEncoded.MatchesEncoding(intEncoded))
  718. {
  719. break;
  720. }
  721. }
  722. // Return to last matching range.
  723. range++;
  724. break;
  725. }
  726. }
  727. // We now have enough to decode our integer sequence.
  728. List<IntegerEncoded> integerEncodedSequence = new List<IntegerEncoded>();
  729. BitArrayStream colorBitStream = new BitArrayStream(new BitArray(inputData));
  730. IntegerEncoded.DecodeIntegerSequence(integerEncodedSequence, colorBitStream, range, numberValues);
  731. // Once we have the decoded values, we need to dequantize them to the 0-255 range
  732. // This procedure is outlined in ASTC spec C.2.13
  733. int outputIndices = 0;
  734. foreach (IntegerEncoded intEncoded in integerEncodedSequence)
  735. {
  736. int bitLength = intEncoded.NumberBits;
  737. int bitValue = intEncoded.BitValue;
  738. Debug.Assert(bitLength >= 1);
  739. int a = 0, b = 0, c = 0, d = 0;
  740. // A is just the lsb replicated 9 times.
  741. a = BitArrayStream.Replicate(bitValue & 1, 1, 9);
  742. switch (intEncoded.GetEncoding())
  743. {
  744. case IntegerEncoded.EIntegerEncoding.JustBits:
  745. {
  746. outputValues[outputIndices++] = BitArrayStream.Replicate(bitValue, bitLength, 8);
  747. break;
  748. }
  749. case IntegerEncoded.EIntegerEncoding.Trit:
  750. {
  751. d = intEncoded.TritValue;
  752. switch (bitLength)
  753. {
  754. case 1:
  755. {
  756. c = 204;
  757. break;
  758. }
  759. case 2:
  760. {
  761. c = 93;
  762. // B = b000b0bb0
  763. int b2 = (bitValue >> 1) & 1;
  764. b = (b2 << 8) | (b2 << 4) | (b2 << 2) | (b2 << 1);
  765. break;
  766. }
  767. case 3:
  768. {
  769. c = 44;
  770. // B = cb000cbcb
  771. int cb = (bitValue >> 1) & 3;
  772. b = (cb << 7) | (cb << 2) | cb;
  773. break;
  774. }
  775. case 4:
  776. {
  777. c = 22;
  778. // B = dcb000dcb
  779. int dcb = (bitValue >> 1) & 7;
  780. b = (dcb << 6) | dcb;
  781. break;
  782. }
  783. case 5:
  784. {
  785. c = 11;
  786. // B = edcb000ed
  787. int edcb = (bitValue >> 1) & 0xF;
  788. b = (edcb << 5) | (edcb >> 2);
  789. break;
  790. }
  791. case 6:
  792. {
  793. c = 5;
  794. // B = fedcb000f
  795. int fedcb = (bitValue >> 1) & 0x1F;
  796. b = (fedcb << 4) | (fedcb >> 4);
  797. break;
  798. }
  799. default:
  800. throw new AstcDecoderException("Unsupported trit encoding for color values.");
  801. }
  802. break;
  803. }
  804. case IntegerEncoded.EIntegerEncoding.Quint:
  805. {
  806. d = intEncoded.QuintValue;
  807. switch (bitLength)
  808. {
  809. case 1:
  810. {
  811. c = 113;
  812. break;
  813. }
  814. case 2:
  815. {
  816. c = 54;
  817. // B = b0000bb00
  818. int b2 = (bitValue >> 1) & 1;
  819. b = (b2 << 8) | (b2 << 3) | (b2 << 2);
  820. break;
  821. }
  822. case 3:
  823. {
  824. c = 26;
  825. // B = cb0000cbc
  826. int cb = (bitValue >> 1) & 3;
  827. b = (cb << 7) | (cb << 1) | (cb >> 1);
  828. break;
  829. }
  830. case 4:
  831. {
  832. c = 13;
  833. // B = dcb0000dc
  834. int dcb = (bitValue >> 1) & 7;
  835. b = (dcb << 6) | (dcb >> 1);
  836. break;
  837. }
  838. case 5:
  839. {
  840. c = 6;
  841. // B = edcb0000e
  842. int edcb = (bitValue >> 1) & 0xF;
  843. b = (edcb << 5) | (edcb >> 3);
  844. break;
  845. }
  846. default:
  847. throw new AstcDecoderException("Unsupported quint encoding for color values.");
  848. }
  849. break;
  850. }
  851. }
  852. if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits)
  853. {
  854. int T = d * c + b;
  855. T ^= a;
  856. T = (a & 0x80) | (T >> 2);
  857. outputValues[outputIndices++] = T;
  858. }
  859. }
  860. // Make sure that each of our values is in the proper range...
  861. for (int i = 0; i < numberValues; i++)
  862. {
  863. Debug.Assert(outputValues[i] <= 255);
  864. }
  865. }
  866. static void FillVoidExtentLdr(BitArrayStream bitStream, int[] outputBuffer, int blockWidth, int blockHeight)
  867. {
  868. // Don't actually care about the void extent, just read the bits...
  869. for (int i = 0; i < 4; ++i)
  870. {
  871. bitStream.ReadBits(13);
  872. }
  873. // Decode the RGBA components and renormalize them to the range [0, 255]
  874. ushort r = (ushort)bitStream.ReadBits(16);
  875. ushort g = (ushort)bitStream.ReadBits(16);
  876. ushort b = (ushort)bitStream.ReadBits(16);
  877. ushort a = (ushort)bitStream.ReadBits(16);
  878. int rgba = (r >> 8) | (g & 0xFF00) | ((b) & 0xFF00) << 8 | ((a) & 0xFF00) << 16;
  879. for (int j = 0; j < blockHeight; j++)
  880. {
  881. for (int i = 0; i < blockWidth; i++)
  882. {
  883. outputBuffer[j * blockWidth + i] = rgba;
  884. }
  885. }
  886. }
  887. static TexelWeightParams DecodeBlockInfo(BitArrayStream bitStream)
  888. {
  889. TexelWeightParams texelParams = new TexelWeightParams();
  890. // Read the entire block mode all at once
  891. ushort modeBits = (ushort)bitStream.ReadBits(11);
  892. // Does this match the void extent block mode?
  893. if ((modeBits & 0x01FF) == 0x1FC)
  894. {
  895. if ((modeBits & 0x200) != 0)
  896. {
  897. texelParams.VoidExtentHdr = true;
  898. }
  899. else
  900. {
  901. texelParams.VoidExtentLdr = true;
  902. }
  903. // Next two bits must be one.
  904. if ((modeBits & 0x400) == 0 || bitStream.ReadBits(1) == 0)
  905. {
  906. texelParams.Error = true;
  907. }
  908. return texelParams;
  909. }
  910. // First check if the last four bits are zero
  911. if ((modeBits & 0xF) == 0)
  912. {
  913. texelParams.Error = true;
  914. return texelParams;
  915. }
  916. // If the last two bits are zero, then if bits
  917. // [6-8] are all ones, this is also reserved.
  918. if ((modeBits & 0x3) == 0 && (modeBits & 0x1C0) == 0x1C0)
  919. {
  920. texelParams.Error = true;
  921. return texelParams;
  922. }
  923. // Otherwise, there is no error... Figure out the layout
  924. // of the block mode. Layout is determined by a number
  925. // between 0 and 9 corresponding to table C.2.8 of the
  926. // ASTC spec.
  927. int layout = 0;
  928. if ((modeBits & 0x1) != 0 || (modeBits & 0x2) != 0)
  929. {
  930. // layout is in [0-4]
  931. if ((modeBits & 0x8) != 0)
  932. {
  933. // layout is in [2-4]
  934. if ((modeBits & 0x4) != 0)
  935. {
  936. // layout is in [3-4]
  937. if ((modeBits & 0x100) != 0)
  938. {
  939. layout = 4;
  940. }
  941. else
  942. {
  943. layout = 3;
  944. }
  945. }
  946. else
  947. {
  948. layout = 2;
  949. }
  950. }
  951. else
  952. {
  953. // layout is in [0-1]
  954. if ((modeBits & 0x4) != 0)
  955. {
  956. layout = 1;
  957. }
  958. else
  959. {
  960. layout = 0;
  961. }
  962. }
  963. }
  964. else
  965. {
  966. // layout is in [5-9]
  967. if ((modeBits & 0x100) != 0)
  968. {
  969. // layout is in [7-9]
  970. if ((modeBits & 0x80) != 0)
  971. {
  972. // layout is in [7-8]
  973. Debug.Assert((modeBits & 0x40) == 0);
  974. if ((modeBits & 0x20) != 0)
  975. {
  976. layout = 8;
  977. }
  978. else
  979. {
  980. layout = 7;
  981. }
  982. }
  983. else
  984. {
  985. layout = 9;
  986. }
  987. }
  988. else
  989. {
  990. // layout is in [5-6]
  991. if ((modeBits & 0x80) != 0)
  992. {
  993. layout = 6;
  994. }
  995. else
  996. {
  997. layout = 5;
  998. }
  999. }
  1000. }
  1001. Debug.Assert(layout < 10);
  1002. // Determine R
  1003. int r = (modeBits >> 4) & 1;
  1004. if (layout < 5)
  1005. {
  1006. r |= (modeBits & 0x3) << 1;
  1007. }
  1008. else
  1009. {
  1010. r |= (modeBits & 0xC) >> 1;
  1011. }
  1012. Debug.Assert(2 <= r && r <= 7);
  1013. // Determine width & height
  1014. switch (layout)
  1015. {
  1016. case 0:
  1017. {
  1018. int a = (modeBits >> 5) & 0x3;
  1019. int b = (modeBits >> 7) & 0x3;
  1020. texelParams.Width = b + 4;
  1021. texelParams.Height = a + 2;
  1022. break;
  1023. }
  1024. case 1:
  1025. {
  1026. int a = (modeBits >> 5) & 0x3;
  1027. int b = (modeBits >> 7) & 0x3;
  1028. texelParams.Width = b + 8;
  1029. texelParams.Height = a + 2;
  1030. break;
  1031. }
  1032. case 2:
  1033. {
  1034. int a = (modeBits >> 5) & 0x3;
  1035. int b = (modeBits >> 7) & 0x3;
  1036. texelParams.Width = a + 2;
  1037. texelParams.Height = b + 8;
  1038. break;
  1039. }
  1040. case 3:
  1041. {
  1042. int a = (modeBits >> 5) & 0x3;
  1043. int b = (modeBits >> 7) & 0x1;
  1044. texelParams.Width = a + 2;
  1045. texelParams.Height = b + 6;
  1046. break;
  1047. }
  1048. case 4:
  1049. {
  1050. int a = (modeBits >> 5) & 0x3;
  1051. int b = (modeBits >> 7) & 0x1;
  1052. texelParams.Width = b + 2;
  1053. texelParams.Height = a + 2;
  1054. break;
  1055. }
  1056. case 5:
  1057. {
  1058. int a = (modeBits >> 5) & 0x3;
  1059. texelParams.Width = 12;
  1060. texelParams.Height = a + 2;
  1061. break;
  1062. }
  1063. case 6:
  1064. {
  1065. int a = (modeBits >> 5) & 0x3;
  1066. texelParams.Width = a + 2;
  1067. texelParams.Height = 12;
  1068. break;
  1069. }
  1070. case 7:
  1071. {
  1072. texelParams.Width = 6;
  1073. texelParams.Height = 10;
  1074. break;
  1075. }
  1076. case 8:
  1077. {
  1078. texelParams.Width = 10;
  1079. texelParams.Height = 6;
  1080. break;
  1081. }
  1082. case 9:
  1083. {
  1084. int a = (modeBits >> 5) & 0x3;
  1085. int b = (modeBits >> 9) & 0x3;
  1086. texelParams.Width = a + 6;
  1087. texelParams.Height = b + 6;
  1088. break;
  1089. }
  1090. default:
  1091. // Don't know this layout...
  1092. texelParams.Error = true;
  1093. break;
  1094. }
  1095. // Determine whether or not we're using dual planes
  1096. // and/or high precision layouts.
  1097. bool d = ((layout != 9) && ((modeBits & 0x400) != 0));
  1098. bool h = (layout != 9) && ((modeBits & 0x200) != 0);
  1099. if (h)
  1100. {
  1101. int[] maxWeights = { 9, 11, 15, 19, 23, 31 };
  1102. texelParams.MaxWeight = maxWeights[r - 2];
  1103. }
  1104. else
  1105. {
  1106. int[] maxWeights = { 1, 2, 3, 4, 5, 7 };
  1107. texelParams.MaxWeight = maxWeights[r - 2];
  1108. }
  1109. texelParams.DualPlane = d;
  1110. return texelParams;
  1111. }
  1112. }
  1113. }