KTX-Software (C, C++)
The Khronos reference implementation of the KTX2 GPU texture container: libktx parses the header, level index, Data Format Descriptor and key/value data, inflates Zstd and ZLIB supercompression, transcodes Basis Universal payloads to a block format the device supports and uploads the result to a Vulkan image, and the ktx tool validates files against the specification; it is the survey's example of a container whose layout is designed for streaming and direct upload, wrapped by a library that loads whole textures and trusts sizes the file declares.
| Field | Value |
|---|---|
| Language | C (built as C11, c_std_11) for the container code (lib/src/texture2.c, vkloader.c, checkheader.c), C++17 for the Basis transcoder glue, the ASTC encoder glue and the ktx tool (tools/ktx/) |
| License | Apache-2.0 for files unique to the repository; bundled dependencies carry their own licences, and external/etcdec/etcdec.cxx is under a non-open-source Ericsson licence (LICENSE.md) |
| Repository | KhronosGroup/KTX-Software |
| Revision read | d9b1dd090f4df6b998bfcd9d6a38b21e94f3c4c6 (October 27, 2026; release notes head 5.0.0-rc2, RELEASE_NOTES.md); CTS submodule pinned at 8465c99944b0e4392fb4de6de47932262e4c2826 |
| Documentation | KTX 2.0 specification (Document Revision 4) · libktx reference · in-tree lib/libktx_mainpage.md · Khronos Data Format Specification |
| Category | GPU and SIMD: GPU texture container, supercompression, Basis Universal transcoding, Vulkan upload |
| Tier | A |
| Last reviewed | November 7, 2026 |
NOTE
Claims marked verified come from two C probes, run against a RelWithDebInfo build (GCC 14.3.0, so _DEBUG is not defined) of the pinned revision in a scratch directory under /tmp: one interposes malloc to record the largest request, the other uploads through ktxTexture2_VkUploadEx to lavapipe (Mesa 25.2.6) with VK_LAYER_KHRONOS_validation (1.4.328 in the first run, 1.4.363 in a rerun with the probes rebuilt by GCC 16.2.0; the results were the same). Inputs were made with ktx create from the repository's tests/resources/input/png/color_grid.png (1024×1024 RGBA8): --format R8G8B8A8_SRGB --generate-mipmap for the uncompressed file, plus --zstd 18 for the Zstd one and --encode basis-lz without mipmaps for the ETC1S one. No performance number is quoted. The CTS submodule is not checked out locally; its README was read at the pinned submodule commit.
Overview
What it solves
A GPU texture is not an image file. It has mip levels, array layers, cube faces and depth slices; its texels may be in a block-compressed format the GPU samples directly; and its bytes must land in a Vulkan image whose VkFormat, extent and level count the file has to state exactly. PNG and JPEG describe none of that. KTX2 is the container that does, and the README positions the software around it (README.md):
"KTX (Khronos Texture) is a lightweight container for textures for OpenGL®, Vulkan® and other GPU APIs. KTX files contain all the parameters needed for texture loading. A single file can contain anything from a simple base-level 2D texture through to a cubemap array texture with mipmaps."
The same paragraph names the two payload families: Basis Universal ("LZ/ETC1S, which combines block-compression and supercompression, and UASTC, a block-compressed format") and "Formats other than LZ/ETC1S", which "can be supercompressed with Zstd and ZLIB". The library "can deflate and inflate zstd and zlib compressed images, can encode and transcode the Basis Universal formats and can encode ASTC formats" (libktx_mainpage.md). The format itself is the subject of the GPU texture compression papers; this page is about the implementation.
Design philosophy
Four commitments recur in the specification and the code.
- The layout serves the upload. The header carries a
VkFormatdirectly; levels are stored smallest first; uncompressed rows are tightly packed ("equivalent to a GL_UNPACK_ALIGNMENT of 1"); and each level starts onlcm(texel_block_size, 4)(spec,levelImages). The ordering exists because "sending smaller mip levels first can be used together with ... appropriate region setting in a VkCmdCopyBufferToImage, to display a low resolution image quickly without waiting for the entire texture data" (spec, Mip Level Array). - Supercompression is per level. "The supercompression scheme is applied independently to each mip level to permit streaming and random access to the levels" (spec,
supercompressionScheme, quoted in the papers). BasisLZ is the exception: its codebooks live in one global block every level needs. - Format semantics come from the Khronos Data Format Descriptor. The
vkFormatfield isVK_FORMAT_UNDEFINEDfor Basis payloads, so the DFD is the authoritative description of colour model, channels, transfer function and primaries, andlibktxcomputes block sizes from it rather than from theVkFormat(ktxFormatSize_initFromDfd). - Length fields are the safety story. The media-type registration says (spec, IANA registration): "Because every item's length is available at its beginning, there is robust defense against corrupted or fraudulent data that might overflow a decoder's buffer", and then, of variable-rate supercompression: "applications must not rely on this and must guard against buffer overflow and ultra large memory allocation." The second sentence is the one this page tests.
How it works
The container
A KTX2 file is a fixed 80-byte little-endian header, a level index, and four optional or required regions addressed by (offset, length) pairs from the header (spec, file structure). libktx mirrors the header in one struct and asserts its size at compile time (ktxint.h):
// lib/src/ktxint.h
typedef struct KTX_header2 {
ktx_uint8_t identifier[12];
ktx_uint32_t vkFormat;
ktx_uint32_t typeSize;
ktx_uint32_t pixelWidth;
ktx_uint32_t pixelHeight;
ktx_uint32_t pixelDepth;
ktx_uint32_t layerCount;
ktx_uint32_t faceCount;
ktx_uint32_t levelCount;
ktx_uint32_t supercompressionScheme;
ktxIndexEntry32 dataFormatDescriptor;
ktxIndexEntry32 keyValueData;
ktxIndexEntry64 supercompressionGlobalData;
} KTX_header2;
/* This will cause compilation to fail if the struct size doesn't match */
typedef int KTX_header2_SIZE_ASSERT [sizeof(KTX_header2) == KTX2_HEADER_SIZE];- Identifier.
«KTX 20»\r\n\x1A\n(KTX2_IDENTIFIER_REF,ktxint.h), modelled on PNG's signature: byte 0 is non-ASCII to catch transfers that clear bit 7, the CR-LF pair and the final LF catch line-ending conversion in either direction, and the control-Z stops display under MS-DOS (spec, identifier). vkFormatandtypeSize. The Vulkan format enum value, or0for Basis payloads.typeSizeis the size of the data type for endian conversion (1 for block formats); the file is little-endian, andlibktxswaps 16, 32 or 64-bit words on big-endian hosts bytypeSize(loadImageDataInt).- Dimensions, layers, faces, levels.
pixelHeight == 0means 1-D,pixelDepth == 0means not 3-D,layerCount == 0means not an array,faceCountis 1 or 6, andlevelCount == 0asks the loader to generate mipmaps.ktxCheckHeader2_derives the dimensionality, rejects cube maps that are not square 2-D, refuses 3-D arrays asKTX_UNSUPPORTED_FEATURE, and boundslevelCountby1 + log2(max dimension)and by 32 (checkheader.c). - Supercompression scheme.
KTX_SS_NONE(0),KTX_SS_BASIS_LZ(1),KTX_SS_ZSTD(2),KTX_SS_ZLIB(3), and at this revisionKTX_SS_UASTC_HDR_6x6_INTERMEDIATE(4) from the draft Revision 5;0x10000–0x1ffffis a vendor range (ktx.h). - Level index.
levelCountentries of threeuint64:byteOffsetfrom the start of the file,byteLengthas stored anduncompressedByteLengthafter inflation (ktxint.h). Index 0 is the largest level, which is stored last in the file. - Data Format Descriptor. A
uint32total size followed by descriptor blocks (spec, DFD);libktxrequires the first block to be a basic descriptor block (descriptor type and vendor 0) at version 1.3 with at least one sample (ktxFormatSize_initFromDfd), and the validator reports the same faults as issues 6008 and 6011 (validation_messages.h). - Key/value data. Length-prefixed, NUL-terminated keys with 4-byte padding:
KTXorientation,KTXswizzle,KTXwriter,KTXanimData,KTXmapRangeand others (ktx.h). - Supercompression global data. Present only for BasisLZ and the UASTC HDR 6×6 intermediate scheme, 8-byte aligned; for BasisLZ it holds the endpoint and selector codebooks, the Huffman tables and one image descriptor per image (spec, BasisLZ global data).
Construction: ktxTexture2_CreateFromMemory
ktxTexture2_CreateFromMemory(bytes, size, createFlags, &texture) wraps the bytes in a read-only memory ktxStream and runs ktxTexture2_constructFromStreamAndHeader (ktx.h, texture2.c). A ktxStream is a struct of seven function pointers (read, skip, write, getpos, setpos, getsize, destruct) over a FILE*, a memory block or a custom pointer (ktx.h). The memory stream's read is a memcpy out of the caller's buffer (memstream.c). Construction does, in order:
ktxCheckHeader2_on the 80 bytes.- Read the level index; then, if the stream knows its size, check that the DFD, the key/value data, the global data and every level lie inside the file, "before memory is allocated for it" (
texture2.c). A pipe has no size, and the check is skipped. - Rebase level offsets to the first level, require
byteLength == uncompressedByteLengthwhen there is no supercompression, and require every level to end inside level 0's extent. - Read the DFD, require
dfdByteLength == dfdTotalSize, and runktxFormatSize_initFromDfd, which walks the descriptor blocks and stops before any read past the declared size. Its own comment on one check: "This is essential to avoid heap-buffer-overflow accesses which are UB!" (texture2.c). Then check the transfer function against the format's sRGB-ness, the colour model against the scheme (BasisLZ requiresKHR_DF_MODEL_ETC1S), and, withKTX_TEXTURE_CREATE_CHECK_GLTF_BASISU_BIT, theKHR_texture_basisurules (texture2.c). - Parse the key/value data into a hash list unless
KTX_TEXTURE_CREATE_SKIP_KVDATA_BITorRAW_KVDATA_BITis set, and liftKTXorientationandKTXanimDatainto fields (texture2.c). - Read the supercompression global data, refusing it for schemes that do not use one (
texture2.c). - If
KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BITis set, load and inflate all levels now.
Without step 7 the texture keeps its stream and loads later. The doc comment says why (texture2.c): the flag "should not be set, if the ktxTexture is ultimately to be uploaded to OpenGL or Vulkan. This will minimize memory usage by allowing, for example, loading the images directly from the source into a Vulkan staging buffer."
Inflation: Zstd and ZLIB
ktxTexture2_LoadImageData(texture, buffer, size) sizes its destination by ktxTexture2_GetDataSizeUncompressed, which, for Zstd and ZLIB, is the sum of the levels' uncompressedByteLength padded to the post-inflation alignment (texture2.c). It then reads all compressed levels into one temporary buffer and inflates level by level, smallest first, into the destination (texture2.c). The Zstd loop uses one ZSTD_DCtx and checks each result against the index (texture2.c):
// lib/src/texture2.c, ktxTexture2_inflateZstdInt()
for (int32_t level = This->numLevels - 1; level >= 0; level--) {
size_t levelByteLength =
ZSTD_decompressDCtx(dctx, pInflatedData + levelOffset,
inflatedDataCapacity,
&pDeflatedData[cindex[level].byteOffset],
cindex[level].byteLength);
...
if (This->_private->_levelIndex[level].uncompressedByteLength != levelByteLength) {
result = KTX_DECOMPRESS_LENGTH_ERROR;
goto cleanup;
}After success the texture is rewritten in place: a new level index, dataSize, and supercompressionScheme = KTX_SS_NONE. ZLIB takes the same path through mz_uncompress from a bundled miniz (texture2.c, miniz_wrapper.cpp). The writer side, ktxTexture2_DeflateZstd, compresses each level independently with ZSTD_compressCCtx into a buffer sized by ZSTD_compressBound (writer2.c). Zstd itself is the copy bundled with Basis Universal (BASISU_ZSTD TRUE in lib/CMakeLists.txt).
Transcoding Basis payloads: ktxTexture2_TranscodeBasis
ktxTexture2_NeedsTranscoding is true for the ETC1S, UASTC and UASTC HDR 6×6 colour models. TranscodeBasis(texture, fmt, flags) takes one of the ktx_transcode_fmt_e targets (KTX_TTF_BC7_RGBA, KTX_TTF_ETC2_RGBA, KTX_TTF_ASTC_4x4_RGBA, KTX_TTF_RGBA32, the HDR targets and others, ktx.h) and maps it to a VkFormat, picking the _SRGB variant when the DFD's transfer function is sRGB. It then creates a prototype ktxTexture2 of the target format with full storage, uses it for sizes and the new DFD, and moves its data into the source texture on success (basis_transcode.cpp). For ETC1S, it validates that the global data is long enough for the image descriptors and tables, decodes the codebooks once with basisu_lowlevel_etc1s_transcoder::decode_palettes and decode_tables, and transcodes every image of every level, smallest level first, with one transcode_image call per image (basis_transcode.cpp). The validation is marked incomplete in the source (basis_transcode.cpp):
// lib/src/basis_transcode.cpp, ktxTexture2_transcodeLzEtc1s()
if (BGD_TABLES_ADDR(0, bgdh, imageCount) + bgdh.tablesByteLength > priv._sgdByteLength) {
return KTX_FILE_DATA_ERROR;
}
// FIXME: Do more validation.The transcoder's global tables are initialised once behind an atomic flag and a mutex, because "By deliberate choice basisu_transcoder_init() does not have its own mutex" (basis_transcode.cpp).
Verified: the ETC1S file made by ktx create --encode basis-lz (71,692 bytes, one level, vkFormat 0, KTX_SS_BASIS_LZ, NeedsTranscoding true) transcodes to KTX_TTF_BC7_RGBA, after which the texture reports vkFormat 146 (VK_FORMAT_BC7_SRGB_BLOCK), scheme KTX_SS_NONE and 1,048,576 bytes of data, and uploads to lavapipe.
Vulkan upload: ktxTexture2_VkUploadEx
The caller fills a ktxVulkanDeviceInfo (instance, physical device, device, queue, command pool, allocator, and a ktxVulkanFunctions table loaded through vkGetInstanceProcAddr, ktxvulkan.h) and calls ktxTexture2_VkUploadEx(texture, vdi, &vkTexture, tiling, usage, finalLayout). The function (vkloader.c):
- Maps dimensionality,
isArrayandisCubemaptoVkImageType,VkImageViewTypeandVK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; refusesVK_FORMAT_UNDEFINED(a Basis texture must be transcoded first). - Asks
vkGetPhysicalDeviceImageFormatPropertiesfor the format, tiling and usage, and refuses when the format is unsupported ormaxArrayLayers/maxMipLevelsare exceeded (vkloader.c). - Creates a host-visible, host-coherent staging buffer of
ktxTexture_GetDataSizeUncompressedbytes, maps it, and, if the data is not loaded yet, callsktxTexture_LoadImageDatawith the mapped pointer as destination, so the file's bytes (or the Zstd output) land in the staging buffer without an intermediate heap copy (vkloader.c). - Builds one
VkBufferImageCopyper level throughktxTexture_IterateLevels, withbufferRowLength = 0,layerCount = numLayers * numFaces,aspectMask = VK_IMAGE_ASPECT_COLOR_BITand the level's extent (vkloader.c). - Creates the optimal-tiling image in device-local memory, records a barrier to
TRANSFER_DST_OPTIMAL,vkCmdCopyBufferToImagefor all regions, then eithervkCmdBlitImagemipmap generation or a barrier tofinalLayout. - Submits, creates a fence and blocks on
vkWaitForFenceswith a 100-second timeout, then frees the staging buffer (vkloader.c).
ktxVulkanTexture returns the VkImage, its memory, format, view type, extent and level and layer counts (ktxvulkan.h); ktxTexture2_VkUploadEx_WithSuballocator replaces the two vkAllocateMemory calls with six caller callbacks (allocate, bind buffer, bind image, map, unmap, free) and rejects allocations that span more than one page with KTX_UNSUPPORTED_FEATURE (ktxvulkan.h, vkloader.c).
Verified: on lavapipe, the uncompressed (VK_FORMAT_R8G8B8A8_SRGB, 11 levels), Zstd and transcoded BC7 files upload with KTX_SUCCESS and no validation-layer error. llvmpipe reports textureCompressionBC = 1, textureCompressionETC2 = 0, textureCompressionASTC_LDR = 0.
The ktx tool and its validator
ktx is one binary with subcommands create, convert, encode, transcode, deflate, extract, compare, info, validate and patch (tools/ktx/); the legacy toktx family was removed in 5.0 (RELEASE_NOTES.md). ktx validate is a second, independent reader of the format written in C++ (ValidationContext), which runs nine passes in order and only then hands the file to libktx (validate.cpp):
// tools/ktx/validate.cpp, ValidationContext::validate()
call(&ValidationContext::validateHeader, "Header");
call(&ValidationContext::validateIndices, "Index");
call(&ValidationContext::calculateExpectedDFD, "Expected DFD", VkFormat(header.vkFormat));
call(&ValidationContext::validateDFD, "DFD");
call(&ValidationContext::validateLevelIndex, "Level Index"); // Must come after the DFD parsed
call(&ValidationContext::validateKVD, "KVD");
call(&ValidationContext::validateSGD, "SGD");
call(&ValidationContext::validatePaddings, "padding");
if (doCreateAndTranscodeChecks)
call(&ValidationContext::validateCreateAndTranscode, "Create and Transcode");Each finding is a typed issue with a numeric ID, a severity (warning, error, fatal), a message and a details format string (validation_messages.h); 176 are declared (three more are commented out, and ID 7013 is used twice). The tool prints them as text or as JSON conforming to the validate_v0.json schema (command_validate.cpp). The final pass compares the two readers: when the validator found errors but libktx accepted the file, it reports warning 5004, "Non-conformant texture file accepted by libktx" (validation_messages.h, validate.cpp).
Analysis
1. Pixel and memory model
The model is the GPU's, not an image library's. A ktxTexture2 is one contiguous pData buffer of dataSize bytes holding all levels, smallest first, each level the concatenation of layers, faces and depth slices, each image a tightly packed raster of texel blocks (ktx.h, spec, levelImages). There is no stride field: rows are tight by definition and levels are aligned to lcm(blockBytes, 4) (lcm4, texture2.c). Addressing is by (level, layer, faceSlice) through ktxTexture_GetImageOffset, which returns a byte offset into pData. Extents go up to 3-D, with cube maps as six faces and 1-D, 2-D and cube arrays; 3-D arrays are refused at the header.
The texel is described twice, by vkFormat and by the DFD. libktx derives block footprint and bytes per block from the DFD (ktxFormatSize); only the validator compares the DFD with the one vk2dfd generates for the vkFormat (calculateExpectedDFD), while the library checks just the sRGB transfer function (texture2.c). Multi-planar YCbCr formats are prohibited, so an image is one plane, with VK_IMAGE_ASPECT_COLOR_BIT hard-coded in the upload (vkloader.c).
2. Genericity mechanism
C single inheritance by macro and a vtable. KTXTEXTURECLASSDEFN expands the common fields into both ktxTexture1 and ktxTexture2, and struct ktxTexture_vtbl holds 17 function pointers (GetImageOffset, IterateLevels, LoadImageData, WriteToStream and others); a macro such as ktxTexture_GetImageOffset(This, ...) expands to (This)->vtbl->GetImageOffset(...) (ktx.h). Vulkan functions sit in a second table, vvtbl, so ktx.h need not include vulkan.h. Format genericity is data, not types: one ktxFormatSize record computed from the DFD drives every size calculation, and every per-format decision (transcode target to VkFormat, sRGB variant) is a switch (basis_transcode.cpp). I/O genericity is the ktxStream function-pointer struct. Nothing is parameterised at compile time.
3. Colour and metadata
Colour lives in the DFD: colorModel (RGBSDA, YUVSDA, the block models, ETC1S, UASTC), colorPrimaries (BT.709, BT.2020, Display P3 and others), transferFunction (linear, sRGB, PQ, HLG and the rest) and per-sample flags such as signed, float, linear and exponent (Khronos Data Format Specification). libktx exposes them as accessors that read one field of the basic block each (ktxTexture2_GetTransferFunction_e, GetPrimaries_e, GetColorModel_e, GetPremultipliedAlpha, texture2.c), and construction rejects transfer functions beyond KHR_DF_TRANSFER_HLG_UNNORMALIZED_OETF (texture2.c). The DFD's primaries and transfer function correspond to CICP's primaries and transfer characteristics; the DFD has no matrix-coefficients field, and the only YCbCr formats KTX2 admits are single-plane *_422_* ones (KHR_DF_MODEL_YUVSDA, spec, DFD), the multi-plane formats being prohibited (spec, vkFormat). There is no ICC profile, no EXIF and no XMP; the specification's key/value data carries texture semantics instead (KTXorientation, KTXswizzle, KTXmapRange, KTXastcDecodeMode, KTXwriter, KTXwriterScParams), and the validator registers a checker for each (validate.cpp). Premultiplied alpha is a DFD flag, not a convention (straight and premultiplied alpha).
4. I/O and codec architecture
Pull, whole-texture, synchronous. The reader asks its ktxStream for exactly the bytes it needs; a short read is KTX_FILE_UNEXPECTED_EOF, never "need more input", so the reader is a pull decoder and is not suspendable. Metadata is eager (step 5 above), image data is either eager or deferred as a whole. LoadImageData reads all levels in one read call and inflates them all; IterateLoadLevelFaces reads and inflates one level at a time, smallest first, into buffers sized for level 0, but only for callers that consume every level through a callback (texture2.c).
The format allows more than the library does. Because each Zstd or ZLIB level is independent and the level index gives its (byteOffset, byteLength), a reader can fetch and inflate any level alone, smallest first, and upload it before the next arrives, which is the streaming case the specification's rationale describes. libktx has no public call to load or inflate one chosen level, and VkUploadEx copies all levels in one submission. BasisLZ breaks per-level independence: its global data must be read before any level can be transcoded (papers).
The codec layers are separate in code even though they ship in one library: container parsing (texture2.c), supercompression (ktxTexture2_inflate*Int), transcoding (basis_transcode.cpp over the vendored basisu_transcoder), and upload (vkloader.c, glloader.c).
5. Hostile input and safety
What libktx checks is thorough at the container level: every header and index entry is bounded by the file size before allocation, level and global-data offsets are tested in subtraction form so they cannot overflow (entry->byteLength > fileSize - entry->byteOffset), the DFD walker stops on zero-sized blocks, levelCount is bounded, and decompressed lengths are compared with the index (texture2.c, texture2.c). CI runs one Linux job under AddressSanitizer with the CLI conformance tests (linux.yml). There is no fuzz target for libktx; the only LLVMFuzzerTestOneInput functions belong to vendored dependencies (astc-encoder, fmt).
Two gaps were demonstrated and a third was read.
- The uncompressed size is trusted for allocation (verified).
GetDataSizeUncompressedsumsuncompressedByteLengthfrom the file andloadImageDataIntpasses it tomallocbefore inflating, so the size is compared with reality only after the allocation (texture2.c). Setting level 0'suncompressedByteLengthto 2^40 in the 814,434-byte Zstd file madektxTexture2_LoadImageDatarequest a 1,099,513,025,876-byte allocation and returnKTX_OUT_OF_MEMORY; setting it to 6 GiB produced a 6,443,849,044-byte request, which succeeded under Linux overcommit, and the load then failed withKTX_DECOMPRESS_LENGTH_ERROR. This is exactly the "ultra large memory allocation" the specification tells consumers to guard against.ktx validatereports the 6 GiB file as error 4008 only through its finallibktxpass; its level-index pass checksuncompressedByteLengthexactly only for unsupercompressed files (validate.cpp). - Level sizes are not checked against the format and extent (verified). Shrinking level 0's
byteLengthanduncompressedByteLengthto 16 in the uncompressed 1024×1024 RGBA8 file is accepted byktxTexture2_CreateFromMemorywithKTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT(dataSize1,398,116, whileGetImageSize(0)is 4,194,304).ktx validaterejects it with errors 4001, 4005 and 4006 and adds warning 5004, "Non-conformant texture file accepted by libktx". Uploading it withktxTexture2_VkUploadExon lavapipe producedVUID-vkCmdCopyBufferToImage-pRegions-00171(a copy region outside the staging buffer) and a segmentation fault (exit 139, five runs out of five) in amemmovecalled from lavapipe'sutil_copy_boxunderhandle_copy_buffer_to_imageon the queue thread: the copy regions come from the level extents (vkloader.c), the staging buffer from the index. Under Valgrind the same upload did not crash and returnedKTX_SUCCESS, so the crash depends on what lies past the mapping; the out-of-bounds region does not. - Vulkan errors vanish in release builds (read).
VK_CHECK_RESULTprints and asserts under_DEBUGand is otherwise((void)f)(vkloader.c), and it wrapsvkCreateBuffer,vkCreateImage, the bind and map calls,vkQueueSubmitandvkWaitForFences. The macro's comment limits it to errors "caused by invalid usage by this loader", but out-of-memory and a fence timeout are not usage errors: in a release build the function carries on past them and ends inreturn KTX_SUCCESS.
The ETC1S path relies on the vendored transcoder to bounds-check slices (basis_transcode.cpp). Background is in the hostile-input papers and concepts; libspng and Wuffs are the counterpoints on default-closed limits.
6. Allocation and ownership
The texture owns everything: pData, pDfd, the key/value hash list, the global data and the private block (which ends in the level index, texture2.h) are separate malloc blocks freed by ktxTexture2_Destroy, and TranscodeBasis replaces pData and pDfd wholesale with the prototype's. There is no allocator parameter for host memory; the only hooks are VkAllocationCallbacks and the sub-allocator callbacks for device memory. LoadImageData(texture, buffer, size) writes into caller storage, and VkUploadEx uses that to inflate straight into mapped staging memory, so a Zstd upload holds the compressed data, the staging buffer and the device image at once. Transcoding holds source, the prototype's full target storage and the transcoder state. CreateFromMemory does not take the caller's bytes; the memory stream copies out of them, so the caller's buffer and pData coexist.
7. CPU parallelism and SIMD
libktx itself is single-threaded and has no SIMD code. Encoding parallelism belongs to the vendored encoders, configured through threadCount in ktxAstcParams and ktxBasisParams (ktx.h); BASISU_SSE and BASISU_OPENCL are build options for the Basis encoder (lib/CMakeLists.txt). Transcoding is one transcode_image call per image in a serial loop; the per-image state (basisu_transcoder_state) exists for thread safety and video P-frames, and the only concurrency test is a smoke test whose own header says "It is not clear how useful this test actually is" (threadtests.cc). Inflation is one ZSTD_DCtx over all levels in sequence, although the levels are independent.
8. GPU offload and interop
The Vulkan path is the library's reason to exist, and it is the plain one: staging buffer, vkCmdCopyBufferToImage, barriers, one submission, a blocking fence wait, all on the caller's queue with a command buffer allocated from the caller's pool (vkloader.c). It uses Vulkan 1.0 entry points only (vkGetPhysicalDeviceImageFormatProperties, vkCmdPipelineBarrier), so it runs on the oldest drivers and Android. It does not use a transfer queue, timeline semaphores, VK_EXT_host_image_copy, external memory or GPU decompression; transcoding and inflation are CPU work. A caller that wants an asynchronous or batched upload can use the parts (LoadImageData into its own buffer, GetImageOffset for regions) and record the copy itself; the library's own upload cannot overlap rendering because it waits on the fence. Format selection, which the hardware matrix shows is necessary (no compressed family is universal across the measured devices), is left to the caller, who picks the ktx_transcode_fmt_e target from the device's features before calling TranscodeBasis.
9. Temporal, animation and containers
KTX2 is itself the container, and it has a minimal animation model: the KTXanimData key holds duration, timescale and loopcount, valid only on array textures, where each layer is a frame; libktx exposes these as isVideo, duration, timescale and loopcount on ktxTexture2 (texture2.c, ktx.h). For ETC1S, the transcoder keeps one state per face when isVideo is set so that P-frames can reference the previous frame, but the I-frame flag is not passed through: the call site says the "API currently doesn't have any way to pass the I-Frame flag", and a FIXME asks for it to be queryable (basis_transcode.cpp). There are no per-frame timestamps or variable frame durations. This is a sprite-sheet model, not a video model; the video subjects in the umbrella cover the rest.
10. Testing and conformance
Three layers exist.
- Unit and texture tests in GoogleTest:
texturetests.cc(120 test macros),unittests.cc(49),streamtests.cc,transcodetests.ccandthreadtests.cc, over 36 KTX2 files intests/resources/ktx2(tests/). The negative cases are mostly API misuse (null parameters, data already loaded), not malformed files. - The CTS, a separate repository included as a submodule (
.gitmodules): black-box tests of the CLI tools, one JSON file per case giving the command line, expected exit status, golden stdout, stderr and output files, with permutations generated from anargsdictionary (CTS README).outputToleranceadmits non-bit-exact output on non-primary platforms: "BasisLZ compression relies on the undefined order of std::unordered_map containers". - The validator as an oracle.
ktx validateis a second implementation of the specification's rules, and its last pass runslibktxon the same file and reports disagreement (warning 5004). This is a built-in differential test between the reference reader and the reference library, and it is what exposed gap 2 above.
There is no fuzz target for libktx and no golden-image comparison of upload results; the ktxdiff tool compares texture files with a tolerance.
Lessons for Sparkles
- Q6 — KTX2's level index is already the request list
sparkles:event-horizonneeds. Each level is an independent(byteOffset, byteLength)with its inflated size beside it, smallest first, so a reader can issue oneOpReadper level, inflate each as it lands and upload it, showing low mips first.libktx's upload path does none of this (whole-texture load, one blocking submission), so it is evidence for the format's design, not a template for the code. Event-horizon has the offset read but no ranged-read helper layer (G1 in the event-horizon baseline); KTX2 is a concrete, bounded first client for one. - Q6 — Inflate or read straight into the staging buffer.
VkUploadEx's best idea isLoadImageDatawith the mapped staging pointer as destination, which removes a heap copy. Sparkles'Uploads.stagecopies a caller'subyte[]into the slot's host-visible arena (G1 in the Vulkan baseline); a KTX2 loader that writes into an arena region, or into a region anio_uringread targets, is the same move one level down. The fence-to-loop seam it would need is G5 there. - Q1, Q6 — The upload path needs levels, layers and block formats before it can carry KTX2.
Uploads.stagetakes one tight extent with no layer or mip (G1 in the Vulkan baseline; G8 in existing code); KTX2 needs aVkBufferImageCopyper level withlayerCount = layers × faces, block-aligned offsets and compressedVkFormats, and the shader side cannot sample a compressed or array image yet (G9 in the shaders baseline). The per-frame upload budget (UVK23/UVK29, decision D10 there) maps naturally onto KTX2's per-level ordering. - Q6, Q8 — Query format properties before upload.
VkUploadExasksvkGetPhysicalDeviceImageFormatPropertiesfor support,maxMipLevelsandmaxArrayLayers; Sparkles binds no such query and passes onlymaxImageExtent(G13 in the Vulkan baseline), so a KTX2 upload has no way to refuse an unsupported format today. - Q4, Q8 — Bound declared sizes before allocating, and check them against the format. Both demonstrated
libktxgaps come from trusting the index: anuncompressedByteLengththat allocates 1 TiB, and a level smaller than its extent that later drives an out-of-bounds GPU copy. For an uncompressed or Zstd/ZLIB texture with a knownvkFormat, every level's inflated size is computable from extent and block size, so a reader can reject a mismatch at parse time and size the destination from the computation, not the file. That computation fits a@safe pure nothrow @nogcfunction oversize_twith checked arithmetic;maxPngPixelsinsparkles.image.pngis the existing default-closed budget (existing code). - Q4 —
sparkles:wiredcannot describe the KTX2 header today. The header is fixed-layout little-endian, but the global-data index and the level index use 64-bit offsets and lengths, which Flat cannot express (G5 in the wired baseline), and wired has no binary backend on main (G1). KTX2 is a small, fully specified test case for whatever binary description wired grows: 80 bytes, three index pairs, an array of triples, a length-prefixed key/value list. - Q5 — Borrow the DFD as the colour vocabulary for GPU textures. The DFD already gives colour model, primaries, transfer function, premultiplication and per-sample bit layout in a Khronos standard; the papers recommend it for block planes. The redundancy is a hazard: the file states the format twice (
vkFormatand DFD), the library trusts the DFD for sizes and theVkFormatfor upload, and only the validator checks they agree. - Q2 — Format mapping is data in disguise.
libktx's target-to-VkFormatmapping with sRGB variants is a longswitch; the D equivalent is a compile-time table checked against the header, option A of decision D2 in the Vulkan baseline. The macro-and-vtable class scheme exists to put KTX 1 and 2 behind one C API; D would express that with two types and introspection. - Q6, Q8 — Choose the transcode target from device features, and test on lavapipe. The hardware matrix shows no compressed family covers all measured devices, which is the case for carrying Basis payloads and transcoding at load.
llvmpipereports BC support (verified), so a BC7 upload readback test fits the existing lavapipe oracle (SPARKLES_VULKAN_READBACK=1, decision D9 in the Vulkan baseline); ETC2 and ASTC paths need real hardware or a CPU decoder as the oracle. - Q4 — Vulkan results are values.
VK_CHECK_RESULTcompiles away in release builds, so a failedvkCreateImagedoes not stop the upload. Sparkles' binding returnsExpected(Vulkan baseline), and thecheckedbuild type keeps assertions; both avoid this class. - Q3, Q7 — Transcoding and inflation are serial CPU loops over independent work. Levels, layers and faces transcode independently and Zstd levels inflate independently;
libktxexploits neither. Whether a D port spreads them over the offload pool or moves transcoding to a compute shader (the papers call it table and bit-field rewriting) is a Q7 measurement that cannot be made today: there is no compute pipeline (G1 in the shaders baseline). - Q8 — A validator separate from the reader, diffed against it. The typed issue catalogue (numeric IDs, severities, JSON output) and the final "accepted by libktx" pass are a reusable pattern: two independent readers of one format, disagreement reported as a finding. The CTS's BasisLZ tolerance warns that encoder output is not a stable oracle.
- Q9 —
libktxis one library with feature switches, and the seams show where a split would go. Container, supercompression, Basis transcoding, ASTC encoding, ETC unpacking and GL and Vulkan upload are separate source files; KTX 1, ETC unpacking and both uploads are switched byLIBKTX_FEATURE_*options, andLIBKTX_VERSION_READ_ONLYdrops the writers (lib/CMakeLists.txt). For Sparkles the analogous pieces are a formats-side KTX2 reader (betterC- and wasm-friendly if it stays@nogcand takes caller buffers), a supercompression layer that needs Zstd (a C library through ImportC, or a port), a Basis transcoder, and an upload layer onsparkles:vulkan, where the recommendation for decision D1 of the Vulkan baseline puts generic uploads.
Strengths
- A container designed for GPUs:
VkFormatin the header, tight rows, block-aligned levels, smallest-first ordering and per-level supercompression make streaming and direct upload possible. - The DFD gives a standard, machine-readable description of colour model, transfer function, primaries and bit layout, including for block and Basis formats.
- Careful container-level bounds checks: every region is checked against the file size before allocation, in overflow-safe form, and the DFD walker is bounded.
- One call from file to
VkImage, with a sub-allocator hook, on Vulkan 1.0 entry points. - An independent validator (176 typed issues, JSON output, a differential check against the library) and a black-box CTS with golden outputs, run under AddressSanitizer in CI.
Weaknesses
- Allocation sizes come from the file: an
uncompressedByteLengthof 2^40 becomes a 1 TiBmallocrequest (verified). - Level sizes are not checked against the format and extent on load, and the Vulkan upload then records an out-of-bounds copy; on lavapipe this crashed the driver (verified).
VK_CHECK_RESULTdiscards everyVkResultit wraps in release builds.- Whole-texture, blocking APIs: no load of one chosen level, no per-level upload, a fence wait inside the upload, no transfer queue.
- Transcoding and inflation are serial over independent work; transcoding holds source and full target storage at once.
- No fuzz target for
libktx; the ETC1S path is markedFIXME: Do more validation.;vkFormatand DFD can disagree and only the validator checks.
Key design decisions and trade-offs
| Decision | Rationale | Trade-off |
|---|---|---|
Store VkFormat in the header and the DFD beside it | Direct mapping to Vulkan; the DFD covers formats Vulkan cannot name (Basis) | Two descriptions of one format; readers must check they agree, and libktx does not |
| Levels stored smallest first, indexed by offset | Streaming low mips first; random access to any level | Index 0 is last in the file; every reader must handle the inversion and the rebasing |
| Supercompress each level independently (Zstd, ZLIB) | Per-level streaming and random access | Redundancy across levels is not exploited; BasisLZ needs global data and loses independence |
uncompressedByteLength in the index | Destination sizing before inflation | An attacker-controlled allocation size unless the reader recomputes it from the format |
| Transcode Basis at load into a prototype texture | One asset for every GPU; reuse of the format-size code for the target | Source plus full target storage at once; whole-texture granularity |
| Upload with staging buffer, one submit, blocking fence | Simple, portable to Vulkan 1.0 and Android, no queue or sync policy to impose | Cannot overlap rendering; no transfer queue; errors hidden by VK_CHECK_RESULT in release |
| Load image data straight into mapped staging memory | Saves a heap copy and peak memory | Only when the caller defers loading; the staging size still comes from the file |
| C classes via macro-expanded fields and vtables | KTX 1 and 2 behind one API in C, bindings for JS, Java and Python | No compile-time specialisation; per-format behaviour is switch code |
Validator as a separate C++ reader that also runs libktx | Conformance checking independent of the library; differential warning on mismatch | Two implementations to keep in step; the validator inherits the library's allocation when it calls it |
Sources
- KTX-Software at the pinned revision:
texture2.c,checkheader.c,vkloader.c,basis_transcode.cpp,writer2.c,ktx.h,ktxvulkan.h,validate.cpp,validation_messages.h; KTX-Software-CTS and its README. - KTX File Format Specification 2.0 (Document Revision 4) and the Khronos Data Format Specification.
- This catalog's GPU texture compression, hostile-input and storage-to-GPU paper threads.
- Probes run for this page (see the note under the metadata table).