Open History to see the last commit
1// Reads the timeline metadata the player needs straight out of a built .riv: artboards,
2// animations (fps, duration, work area) and every AudioEvent keyframe with its asset and
3// volume. A bare .riv has no project for `rive inspect`, so without this it gets no
4// audio timing.
5//
6// .riv layout: "RIVE", varuint major/minor/fileId, a table of contents (property keys
7// the file uses that a runtime might not know, with their field types), then a flat list
8// of objects: varuint typeKey, then (varuint propertyKey, value)* terminated by key 0.
9// Field types of core keys come from lib/riv-schema.json (scripts/gen-riv-schema.mjs).
10import { readFileSync } from 'node:fs';
11
12const SCHEMA = JSON.parse(readFileSync(new URL('./riv-schema.json', import.meta.url), 'utf8'));
13const COMPONENTS = new Set(SCHEMA.components);
14const T = SCHEMA.typeKeys;
15
16// field kinds: 0 varuint, 1 length-prefixed bytes, 2 float32, 3 uint32 (color)
17const KIND_OF = {
18 Bytes: 1, String: 1, FractionalIndex: 1, 'List<Id>': 1,
19 double: 2,
20 Color: 3,
21};
22const coreKind = (k) => {
23 const t = SCHEMA.keys[k];
24 if (t === undefined) return undefined;
25 return KIND_OF[t] ?? 0;
26};
27
28// property keys used below
29const K = {
30 name: 4, // Component.name
31 objectId: 51, // KeyedObject
32 propertyKey: 53, // KeyedProperty
33 animName: 55, fps: 56, duration: 57, loop: 59, workStart: 60, workEnd: 61, enableWorkArea: 62,
34 frame: 67, // KeyFrame
35 assetName: 203, assetVolume: 530,
36 audioAssetId: 408, // AudioEvent.assetId: index into the file's assets
37 defaultStateMachineId: 236,
38};
39const NONE = 4294967295;
40
41function parseObjects(buf) {
42 if (buf.toString('latin1', 0, 4) !== 'RIVE') throw new Error('not a .riv file');
43 let p = 4;
44 const vu = () => {
45 let r = 0;
46 let s = 0;
47 let x;
48 do {
49 if (p >= buf.length) throw new Error('unexpected end of file');
50 x = buf[p++];
51 r += (x & 0x7f) * 2 ** s;
52 s += 7;
53 } while (x & 0x80);
54 return r;
55 };
56 const major = vu();
57 vu(); // minor
58 vu(); // fileId
59 if (major !== 7) throw new Error(`unsupported .riv version ${major}`);
60 const tocKeys = [];
61 for (let k; (k = vu()); ) tocKeys.push(k);
62 // Field types, 2 bits each, packed 4 to a uint32 (as the runtime reads them).
63 const toc = new Map();
64 let word = 0;
65 let bit = 8;
66 for (const k of tocKeys) {
67 if (bit === 8) {
68 word = buf.readUInt32LE(p);
69 p += 4;
70 bit = 0;
71 }
72 toc.set(k, (word >>> bit) & 3);
73 bit += 2;
74 }
75 const objects = [];
76 while (p < buf.length) {
77 const type = vu();
78 const props = {};
79 for (let k; (k = vu()); ) {
80 const kind = toc.get(k) ?? coreKind(k);
81 if (kind === undefined) throw new Error(`unknown property ${k} on type ${type}`);
82 if (kind === 0) props[k] = vu();
83 else if (kind === 1) {
84 const n = vu();
85 if (k === K.name || k === K.animName || k === K.assetName) props[k] = buf.toString('utf8', p, p + n);
86 p += n;
87 } else if (kind === 2) {
88 props[k] = buf.readFloatLE(p);
89 p += 4;
90 } else {
91 props[k] = buf.readUInt32LE(p);
92 p += 4;
93 }
94 }
95 objects.push({ type, props });
96 }
97 return objects;
98}
99
100/** Same shape as build.mjs extractMeta(). Throws if the file can't be read. */
101export function rivMeta(buf) {
102 const objects = parseObjects(buf);
103 const assets = []; // file assets in order: AudioEvent.assetId indexes this
104 const artboards = [];
105 let ab = null;
106 let anim = null;
107 let keyedTarget = null;
108 let keyedIsTrigger = false;
109 for (const o of objects) {
110 const { type, props } = o;
111 if (type === T.AudioAsset || type === T.ImageAsset || type === T.FontAsset || type === T.BlobAsset || type === T.AudioAssetClip || type === T.ScriptAsset || type === T.ShaderAsset) {
112 assets.push({ type, name: props[K.assetName] ?? null, volume: props[K.assetVolume] ?? 1 });
113 continue;
114 }
115 if (type === T.Artboard) {
116 ab = { name: props[K.name] ?? `Artboard ${artboards.length + 1}`, objects: [o], animations: [] };
117 artboards.push(ab);
118 anim = null;
119 continue;
120 }
121 if (!ab) continue;
122 if (COMPONENTS.has(type)) {
123 ab.objects.push(o);
124 continue;
125 }
126 if (type === T.LinearAnimation) {
127 anim = {
128 name: props[K.animName] ?? `Animation ${ab.animations.length + 1}`,
129 fps: props[K.fps] ?? 60,
130 duration: props[K.duration] ?? 60,
131 loop: props[K.loop] ?? 0,
132 workStart: props[K.workStart] ?? NONE,
133 workEnd: props[K.workEnd] ?? NONE,
134 enableWorkArea: !!props[K.enableWorkArea],
135 callbacks: [],
136 };
137 ab.animations.push(anim);
138 keyedTarget = null;
139 continue;
140 }
141 if (!anim) continue;
142 if (type === T.KeyedObject) {
143 keyedTarget = ab.objects[props[K.objectId] ?? -1] ?? null;
144 keyedIsTrigger = false;
145 } else if (type === T.KeyedProperty) {
146 keyedIsTrigger = props[K.propertyKey] === 395; // Event.trigger
147 } else if (type === T.KeyFrameCallback && keyedTarget?.type === T.AudioEvent && keyedIsTrigger) {
148 anim.callbacks.push({ frame: props[K.frame] ?? 0, target: keyedTarget });
149 } else if (type === T.StateMachine) {
150 anim = null; // state machines follow the animations
151 }
152 }
153
154 const out = artboards.map((a) => {
155 const animations = a.animations.map((x) => {
156 const audio = x.callbacks
157 .map(({ frame, target }) => {
158 const asset = assets[target.props[K.audioAssetId]];
159 return {
160 frame,
161 time: frame / x.fps,
162 event: target.props[K.name] ?? 'audio',
163 asset: asset?.name ?? null,
164 volume: asset?.volume ?? 1,
165 };
166 })
167 .sort((p, q) => p.time - q.time);
168 const useWork = x.enableWorkArea && x.workStart !== NONE && x.workEnd !== NONE;
169 return {
170 name: x.name,
171 fps: x.fps,
172 durationFrames: x.duration,
173 startFrame: useWork ? x.workStart : 0,
174 endFrame: useWork ? x.workEnd : x.duration,
175 loop: x.loop,
176 audio,
177 };
178 });
179 return { name: a.name, defaultAnimation: animations[0]?.name ?? null, animations };
180 });
181 return { defaultArtboard: out[0]?.name ?? null, artboards: out, problems: [], source: 'riv' };
182}