skia-motion-runtime 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -34,6 +34,7 @@
34
34
  "files": [
35
35
  "LICENSE",
36
36
  "NOTICE.md",
37
+ "runtime/asset-binary.ts",
37
38
  "runtime/asset-draw.ts",
38
39
  "runtime/asset-image.ts",
39
40
  "runtime/asset-layout.ts",
@@ -54,7 +55,7 @@
54
55
  "templates/motion/machine.ts",
55
56
  "templates/motion/motion.ts"
56
57
  ],
57
- "version": "3.1.0",
58
+ "version": "3.2.0",
58
59
  "license": "MIT",
59
60
  "repository": {
60
61
  "type": "git",
@@ -0,0 +1,149 @@
1
+ import { decodeBase64, encodeBase64 } from './base64';
2
+
3
+ export type MotionAssetData = string | Uint8Array;
4
+ export type ResourceBytes = { readonly mime: string; readonly bytes: Uint8Array };
5
+ export type AssetResource = string | ResourceBytes;
6
+
7
+ export function isResourceBytes(value: unknown): value is ResourceBytes {
8
+ return isRecord(value) && typeof value.mime === 'string' && value.bytes instanceof Uint8Array;
9
+ }
10
+
11
+ const HEADER_SIZE = 12;
12
+ const MAGIC = 0x534b4d4f; // SKMO
13
+ const VERSION = 1;
14
+ const MAX_RESOURCES = 4096;
15
+ const RESOURCE_KEYS = ['images', 'fonts', 'audio'] as const;
16
+ const RESOURCE_MIMES = new Set([
17
+ 'image/png', 'image/webp', 'font/ttf', 'font/otf', 'audio/mpeg', 'audio/wav', 'audio/mp4', 'audio/aac',
18
+ ]);
19
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
20
+ value !== null && typeof value === 'object' && !Array.isArray(value);
21
+
22
+ function invalid(message: string): never {
23
+ throw new Error(`invalid SKMO asset: ${message}`);
24
+ }
25
+
26
+ export function isBinaryAsset(bytes: Uint8Array): boolean {
27
+ return bytes.length >= 4 && new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0) === MAGIC;
28
+ }
29
+
30
+ export function decodeAssetText(bytes: Uint8Array): string {
31
+ if (typeof TextDecoder !== 'undefined') return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
32
+ // Older React Native hosts may have no TextDecoder.
33
+ const chunks: string[] = [];
34
+ let chunk = '';
35
+ for (const byte of bytes) {
36
+ chunk += byte < 128 && byte !== 37 ? String.fromCharCode(byte) : '%' + byte.toString(16).padStart(2, '0');
37
+ if (chunk.length >= 8192) {
38
+ chunks.push(chunk);
39
+ chunk = '';
40
+ }
41
+ }
42
+ chunks.push(chunk);
43
+ return decodeURIComponent(chunks.join('')).replace(/^\uFEFF/, '');
44
+ }
45
+
46
+ function mapResources(value: unknown, map: (value: unknown) => unknown): unknown {
47
+ if (!isRecord(value)) return value;
48
+ const result = { ...value };
49
+ for (const key of RESOURCE_KEYS) {
50
+ const resources = value[key];
51
+ if (isRecord(resources)) {
52
+ result[key] = Object.fromEntries(Object.entries(resources).map(([name, resource]) => [name, map(resource)]));
53
+ }
54
+ }
55
+ return result;
56
+ }
57
+
58
+ export function mapFileResources(value: unknown, map: (value: unknown) => unknown): unknown {
59
+ const file = mapResources(value, map);
60
+ if (isRecord(file) && file.schema === 'skac.bundle/1' && isRecord(file.artboards)) {
61
+ file.artboards = Object.fromEntries(Object.entries(file.artboards).map(([name, board]) => [name, mapResources(board, map)]));
62
+ }
63
+ return file;
64
+ }
65
+
66
+ export function resourceDataUri(resource: AssetResource, cache?: Map<ResourceBytes, string>): string {
67
+ if (typeof resource === 'string') return resource;
68
+ const cached = cache?.get(resource);
69
+ if (cached !== undefined) return cached;
70
+ const uri = `data:${resource.mime};base64,${encodeBase64(resource.bytes)}`;
71
+ cache?.set(resource, uri);
72
+ return uri;
73
+ }
74
+
75
+ export function decodeBinaryAsset(bytes: Uint8Array, parseJSON: (text: string) => unknown): unknown {
76
+ if (bytes.length < HEADER_SIZE) invalid('truncated header');
77
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
78
+ if (view.getUint8(4) !== VERSION) invalid(`unsupported container version ${view.getUint8(4)}`);
79
+ if (view.getUint8(5) || view.getUint16(6)) invalid('unsupported header flags');
80
+ const manifestSize = view.getUint32(8, true);
81
+ const manifestEnd = HEADER_SIZE + manifestSize;
82
+ if (!manifestSize || manifestEnd > bytes.length) invalid('manifest length exceeds file bounds');
83
+ const manifest = parseJSON(decodeAssetText(bytes.subarray(HEADER_SIZE, manifestEnd)));
84
+ if (!isRecord(manifest) || Object.keys(manifest).length !== 2 || !isRecord(manifest.asset) ||
85
+ !Array.isArray(manifest.resources) || manifest.resources.length > MAX_RESOURCES) invalid('invalid manifest');
86
+
87
+ let offset = manifestEnd;
88
+ const resources: ResourceBytes[] = manifest.resources.map((entry: unknown) => {
89
+ if (!Array.isArray(entry) || entry.length !== 2) invalid('invalid resource entry');
90
+ const [mime, length] = entry;
91
+ if (!RESOURCE_MIMES.has(mime) || !Number.isSafeInteger(length) || length <= 0 || length > bytes.length - offset) {
92
+ invalid('resource type or length is invalid');
93
+ }
94
+ const resource = { mime, bytes: bytes.subarray(offset, offset + length) };
95
+ offset += length;
96
+ return resource;
97
+ });
98
+ if (offset !== bytes.length) invalid('unexpected trailing bytes');
99
+ return mapFileResources(manifest.asset, (index) => {
100
+ if (typeof index !== 'number' || !Number.isInteger(index) || !resources[index]) invalid('unknown resource index');
101
+ return resources[index]!;
102
+ });
103
+ }
104
+
105
+ /** The authoring CLI writes a validated legacy scene into an SKMO container. */
106
+ export function encodeBinaryAsset(file: unknown, encodeText: (text: string) => Uint8Array, limit: number): Uint8Array {
107
+ const uriIndices = new Map<string, number>();
108
+ const payloadIndices = new Map<string, number[]>();
109
+ const payload: ResourceBytes[] = [];
110
+ const asset = mapFileResources(file, (resource) => {
111
+ if (typeof resource !== 'string') invalid('expected a data URI to pack');
112
+ const known = uriIndices.get(resource);
113
+ if (known !== undefined) return known;
114
+ const header = /^data:([^;,]+);base64,/.exec(resource);
115
+ if (!header || !RESOURCE_MIMES.has(header[1]!)) invalid('unsupported resource type');
116
+ const mime = header[1]!;
117
+ const bytes = decodeBase64(resource.slice(header[0].length));
118
+ // Use FNV-1a to narrow candidates, then compare every byte before reusing an entry.
119
+ let hash = 2166136261;
120
+ for (const byte of bytes) hash = Math.imul(hash ^ byte, 16777619);
121
+ const key = `${mime}:${bytes.length}:${hash}`;
122
+ const candidates = payloadIndices.get(key) ?? [];
123
+ let index = candidates.find((candidate) => bytes.every((byte, i) => byte === payload[candidate]!.bytes[i]));
124
+ if (index === undefined) {
125
+ index = payload.length;
126
+ if (index >= MAX_RESOURCES) invalid('too many resources');
127
+ payload.push({ mime, bytes });
128
+ candidates.push(index);
129
+ payloadIndices.set(key, candidates);
130
+ }
131
+ uriIndices.set(resource, index);
132
+ return index;
133
+ });
134
+ const manifest = encodeText(JSON.stringify({ asset, resources: payload.map(({ mime, bytes }) => [mime, bytes.length]) }));
135
+ const size = payload.reduce((total, { bytes }) => total + bytes.length, HEADER_SIZE + manifest.length);
136
+ if (size > limit) throw new Error('packed asset exceeds 1 MiB');
137
+ const result = new Uint8Array(size);
138
+ const view = new DataView(result.buffer);
139
+ view.setUint32(0, MAGIC);
140
+ view.setUint8(4, VERSION);
141
+ view.setUint32(8, manifest.length, true);
142
+ result.set(manifest, HEADER_SIZE);
143
+ let offset = HEADER_SIZE + manifest.length;
144
+ for (const resource of payload) {
145
+ result.set(resource.bytes, offset);
146
+ offset += resource.bytes.length;
147
+ }
148
+ return result;
149
+ }
@@ -2,7 +2,8 @@ import {
2
2
  BlendMode, BlurStyle, ClipOp, FilterMode, MipmapMode, PaintStyle, Skia, StrokeCap, StrokeJoin, TextAlign, TextDirection, TileMode, VertexMode,
3
3
  type SkCanvas, type SkData, type SkImage, type SkPaint, type SkParagraph, type SkPath, type SkShader, type SkTypeface, type SkTypefaceFontProvider,
4
4
  } from 'react-native-skia';
