AstcDecoder.cs 48 KB

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