animader-cli 0.4.0 → 0.6.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.
@@ -29,7 +29,7 @@
29
29
  * resume: () => Promise<void>,
30
30
  * suspend: () => Promise<void>,
31
31
  * now: () => number,
32
- * play: (decoded: AudioBuffer, origin: number, stopAt: number) => AudioBufferSourceNode,
32
+ * play: (decoded: AudioBuffer, origin: number, stopAt: number, offset?: number) => AudioBufferSourceNode,
33
33
  * stop: (source: AudioBufferSourceNode) => void,
34
34
  * analyser: AnalyserNode,
35
35
  * }}
@@ -71,13 +71,15 @@ export function createWebAudioPort({ context }) {
71
71
 
72
72
  /**
73
73
  * One fresh single-use source per start, scheduled on the context's
74
- * own timeline: begin at `origin`, STOP at `stopAt` (origin+seconds).
74
+ * own timeline: begin at `origin` from `offset` seconds into the
75
+ * buffer, STOP at `stopAt` (the host end on the context clock). A
76
+ * seek passes its position as the offset; a fresh start passes 0.
75
77
  */
76
- play(decoded, origin, stopAt) {
78
+ play(decoded, origin, stopAt, offset = 0) {
77
79
  const source = context.createBufferSource();
78
80
  source.buffer = decoded;
79
81
  source.connect(analyser);
80
- source.start(origin);
82
+ source.start(origin, offset);
81
83
  source.stop(stopAt);
82
84
  return source;
83
85
  },
package/hello/run.js CHANGED
@@ -137,21 +137,19 @@ export function createPlayer({ pacer, routeWrites, toUniforms, setUniform, setPa
137
137
  }
138
138
 
139
139
  /**
140
- * One tick: the score's writes at the tick's own time, then one frame of
141
- * the program at that time. pacer's route pair splits the frame's entries
142
- * across the buses in wire order (`routeWrites`), and folding one entry at
143
- * a time through `toUniforms` gives each write's value in the shape its bus
144
- * sink takes: a number for one lane, a plain array otherwise. The writes
145
- * reach the sinks in that order, so when two write the same name the later
146
- * one wins, the frame contract's last-word rule. Every write rides
147
- * `redraw: false`, and the tick's one draw carries them. Registry 0 lands
140
+ * Apply one tick's score writes to the sinks, without drawing: the frame
141
+ * contract's eval, route and fold at `redraw: false`, with the later
142
+ * write winning. pacer's route pair splits the frame's entries across the
143
+ * buses in wire order (`routeWrites`), and folding one entry at a time
144
+ * through `toUniforms` gives each write's value in the shape its bus sink
145
+ * takes: a number for one lane, a plain array otherwise. Registry 0 lands
148
146
  * by the target's own reflected name; registry 1 goes to `setParam` when
149
147
  * the page has an audio sink. A declared-only target with no host name
150
148
  * cannot key a by-name fold, so it is not written, exactly as the sinks
151
- * could not have taken it.
149
+ * could not have taken it. Leaves `state.writes` holding this tick's
150
+ * writes for the frame a caller paints afterwards.
152
151
  */
153
- function step() {
154
- const t = state.tick / TICKS_PER_SECOND;
152
+ function applyTick() {
155
153
  const entries = pacer.eval(state.tick * MICROS_PER_TICK);
156
154
  state.writes = [];
157
155
  if (entries) {
@@ -172,19 +170,81 @@ export function createPlayer({ pacer, routeWrites, toUniforms, setUniform, setPa
172
170
  }
173
171
  }
174
172
  }
175
- draw({ time: t });
176
- state.tick += 1;
177
- state.draws += 1;
178
- // pngine drains dx, dy and the wheel sums after each frame
179
- // (vendor/pngine.mjs, the draw path).
173
+ }
174
+
175
+ /** pngine drains dx, dy and the wheel sums after each frame. */
176
+ function drainPointerDeltas() {
180
177
  pointer[4] = 0;
181
178
  pointer[5] = 0;
182
179
  pointer[9] = 0;
183
180
  pointer[10] = 0;
181
+ }
182
+
183
+ /**
184
+ * One tick: the score's writes at the tick's own time, then one frame of
185
+ * the program at that time. Every write rides `redraw: false`, and the
186
+ * tick's one draw carries them. The tick advances after its frame, so the
187
+ * last shown tick is always `tick - 1`.
188
+ */
189
+ function step() {
190
+ const t = state.tick / TICKS_PER_SECOND;
191
+ applyTick();
192
+ draw({ time: t });
193
+ state.tick += 1;
194
+ state.draws += 1;
195
+ drainPointerDeltas();
184
196
  if (onFrame) onFrame(frame());
185
197
  return state.tick;
186
198
  }
187
199
 
200
+ /**
201
+ * Step the score to `tick` without drawing. Every tick's writes and
202
+ * uniforms land at `redraw: false`; the last tick's writes stay in
203
+ * `state.writes` for the frame the caller paints afterwards. No draw, no
204
+ * `draws` count and no `onFrame` announcement: a seek is not a played
205
+ * frame. The clock never moves backwards; a target behind the current
206
+ * tick is a no-op.
207
+ */
208
+ function advanceTo(tick) {
209
+ while (state.tick < tick) {
210
+ applyTick();
211
+ state.tick += 1;
212
+ }
213
+ return state.tick;
214
+ }
215
+
216
+ /**
217
+ * Draw the frame the last advance left: `state.tick - 1` at its own time,
218
+ * without evaluating the score again. The zero tick is the one boundary
219
+ * with no preceding frame, so it paints the zero frame rather than a
220
+ * negative time. A real draw drains the pointer deltas and announces its
221
+ * frame, exactly like `step`'s draw.
222
+ */
223
+ function drawFrame() {
224
+ const shown = state.tick === 0 ? 0 : state.tick - 1;
225
+ draw({ time: shown / TICKS_PER_SECOND });
226
+ state.draws += 1;
227
+ drainPointerDeltas();
228
+ if (onFrame) onFrame(frame());
229
+ }
230
+
231
+ /**
232
+ * Reset and replay silently to `tick`, then paint exactly that frame.
233
+ * The zero tick has no preceding frame: it applies tick 0's own writes
234
+ * (without advancing) so the zero frame is score-exact rather than the
235
+ * stale uniforms the previous frame left on the sinks.
236
+ */
237
+ function seekTo(tick) {
238
+ reset();
239
+ if (tick === 0) {
240
+ applyTick();
241
+ } else {
242
+ advanceTo(tick);
243
+ }
244
+ drawFrame();
245
+ return state.tick;
246
+ }
247
+
188
248
  /** The writes the last tick applied and the lanes it left, as plain values. */
189
249
  function frame() {
190
250
  return {
@@ -247,6 +307,12 @@ export function createPlayer({ pacer, routeWrites, toUniforms, setUniform, setPa
247
307
  step,
248
308
  stepTo,
249
309
  stepAt,
310
+ /** Advance silently to `tick` (no draw, no frame announcement). */
311
+ advanceTo,
312
+ /** Paint the last advanced frame (`tick - 1`), never re-evaluating. */
313
+ draw: drawFrame,
314
+ /** Reset, replay silently to `tick`, then paint that frame. */
315
+ seekTo,
250
316
  tick(n) {
251
317
  for (let i = 0; i < n; i++) step();
252
318
  return state.tick;
package/lib/routes.mjs CHANGED
@@ -25,7 +25,7 @@ const MIME = Object.freeze({
25
25
  '.html': 'text/html; charset=utf-8',
26
26
  });
27
27
 
28
- const PLAYER_FILES = new Set(['index.html', 'page.mjs', 'boot.mjs', 'controller.mjs', 'player.css', 'devchannel.mjs']);
28
+ const PLAYER_FILES = new Set(['index.html', 'page.mjs', 'boot.mjs', 'controller.mjs', 'transport.mjs', 'player.css', 'devchannel.mjs']);
29
29
  const APP_LIB_FILES = new Set(['score.mjs', 'show.mjs', 'soundtrack.mjs']);
30
30
  const APP_ADAPTER_FILES = new Set(['webaudio.mjs']);
31
31
  const HELLO_PLAYER_FILES = new Set(['run.js', 'join.js']);
package/lib/show.mjs CHANGED
@@ -34,10 +34,10 @@
34
34
  // ticks through the run core's own reset, returns every held control to
35
35
  // the document default, and resets the visual feedback state through
36
36
  // the renderer's public restart verb — never by patching private
37
- // workers. `seconds` is a host policy received here (never inferred
38
- // from the compiled transport) and must be a whole number of ticks on
39
- // the run core's grid; a score's own `:end loop|hold` stays authored
40
- // and is not acted on by this transport.
37
+ // workers. `seconds` is the effective show length (the shorter of the host
38
+ // policy and the score's own tempo-integrated end), received here on the run
39
+ // core's whole-tick grid; a score's own `:end loop|hold` stays authored and is
40
+ // not acted on by this transport.
41
41
  //
42
42
  // Ownership: the state machine, the clock arithmetic, the serialization.
43
43
  // The audio graph, the wake source, the renderer and the driver belong
@@ -61,8 +61,9 @@ export const SHOW_STATES = Object.freeze([
61
61
  /**
62
62
  * @param {object} options
63
63
  * @param {number} options.seconds
64
- * the host show length; must be positive, finite and a whole number
65
- * of ticks on the tick grid.
64
+ * the effective show length (no longer than the host or the score);
65
+ * must be positive, finite and on the tick grid to within the transport's
66
+ * own sub-tick guard.
66
67
  * @param {() => Promise<{driver: object, player: object, renderer: object}>} options.prepare
67
68
  * composes the show: renderer ready, score compiled (a `loadShow`
68
69
  * result wired through `createPlayer`). READY waits for this.
@@ -72,9 +73,10 @@ export const SHOW_STATES = Object.freeze([
72
73
  * @param {object} options.audio
73
74
  * the audio port: `resume(): Promise`, `suspend(): Promise` (the
74
75
  * clock freezes once it settles), `now(): number` (a
75
- * context-currentTime-style reader), `play(decoded, origin, stopAt):
76
- * handle` (a fresh single-use source started at `origin` with its
77
- * STOP scheduled at `stopAt`), `stop(handle)`.
76
+ * context-currentTime-style reader), `play(decoded, origin, stopAt,
77
+ * offset): handle` (a fresh single-use source started at `origin` from
78
+ * `offset` seconds into the buffer, with its STOP scheduled at `stopAt`),
79
+ * `stop(handle)`.
78
80
  * @param {(fn: () => void) => () => void} options.scheduleWake
79
81
  * schedules one pump (requestAnimationFrame-shaped) and answers a
80
82
  * cancel function.
@@ -114,7 +116,14 @@ export function createShow({
114
116
  stage: 'transport',
115
117
  });
116
118
  }
117
- if (!Number.isInteger(seconds * ticksPerSecond)) {
119
+ // A score end lands on the 100-tick grid as a hundredth-of-a-second value
120
+ // (35.12), whose binary product can sit a few ulps below the whole tick.
121
+ // The same 1e-6-tick guard the pump uses keeps that representation detail
122
+ // from refusing a real show length; a genuinely off-grid value (8.001) is
123
+ // still refused.
124
+ const rawTicks = seconds * ticksPerSecond;
125
+ const totalTicks = Math.round(rawTicks);
126
+ if (!(Math.abs(rawTicks - totalTicks) <= 1e-6)) {
118
127
  throw new ShowError(
119
128
  'seconds_not_representable',
120
129
  `--seconds ${seconds} is not a whole number of ticks on the ${ticksPerSecond}-tick grid; pass a length the grid represents exactly instead of rounding forever`,
@@ -123,7 +132,6 @@ export function createShow({
123
132
  }
124
133
 
125
134
  const clock = readClock ?? audio.now;
126
- const totalTicks = seconds * ticksPerSecond;
127
135
 
128
136
  let state = 'loading';
129
137
  let failure = null;
@@ -170,6 +178,61 @@ export function createShow({
170
178
  };
171
179
  }
172
180
 
181
+ /**
182
+ * Start one fresh source at `elapsed` seconds on the context clock `now`,
183
+ * unless that position is at/after the host end or past the decoded
184
+ * soundtrack — a soundtrack shorter than the seek point leaves no source
185
+ * at all and the context clock keeps running. The STOP is scheduled at
186
+ * the host end on the same clock (`origin + seconds`), so a seek's source
187
+ * ends with the show, not with the buffer's remaining length.
188
+ */
189
+ function startSource(now, elapsed) {
190
+ const offset = Math.max(0, elapsed);
191
+ if (offset >= seconds) return null;
192
+ const duration = loaded?.decoded?.duration;
193
+ if (typeof duration === 'number' && offset >= duration) return null;
194
+ return audio.play(loaded.decoded, now, origin + seconds, offset);
195
+ }
196
+
197
+ /** A replay failure keeps a structured cause's own fields, like start. */
198
+ function failSeek(cause) {
199
+ const error = cause instanceof ShowError
200
+ ? cause
201
+ : new ShowError('seek_failed', `the show could not seek: ${cause?.message ?? cause}`, { stage: 'seek', cause });
202
+ return failShow(error.code, error.message, {
203
+ stage: error.stage,
204
+ document: error.document,
205
+ diagnostics: error.diagnostics,
206
+ cause: error.cause ?? cause,
207
+ });
208
+ }
209
+
210
+ /** An audio-port failure during a seek takes the transport's error path. */
211
+ function failAudio(message, cause) {
212
+ const error = cause instanceof ShowError
213
+ ? cause
214
+ : new ShowError('audio_failed', `${message}: ${cause?.message ?? cause}`, { stage: 'audio', cause });
215
+ return failShow(error.code, error.message, {
216
+ stage: error.stage,
217
+ document: error.document,
218
+ diagnostics: error.diagnostics,
219
+ cause: error.cause ?? cause,
220
+ });
221
+ }
222
+
223
+ /** Read the clock for a seek; a non-finite read is the loud clock failure. */
224
+ function seekClock(where) {
225
+ const now = clock();
226
+ if (!Number.isFinite(now)) {
227
+ throw failShow(
228
+ 'clock_invalid',
229
+ `the master clock read ${now} ${where}; the show refuses to guess time`,
230
+ { stage: 'clock' },
231
+ );
232
+ }
233
+ return now;
234
+ }
235
+
173
236
  /**
174
237
  * One paint: step every tick the clock has passed, bounded by the
175
238
  * grid's end, then schedule the next paint unless the show is over.
@@ -344,12 +407,123 @@ export function createShow({
344
407
  );
345
408
  }
346
409
  lastNow = now;
410
+ // A seek to a paused landing ended the source; Resume is the gesture
411
+ // that starts sound from the landed tick. A normal pause keeps its
412
+ // suspended source, so it is reused rather than re-created.
413
+ try {
414
+ if (handle === null) {
415
+ if (origin === null) origin = now - loaded.player.state.tick / ticksPerSecond;
416
+ handle = startSource(now, now - origin);
417
+ }
418
+ } catch (cause) {
419
+ if (state === 'error') throw failure;
420
+ throw failAudio('the audio could not restart on resume', cause);
421
+ }
347
422
  announce('playing');
348
423
  schedulePump();
349
424
  return state;
350
425
  });
351
426
  }
352
427
 
428
+ /**
429
+ * The serialized seek: clamp and round to the tick grid, replay the score
430
+ * silently to the landed tick, and take the landing state from the spec's
431
+ * table. A playing seek rebases the origin, restarts the source at the
432
+ * offset and reschedules the pump; a paused landing suspends the context
433
+ * (so the clock is frozen) and starts no sound; the effective end is the
434
+ * one terminal landing from every row. A failure takes the transport's
435
+ * existing error path, and a host failure that arrives during a platform
436
+ * await keeps its original identity.
437
+ */
438
+ function seek(tick) {
439
+ return enqueue(async () => {
440
+ if (state === 'loading' || state === 'error' || loaded === null) return state;
441
+ const rounded = Math.round(tick);
442
+ if (!Number.isFinite(rounded)) return state;
443
+ const target = Math.min(totalTicks, Math.max(0, rounded));
444
+ const from = state;
445
+ const position = target / ticksPerSecond;
446
+ endAudio();
447
+ try {
448
+ loaded.player.seekTo(target);
449
+ } catch (cause) {
450
+ if (state === 'error') throw failure;
451
+ throw failSeek(cause);
452
+ }
453
+ // A host failure raised synchronously by the replay (a draw callback,
454
+ // for instance) is already the answer; no landing may repaint over it.
455
+ if (state === 'error') throw failure;
456
+
457
+ // READY at zero is the one landing that stays READY.
458
+ if (from === 'ready' && target === 0) {
459
+ origin = null;
460
+ lastNow = null;
461
+ announce('ready');
462
+ return state;
463
+ }
464
+
465
+ // A playing seek between the ends keeps playing: the context is
466
+ // running, the origin is rebased to now - t, and a fresh source
467
+ // starts at that position.
468
+ if (from === 'playing' && target > 0 && target < totalTicks) {
469
+ try {
470
+ await audio.resume();
471
+ } catch (cause) {
472
+ if (state === 'error') throw failure;
473
+ throw failAudio('the audio could not be resumed for the seek', cause);
474
+ }
475
+ if (state === 'error') throw failure;
476
+ const now = seekClock('at the seek');
477
+ origin = now - position;
478
+ lastNow = now;
479
+ try {
480
+ handle = startSource(now, position);
481
+ } catch (cause) {
482
+ if (state === 'error') throw failure;
483
+ throw failAudio('the audio could not restart at the seek', cause);
484
+ }
485
+ announce('playing');
486
+ schedulePump();
487
+ return state;
488
+ }
489
+
490
+ // A playing seek to the effective end is the direct ENDED landing.
491
+ if (from === 'playing' && target === totalTicks) {
492
+ const now = seekClock('at the end seek');
493
+ origin = now - position;
494
+ lastNow = now;
495
+ announce('ended');
496
+ return state;
497
+ }
498
+
499
+ // Every non-playing row lands silently. The effective end is one
500
+ // terminal landing from every row: the show has stopped, the last frame
501
+ // stays, and no source or wake survives. A paused seek short of it is
502
+ // still the paused still frame; a press-to-resume seek keeps the owed
503
+ // gesture.
504
+ try {
505
+ await audio.suspend();
506
+ } catch (cause) {
507
+ if (state === 'error') throw failure;
508
+ throw failAudio('the audio could not be suspended for the seek', cause);
509
+ }
510
+ if (state === 'error') throw failure;
511
+ const now = seekClock('at the paused seek');
512
+ origin = now - position;
513
+ lastNow = now;
514
+ if (target === totalTicks) {
515
+ announce('ended');
516
+ return state;
517
+ }
518
+ if (from === 'press-to-resume') {
519
+ announce('press-to-resume');
520
+ return state;
521
+ }
522
+ announce('paused');
523
+ return state;
524
+ });
525
+ }
526
+
353
527
  /** End the show now: the audio stops and no pump is scheduled again. */
354
528
  function stop() {
355
529
  return enqueue(async () => {
@@ -449,6 +623,7 @@ export function createShow({
449
623
  start,
450
624
  pause,
451
625
  resume,
626
+ seek,
452
627
  stop,
453
628
  restart,
454
629
  fail,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "animader-cli",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "The animader command line: project creation, dev server, build, standalone export and host/project doctor checks",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,14 +11,14 @@
11
11
  },
12
12
  "license": "CC0-1.0",
13
13
  "dependencies": {
14
- "animader": "0.4.0",
14
+ "animader": "0.6.0",
15
15
  "esbuild": "0.24.2",
16
16
  "@mr_hugo/pacer": "0.2.0",
17
- "pngine": "4.2.1"
17
+ "pngine": "4.3.1"
18
18
  },
19
19
  "optionalDependencies": {
20
20
  "@mr_hugo/pacer-darwin-arm64": "0.2.0",
21
- "@pngine/darwin-arm64": "4.2.1"
21
+ "@pngine/darwin-arm64": "4.3.1"
22
22
  },
23
23
  "files": [
24
24
  "bin",