5
- import { MAX_FEATHER, resolveAssetColor, usedAssetImages, type AssetNode, type AssetStroke, type AssetTextNode, type MotionAsset, type PathCommand } from './asset';
5
+ import { MAX_FEATHER, resolveAssetColor, usedAssetImages, type AssetNode, type AssetStroke, type AssetTextNode, type DrawableMotionAsset, type MotionAsset, type PathCommand } from './asset';
6
+ import type { AssetResource } from './asset-binary';
6
7
  import { fitAsset, fittedAnchorOffset, type AssetLayoutOptions } from './asset-layout';
7
8
  import { meshPinPosition, meshPosition, type MeshNode, type MeshPin } from './asset-mesh';
8
9
 
@@ -37,8 +38,15 @@ export type DrawableAsset = Pick<MotionAsset, 'channels'> & {
37
38
  export type AssetImages = Readonly<Record<string, SkImage>>;
38
39
  export type AssetMeshShaders = Readonly<Record<string, SkShader>>;
39
40
 
41
+ function skiaData(resource: AssetResource): SkData {
42
+ if (typeof resource === 'string') return Skia.Data.fromBase64(resource.slice(resource.indexOf(',') + 1));
43
+ const { bytes } = resource;
44
+ // Skia v3 reads the whole backing buffer. Give it only this resource.
45
+ return Skia.Data.fromBytes(bytes.byteOffset === 0 && bytes.length === bytes.buffer.byteLength ? bytes : new Uint8Array(bytes));
46
+ }
47
+
40
48
  /** Decode on the JS thread once per loaded file. Only the native images enter the UI worklet. */
41
- export function decodeAssetImages(asset: MotionAsset, slots: AssetImages = {}): AssetImages {
49
+ export function decodeAssetImages(asset: DrawableMotionAsset, slots: AssetImages = {}): AssetImages {
42
50
  for (const name of Object.keys(slots)) {
43
51
  if (!asset.imageSlots || !Object.hasOwn(asset.imageSlots, name)) throw new Error(`Unknown motion image slot "${name}"`);
44
52
  }
@@ -48,18 +56,18 @@ export function decodeAssetImages(asset: MotionAsset, slots: AssetImages = {}):
48
56
  MakeFromEncoded?: (data: SkData) => SkImage | null;
49
57
  MakeImageFromEncoded?: (data: SkData) => SkImage | null;
50
58
  };
51
- const byUri = new Map<string, SkImage>();
59
+ const byResource = new Map<AssetResource, SkImage>();
52
60
  const embedded = asset.images;
53
61
  const used = usedAssetImages(asset.artboard.nodes);
54
62
  return Object.fromEntries(Array.from(used, (name) => {
55
63
  if (Object.hasOwn(slots, name)) return [name, slots[name]!];
56
- const uri = embedded[asset.imageSlots?.[name] ?? name]!;
57
- const previous = byUri.get(uri);
64
+ const resource = embedded[asset.imageSlots?.[name] ?? name]!;
65
+ const previous = byResource.get(resource);
58
66
  if (previous) return [name, previous];
59
- const data = Skia.Data.fromBase64(uri.slice(uri.indexOf(',') + 1));
67
+ const data = skiaData(resource);
60
68
  const image = factory.MakeFromEncoded ? factory.MakeFromEncoded(data) : factory.MakeImageFromEncoded?.(data);
61
69
  if (!image) throw new Error(`images.${name}: could not decode the embedded image`);
62
- byUri.set(uri, image);
70
+ byResource.set(resource, image);
63
71
  return [name, image];
64
72
  }));
65
73
  }
@@ -145,6 +153,7 @@ function makeParagraph(node: AssetTextNode, text: string, provider?: SkTypefaceF
145
153
  builder.pushStyle({
146
154
  color: Skia.Color(node.fill), fontSize: node.fontSize,
147
155
  ...(node.fonts?.length ? { fontFamilies: [...node.fonts] } : {}),
156
+ ...(node.fontFeatures?.length ? { fontFeatures: [...node.fontFeatures] } : {}),
148
157
  });
149
158
  builder.addText(text);
150
159
  const paragraph = builder.build();
@@ -192,20 +201,26 @@ function prepareNode(
192
201
  }
193
202
 
194
203
  /** Build fixed geometry and paints once. Channel-driven paths and clips are still evaluated for each pose. */
195
- export function prepareAssetDrawing(asset: MotionAsset, images: AssetImages = {}): DrawableAsset {
204
+ export function prepareAssetDrawing(asset: DrawableMotionAsset, images: AssetImages = {}): DrawableAsset {
196
205
  const shaders: Record<string, SkShader> = {};
197
206
  const shadersByImage = new Map<SkImage, SkShader>();
198
207
  let fontProvider: SkTypefaceFontProvider | undefined;
199
- for (const [name, uri] of Object.entries(asset.fonts ?? {})) {
208
+ const typefaces = new Map<AssetResource, SkTypeface>();
209
+ for (const [name, resource] of Object.entries(asset.fonts ?? {})) {
200
210
  fontProvider ??= Skia.TypefaceFontProvider.Make();
201
- const data = Skia.Data.fromBase64(uri.slice(uri.indexOf(',') + 1));
202
- // Match the renamed factory while retaining the Skia 3.0 peer floor.
203
- const factory = Skia.Typeface as {
204
- MakeFromData?: (data: SkData) => SkTypeface | null;
205
- MakeFreeTypeFaceFromData?: (data: SkData) => SkTypeface | null;
206
- };
207
- const typeface = factory.MakeFromData ? factory.MakeFromData(data) : factory.MakeFreeTypeFaceFromData?.(data);
208
- if (!typeface) throw new Error(`fonts.${name}: Skia could not decode the font`);
211
+ let typeface = typefaces.get(resource);
212
+ if (!typeface) {
213
+ const data = skiaData(resource);
214
+ // Match the renamed factory while retaining the Skia 3.0 peer floor.
215
+ const factory = Skia.Typeface as {
216
+ MakeFromData?: (data: SkData) => SkTypeface | null;
217
+ MakeFreeTypeFaceFromData?: (data: SkData) => SkTypeface | null;
218
+ };
219
+ const decoded = factory.MakeFromData ? factory.MakeFromData(data) : factory.MakeFreeTypeFaceFromData?.(data);
220
+ if (!decoded) throw new Error(`fonts.${name}: Skia could not decode the font`);
221
+ typefaces.set(resource, decoded);
222
+ typeface = decoded;
223
+ }
209
224
  fontProvider.registerFont(typeface, name);
210
225
  }
211
226
  const textBindings = new Set<string>();
@@ -1,7 +1,11 @@
1
1
  import { decodeBase64 } from './base64';
2
+ import { isResourceBytes } from './asset-binary';
2
3
 
3
4
  /** Check the embedded image header before passing its bytes to a renderer. */
4
5
  export function imageSize(uri: unknown): { width: number; height: number } | null {
6
+ if (isResourceBytes(uri)) {
7
+ return uri.mime.startsWith('image/') ? imageFileSize(uri.mime.slice(6), uri.bytes) : null;
8
+ }
5
9
  if (typeof uri !== 'string') return null;
6
10
  const match = /^data:image\/(png|webp);base64,([A-Za-z0-9+/]+={0,2})$/.exec(uri);
7
11
  if (!match || match[0] !== uri || match[2]!.length % 4 !== 0) return null;
@@ -1,5 +1,6 @@
1
1
  import type { SkImage } from 'react-native-skia';
2
- import { assetClips, bindAssetPalette, parseAsset, type MotionAsset } from './asset';
2
+ import { assetClips, bindAssetPalette, parseDrawableAsset, type MotionAsset } from './asset';
3
+ import { resourceDataUri, type MotionAssetData, type ResourceBytes } from './asset-binary';
3
4
  import { decodeAssetImages, prepareAssetDrawing, rebindAssetMeshShaders, type AssetImages, type DrawableAsset } from './asset-draw';
4
5
 
5
6
  let nextAssetKey = 0;
@@ -18,9 +19,14 @@ export type LoadedMotionAsset = Readonly<{
18
19
  /** Prepare one file for reuse by independent player instances. Keep the result while those players are mounted. */
19
20
  export type MotionPrepareOptions = { artboard?: string; imageSlots?: AssetImages; palette?: Readonly<Record<string, string>> };
20
21
 
21
- export function loadMotionAsset(source: string, { artboard, imageSlots, palette }: MotionPrepareOptions = {}): LoadedMotionAsset {
22
- const asset = bindAssetPalette(parseAsset(source, artboard), palette);
22
+ export function loadMotionAsset(source: MotionAssetData, { artboard, imageSlots, palette }: MotionPrepareOptions = {}): LoadedMotionAsset {
23
+ const asset = bindAssetPalette(parseDrawableAsset(source, artboard), palette);
23
24
  const images = decodeAssetImages(asset, imageSlots);
25
+ let audio: LoadedMotionAsset['audio'];
26
+ if (asset.audio) {
27
+ const uris = new Map<ResourceBytes, string>();
28
+ audio = Object.fromEntries(Object.entries(asset.audio).map(([name, resource]) => [name, resourceDataUri(resource, uris)]));
29
+ }
24
30
  return {
25
31
  key: nextAssetKey++,
26
32
  machine: asset.machine,
@@ -29,7 +35,7 @@ export function loadMotionAsset(source: string, { artboard, imageSlots, palette
29
35
  images,
30
36
  clips: assetClips(asset),
31
37
  semantics: asset.semantics,
32
- audio: asset.audio,
38
+ audio,
33
39
  };
34
40
  }
35
41
 
@@ -38,10 +44,10 @@ export function loadMotionAsset(source: string, { artboard, imageSlots, palette
38
44
  * that work off the JS thread. Upload is opt-in and can retain textures until the file is released.
39
45
  */
40
46
  export async function preloadMotionAsset(
41
- source: string | LoadedMotionAsset,
47
+ source: MotionAssetData | LoadedMotionAsset,
42
48
  { uploadImages = false, ...options }: MotionPrepareOptions & { uploadImages?: boolean } = {},
43
49
  ): Promise<LoadedMotionAsset> {
44
- const loaded = typeof source === 'string' ? loadMotionAsset(source, options) : source;
50
+ const loaded = typeof source === 'string' || source instanceof Uint8Array ? loadMotionAsset(source, options) : source;
45
51
  const warmed = new Map<SkImage, SkImage>();
46
52
  const images: [string, SkImage][] = [];
47
53
  let changed = false;
package/runtime/asset.ts CHANGED
@@ -3,11 +3,14 @@ import { EASE_IN, EASE_IN_OUT, EASE_OUT } from '../templates/motion/motion';
3
3
  import type { Clips, Machine, StateEntry } from '../templates/motion/machine';
4
4
  import type { AssetAnchor } from './asset-layout';
5
5
  import { imageSize } from './asset-image';
6
+ import { decodeBase64 } from './base64';
7
+ import { decodeAssetText, decodeBinaryAsset, isBinaryAsset, isResourceBytes, mapFileResources, resourceDataUri, type AssetResource, type MotionAssetData, type ResourceBytes } from './asset-binary';
6
8
  import type { MeshNode, MeshVertex } from './asset-mesh';
7
9
 
8
10
  export const ASSET_SCHEMA = 'skac.asset/1';
9
11
  export const ASSET_BUNDLE_SCHEMA = 'skac.bundle/1';
10
12
  export const MAX_ASSET_BYTES = 1024 * 1024;
13
+ export const MAX_ASSET_SOURCE_BYTES = 8 * MAX_ASSET_BYTES;
11
14
  export const MAX_FEATHER = 64;
12
15
 
13
16
  export type Scalar = number | string;
@@ -47,9 +50,11 @@ type ImageNode = {
47
50
  };
48
51
 
49
52
  export type BoundText = string | { value: string };
53
+ type FontFeature = { name: string; value: number };
50
54
  export type AssetTextNode = {
51
55
  kind: 'text'; text: BoundText; x: Scalar; y: Scalar; width: number; fontSize: number; fill: string;
52
56
  fonts?: readonly string[]; direction?: 'ltr' | 'rtl'; align?: 'start' | 'center' | 'end'; maxLines?: number;
57
+ fontFeatures?: readonly FontFeature[];
53
58
  };
54
59
  export type AssetSemantic = {
55
60
  name: string; label: BoundText; role: 'button' | 'image' | 'text' | 'header';
@@ -61,31 +66,32 @@ export type AssetNode = Group | Shape | ImageNode | MeshNode | AssetTextNode;
61
66
  export type AssetMarker = { name: string; layer: string; state: string; audio?: string };
62
67
  export type AssetMarkerEvent = AssetMarker & { at: number };
63
68
  export type AssetAttachment = { from: string; to: string; maxDistance: number };
64
- export type MotionAsset<M extends Machine = Machine> = {
69
+ export type MotionAsset<M extends Machine = Machine, R extends AssetResource = string> = {
65
70
  schema: typeof ASSET_SCHEMA;
66
71
  name: string;
67
72
  artboard: { width: number; height: number; nodes: readonly AssetNode[] };
68
73
  channels: Readonly<Record<string, number>>;
69
- images?: Readonly<Record<string, string>>;
74
+ images?: Readonly<Record<string, R>>;
70
75
  imageSlots?: Readonly<Record<string, string>>;
71
76
  palette?: Readonly<Record<string, string>>;
72
- fonts?: Readonly<Record<string, string>>;
77
+ fonts?: Readonly<Record<string, R>>;
73
78
  fontLicenses?: Readonly<Record<string, string>>;
74
- audio?: Readonly<Record<string, string>>;
79
+ audio?: Readonly<Record<string, R>>;
75
80
  semantics?: readonly AssetSemantic[];
76
81
  clips: Readonly<Record<string, { ms: number; reducedAt?: number; tracks: Readonly<Record<string, Track>> }>>;
77
82
  machine: M;
78
83
  markers?: readonly AssetMarker[];
79
84
  attachments?: readonly AssetAttachment[];
80
85
  };
81
- export type MotionAssetFile = MotionAsset | {
86
+ export type DrawableMotionAsset = MotionAsset<Machine, AssetResource>;
87
+ export type MotionAssetFile<R extends AssetResource = string> = MotionAsset<Machine, R> | {
82
88
  schema: typeof ASSET_BUNDLE_SCHEMA;
83
89
  name: string;
84
90
  defaultArtboard: string;
85
- artboards: Readonly<Record<string, MotionAsset>>;
86
- fonts?: MotionAsset['fonts'];
91
+ artboards: Readonly<Record<string, MotionAsset<Machine, R>>>;
92
+ fonts?: MotionAsset<Machine, R>['fonts'];
87
93
  fontLicenses?: MotionAsset['fontLicenses'];
88
- audio?: MotionAsset['audio'];
94
+ audio?: MotionAsset<Machine, R>['audio'];
89
95
  };
90
96
 
91
97
  const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
@@ -200,12 +206,33 @@ function resourceMap(value: unknown, at: string, pattern: RegExp) {
200
206
  for (const [name, uri] of Object.entries(resources)) {
201
207
  const key = `${at}.${name}`;
202
208
  identifier(name, key);
209
+ if (isResourceBytes(uri)) {
210
+ if (!pattern.test(`data:${uri.mime};base64,AAAA`)) invalid(key, 'invalid embedded resource media type');
211
+ if (pattern === FONT_URI && !hasFontHeader(uri.bytes)) invalid(key, 'expected a TTF or OTF font header');
212
+ continue;
213
+ }
203
214
  const match = typeof uri === 'string' ? pattern.exec(uri) : null;
204
215
  if (!match || match[0] !== uri || match[2]!.length % 4 !== 0) invalid(key, 'expected an embedded base64 data URI');
216
+ if (pattern === FONT_URI) {
217
+ const encoded = match[2]!;
218
+ const padding = encoded.endsWith('==') ? 2 : encoded.endsWith('=') ? 1 : 0;
219
+ if (!hasFontHeader(decodeBase64(encoded.slice(0, 16)), encoded.length * 3 / 4 - padding)) {
220
+ invalid(key, 'expected a TTF or OTF font header');
221
+ }
222
+ }
205
223
  }
206
224
  return resources;
207
225
  }
208
226
 
227
+ export function hasFontHeader(bytes: Uint8Array, size = bytes.byteLength): boolean {
228
+ if (bytes.byteLength < 12) return false;
229
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
230
+ const format = view.getUint32(0);
231
+ const tables = view.getUint16(4);
232
+ return (format === 0x00010000 || format === 0x4f54544f || format === 0x74727565 || format === 0x74797031)
233
+ && tables > 0 && 12 + 16 * tables <= size;
234
+ }
235
+
209
236
  function checkFontLicenses(value: unknown, fonts: Record<string, unknown>, at: string): void {
210
237
  if (value === undefined) return;
211
238
  for (const [name, license] of Object.entries(record(value, at))) {
@@ -272,7 +299,7 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
272
299
  const { channels, images, imageSlots, points } = context;
273
300
  const node = record(value, at);
274
301
  if (node.kind === 'text') {
275
- record(node, at, ['kind', 'text', 'x', 'y', 'width', 'fontSize', 'fill', 'fonts', 'direction', 'align', 'maxLines']);
302
+ record(node, at, ['kind', 'text', 'x', 'y', 'width', 'fontSize', 'fill', 'fonts', 'direction', 'align', 'maxLines', 'fontFeatures']);
276
303
  checkText(node.text, `${at}.text`, context.values);
277
304
  scalar(node.x, `${at}.x`, channels);
278
305
  scalar(node.y, `${at}.y`, channels);
@@ -282,6 +309,21 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
282
309
  if (node.fonts !== undefined) list(node.fonts, `${at}.fonts`, 8).forEach((name, i) => {
283
310
  if (typeof name !== 'string' || !Object.hasOwn(context.fonts, name)) invalid(`${at}.fonts[${i}]`, 'unknown embedded font');
284
311
  });
312
+ if (node.fontFeatures !== undefined) {
313
+ const names = new Set<string>();
314
+ list(node.fontFeatures, `${at}.fontFeatures`, 16).forEach((value, i) => {
315
+ const key = `${at}.fontFeatures[${i}]`;
316
+ const feature = record(value, key, ['name', 'value']);
317
+ if (typeof feature.name !== 'string' || !/^[a-zA-Z0-9]{4}$/.test(feature.name)) {
318
+ invalid(`${key}.name`, 'expected a four-character OpenType feature tag');
319
+ }
320
+ if (names.has(feature.name)) invalid(`${key}.name`, 'duplicate font feature');
321
+ names.add(feature.name);
322
+ if (!Number.isInteger(number(feature.value, `${key}.value`, 0, 65535))) {
323
+ invalid(`${key}.value`, 'expected an integer');
324
+ }
325
+ });
326
+ }
285
327
  if (node.direction !== undefined && node.direction !== 'ltr' && node.direction !== 'rtl') invalid(`${at}.direction`, 'expected ltr or rtl');
286
328
  if (node.align !== undefined && !['start', 'center', 'end'].includes(node.align as string)) invalid(`${at}.align`, 'expected start, center or end');
287
329
  if (node.maxLines !== undefined && !Number.isInteger(number(node.maxLines, `${at}.maxLines`, 1, 16))) {
@@ -366,7 +408,7 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
366
408
  colors.forEach((item, i) => color(item, `${at}.fill.colors[${i}]`));
367
409
  }
368
410
 
369
- function validateAsset(value: unknown): MotionAsset {
411
+ function validateAsset(value: unknown): DrawableMotionAsset {
370
412
  const data = record(value, 'asset', [
371
413
  'schema', 'name', 'artboard', 'channels', 'clips', 'machine', 'markers', 'images', 'imageSlots', 'palette', 'attachments', 'fonts', 'fontLicenses', 'audio', 'semantics',
372
414
  ]);
@@ -485,7 +527,7 @@ function validateAsset(value: unknown): MotionAsset {
485
527
  const { where, error, hint } = checked.problems[0]!;
486
528
  invalid(where ? `machine.${where}` : 'machine', `${error}. ${hint}`);
487
529
  }
488
- const typed = data as MotionAsset;
530
+ const typed = data as DrawableMotionAsset;
489
531
  const names = new Set();
490
532
  if (data.markers !== undefined) {
491
533
  list(data.markers, 'markers', 256).forEach((item, i) => {
@@ -505,26 +547,53 @@ function validateAsset(value: unknown): MotionAsset {
505
547
  return typed;
506
548
  }
507
549
 
508
- /** Decode the same data file on a React Native JS thread and in the CLI. */
509
- export function parseAssetFile(text: string): MotionAssetFile {
510
- if (typeof text !== 'string' || text.length > MAX_ASSET_BYTES) invalid('asset', 'expected a JSON asset of at most 1 MiB');
550
+ /** Read the portable scene as editable JSON-compatible data. */
551
+ export function parseAssetFile(source: MotionAssetData): MotionAssetFile {
552
+ const file = parseDrawableFile(source);
553
+ if (typeof source === 'string' || !isBinaryAsset(source)) return file as MotionAssetFile;
554
+ const uris = new Map<ResourceBytes, string>();
555
+ return mapFileResources(file, (value) => resourceDataUri(value as AssetResource, uris)) as MotionAssetFile;
556
+ }
557
+
558
+ /** The CLI may prune unused resources before enforcing the shipped limit. */
559
+ export function parseAssetSource(text: string): MotionAssetFile {
560
+ return parseAssetText(text, MAX_ASSET_SOURCE_BYTES) as MotionAssetFile;
561
+ }
562
+
563
+ function parseDrawableFile(source: MotionAssetData): MotionAssetFile<AssetResource> {
564
+ if (typeof source === 'string') return parseAssetText(source, MAX_ASSET_BYTES);
565
+ if (!(source instanceof Uint8Array) || source.length > MAX_ASSET_BYTES) invalid('asset', 'expected an asset of at most 1 MiB');
566
+ if (isBinaryAsset(source)) return validateAssetFile(decodeBinaryAsset(source, parseJSON));
567
+ return validateAssetFile(parseJSON(decodeAssetText(source)));
568
+ }
569
+
570
+ function parseAssetText(text: string, limit: number): MotionAssetFile<AssetResource> {
571
+ const message = `expected a JSON asset of at most ${limit / MAX_ASSET_BYTES} MiB`;
572
+ if (typeof text !== 'string' || text.length > limit) invalid('asset', message);
511
573
  const bytes = encodeURI(text).replace(/%[0-9A-F]{2}/g, 'x').length;
512
- if (bytes > MAX_ASSET_BYTES) invalid('asset', 'expected a JSON asset of at most 1 MiB');
513
- const decoded: unknown = JSON.parse(text, (key, value: unknown) => {
574
+ if (bytes > limit) invalid('asset', message);
575
+ return validateAssetFile(parseJSON(text));
576
+ }
577
+
578
+ function parseJSON(text: string): unknown {
579
+ return JSON.parse(text, (key, value: unknown) => {
514
580
  if (RESERVED_KEYS.has(key)) invalid(key, 'reserved field name');
515
581
  if (typeof value === 'number' && !Number.isFinite(value)) invalid(key, 'expected a finite number');
516
582
  return value;
517
583
  });
584
+ }
585
+
586
+ function validateAssetFile(decoded: unknown): MotionAssetFile<AssetResource> {
518
587
  const file = record(decoded, 'asset');
519
588
  if (file.schema !== ASSET_BUNDLE_SCHEMA) return validateAsset(file);
520
589
  record(file, 'bundle', ['schema', 'name', 'defaultArtboard', 'artboards', 'fonts', 'fontLicenses', 'audio']);
521
590
  const name = identifier(file.name, 'bundle.name');
522
591
  const defaultArtboard = identifier(file.defaultArtboard, 'bundle.defaultArtboard');
523
592
  const artboards = record(file.artboards, 'bundle.artboards');
524
- const fonts = resourceMap(file.fonts, 'bundle.fonts', FONT_URI) as NonNullable<MotionAsset['fonts']>;
593
+ const fonts = resourceMap(file.fonts, 'bundle.fonts', FONT_URI) as NonNullable<DrawableMotionAsset['fonts']>;
525
594
  checkFontLicenses(file.fontLicenses, fonts, 'bundle.fontLicenses');
526
595
  const fontLicenses = file.fontLicenses as MotionAsset['fontLicenses'];
527
- const audio = resourceMap(file.audio, 'bundle.audio', AUDIO_URI) as NonNullable<MotionAsset['audio']>;
596
+ const audio = resourceMap(file.audio, 'bundle.audio', AUDIO_URI) as NonNullable<DrawableMotionAsset['audio']>;
528
597
  const entries = Object.entries(artboards);
529
598
  if (entries.length < 1 || entries.length > 16) invalid('bundle.artboards', 'expected one to sixteen artboards');
530
599
  if (!Object.hasOwn(artboards, defaultArtboard)) invalid('bundle.defaultArtboard', 'unknown artboard');
@@ -544,7 +613,7 @@ export function parseAssetFile(text: string): MotionAssetFile {
544
613
  ...board, fonts: { ...fonts, ...localFonts },
545
614
  fontLicenses: { ...fontLicenses, ...localLicenses }, audio: { ...audio, ...localAudio },
546
615
  });
547
- return [key, board as MotionAsset];
616
+ return [key, board as DrawableMotionAsset];
548
617
  } catch (error) {
549
618
  invalid(`bundle.artboards.${key}`, (error as Error).message);
550
619
  }
@@ -552,7 +621,7 @@ export function parseAssetFile(text: string): MotionAssetFile {
552
621
  };
553
622
  }
554
623
 
555
- export function selectArtboard(file: MotionAssetFile, artboard?: string): MotionAsset {
624
+ export function selectArtboard<R extends AssetResource>(file: MotionAssetFile<R>, artboard?: string): MotionAsset<Machine, R> {
556
625
  if (file.schema === ASSET_SCHEMA) {
557
626
  if (artboard === undefined || artboard === file.name) return file;
558
627
  invalid('artboard', `unknown artboard "${artboard}". Available: ${file.name}`);
@@ -570,8 +639,13 @@ export function selectArtboard(file: MotionAssetFile, artboard?: string): Motion
570
639
  };
571
640
  }
572
641
 
573
- export function parseAsset(text: string, artboard?: string): MotionAsset {
574
- return selectArtboard(parseAssetFile(text), artboard);
642
+ export function parseAsset(source: MotionAssetData, artboard?: string): MotionAsset {
643
+ return selectArtboard(parseAssetFile(source), artboard);
644
+ }
645
+
646
+ /** Decode a scene for drawing and preserve encoded image and font bytes for Skia. */
647
+ export function parseDrawableAsset(source: MotionAssetData, artboard?: string): DrawableMotionAsset {
648
+ return selectArtboard(parseDrawableFile(source), artboard);
575
649
  }
576
650
 
577
651
  export function resolveAssetColor(value: AssetColor, palette: Readonly<Record<string, string>>): string {
@@ -579,7 +653,7 @@ export function resolveAssetColor(value: AssetColor, palette: Readonly<Record<st
579
653
  return typeof value === 'string' ? value : palette[value.palette]!;
580
654
  }
581
655
 
582
- export function bindAssetPalette(asset: MotionAsset, overrides?: Readonly<Record<string, string>>): MotionAsset {
656
+ export function bindAssetPalette<R extends AssetResource>(asset: MotionAsset<Machine, R>, overrides?: Readonly<Record<string, string>>): MotionAsset<Machine, R> {
583
657
  if (!overrides) return asset;
584
658
  for (const [name, value] of Object.entries(overrides)) {
585
659
  if (!asset.palette || !Object.hasOwn(asset.palette, name)) invalid(`palette.${name}`, 'unknown palette entry');
@@ -625,7 +699,7 @@ function trackValue(track: Track, ms: number): number {
625
699
  }
626
700
 
627
701
  /** Adapt data tracks to the existing state-machine clip interface. */
628
- export function assetClips(asset: MotionAsset): Clips {
702
+ export function assetClips(asset: Pick<MotionAsset, 'clips'>): Clips {
629
703
  return Object.fromEntries(Object.entries(asset.clips).map(([name, { ms, reducedAt, tracks }]) => {
630
704
  const channels = Object.entries(tracks);
631
705
  return [name, {
package/runtime/base64.ts CHANGED
@@ -17,3 +17,21 @@ export function decodeBase64(encoded: string): Uint8Array {
17
17
  }
18
18
  return bytes.subarray(0, length);
19
19
  }
20
+
21
+ export function encodeBase64(bytes: Uint8Array): string {
22
+ const chunks: string[] = [];
23
+ let chunk = '';
24
+ for (let i = 0; i < bytes.length; i += 3) {
25
+ const a = bytes[i]!;
26
+ const b = bytes[i + 1] ?? 0;
27
+ const c = bytes[i + 2] ?? 0;
28
+ chunk += ALPHABET[a >> 2]! + ALPHABET[((a & 3) << 4) | (b >> 4)]! +
29
+ (i + 1 < bytes.length ? ALPHABET[((b & 15) << 2) | (c >> 6)]! : '=') +
30
+ (i + 2 < bytes.length ? ALPHABET[c & 63]! : '=');
31
+ if (chunk.length >= 8192) {
32
+ chunks.push(chunk);
33
+ chunk = '';
34
+ }
35
+ }
36
+ return chunks.join('') + chunk;
37
+ }
package/runtime/expo.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Asset } from 'expo-asset';
2
2
  import { File } from 'expo-file-system';
3
+ import { MAX_ASSET_BYTES } from './asset';
3
4
  import { useMotionAsset, type MotionAssetOptions } from './useMotionAsset';
4
5
 
5
6
  /** Read a .skmotion from Expo's Metro asset registry in a development or release build. */
@@ -10,7 +11,9 @@ export function useExpoMotionAsset(moduleId: number | null | undefined, options?
10
11
  const asset = await Asset.fromModule(moduleId).downloadAsync();
11
12
  if (signal.aborted) throw new Error('Motion asset load cancelled');
12
13
  if (!asset.localUri) throw new Error('Expo did not produce a local motion file');
13
- return new File(asset.localUri).text();
14
+ const file = new File(asset.localUri);
15
+ if (file.size > MAX_ASSET_BYTES) throw new Error('Motion asset exceeds 1 MiB');
16
+ return file.bytes();
14
17
  },
15
18
  }, options);
16
19
  }
@@ -2,8 +2,9 @@ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRe
2
2
  import type { ForwardedRef, ReactElement, RefAttributes } from 'react';
3
3
  import { AppState, Pressable, StyleSheet, View, type LayoutChangeEvent, type ViewProps } from 'react-native';
4
4
  import { Canvas, Picture, Skia, createPicture, type SkCanvas } from 'react-native-skia';
5
- import { useDerivedValue, type SharedValue } from 'react-native-reanimated';
5
+ import { useAnimatedReaction, useDerivedValue, useSharedValue, type SharedValue } from 'react-native-reanimated';
6
6
  import { assetMarkerEvents, type AssetMarkerEvent, type AssetSemantic } from './asset';
7
+ import type { MotionAssetData } from './asset-binary';
7
8
  import { drawAsset, type AssetImages, type DrawableAsset } from './asset-draw';
8
9
  import { loadMotionAsset, type LoadedMotionAsset } from './asset-load';
9
10
  import { fitAsset, type AssetLayoutOptions } from './asset-layout';
@@ -11,6 +12,7 @@ import { useMachine, type MachineHandle, type MachineInputs, type MachineValues
11
12
  import type { Machine, Pose, StateEntry } from '../templates/motion/machine';
12
13
 
13
14
  export { parseAsset, parseAssetFile, selectArtboard, type MotionAsset, type MotionAssetFile, type AssetMarkerEvent } from './asset';
15
+ export type { MotionAssetData } from './asset-binary';
14
16
 
15
17
  export { loadMotionAsset, preloadMotionAsset, type LoadedMotionAsset, type MotionPrepareOptions } from './asset-load';
16
18
  export { useMotionAsset, type MotionAssetOptions, type MotionAssetSource, type MotionAssetResult } from './useMotionAsset';
@@ -31,7 +33,7 @@ export type MotionPlayerProps<B extends MotionBindings = MotionBindings> = Pick<
31
33
  'accessibilityHint' | 'accessibilityValue' | 'accessibilityState' |
32
34
  'accessibilityActions' | 'onAccessibilityAction'
33
35
  > & AssetLayoutOptions & {
34
- source: string | LoadedMotionAsset;
36
+ source: MotionAssetData | LoadedMotionAsset;
35
37
  artboard?: string;
36
38
  width?: number;
37
39
  height?: number;
@@ -53,10 +55,10 @@ export type MotionPlayerProps<B extends MotionBindings = MotionBindings> = Pick<
53
55
 
54
56
  type LoadedProps = Omit<MotionPlayerProps, 'source'> & { loaded: LoadedMotionAsset; playerRef: ForwardedRef<MotionPlayerHandle> };
55
57
 
56
- function readChannels(pose: Pose, channels?: MotionSharedNumbers) {
58
+ function readChannels(base: Pose['channels'], channels?: MotionSharedNumbers) {
57
59
  'worklet';
58
- if (!channels) return pose.channels;
59
- const values = { ...pose.channels };
60
+ if (!channels) return base;
61
+ const values = { ...base };
60
62
  for (const [name, shared] of Object.entries(channels)) {
61
63
  const value = shared.value;
62
64
  if (Number.isFinite(value)) values[name] = value;
@@ -64,7 +66,7 @@ function readChannels(pose: Pose, channels?: MotionSharedNumbers) {
64
66
  return values;
65
67
  }
66
68
 
67
- function AssetPicture({ drawing, images, pose, snapshot, readOnUI, width, height, layout, channels }: {
69
+ function AssetPicture({ drawing, images, pose, snapshot, readOnUI, width, height, layout, channels, active }: {
68
70
  drawing: DrawableAsset;
69
71
  images: AssetImages;
70
72
  pose: SharedValue<Pose>;
@@ -74,7 +76,19 @@ function AssetPicture({ drawing, images, pose, snapshot, readOnUI, width, height
74
76
  height: number;
75
77
  layout: AssetLayoutOptions;
76
78
  channels?: MotionSharedNumbers;
79
+ active: boolean;
77
80
  }) {
81
+ const overrides = useSharedValue<Record<string, number> | undefined>(undefined);
82
+ useAnimatedReaction(
83
+ () => active ? readChannels({}, channels) : null,
84
+ (next, previous) => {
85
+ if (next === null) return;
86
+ const keys = Object.keys(next);
87
+ if (!previous || keys.length !== Object.keys(previous).length || keys.some((name) => next[name] !== previous[name])) {
88
+ overrides.value = next;
89
+ }
90
+ },
91
+ );
78
92
  const picture = useDerivedValue(() => {
79
93
  // The mapper subscribes to captured shared values, and readOnUI hides its snapshot.
80
94
  void snapshot?.value;
@@ -84,7 +98,7 @@ function AssetPicture({ drawing, images, pose, snapshot, readOnUI, width, height
84
98
  if (typeof value === 'string') values[name] = value;
85
99
  }
86
100
  return createPicture(
87
- (canvas) => drawAsset(canvas, drawing, readChannels(pose.value, channels), width, height, images, values, layout),
101
+ (canvas) => drawAsset(canvas, drawing, { ...pose.value.channels, ...overrides.value }, width, height, images, values, layout),
88
102
  Skia.XYWHRect(0, 0, width, height),
89
103
  );
90
104
  });
@@ -151,11 +165,13 @@ function LoadedPlayer({
151
165
  if (Object.keys(labelChanges).length) setLabels((previous) => ({ ...previous, ...labelChanges }));
152
166
  if (Object.keys(appChanges).length) valuesCallback.current?.(appChanges);
153
167
  }, [observeValues, semanticNames]);
168
+ const active = measured && foreground && (live ?? true);
154
169
  const machine = useMachine(loaded.machine, clips, {
155
- live: measured && foreground && (live ?? true),
170
+ live: active,
156
171
  reduced,
157
172
  frameRate,
158
173
  clocks,
174
+ channelDefaults: drawing.channels,
159
175
  onStateEntries: markers?.length && (onMarker || onAudio) ? onStateEntries : undefined,
160
176
  initialValues,
161
177
  observeValues: watched,
@@ -188,7 +204,7 @@ function LoadedPlayer({
188
204
  <Canvas style={StyleSheet.absoluteFill}>
189
205
  {measured && <AssetPicture drawing={drawing} images={images} pose={machine.pose} readOnUI={machine.readOnUI}
190
206
  snapshot={drawing.textBindings?.length ? machine.snapshot : undefined}
191
- width={viewport.width} height={viewport.height} layout={layout} channels={channels} />}
207
+ width={viewport.width} height={viewport.height} layout={layout} channels={channels} active={active} />}
192
208
  </Canvas>
193
209
  {regions}
194
210
  </View>
@@ -218,7 +234,8 @@ function SemanticRegion({ entry, label, artboard, viewport, layout, fire }: {
218
234
 
219
235
  export const MotionPlayer = forwardRef<MotionPlayerHandle, MotionPlayerProps>(function MotionPlayer({ source, artboard, ...props }, ref) {
220
236
  // The inner hook owns one machine snapshot per loaded file. An updated file starts at t=0.
221
- const loaded = useMemo(() => typeof source === 'string' ? loadMotionAsset(source, { artboard }) : source, [source, artboard]);
237
+ const loaded = useMemo(() => typeof source === 'string' || source instanceof Uint8Array
238
+ ? loadMotionAsset(source, { artboard }) : source, [source, artboard]);
222
239
  return <LoadedPlayer key={loaded.key} loaded={loaded} playerRef={ref} {...props} />;
223
240
  }) as <B extends MotionBindings = MotionBindings>(props: MotionPlayerProps<B> & RefAttributes<MotionPlayerHandle<B>>) => ReactElement;
224
241
 
@@ -244,7 +261,7 @@ export function drawMotionClip(
244
261
  const value = options.text?.[key] ?? asset.machine.values?.[key]?.default;
245
262
  if (typeof value === 'string') text[key] = value;
246
263
  }
247
- drawAsset(canvas, asset.drawing, readChannels(clip.play(time), options.channels),
264
+ drawAsset(canvas, asset.drawing, readChannels(clip.play(time).channels, options.channels),
248
265
  options.width, options.height, asset.images, text, options);
249
266
  }
250
267
 
@@ -29,6 +29,8 @@ export type MachineOptions = {
29
29
  frameRate?: number;
30
30
  /** Host clocks in milliseconds, keyed by the machine's declared clock names. */
31
31
  clocks?: Record<string, SharedValue<number>>;
32
+ /** Resting values for channels that an animation does not key. */
33
+ channelDefaults?: Readonly<Record<string, number>>;
32
34
  probe?: MachineProbe;
33
35
  /** Entries after initialization, in machine order. Delivered on the React Native thread. */
34
36
  onStateEntries?: (entries: StateEntry[]) => void;
@@ -117,7 +119,7 @@ function samePose(left: Pose, right: Pose): boolean {
117
119
  /** Play `machine` with its `clips`. The machine and clips must be stable (module constants), as an exported scene's are. */
118
120
  export function useMachine<const M extends Machine>(machine: M, clips: Clips, options: MachineOptions = {}): MachineHandle<M> {
119
121
  if (__DEV__ && options.exportedBy !== undefined) assertRuntimeVersion(options.exportedBy);
120
- const { live = true, clocks = noClocks, probe, onStateEntries, onValuesChange, observeValues } = options;
122
+ const { live = true, clocks = noClocks, channelDefaults, probe, onStateEntries, onValuesChange, observeValues } = options;
121
123
  const systemReduced = useReducedMotion();
122
124
  const reduced = options.reduced ?? systemReduced;
123
125
  const rate = options.frameRate;
@@ -145,7 +147,7 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
145
147
  const lastChannels = useSharedValue('');
146
148
  const awaitingChange = useSharedValue(false);
147
149
  const liveNow = useSharedValue(live);
148
- const firstPose = useMemo(() => poseAt(compiled, clips, first, 0, read, reduced), [first]); // eslint-disable-line react-hooks/exhaustive-deps
150
+ const firstPose = useMemo(() => poseAt(compiled, clips, first, 0, read, reduced, channelDefaults), [first]); // eslint-disable-line react-hooks/exhaustive-deps
149
151
  const pose = useSharedValue<Pose>(firstPose);
150
152
 
151
153
  const observed = useMemo(() => Array.from(new Set(observeValues), (name) => {
@@ -173,7 +175,7 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
173
175
  if (!liveNow.value) return undefined;
174
176
  // Subscribe to the named clocks, including when the frame callback sleeps.
175
177
  for (const n of clockNames) void clocks[n]!.value;
176
- return poseAt(compiled, clips, snapshot.value, ms.value, read, reduced);
178
+ return poseAt(compiled, clips, snapshot.value, ms.value, read, reduced, channelDefaults);
177
179
  },
178
180
  (next) => {
179
181
  // The reaction subscribes only to the prepare inputs. Updating its output cannot wake it again.
@@ -203,14 +205,14 @@ export function useMachine<const M extends Machine>(machine: M, clips: Clips, op
203
205
  snapshot.value = next;
204
206
  if (entries?.length && onStateEntries) scheduleOnRN(onStateEntries, entries);
205
207
  if (probe?.onChanged) {
206
- const key = JSON.stringify(poseAt(compiled, clips, next, t, read, reduced).channels);
208
+ const key = JSON.stringify(poseAt(compiled, clips, next, t, read, reduced, channelDefaults).channels);
207
209
  if (key !== lastChannels.value) {
208
210
  lastChannels.value = key;
209
211
  if (awaitingChange.value) { awaitingChange.value = false; scheduleOnRN(probe.onChanged, frame.timestamp); }
210
212
  }
211
213
  }
212
214
  if (pending.value.length === 0 && settled(compiled, next, read, reduced).frame) scheduleOnRN(sleep);
213
- }, [compiled, clips, reduced, probe, onStateEntries, frameInterval, read]);
215
+ }, [compiled, clips, reduced, probe, onStateEntries, frameInterval, read, channelDefaults]);
214
216
 
215
217
  const frames = useFrameCallback(tick, false);
216
218
  // The callback is switched from JavaScript only: switching it from a worklet makes a synchronous remote call that
@@ -1,11 +1,12 @@
1
1
  import { useEffect, useMemo, useState } from 'react';
2
2
  import { preloadMotionAsset, type LoadedMotionAsset, type MotionPrepareOptions } from './asset-load';
3
3
  import type { AssetImages } from './asset-draw';
4
+ import type { MotionAssetData } from './asset-binary';
4
5
 
5
- export type MotionAssetSource = string | { uri: string } | {
6
+ export type MotionAssetSource = MotionAssetData | { uri: string } | {
6
7
  /** Stable identity for a custom loader. Change it when the source changes. */
7
8
  key: string;
8
- read: (signal: AbortSignal) => Promise<string>;
9
+ read: (signal: AbortSignal) => Promise<MotionAssetData>;
9
10
  };
10
11
  export type MotionAssetOptions = MotionPrepareOptions & { uploadImages?: boolean };
11
12
  type Failure = { status: 'error'; asset: null; error: Error };
@@ -23,7 +24,9 @@ type CacheEntry = {
23
24
  // Cache prepared resources while subscribers own them. Each player creates its own machine snapshot.
24
25
  const cache = new Map<string, CacheEntry>();
25
26
  const imageIds = new WeakMap<object, number>();
27
+ const byteIds = new WeakMap<Uint8Array, number>();
26
28
  let nextImageId = 0;
29
+ let nextByteId = 0;
27
30
  const idle = { status: 'idle', asset: null, error: null } as const;
28
31
  const loading = { status: 'loading', asset: null, error: null } as const;
29
32
 
@@ -40,11 +43,20 @@ function slotKey(images: AssetImages | undefined) {
40
43
  }
41
44
 
42
45
  async function readSource(source: MotionAssetSource, signal: AbortSignal) {
43
- if (typeof source === 'string') return source;
46
+ if (typeof source === 'string' || source instanceof Uint8Array) return source;
44
47
  if ('read' in source) return source.read(signal);
45
48
  const response = await fetch(source.uri, { signal });
46
49
  if (!response.ok) throw new Error(`Unable to load motion asset (HTTP ${response.status})`);
47
- return response.text();
50
+ return new Uint8Array(await response.arrayBuffer());
51
+ }
52
+
53
+ function byteId(bytes: Uint8Array) {
54
+ let id = byteIds.get(bytes);
55
+ if (id === undefined) {
56
+ id = nextByteId++;
57
+ byteIds.set(bytes, id);
58
+ }
59
+ return id;
48
60
  }
49
61
 
50
62
  function retain(key: string, source: MotionAssetSource, options: MotionAssetOptions) {
@@ -54,9 +66,9 @@ function retain(key: string, source: MotionAssetSource, options: MotionAssetOpti
54
66
  const signal = controller.signal;
55
67
  const promise = Promise.resolve().then(async () => {
56
68
  if (signal.aborted) throw new Error('Motion asset load cancelled');
57
- const text = await readSource(source, signal);
69
+ const data = await readSource(source, signal);
58
70
  if (signal.aborted) throw new Error('Motion asset load cancelled');
59
- return preloadMotionAsset(text, options);
71
+ return preloadMotionAsset(data, options);
60
72
  });
61
73
  entry = { promise, controller, users: 0 };
62
74
  const created = entry;
@@ -72,8 +84,10 @@ function retain(key: string, source: MotionAssetSource, options: MotionAssetOpti
72
84
  /** Asynchronously load and share an asset. For Expo module IDs use the /expo entry point. */
73
85
  export function useMotionAsset(source?: MotionAssetSource | null, options: MotionAssetOptions = {}): MotionAssetResult {
74
86
  const { uploadImages = false, artboard, imageSlots, palette } = options;
75
- const kind = source == null ? undefined : typeof source === 'string' ? 'text' : 'uri' in source ? 'uri' : 'custom';
76
- const id = typeof source === 'string' ? source : source == null ? undefined : 'uri' in source ? source.uri : source.key;
87
+ const kind = source == null ? undefined : typeof source === 'string' ? 'text'
88
+ : source instanceof Uint8Array ? 'bytes' : 'uri' in source ? 'uri' : 'custom';
89
+ const id = source == null || typeof source === 'string' ? source
90
+ : source instanceof Uint8Array ? byteId(source) : 'uri' in source ? source.uri : source.key;
77
91
  const key = useMemo(() => kind === undefined ? undefined : JSON.stringify([
78
92
  kind, id, uploadImages, artboard, slotKey(imageSlots),
79
93
  Object.keys(palette ?? {}).sort().map((name) => [name, palette![name]]),
@@ -388,14 +388,19 @@ function clipTime(loop: number, ms: number, local: number, reduced: boolean, red
388
388
  return p <= ms ? p : 2 * ms - p;
389
389
  }
390
390
 
391
- function lerpPose(a: Pose, b: Pose, w: number): Pose {
391
+ function lerpPose(a: Pose, b: Pose, w: number, underneath: Readonly<Record<string, number>>): Pose {
392
392
  'worklet';
393
393
  const channels: Record<string, number> = { ...a.channels };
394
394
  for (const k of Object.keys(b.channels)) {
395
395
  const bv = b.channels[k]!;
396
- const av = a.channels[k];
396
+ const av = a.channels[k] ?? underneath[k];
397
397
  channels[k] = av === undefined ? bv : av + (bv - av) * w;
398
398
  }
399
+ for (const k of Object.keys(a.channels)) {
400
+ if (Object.hasOwn(b.channels, k) || !Object.hasOwn(underneath, k)) continue;
401
+ const av = a.channels[k]!;
402
+ channels[k] = av + (underneath[k]! - av) * w;
403
+ }
399
404
  let parts: Record<string, PartBox> | undefined;
400
405
  if (a.parts || b.parts) {
401
406
  parts = { ...(a.parts ?? {}) };
@@ -413,7 +418,7 @@ function lerpPose(a: Pose, b: Pose, w: number): Pose {
413
418
  }
414
419
 
415
420
  /** State `si`'s pose `local` ms in: its clip, or its 1D blend at the current value. */
416
- function statePose(L: CLayer, si: number, local: number, vals: Literal[], clips: Clips, reduced: boolean): Pose {
421
+ function statePose(L: CLayer, si: number, local: number, vals: Literal[], clips: Clips, reduced: boolean, underneath: Readonly<Record<string, number>> = {}): Pose {
417
422
  'worklet';
418
423
  const st = L.states[si]!;
419
424
  if (!st.keys) {
@@ -432,7 +437,7 @@ function statePose(L: CLayer, si: number, local: number, vals: Literal[], clips:
432
437
  if (v <= keys[i]![0]) {
433
438
  const a = keys[i - 1]!;
434
439
  const b = keys[i]!;
435
- return lerpPose(at(a), at(b), (v - a[0]) / (b[0] - a[0]));
440
+ return lerpPose(at(a), at(b), (v - a[0]) / (b[0] - a[0]), underneath);
436
441
  }
437
442
  }
438
443
  return at(keys[keys.length - 1]!);
@@ -451,9 +456,9 @@ function ease(kind: number, p: number): number {
451
456
  * What the machine draws at `t` (at or after `s.t`, before the next instant): every layer's pose, mixes applied, a later
452
457
  * layer's channel or part over an earlier one's.
453
458
  */
454
- export function pose(c: Compiled, clips: Clips, s: Snapshot, t: number, clock: ClockRead, reduced = false): Pose {
459
+ export function pose(c: Compiled, clips: Clips, s: Snapshot, t: number, clock: ClockRead, reduced = false, defaults?: Readonly<Record<string, number>>): Pose {
455
460
  'worklet';
456
- const channels: Record<string, number> = {};
461
+ const channels: Record<string, number> = { ...defaults };
457
462
  let parts: Record<string, PartBox> | undefined;
458
463
  for (let li = 0; li < c.layers.length; li++) {
459
464
  const L = c.layers[li]!;
@@ -465,16 +470,16 @@ export function pose(c: Compiled, clips: Clips, s: Snapshot, t: number, clock: C
465
470
  const by = L.states[l.heldS]!.by;
466
471
  let vals = s.vals;
467
472
  if (by >= 0) { vals = s.vals.slice(); vals[by] = l.heldBy; }
468
- p = statePose(L, l.heldS, l.held, vals, clips, reduced);
473
+ p = statePose(L, l.heldS, l.held, vals, clips, reduced, channels);
469
474
  } else if (l.s < 0) {
470
475
  continue;
471
476
  } else {
472
- p = statePose(L, l.s, localMs(L, l, t, clock), s.vals, clips, reduced);
477
+ p = statePose(L, l.s, localMs(L, l, t, clock), s.vals, clips, reduced, channels);
473
478
  if (l.mixTr >= 0 && t < l.mixEnd && !reduced) {
474
479
  const from = L.states[l.mixFrom]!;
475
- const fromPose = statePose(L, l.mixFrom, sinceEntry(L, l.mixAt, l.mixCAt, t, clock) * from.speed, s.vals, clips, reduced);
480
+ const fromPose = statePose(L, l.mixFrom, sinceEntry(L, l.mixAt, l.mixCAt, t, clock) * from.speed, s.vals, clips, reduced, channels);
476
481
  const tr = L.trans[l.mixTr]!;
477
- p = lerpPose(fromPose, p, ease(tr.ease, (t - l.mixStart) / (l.mixEnd - l.mixStart)));
482
+ p = lerpPose(fromPose, p, ease(tr.ease, (t - l.mixStart) / (l.mixEnd - l.mixStart)), channels);
478
483
  }
479
484
  }
480
485
  for (const k of Object.keys(p.channels)) channels[k] = p.channels[k]!;