Skip to content
Merged
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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@ All notable changes to the Stems Toggle plugin are documented here.

### Changed

- **ES-module migration, step 11.1 — streaming/transport hardening.** (1) Guard
`handleNaturalEnd()` on `transport.playing`: in worklet mode a queued `ended`
message could arrive just after a user pause/stop flipped `playing=false` and
dispatch a spurious `ended`, jumping the playhead to `duration` (pre-existing;
buffer mode was already safe via `onended=null`). (2) Export `appendRound` +
add unit tests pinning the step-9.1 seek-token guard (posts only when the token
still matches; drops the block otherwise). (3) Document the synchronous
`t.done=true` invariant in `cancelStreamReaders` that makes reader-reopen
seek-safe (so the immutable-track refactor isn't needed — the steal is
unreachable given that invariant + the per-track token guard).
- **ES-module migration, step 11 — extract the buffer transport + `#audio` shims
to `src/transport.js`.** The top of the playback engine moves out of `main.js`:
the playhead clock (`transportPlayhead`/`Raw`), source start/stop
Expand Down
11 changes: 10 additions & 1 deletion src/streaming.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ async function dequeueTrackFrames(t, frames) {

// Append one aligned block for every track at the current write frontier,
// reading PCM as needed and zero-padding tracks past their own end.
async function appendRound(token = ST.streamSeekToken) {
// (Exported for the seek-token guard test; not part of the plugin's public API.)
export async function appendRound(token = ST.streamSeekToken) {
const remaining = ST.streamTotalSamples - ST.jsWriteFrontier;
if (remaining <= 0) return false;
const aheadTarget = Math.min(ST.streamTotalSamples,
Expand Down Expand Up @@ -203,6 +204,14 @@ async function runPump(isInitial) {
}
}

// INVARIANT (seek safety): this sets t.done = true SYNCHRONOUSLY for every track.
// repositionStream calls it before its first await, so any in-flight dequeue's
// parked t.reader.read() resolves (cancelled) with t.done already true and
// ensureBytes exits — it can't loop onto a reopened reader, because openTrackStreams
// only reinstalls t.reader/t.done=false AFTER a network fetch (a macrotask later).
// Keep the synchronous t.done=true if this is ever refactored, or reopened readers
// on the same track objects could be consumed by a stale append (see appendRound's
// per-track token guard, which is the second line of defence).
function cancelStreamReaders() {
for (const t of ST.streamTracks) {
try { t.reader && t.reader.cancel(); } catch (_) {}
Expand Down
8 changes: 7 additions & 1 deletion src/transport.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,13 @@ function setTransportRate(r) {
}

function handleNaturalEnd() {
if (!S.sloppakActive) return;
// Guard on active playback: in worklet mode a queued 'ended' can arrive just
// after transportPause()/lightStop() flipped playing=false (stopSources posts
// 'stop' but can't unqueue an in-flight 'ended'), which would otherwise
// dispatch a spurious 'ended' and jump the playhead to duration. No genuine
// natural-end enters with playing===false (it's set false below). (Buffer mode
// is already safe — stopSources nulls src.onended before stop().)
if (!S.sloppakActive || !transport.playing) return;
transport.baseOffset = transport.duration;
transport.playing = false;
stopSources();
Expand Down
Binary file modified tests/__pycache__/test_manifest.cpython-314-pytest-9.0.3.pyc
Binary file not shown.
48 changes: 42 additions & 6 deletions tests/streaming.test.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// Unit tests for src/streaming.js's pure-ish exports. Real ES-module import.
// The pump/seek internals (appendRound/runPump/repositionStream) drive the Web
// Audio worklet + fetch and aren't exported, so their seek-token race guard is
// covered by the on-device seek-stress smoke, not here.
// Unit tests for src/streaming.js. The pure-ish exports (streamingSupported,
// isWavResponse, streamOffsetBuffered) plus the seek-token guard on appendRound.
// The rest of the pump/seek internals drive fetch + the worklet, so their end-to-
// end behaviour is covered by the on-device seek-stress smoke.
import test, { beforeEach } from 'node:test';
import assert from 'node:assert/strict';

import { ST } from '../src/state.js';
import { streamingSupported, isWavResponse, streamOffsetBuffered } from '../src/streaming.js';
import { S, ST } from '../src/state.js';
import { streamingSupported, isWavResponse, streamOffsetBuffered, appendRound } from '../src/streaming.js';

test('isWavResponse: true only when content-type contains "wav"', () => {
const mk = (ct) => ({ headers: { get: () => ct } });
Expand Down Expand Up @@ -63,3 +63,39 @@ test('streamOffsetBuffered: always true when not streaming or rate unknown', ()
ST.streaming = true; ST.streamSampleRate = 0;
assert.equal(streamOffsetBuffered(999), true);
});

// ── appendRound seek-token guard (the step-9.1 race fix) ──────────────────────
// A silent track (totalFrames=0 → realWanted<=0) exercises the guards without a
// reader/fetch: appendRound must post only when its captured token still matches
// ST.streamSeekToken, else drop the block (a seek superseded it).
function primeAppendRound() {
const posted = [];
S.workletNode = { port: { postMessage: (m) => posted.push(m) } };
ST.streamTracks = [{ nch: 2, totalFrames: 0 }]; // silent path, no reader needed
ST.streamTotalSamples = 10000;
ST.jsWriteFrontier = 0;
ST.streamSampleRate = 48000;
ST.lastWorkletPos = 10000; // aheadTarget high → frames > 0
ST.pumpStop = false;
ST.streamSeekToken = 5;
return posted;
}

test('appendRound posts the block when its token still matches', async () => {
const posted = primeAppendRound();
const ok = await appendRound(5);
assert.equal(ok, true);
assert.equal(posted.length, 1);
assert.equal(posted[0].type, 'append');
assert.equal(posted[0].base, 0);
assert.ok(posted[0].frames > 0); // a real block was posted
assert.equal(ST.jsWriteFrontier, posted[0].frames); // frontier advanced by exactly that
});

test('appendRound drops the block (no post) once a seek supersedes its token', async () => {
const posted = primeAppendRound();
const ok = await appendRound(4); // stale token (current is 5)
assert.equal(ok, false);
assert.deepEqual(posted, []); // nothing posted to the worklet
assert.equal(ST.jsWriteFrontier, 0); // frontier NOT advanced
});
Loading