AstcDecoder.cs 48 KB

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