Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,22 @@ if let bundle = result.appIconBundle {
}
```

For a tvOS catalog, select the platform explicitly:

```swift
let compiler = XCAssetCompiler(deploymentTarget: "17.0", platform: .tvOS)
let result = try await compiler.compile(catalog: catalogURL)
```

The default platform remains iOS. In a mixed catalog, iOS selects its
`.appiconset` and ignores TV-only Brand Assets; tvOS selects its `.brandassets`
and ignores the iOS app icon. Merge the returned `appIconBundle` metadata into
the app's Info.plist. tvOS names the small stack in `CFBundleIcons` and maps
the supplied Top Shelf roles into `TVTopShelfImage`.
tvOS compilation rejects distinct facet names that collide in the current
16-bit CoreUI identifier mapping, so a layer cannot alias another asset.
Branding elements must also have unique names across their roles and types.

## What it supports

- `.imageset`
Expand All @@ -38,13 +54,26 @@ if let bundle = result.appIconBundle {
- JPG sources stored as preserved raw renditions (JPEG bytes passed through; original compression preserved)
- `.colorset` (sRGB and display-P3, hex or float components, dark/light appearances)
- `.appiconset` (per-idiom and per-size, with the loose-PNG fallback that SpringBoard expects alongside `Assets.car`). PNG sources only; SVG/JPG are rejected because SpringBoard's icon-render pipeline requires PNG.
- tvOS `.brandassets` with a 400×240 primary icon and an optional 1280×768
marketing icon, each containing two embedded PNG layers with default canvas
and frame geometry. Layer relationships and qualified names are retained in
CoreUI LayerStack renditions; flattened previews are emitted separately.
Top Shelf image roles and app icon metadata are returned in `appIconBundle`.
Sources must use sRGB, the `tv` idiom, and distinct 1x/2x scales (marketing
icons use 1x only), with an opaque background layer.

## What it deliberately doesn't support

- `.pdf` vector sources (the CoreUI 970 DWAR envelope path is SVG-flavoured; adding PDF would need a separate `pixelFormat`)
- Multi-rendition fanout — actool emits multiple compression variants per asset (`deepmap-lzfse`, `deepmap2`, `palette-img`); this writer emits one rendition per `(idiom, scale, appearance)` tuple per source format. Sufficient for iOS 16+.
- Data sets, sticker sets, AR reference objects
- macOS / tvOS / watchOS asset variants beyond what the structural attribute IDs encode
- Standalone `.imagestack` assets, custom tvOS layer geometry, referenced layers, additional layers, and dark or
display-P3 Brand Assets. Unsupported forms are rejected, rather than flattened
or emitted with incomplete layer relationships.
- Apple's undocumented blurred radiosity renditions for tvOS focus effects.
The current output's icon-loading and focus behavior still needs native tvOS
runtime validation; structural CAR compatibility does not prove that behavior.
- macOS / watchOS asset variants beyond what the structural attribute IDs encode

These can be added; the format mechanisms in `Sources/AssetKit/CAR/` are general enough.

Expand All @@ -60,7 +89,11 @@ output is byte-deterministic across Linux and macOS.
swift test
```

The test suite includes a macOS-only gate (`AssetutilParseTests`) that compiles a fixture catalog and verifies Apple's own `xcrun assetutil --info` parses the bytes and reports the expected rendition fields. This is the durable verification for CoreUI format compatibility and gates merges via CI.
The test suite includes macOS-only gates that compile iOS and tvOS fixture
catalogs and verify Apple's own `xcrun assetutil --info` parses the bytes and
reports the expected rendition fields. These checks run in CI. Linux tests
cover layer ordering and references, mixed-catalog platform selection, the
observed LayerStack record layout, compositing, and unsupported geometry.

## License

