basis_transcode.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. /* -*- tab-width: 4; -*- */
  2. /* vi: set sw=2 ts=4 expandtab: */
  3. /*
  4. * Copyright 2019-2020 The Khronos Group Inc.
  5. * SPDX-License-Identifier: Apache-2.0
  6. */
  7. /**
  8. * @internal
  9. * @file basis_transcode.cpp
  10. * @~English
  11. *
  12. * @brief Functions for transcoding Basis Universal BasisLZ/ETC1S and UASTC textures.
  13. *
  14. * Two worlds collide here too. More uglyness!
  15. *
  16. * @author Mark Callow, www.edgewise-consulting.com
  17. */
  18. #include <inttypes.h>
  19. #include <stdio.h>
  20. #include <KHR/khr_df.h>
  21. #include "dfdutils/dfd.h"
  22. #include "ktx.h"
  23. #include "ktxint.h"
  24. #include "texture2.h"
  25. #include "vkformat_enum.h"
  26. #include "vk_format.h"
  27. #include "basis_sgd.h"
  28. #include "transcoder/basisu_file_headers.h"
  29. #include "transcoder/basisu_transcoder.h"
  30. #include "transcoder/basisu_transcoder_internal.h"
  31. #undef DECLARE_PRIVATE
  32. #undef DECLARE_PROTECTED
  33. #define DECLARE_PRIVATE(n,t2) ktxTexture2_private& n = *(t2->_private)
  34. #define DECLARE_PROTECTED(n,t2) ktxTexture_protected& n = *(t2->_protected)
  35. using namespace basisu;
  36. using namespace basist;
  37. inline bool isPow2(uint32_t x) { return x && ((x & (x - 1U)) == 0U); }
  38. inline bool isPow2(uint64_t x) { return x && ((x & (x - 1U)) == 0U); }
  39. KTX_error_code
  40. ktxTexture2_transcodeLzEtc1s(ktxTexture2* This,
  41. alpha_content_e alphaContent,
  42. ktxTexture2* prototype,
  43. ktx_transcode_fmt_e outputFormat,
  44. ktx_transcode_flags transcodeFlags);
  45. KTX_error_code
  46. ktxTexture2_transcodeUastc(ktxTexture2* This,
  47. alpha_content_e alphaContent,
  48. ktxTexture2* prototype,
  49. ktx_transcode_fmt_e outputFormat,
  50. ktx_transcode_flags transcodeFlags);
  51. /**
  52. * @memberof ktxTexture2
  53. * @ingroup reader
  54. * @~English
  55. * @brief Transcode a KTX2 texture with BasisLZ/ETC1S or UASTC images.
  56. *
  57. * If the texture contains BasisLZ supercompressed images, Inflates them from
  58. * back to ETC1S then transcodes them to the specified block-compressed
  59. * format. If the texture contains UASTC images, inflates them, if they have been
  60. * supercompressed with zstd, then transcodes then to the specified format, The
  61. * transcoded images replace the original images and the texture's fields including
  62. * the DFD are modified to reflect the new format.
  63. *
  64. * These types of textures must be transcoded to a desired target
  65. * block-compressed format before they can be uploaded to a GPU via a
  66. * graphics API.
  67. *
  68. * The following block compressed transcode targets are available: @c KTX_TTF_ETC1_RGB,
  69. * @c KTX_TTF_ETC2_RGBA, @c KTX_TTF_BC1_RGB, @c KTX_TTF_BC3_RGBA,
  70. * @c KTX_TTF_BC4_R, @c KTX_TTF_BC5_RG, @c KTX_TTF_BC7_RGBA,
  71. * @c @c KTX_TTF_PVRTC1_4_RGB, @c KTX_TTF_PVRTC1_4_RGBA,
  72. * @c KTX_TTF_PVRTC2_4_RGB, @c KTX_TTF_PVRTC2_4_RGBA, @c KTX_TTF_ASTC_4x4_RGBA,
  73. * @c KTX_TTF_ETC2_EAC_R11, @c KTX_TTF_ETC2_EAC_RG11, @c KTX_TTF_ETC and
  74. * @c KTX_TTF_BC1_OR_3.
  75. *
  76. * @c KTX_TTF_ETC automatically selects between @c KTX_TTF_ETC1_RGB and
  77. * @c KTX_TTF_ETC2_RGBA according to whether an alpha channel is available. @c KTX_TTF_BC1_OR_3
  78. * does likewise between @c KTX_TTF_BC1_RGB and @c KTX_TTF_BC3_RGBA. Note that if
  79. * @c KTX_TTF_PVRTC1_4_RGBA or @c KTX_TTF_PVRTC2_4_RGBA is specified and there is no alpha
  80. * channel @c KTX_TTF_PVRTC1_4_RGB or @c KTX_TTF_PVRTC2_4_RGB respectively will be selected.
  81. *
  82. * Transcoding to ATC & FXT1 formats is not supported by libktx as there
  83. * are no equivalent Vulkan formats.
  84. *
  85. * The following uncompressed transcode targets are also available: @c KTX_TTF_RGBA32,
  86. * @c KTX_TTF_RGB565, KTX_TTF_BGR565 and KTX_TTF_RGBA4444.
  87. *
  88. * The following @p transcodeFlags are available.
  89. *
  90. * @sa ktxtexture2_CompressBasis().
  91. *
  92. * @param[in] This pointer to the ktxTexture2 object of interest.
  93. * @param[in] outputFormat a value from the ktx_texture_transcode_fmt_e enum
  94. * specifying the target format.
  95. * @param[in] transcodeFlags bitfield of flags modifying the transcode
  96. * operation. @sa ktx_texture_decode_flags_e.
  97. *
  98. * @return KTX_SUCCESS on success, other KTX_* enum values on error.
  99. *
  100. * @exception KTX_FILE_DATA_ERROR
  101. * Supercompression global data is corrupted.
  102. * @exception KTX_INVALID_OPERATION
  103. * The texture's format is not transcodable (not
  104. * ETC1S/BasisLZ or UASTC).
  105. * @exception KTX_INVALID_OPERATION
  106. * Supercompression global data is missing, i.e.,
  107. * the texture object is invalid.
  108. * @exception KTX_INVALID_OPERATION
  109. * Image data is missing, i.e., the texture object
  110. * is invalid.
  111. * @exception KTX_INVALID_OPERATION
  112. * @p outputFormat is PVRTC1 but the texture does
  113. * does not have power-of-two dimensions.
  114. * @exception KTX_INVALID_VALUE @p outputFormat is invalid.
  115. * @exception KTX_TRANSCODE_FAILED
  116. * Something went wrong during transcoding.
  117. * @exception KTX_UNSUPPORTED_FEATURE
  118. * KTX_TF_PVRTC_DECODE_TO_NEXT_POW2 was requested
  119. * or the specified transcode target has not been
  120. * included in the library being used.
  121. * @exception KTX_OUT_OF_MEMORY Not enough memory to carry out transcoding.
  122. */
  123. KTX_error_code
  124. ktxTexture2_TranscodeBasis(ktxTexture2* This,
  125. ktx_transcode_fmt_e outputFormat,
  126. ktx_transcode_flags transcodeFlags)
  127. {
  128. uint32_t* BDB = This->pDfd + 1;
  129. khr_df_model_e colorModel = (khr_df_model_e)KHR_DFDVAL(BDB, MODEL);
  130. if (colorModel != KHR_DF_MODEL_UASTC
  131. // Constructor has checked color model matches BASIS_LZ.
  132. && This->supercompressionScheme != KTX_SS_BASIS_LZ)
  133. {
  134. return KTX_INVALID_OPERATION; // Not in a transcodable format.
  135. }
  136. DECLARE_PRIVATE(priv, This);
  137. if (This->supercompressionScheme == KTX_SS_BASIS_LZ) {
  138. if (!priv._supercompressionGlobalData || priv._sgdByteLength == 0)
  139. return KTX_INVALID_OPERATION;
  140. }
  141. if (transcodeFlags & KTX_TF_PVRTC_DECODE_TO_NEXT_POW2) {
  142. debug_printf("ktxTexture_TranscodeBasis: KTX_TF_PVRTC_DECODE_TO_NEXT_POW2 currently unsupported\n");
  143. return KTX_UNSUPPORTED_FEATURE;
  144. }
  145. if (outputFormat == KTX_TTF_PVRTC1_4_RGB
  146. || outputFormat == KTX_TTF_PVRTC1_4_RGBA) {
  147. if ((!isPow2(This->baseWidth)) || (!isPow2(This->baseHeight))) {
  148. debug_printf("ktxTexture_TranscodeBasis: PVRTC1 only supports power of 2 dimensions\n");
  149. return KTX_INVALID_OPERATION;
  150. }
  151. }
  152. const bool srgb = (KHR_DFDVAL(BDB, TRANSFER) == KHR_DF_TRANSFER_SRGB);
  153. alpha_content_e alphaContent = eNone;
  154. if (colorModel == KHR_DF_MODEL_ETC1S) {
  155. if (KHR_DFDSAMPLECOUNT(BDB) == 2) {
  156. uint32_t channelId = KHR_DFDSVAL(BDB, 1, CHANNELID);
  157. if (channelId == KHR_DF_CHANNEL_ETC1S_AAA) {
  158. alphaContent = eAlpha;
  159. } else if (channelId == KHR_DF_CHANNEL_ETC1S_GGG){
  160. alphaContent = eGreen;
  161. } else {
  162. return KTX_FILE_DATA_ERROR;
  163. }
  164. }
  165. } else {
  166. uint32_t channelId = KHR_DFDSVAL(BDB, 0, CHANNELID);
  167. if (channelId == KHR_DF_CHANNEL_UASTC_RGBA)
  168. alphaContent = eAlpha;
  169. else if (channelId == KHR_DF_CHANNEL_UASTC_RRRG)
  170. alphaContent = eGreen;
  171. }
  172. VkFormat vkFormat;
  173. // Do some format mapping.
  174. switch (outputFormat) {
  175. case KTX_TTF_BC1_OR_3:
  176. outputFormat = alphaContent != eNone ? KTX_TTF_BC3_RGBA
  177. : KTX_TTF_BC1_RGB;
  178. break;
  179. case KTX_TTF_ETC:
  180. outputFormat = alphaContent != eNone ? KTX_TTF_ETC2_RGBA
  181. : KTX_TTF_ETC1_RGB;
  182. break;
  183. case KTX_TTF_PVRTC1_4_RGBA:
  184. // This transcoder does not write opaque alpha blocks.
  185. outputFormat = alphaContent != eNone ? KTX_TTF_PVRTC1_4_RGBA
  186. : KTX_TTF_PVRTC1_4_RGB;
  187. break;
  188. case KTX_TTF_PVRTC2_4_RGBA:
  189. // This transcoder does not write opaque alpha blocks.
  190. outputFormat = alphaContent != eNone ? KTX_TTF_PVRTC2_4_RGBA
  191. : KTX_TTF_PVRTC2_4_RGB;
  192. break;
  193. default:
  194. /*NOP*/;
  195. }
  196. switch (outputFormat) {
  197. case KTX_TTF_ETC1_RGB:
  198. vkFormat = srgb ? VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK
  199. : VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;
  200. break;
  201. case KTX_TTF_ETC2_RGBA:
  202. vkFormat = srgb ? VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK
  203. : VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK;
  204. break;
  205. case KTX_TTF_ETC2_EAC_R11:
  206. vkFormat = VK_FORMAT_EAC_R11_UNORM_BLOCK;
  207. break;
  208. case KTX_TTF_ETC2_EAC_RG11:
  209. vkFormat = VK_FORMAT_EAC_R11G11_UNORM_BLOCK;
  210. break;
  211. case KTX_TTF_BC1_RGB:
  212. // Transcoding doesn't support BC1 alpha.
  213. vkFormat = srgb ? VK_FORMAT_BC1_RGB_SRGB_BLOCK
  214. : VK_FORMAT_BC1_RGB_UNORM_BLOCK;
  215. break;
  216. case KTX_TTF_BC3_RGBA:
  217. vkFormat = srgb ? VK_FORMAT_BC3_SRGB_BLOCK
  218. : VK_FORMAT_BC3_UNORM_BLOCK;
  219. break;
  220. case KTX_TTF_BC4_R:
  221. vkFormat = VK_FORMAT_BC4_UNORM_BLOCK;
  222. break;
  223. case KTX_TTF_BC5_RG:
  224. vkFormat = VK_FORMAT_BC5_UNORM_BLOCK;
  225. break;
  226. case KTX_TTF_PVRTC1_4_RGB:
  227. case KTX_TTF_PVRTC1_4_RGBA:
  228. vkFormat = srgb ? VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG
  229. : VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG;
  230. break;
  231. case KTX_TTF_PVRTC2_4_RGB:
  232. case KTX_TTF_PVRTC2_4_RGBA:
  233. vkFormat = srgb ? VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG
  234. : VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG;
  235. break;
  236. case KTX_TTF_BC7_RGBA:
  237. vkFormat = srgb ? VK_FORMAT_BC7_SRGB_BLOCK
  238. : VK_FORMAT_BC7_UNORM_BLOCK;
  239. break;
  240. case KTX_TTF_ASTC_4x4_RGBA:
  241. vkFormat = srgb ? VK_FORMAT_ASTC_4x4_SRGB_BLOCK
  242. : VK_FORMAT_ASTC_4x4_UNORM_BLOCK;
  243. break;
  244. case KTX_TTF_RGB565:
  245. vkFormat = VK_FORMAT_R5G6B5_UNORM_PACK16;
  246. break;
  247. case KTX_TTF_BGR565:
  248. vkFormat = VK_FORMAT_B5G6R5_UNORM_PACK16;
  249. break;
  250. case KTX_TTF_RGBA4444:
  251. vkFormat = VK_FORMAT_R4G4B4A4_UNORM_PACK16;
  252. break;
  253. case KTX_TTF_RGBA32:
  254. vkFormat = srgb ? VK_FORMAT_R8G8B8A8_SRGB
  255. : VK_FORMAT_R8G8B8A8_UNORM;
  256. break;
  257. default:
  258. return KTX_INVALID_VALUE;
  259. }
  260. basis_tex_format textureFormat;
  261. if (colorModel == KHR_DF_MODEL_UASTC)
  262. textureFormat = basis_tex_format::cUASTC4x4;
  263. else
  264. textureFormat = basis_tex_format::cETC1S;
  265. if (!basis_is_format_supported((transcoder_texture_format)outputFormat,
  266. textureFormat)) {
  267. return KTX_UNSUPPORTED_FEATURE;
  268. }
  269. // Create a prototype texture to use for calculating sizes in the target
  270. // format and, as useful side effects, provide us with a properly sized
  271. // data allocation and the DFD for the target format.
  272. ktxTextureCreateInfo createInfo;
  273. createInfo.glInternalformat = 0;
  274. createInfo.vkFormat = vkFormat;
  275. createInfo.baseWidth = This->baseWidth;
  276. createInfo.baseHeight = This->baseHeight;
  277. createInfo.baseDepth = This->baseDepth;
  278. createInfo.generateMipmaps = This->generateMipmaps;
  279. createInfo.isArray = This->isArray;
  280. createInfo.numDimensions = This->numDimensions;
  281. createInfo.numFaces = This->numFaces;
  282. createInfo.numLayers = This->numLayers;
  283. createInfo.numLevels = This->numLevels;
  284. createInfo.pDfd = nullptr;
  285. KTX_error_code result;
  286. ktxTexture2* prototype;
  287. result = ktxTexture2_Create(&createInfo, KTX_TEXTURE_CREATE_ALLOC_STORAGE,
  288. &prototype);
  289. if (result != KTX_SUCCESS) {
  290. assert(result == KTX_OUT_OF_MEMORY); // The only run time error
  291. return result;
  292. }
  293. if (!This->pData) {
  294. if (ktxTexture_isActiveStream((ktxTexture*)This)) {
  295. // Load pending. Complete it.
  296. result = ktxTexture2_LoadImageData(This, NULL, 0);
  297. if (result != KTX_SUCCESS)
  298. {
  299. ktxTexture2_Destroy(prototype);
  300. return result;
  301. }
  302. } else {
  303. // No data to transcode.
  304. ktxTexture2_Destroy(prototype);
  305. return KTX_INVALID_OPERATION;
  306. }
  307. }
  308. // Transcoder global initialization. Requires ~9 milliseconds when compiled
  309. // and executed natively on a Core i7 2.2 GHz. If this is too slow, the
  310. // tables it computes can easily be moved to be compiled in.
  311. static bool transcoderInitialized;
  312. if (!transcoderInitialized) {
  313. basisu_transcoder_init();
  314. transcoderInitialized = true;
  315. }
  316. if (textureFormat == basis_tex_format::cETC1S) {
  317. result = ktxTexture2_transcodeLzEtc1s(This, alphaContent,
  318. prototype, outputFormat,
  319. transcodeFlags);
  320. } else {
  321. result = ktxTexture2_transcodeUastc(This, alphaContent,
  322. prototype, outputFormat,
  323. transcodeFlags);
  324. }
  325. if (result == KTX_SUCCESS) {
  326. // Fix up the current texture
  327. DECLARE_PROTECTED(thisPrtctd, This);
  328. DECLARE_PRIVATE(protoPriv, prototype);
  329. DECLARE_PROTECTED(protoPrtctd, prototype);
  330. memcpy(&thisPrtctd._formatSize, &protoPrtctd._formatSize,
  331. sizeof(ktxFormatSize));
  332. This->vkFormat = vkFormat;
  333. This->isCompressed = prototype->isCompressed;
  334. This->supercompressionScheme = KTX_SS_NONE;
  335. priv._requiredLevelAlignment = protoPriv._requiredLevelAlignment;
  336. // Copy the levelIndex from the prototype to This.
  337. memcpy(priv._levelIndex, protoPriv._levelIndex,
  338. This->numLevels * sizeof(ktxLevelIndexEntry));
  339. // Move the DFD and data from the prototype to This.
  340. free(This->pDfd);
  341. This->pDfd = prototype->pDfd;
  342. prototype->pDfd = 0;
  343. free(This->pData);
  344. This->pData = prototype->pData;
  345. This->dataSize = prototype->dataSize;
  346. prototype->pData = 0;
  347. prototype->dataSize = 0;
  348. }
  349. ktxTexture2_Destroy(prototype);
  350. return result;
  351. }
  352. /**
  353. * @memberof ktxTexture2 @private
  354. * @ingroup reader
  355. * @~English
  356. * @brief Transcode a KTX2 texture with BasisLZ supercompressed ETC1S images.
  357. *
  358. * Inflates the images from BasisLZ supercompression back to ETC1S
  359. * then transcodes them to the specified block-compressed format. The
  360. * transcoded images replace the original images and the texture's fields
  361. * including the DFD are modified to reflect the new format.
  362. *
  363. * BasisLZ supercompressed textures must be transcoded to a desired target
  364. * block-compressed format before they can be uploaded to a GPU via a graphics
  365. * API.
  366. *
  367. * The following block compressed transcode targets are available: @c KTX_TTF_ETC1_RGB,
  368. * @c KTX_TTF_ETC2_RGBA, @c KTX_TTF_BC1_RGB, @c KTX_TTF_BC3_RGBA,
  369. * @c KTX_TTF_BC4_R, @c KTX_TTF_BC5_RG, @c KTX_TTF_BC7_RGBA,
  370. * @c @c KTX_TTF_PVRTC1_4_RGB, @c KTX_TTF_PVRTC1_4_RGBA,
  371. * @c KTX_TTF_PVRTC2_4_RGB, @c KTX_TTF_PVRTC2_4_RGBA, @c KTX_TTF_ASTC_4x4_RGBA,
  372. * @c KTX_TTF_ETC2_EAC_R11, @c KTX_TTF_ETC2_EAC_RG11, @c KTX_TTF_ETC and
  373. * @c KTX_TTF_BC1_OR_3.
  374. *
  375. * @c KTX_TTF_ETC automatically selects between @c KTX_TTF_ETC1_RGB and
  376. * @c KTX_TTF_ETC2_RGBA according to whether an alpha channel is available. @c KTX_TTF_BC1_OR_3
  377. * does likewise between @c KTX_TTF_BC1_RGB and @c KTX_TTF_BC3_RGBA. Note that if
  378. * @c KTX_TTF_PVRTC1_4_RGBA or @c KTX_TTF_PVRTC2_4_RGBA is specified and there is no alpha
  379. * channel @c KTX_TTF_PVRTC1_4_RGB or @c KTX_TTF_PVRTC2_4_RGB respectively will be selected.
  380. *
  381. * ATC & FXT1 formats are not supported by KTX2 & libktx as there are no equivalent Vulkan formats.
  382. *
  383. * The following uncompressed transcode targets are also available: @c KTX_TTF_RGBA32,
  384. * @c KTX_TTF_RGB565, KTX_TTF_BGR565 and KTX_TTF_RGBA4444.
  385. *
  386. * The following @p transcodeFlags are available.
  387. *
  388. * @sa ktxtexture2_CompressBasis().
  389. *
  390. * @param[in] This pointer to the ktxTexture2 object of interest.
  391. * @param[in] outputFormat a value from the ktx_texture_transcode_fmt_e enum
  392. * specifying the target format.
  393. * @param[in] transcodeFlags bitfield of flags modifying the transcode
  394. * operation. @sa ktx_texture_decode_flags_e.
  395. *
  396. * @return KTX_SUCCESS on success, other KTX_* enum values on error.
  397. *
  398. * @exception KTX_FILE_DATA_ERROR
  399. * Supercompression global data is corrupted.
  400. * @exception KTX_INVALID_OPERATION
  401. * The texture's format is not transcodable (not
  402. * ETC1S/BasisLZ or UASTC).
  403. * @exception KTX_INVALID_OPERATION
  404. * Supercompression global data is missing, i.e.,
  405. * the texture object is invalid.
  406. * @exception KTX_INVALID_OPERATION
  407. * Image data is missing, i.e., the texture object
  408. * is invalid.
  409. * @exception KTX_INVALID_OPERATION
  410. * @p outputFormat is PVRTC1 but the texture does
  411. * does not have power-of-two dimensions.
  412. * @exception KTX_INVALID_VALUE @p outputFormat is invalid.
  413. * @exception KTX_TRANSCODE_FAILED
  414. * Something went wrong during transcoding. The
  415. * texture object will be corrupted.
  416. * @exception KTX_UNSUPPORTED_FEATURE
  417. * KTX_TF_PVRTC_DECODE_TO_NEXT_POW2 was requested
  418. * or the specified transcode target has not been
  419. * included in the library being used.
  420. * @exception KTX_OUT_OF_MEMORY Not enough memory to carry out transcoding.
  421. */
  422. KTX_error_code
  423. ktxTexture2_transcodeLzEtc1s(ktxTexture2* This,
  424. alpha_content_e alphaContent,
  425. ktxTexture2* prototype,
  426. ktx_transcode_fmt_e outputFormat,
  427. ktx_transcode_flags transcodeFlags)
  428. {
  429. DECLARE_PRIVATE(priv, This);
  430. DECLARE_PRIVATE(protoPriv, prototype);
  431. KTX_error_code result = KTX_SUCCESS;
  432. assert(This->supercompressionScheme == KTX_SS_BASIS_LZ);
  433. uint8_t* bgd = priv._supercompressionGlobalData;
  434. ktxBasisLzGlobalHeader& bgdh = *reinterpret_cast<ktxBasisLzGlobalHeader*>(bgd);
  435. if (!(bgdh.endpointsByteLength && bgdh.selectorsByteLength && bgdh.tablesByteLength)) {
  436. debug_printf("ktxTexture_TranscodeBasis: missing endpoints, selectors or tables");
  437. return KTX_FILE_DATA_ERROR;
  438. }
  439. // Compute some helpful numbers.
  440. //
  441. // firstImages contains the indices of the first images for each level to
  442. // ease finding the correct slice description when iterating from smallest
  443. // level to largest or when randomly accessing them (t.b.c). The last array
  444. // entry contains the total number of images, for calculating the offsets
  445. // of the endpoints, etc.
  446. uint32_t* firstImages = new uint32_t[This->numLevels+1];
  447. // Temporary invariant value
  448. uint32_t layersFaces = This->numLayers * This->numFaces;
  449. firstImages[0] = 0;
  450. for (uint32_t level = 1; level <= This->numLevels; level++) {
  451. // NOTA BENE: numFaces * depth is only reasonable because they can't
  452. // both be > 1. I.e there are no 3d cubemaps.
  453. firstImages[level] = firstImages[level - 1]
  454. + layersFaces * MAX(This->baseDepth >> (level - 1), 1);
  455. }
  456. uint32_t& imageCount = firstImages[This->numLevels];
  457. if (BGD_TABLES_ADDR(0, bgdh, imageCount) + bgdh.tablesByteLength > priv._sgdByteLength) {
  458. return KTX_FILE_DATA_ERROR;
  459. }
  460. // FIXME: Do more validation.
  461. // Prepare low-level transcoder for transcoding slices.
  462. basist::basisu_lowlevel_etc1s_transcoder bit;
  463. // basisu_transcoder_state is used to find the previous frame when
  464. // decoding a video P-Frame. It tracks the previous frame for each mip
  465. // level. For cube map array textures we need to find the previous frame
  466. // for each face so we a state per face. Although providing this is only
  467. // needed for video, it is easier to always pass our own.
  468. std::vector<basisu_transcoder_state> xcoderStates;
  469. xcoderStates.resize(This->isVideo ? This->numFaces : 1);
  470. bit.decode_palettes(bgdh.endpointCount, BGD_ENDPOINTS_ADDR(bgd, imageCount),
  471. bgdh.endpointsByteLength,
  472. bgdh.selectorCount, BGD_SELECTORS_ADDR(bgd, bgdh, imageCount),
  473. bgdh.selectorsByteLength);
  474. bit.decode_tables(BGD_TABLES_ADDR(bgd, bgdh, imageCount),
  475. bgdh.tablesByteLength);
  476. // Find matching VkFormat and calculate output sizes.
  477. const bool isVideo = This->isVideo;
  478. ktx_uint8_t* pXcodedData = prototype->pData;
  479. // Inconveniently, the output buffer size parameter of transcode_image
  480. // has to be in pixels for uncompressed output and in blocks for
  481. // compressed output. The only reason for humouring the API is so
  482. // its buffer size tests provide a real check. An alternative is to
  483. // always provide the size in bytes which will always pass.
  484. ktx_uint32_t outputBlockByteLength
  485. = prototype->_protected->_formatSize.blockSizeInBits / 8;
  486. ktx_size_t xcodedDataLength
  487. = prototype->dataSize / outputBlockByteLength;
  488. ktxLevelIndexEntry* protoLevelIndex;
  489. uint64_t levelOffsetWrite;
  490. const ktxBasisLzEtc1sImageDesc* imageDescs = BGD_ETC1S_IMAGE_DESCS(bgd);
  491. // Finally we're ready to transcode the slices.
  492. // FIXME: Iframe flag needs to be queryable by the application. In Basis
  493. // the app can query file_info and image_info from the transcoder which
  494. // returns a structure with lots of info about the image.
  495. protoLevelIndex = protoPriv._levelIndex;
  496. levelOffsetWrite = 0;
  497. for (int32_t level = This->numLevels - 1; level >= 0; level--) {
  498. uint64_t levelOffset = ktxTexture2_levelDataOffset(This, level);
  499. uint64_t writeOffset = levelOffsetWrite;
  500. uint64_t writeOffsetBlocks = levelOffsetWrite / outputBlockByteLength;
  501. uint32_t levelWidth = MAX(1, This->baseWidth >> level);
  502. uint32_t levelHeight = MAX(1, This->baseHeight >> level);
  503. // ETC1S texel block dimensions
  504. const uint32_t bw = 4, bh = 4;
  505. uint32_t levelBlocksX = (levelWidth + (bw - 1)) / bw;
  506. uint32_t levelBlocksY = (levelHeight + (bh - 1)) / bh;
  507. uint32_t depth = MAX(1, This->baseDepth >> level);
  508. //uint32_t faceSlices = This->numFaces == 1 ? depth : This->numFaces;
  509. uint32_t faceSlices = This->numFaces * depth;
  510. uint32_t numImages = This->numLayers * faceSlices;
  511. uint32_t image = firstImages[level];
  512. uint32_t endImage = image + numImages;
  513. ktx_size_t levelImageSizeOut, levelSizeOut;
  514. uint32_t stateIndex = 0;
  515. levelSizeOut = 0;
  516. // FIXME: Figure out a way to get the size out of the transcoder.
  517. levelImageSizeOut = ktxTexture2_GetImageSize(prototype, level);
  518. for (; image < endImage; image++) {
  519. const ktxBasisLzEtc1sImageDesc& imageDesc = imageDescs[image];
  520. basisu_transcoder_state& xcoderState = xcoderStates[stateIndex];
  521. // We have face0 [face1 ...] within each layer. Use `stateIndex`
  522. // rather than a double loop of layers and faceSlices as this
  523. // works for 3d texture and non-array cube maps as well as
  524. // cube map arrays without special casing.
  525. if (++stateIndex == xcoderStates.size())
  526. stateIndex = 0;
  527. if (alphaContent != eNone)
  528. {
  529. // The slice descriptions should have alpha information.
  530. if (imageDesc.alphaSliceByteOffset == 0
  531. || imageDesc.alphaSliceByteLength == 0)
  532. return KTX_FILE_DATA_ERROR;
  533. }
  534. bool status;
  535. status = bit.transcode_image(
  536. (transcoder_texture_format)outputFormat,
  537. pXcodedData + writeOffset,
  538. (uint32_t)(xcodedDataLength - writeOffsetBlocks),
  539. This->pData,
  540. (uint32_t)This->dataSize,
  541. levelBlocksX,
  542. levelBlocksY,
  543. levelWidth,
  544. levelHeight,
  545. level,
  546. (uint32_t)(levelOffset + imageDesc.rgbSliceByteOffset),
  547. imageDesc.rgbSliceByteLength,
  548. (uint32_t)(levelOffset + imageDesc.alphaSliceByteOffset),
  549. imageDesc.alphaSliceByteLength,
  550. transcodeFlags,
  551. alphaContent != eNone,
  552. isVideo,
  553. // Our P-Frame flag is in the same bit as
  554. // cSliceDescFlagsFrameIsIFrame. We have to
  555. // invert it to make it an I-Frame flag.
  556. //
  557. // API currently doesn't have any way to pass
  558. // the I-Frame flag.
  559. //imageDesc.imageFlags ^ cSliceDescFlagsFrameIsIFrame,
  560. 0, // output_row_pitch_in_blocks_or_pixels
  561. &xcoderState,
  562. 0 // output_rows_in_pixels
  563. );
  564. if (!status) {
  565. result = KTX_TRANSCODE_FAILED;
  566. goto cleanup;
  567. }
  568. writeOffset += levelImageSizeOut;
  569. levelSizeOut += levelImageSizeOut;
  570. } // end images loop
  571. protoLevelIndex[level].byteOffset = levelOffsetWrite;
  572. protoLevelIndex[level].byteLength = levelSizeOut;
  573. protoLevelIndex[level].uncompressedByteLength = levelSizeOut;
  574. levelOffsetWrite += levelSizeOut;
  575. assert(levelOffsetWrite == writeOffset);
  576. // In case of transcoding to uncompressed.
  577. levelOffsetWrite = _KTX_PADN(protoPriv._requiredLevelAlignment,
  578. levelOffsetWrite);
  579. } // level loop
  580. result = KTX_SUCCESS;
  581. cleanup:
  582. delete[] firstImages;
  583. return result;
  584. }
  585. KTX_error_code
  586. ktxTexture2_transcodeUastc(ktxTexture2* This,
  587. alpha_content_e alphaContent,
  588. ktxTexture2* prototype,
  589. ktx_transcode_fmt_e outputFormat,
  590. ktx_transcode_flags transcodeFlags)
  591. {
  592. assert(This->supercompressionScheme != KTX_SS_BASIS_LZ);
  593. ktx_uint8_t* pXcodedData = prototype->pData;
  594. ktx_uint32_t outputBlockByteLength
  595. = prototype->_protected->_formatSize.blockSizeInBits / 8;
  596. ktx_size_t xcodedDataLength
  597. = prototype->dataSize / outputBlockByteLength;
  598. DECLARE_PRIVATE(protoPriv, prototype);
  599. ktxLevelIndexEntry* protoLevelIndex = protoPriv._levelIndex;
  600. ktx_size_t levelOffsetWrite = 0;
  601. basisu_lowlevel_uastc_transcoder uit;
  602. // See comment on same declaration in transcodeEtc1s.
  603. std::vector<basisu_transcoder_state> xcoderStates;
  604. xcoderStates.resize(This->isVideo ? This->numFaces : 1);
  605. for (ktx_int32_t level = This->numLevels - 1; level >= 0; level--)
  606. {
  607. ktx_uint32_t depth;
  608. uint64_t writeOffset = levelOffsetWrite;
  609. uint64_t writeOffsetBlocks = levelOffsetWrite / outputBlockByteLength;
  610. ktx_size_t levelImageSizeIn, levelImageOffsetIn;
  611. ktx_size_t levelImageSizeOut, levelSizeOut;
  612. ktx_uint32_t levelImageCount;
  613. uint32_t levelWidth = MAX(1, This->baseWidth >> level);
  614. uint32_t levelHeight = MAX(1, This->baseHeight >> level);
  615. // UASTC texel block dimensions
  616. const uint32_t bw = 4, bh = 4;
  617. uint32_t levelBlocksX = (levelWidth + (bw - 1)) / bw;
  618. uint32_t levelBlocksY = (levelHeight + (bh - 1)) / bh;
  619. uint32_t stateIndex = 0;
  620. depth = MAX(1, This->baseDepth >> level);
  621. levelImageCount = This->numLayers * This->numFaces * depth;
  622. levelImageSizeIn = ktxTexture_calcImageSize(ktxTexture(This), level,
  623. KTX_FORMAT_VERSION_TWO);
  624. levelImageSizeOut = ktxTexture_calcImageSize(ktxTexture(prototype),
  625. level,
  626. KTX_FORMAT_VERSION_TWO);
  627. levelImageOffsetIn = ktxTexture2_levelDataOffset(This, level);
  628. levelSizeOut = 0;
  629. bool status;
  630. for (uint32_t image = 0; image < levelImageCount; image++) {
  631. basisu_transcoder_state& xcoderState = xcoderStates[stateIndex];
  632. // See comment before same lines in transcodeEtc1s.
  633. if (++stateIndex == xcoderStates.size())
  634. stateIndex = 0;
  635. status = uit.transcode_image(
  636. (transcoder_texture_format)outputFormat,
  637. pXcodedData + writeOffset,
  638. (uint32_t)(xcodedDataLength - writeOffsetBlocks),
  639. This->pData,
  640. (uint32_t)This->dataSize,
  641. levelBlocksX,
  642. levelBlocksY,
  643. levelWidth,
  644. levelHeight,
  645. level,
  646. (uint32_t)levelImageOffsetIn,
  647. (uint32_t)levelImageSizeIn,
  648. transcodeFlags,
  649. alphaContent != eNone,
  650. This->isVideo, // is_video
  651. //imageDesc.imageFlags ^ cSliceDescFlagsFrameIsIFrame,
  652. 0, // output_row_pitch_in_blocks_or_pixels
  653. &xcoderState, // pState
  654. 0, // output_rows_in_pixels,
  655. -1, // channel0
  656. -1 // channel1
  657. );
  658. if (!status)
  659. return KTX_TRANSCODE_FAILED;
  660. writeOffset += levelImageSizeOut;
  661. levelSizeOut += levelImageSizeOut;
  662. levelImageOffsetIn += levelImageSizeIn;
  663. }
  664. protoLevelIndex[level].byteOffset = levelOffsetWrite;
  665. // writeOffset will be equal to total size of the images in the level.
  666. protoLevelIndex[level].byteLength = levelSizeOut;
  667. protoLevelIndex[level].uncompressedByteLength = levelSizeOut;
  668. levelOffsetWrite += levelSizeOut;
  669. }
  670. // In case of transcoding to uncompressed.
  671. levelOffsetWrite = _KTX_PADN(protoPriv._requiredLevelAlignment,
  672. levelOffsetWrite);
  673. return KTX_SUCCESS;
  674. }