Expand Down
62 changes: 36 additions & 26 deletions Sources/AssetKit/CAR/BitmapKeys.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@ import Foundation
/// resolve correctly. SpringBoard's appicon-render path does NOT depend on
/// BITMAPKEYS (the home icon still renders via the loose-PNG fallback).
enum BitmapKeys {
/// The 52-byte descriptor. Layout was derived by diffing actool's outputs
/// for `.appiconset` vs `.imageset` (bitmap) vs `.imageset` (vector)
/// renditions. The first 7 u32s are header-like; only slot 6 varies
/// across asset kinds. The remaining 6 vary by asset kind.
/// The 52-byte descriptor. The tvOS reference identifies slots 6 and 7
/// as masks of the emitted scale and idiom key values. Existing iOS
/// templates are retained separately to preserve their output.
struct Descriptor {
var kind: Kind
/// Number of distinct (idiom, subtype) tuples this asset is keyed on.
/// The original iOS template's (idiom, subtype) tuple count.
var idiomSubtypeCount: UInt32
var scaleMask: UInt32 = 0
var idiomMask: UInt32 = 0

enum Kind {
case appIcon
Expand All @@ -32,42 +33,41 @@ enum BitmapKeys {
case vector
}

/// Slot 6 of the header (the only header u32 that varies by kind).
/// `0x04` for bitmap-source assets (PNG, JPG); `0x0e` for vector
/// sources (SVG). AppIcon keeps `0x0e` -- we have no reference dump
/// for appicon-only catalogs to confirm which value it expects, and
/// the current value is verified end-to-end on device.
private var assetKindMarker: UInt32 {
/// Preserve the original iOS template values in this tvOS change.
/// The tvOS path derives its scale mask from actual rendition keys.
private var legacyScaleMask: UInt32 {
switch kind {
case .image: return 0x04
case .vector, .appIcon: return 0x0e
}
}

func encode() -> Data {
func encode(platform: XCAssetCompiler.Platform = .iOS) -> Data {
var w = ByteWriter()
w.writeLE(UInt32(1))
w.writeLE(UInt32(0))
w.writeLE(UInt32(0x28))
w.writeLE(UInt32(9))
w.writeLE(UInt32(0xFFFFFFFF))
w.writeLE(UInt32(1))
w.writeLE(assetKindMarker)
// Variable section. Values come from the actool reference.
w.writeLE(platform == .tvOS ? scaleMask : legacyScaleMask)
// The remaining original iOS template fields vary by kind.
// AppIcon : [u32=2, u16=1, u16=1, u32=7]
// Image : [u32=1, u16=1, u16=0, u32=1]
// Vector : [u32=1, u16=1, u16=0, u32=1] (same shape as Image)
// The exact semantics aren't fully reverse-engineered yet, so for
// v1 we hardcode the templates per kind and pass through the
// discovered (idiom, subtype) count. Field 7 in particular seems
// to track that count.
w.writeLE(idiomSubtypeCount)
switch kind {
case .appIcon:
// tvOS uses the observed common (1, 0, 1) suffix and actual
// idiom mask; iOS retains its existing template byte-for-byte.
w.writeLE(platform == .tvOS ? idiomMask : idiomSubtypeCount)
switch (platform, kind) {
case (.tvOS, _):
w.writeLE(UInt16(1))
w.writeLE(UInt16(0))
w.writeLE(UInt32(1))
case (.iOS, .appIcon):
w.writeLE(UInt16(1)) // (u16, u16) tuple
w.writeLE(UInt16(1))
w.writeLE(UInt32(7))
case .image, .vector:
case (.iOS, .image), (.iOS, .vector):
w.writeLE(UInt16(1))
w.writeLE(UInt16(0))
w.writeLE(UInt32(1))
Expand All @@ -82,11 +82,13 @@ enum BitmapKeys {
}

/// Per-asset BITMAPKEYS entry: `(NameIdentifier, descriptor bytes)`.
static func entries(for assets: [(name: String, descriptor: Descriptor)]) -> [BOMTree.InlineKeyEntry] {
static func entries(
for assets: [(name: String, descriptor: Descriptor)], platform: XCAssetCompiler.Platform = .iOS
) -> [BOMTree.InlineKeyEntry] {
return assets.map { asset in
BOMTree.InlineKeyEntry(
key: FacetKeys.nameHash(asset.name) & 0xFFFF,
value: asset.descriptor.encode()
value: asset.descriptor.encode(platform: platform)
)
}
}
Expand All @@ -100,7 +102,7 @@ enum BitmapKeys {
static func descriptor(forAsset name: String, renditions: [Rendition]) -> Descriptor? {
let hasBitmapOrPreservedSource = renditions.contains { rendition in
switch rendition.body {
case .bitmap, .preservedSource: return true
case .bitmap, .preservedSource, .layerStack: return true
case .color: return false
}
}
Expand All @@ -118,7 +120,15 @@ enum BitmapKeys {
return (idiom << 16) | subtype
})

return Descriptor(kind: kind, idiomSubtypeCount: UInt32(idiomSubtypes.count))
let keys = renditions.map(RenditionKey.init)
let scaleMask = keys.reduce(UInt32(0)) { $0 | (UInt32(1) << UInt32($1.scale)) }
let idiomMask = keys.reduce(UInt32(0)) { $0 | (UInt32(1) << UInt32($1.idiom)) }
return Descriptor(
kind: kind,
idiomSubtypeCount: UInt32(idiomSubtypes.count),
scaleMask: scaleMask,
idiomMask: idiomMask
)
}

/// AppIcon takes precedence over Vector takes precedence over Image:
Expand Down
3 changes: 2 additions & 1 deletion Sources/AssetKit/CAR/CARLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,15 @@ struct CARLayout {
case .bitmap(let body):
switch body.kind {
case .appIcon: return .appIcon
case .image: return .image
case .image, .layerStackPreview: return .image
}
case .color: return .color
// Preserved-source renditions live in the `.image` category at every
// layer above the CSI body: FACETKEYS, BITMAPKEYS, and the rendition
// key all reuse the same element/part as a generic PNG imageset.
// The source format only shows up in the CSI header's pixelFormat.
case .preservedSource: return .image
case .layerStack: return .image
}
}
}
12 changes: 9 additions & 3 deletions Sources/AssetKit/CAR/CARWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Foundation
struct CARWriter: Sendable {
var deploymentTarget: String
var renditions: [Rendition]
var platform: XCAssetCompiler.Platform = .iOS

func write() throws -> Data {
let layout = CARLayout(renditions: renditions)
Expand Down Expand Up @@ -48,10 +49,13 @@ struct CARWriter: Sendable {
)
bom.setVariable("APPEARANCEKEYS", blockID: appearanceTreeID)

let kfmtBlockID = bom.addBlock(KeyFormatBlock.data())
let keyFormat = platform == .tvOS ? tvKeyFormat : v1KeyFormat
let kfmtBlockID = bom.addBlock(KeyFormatBlock.data(attributes: keyFormat))
bom.setVariable("KEYFORMAT", blockID: kfmtBlockID)

let extendedMetadataBlockID = bom.addBlock(ExtendedMetadata.data(deploymentTarget: deploymentTarget))
let extendedMetadataBlockID = bom.addBlock(ExtendedMetadata.data(
deploymentTarget: deploymentTarget, platform: platform.rawValue
))
bom.setVariable("EXTENDED_METADATA", blockID: extendedMetadataBlockID)

let bitmapAssets: [(name: String, descriptor: BitmapKeys.Descriptor)] =
Expand All @@ -65,7 +69,7 @@ struct CARWriter: Sendable {
if !bitmapAssets.isEmpty {
let bitmapKeysTreeID = BOMTree.insertInlineKey(
into: &bom,
entries: BitmapKeys.entries(for: bitmapAssets),
entries: BitmapKeys.entries(for: bitmapAssets, platform: platform),
blockSize: 1024
)
bom.setVariable("BITMAPKEYS", blockID: bitmapKeysTreeID)
Expand All @@ -81,6 +85,8 @@ struct CARWriter: Sendable {
return CSIWriter.bitmap(name: rendition.name, body: body, scaleFactor: scaleFactor)
case .color(let body):
return CSIWriter.color(name: rendition.name, body: body)
case .layerStack(let body):
return CSIWriter.layerStack(body: body)
case .preservedSource(let body):
// SVG renditions are scale-free; the reference leaves
// scaleFactor=0 for them. JPGs respect the @Nx suffix the same
Expand Down
4 changes: 4 additions & 0 deletions Sources/AssetKit/CAR/CSIHeader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ enum CSIHeader {
/// renderer on the DWAR-wrapped body.
static let pixelFormatSVG: UInt32 = 0x53564720

static let pixelFormatData: UInt32 = 0x44415441

/// Layout types observed in the reference. The names are derived from
/// CoreUI symbol names where known.
enum Layout: UInt16 {
Expand All @@ -40,6 +42,8 @@ enum CSIHeader {
/// category; SVG promotes to its own layout because vector
/// renditions surface a different AssetType to `assetutil`.
case vector = 9
case layerStack = 1002
case layerStackPreview = 0
}

// swiftlint:disable:next function_parameter_count
Expand Down
7 changes: 5 additions & 2 deletions Sources/AssetKit/CAR/CSIWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import Foundation
/// COLR block for color).
enum CSIWriter {
static func bitmap(name: String, body: BitmapBody, scaleFactor: UInt32) -> Data {
let tvl = CSITVL.encode([
let preview = body.kind == .layerStackPreview
let tvl = CSITVL.encode(preview ? [
.bitmapDescriptor(width: 0, height: 0), .sliceScale, .bitmapFlag, .bytesPerRow(width: body.width),
] : [
.bitmapDescriptor(width: body.width, height: body.height),
.destRect(width: body.width, height: body.height),
.sliceScale,
Expand Down Expand Up @@ -42,7 +45,7 @@ enum CSIWriter {
scaleFactor: scaleFactor,
pixelFormat: CSIHeader.pixelFormatARGB,
colorSpace: UInt32(body.colorSpaceID),
layout: .bitmapIcon,
layout: preview ? .layerStackPreview : .bitmapIcon,
name: body.renditionName,
tvlLength: UInt32(tvl.count),
bitmapCount: 1,
Expand Down
13 changes: 13 additions & 0 deletions Sources/AssetKit/CAR/KeyFormat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ enum AttributeID: UInt32 {
case element = 1
case part = 2
case appearance = 7
case dimension1 = 8
case dimension2 = 9
case scale = 12
case localization = 13
Expand All @@ -33,6 +34,18 @@ let v1KeyFormat: [AttributeID] = [
.part,
]

let tvKeyFormat: [AttributeID] = [
.appearance,
.localization,
.scale,
.idiom,
.subtype,
.dimension1,
.identifier,
.element,
.part,
]

/// `kfmt` block payload.
enum KeyFormatBlock {
static let magic: UInt32 = 0x6B666D74 // 'kfmt' as LE multi-char constant
Expand Down
77 changes: 77 additions & 0 deletions Sources/AssetKit/CAR/LayerStackCSI.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import Foundation

extension CSIWriter {
static func layerStack(body: LayerStackBody) -> Data {
var metadata = ByteWriter()
writeLayerReferences(body, into: &metadata)

// Stock two-layer metadata observed in actool's CoreUI 969 output.
// Its remaining fields are not generalised to custom frame geometry.
var flags = ByteWriter()
flags.writeLE(UInt32(2))
flags.writeZeros(12)
flags.write(byte: 1)
flags.writeZeros(12)
flags.write(byte: 1)
flags.writeZeros(4)
writeTLV(1020, flags.data, into: &metadata)

var layout = ByteWriter()
layout.writeLE(UInt32(2))
layout.writeZeros(44)
writeTLV(1021, layout.data, into: &metadata)
metadata.write(CSITVL.encode([.sliceScale]))

let uti = Array("public.layeredimage".utf8) + [0]
var type = ByteWriter()
type.writeLE(UInt32(uti.count))
type.writeLE(UInt32(0))
type.write(uti)
writeTLV(1005, type.data, into: &metadata)
metadata.write(CSITVL.encode([.bitmapFlag]))

let payload = DWAREnvelope.encode(flags: 0, payload: [])
let header = CSIHeader.encode(
renditionFlags: 0,
width: body.width,
height: body.height,
scaleFactor: 100,
pixelFormat: CSIHeader.pixelFormatData,
colorSpace: 0,
layout: .layerStack,
name: "Contents.json",
tvlLength: UInt32(metadata.offset),
bitmapCount: 1,
renditionLength: UInt32(payload.count)
)
return header + metadata.data + payload
}

private static func writeLayerReferences(_ body: LayerStackBody, into metadata: inout ByteWriter) {
var references = ByteWriter()
references.writeLE(UInt32(2))
for name in [body.backgroundName, body.foregroundName] {
references.writeZeros(16)
references.writeLE(body.width)
references.writeLE(body.height)
references.writeLE(UInt32(0))
references.writeLE(Float(1).bitPattern)
// The length includes this word and the three attribute pairs.
references.writeLE(UInt32(16))
references.writeLE(UInt16(AttributeID.element.rawValue))
references.writeLE(RenditionKey.Element.bitmap.rawValue)
references.writeLE(UInt16(AttributeID.part.rawValue))
references.writeLE(RenditionKey.Part.image.rawValue)
references.writeLE(UInt16(AttributeID.identifier.rawValue))
references.writeLE(UInt16(FacetKeys.nameHash(name) & 0xFFFF))
}
references.writeLE(UInt32(0))
writeTLV(1012, references.data, into: &metadata)
}

private static func writeTLV(_ tag: UInt32, _ value: Data, into writer: inout ByteWriter) {
writer.writeLE(tag)
writer.writeLE(UInt32(value.count))
writer.write(value)
}
}
Loading