From d4b278c43d996273a4606bdadef372ac9b162025 Mon Sep 17 00:00:00 2001 From: Daniel Saewitz Date: Sat, 7 Nov 2026 23:05:33 -0500 Subject: [PATCH 1/6] Unload tracks that leave the preload window Moving a track out of the window now aborts its download, drops a decode in progress and releases its decoded buffer, instead of only cancelling an unfinished fetch. Late fetch/decode results from an unloaded load are ignored. --- README.md | 8 +++-- src/Queue.ts | 23 +++++++------- src/Track.ts | 41 +++++++++++++++---------- src/machines/track.machine.ts | 23 +++++++------- tests/unit/preload-cancel.test.ts | 50 +++++++++++++++++++++++++++++-- tests/unit/queue.test.ts | 17 +++++------ 6 files changed, 110 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 8d87e87..7bced09 100644 --- a/README.md +++ b/README.md @@ -143,9 +143,11 @@ safe at any point: - the current entry keeps playing, untouched; - if the entry after it changed, the old one's scheduled gapless start is cancelled, and the new one is preloaded and scheduled; -- downloads for entries that left the preload window (the current entry plus - the next `preloadNumTracks`) are aborted, so they don't compete with the - entries about to play; decoded audio is kept. +- entries that left the preload window (the current entry plus the next + `preloadNumTracks`) are unloaded: downloads are aborted, so they don't + compete with the entries about to play, and decoded audio is released, + since a decoded track takes hundreds of MB. An entry that comes back into + the window loads again. #### Repeat diff --git a/src/Queue.ts b/src/Queue.ts index e32464f..13a2226 100644 --- a/src/Queue.ts +++ b/src/Queue.ts @@ -604,7 +604,7 @@ export class Queue implements TrackQueueRef { if (this.isPlaying) { this._preloadAhead(this._currentTrack); } else { - this._cancelPreloadsOutsideWindow(this._currentTrack); + this._unloadOutsideWindow(this._currentTrack); } } @@ -709,9 +709,9 @@ export class Queue implements TrackQueueRef { this._preloadAhead(current); this._tryScheduleGapless(current); } else { - // "Next" is unchanged, but a move can still push a downloading track - // out of the window. - this._cancelPreloadsOutsideWindow(current); + // "Next" is unchanged, but a move can still push a loading or loaded + // track out of the window. + this._unloadOutsideWindow(current); } } @@ -746,7 +746,7 @@ export class Queue implements TrackQueueRef { this._preloadAhead(cur); this._tryScheduleGapless(cur); } else { - this._cancelPreloadsOutsideWindow(cur); + this._unloadOutsideWindow(cur); } } @@ -860,17 +860,18 @@ export class Queue implements TrackQueueRef { } /** - * Abort downloads for tracks that are no longer in the preload window (the - * current track plus the next preloadNumTracks in play order), so they don't - * compete with the tracks that are about to play. Decoded buffers are kept. + * Unload tracks that are no longer in the preload window (the current track + * plus the next preloadNumTracks in play order): abort their downloads, so + * they don't compete with the tracks about to play, and release their + * decoded audio, which is large. They load again if they come back. */ - private _cancelPreloadsOutsideWindow(from: Track | null | undefined): void { + private _unloadOutsideWindow(from: Track | null | undefined): void { const window = new Set(from ? this._preloadWindow(from) : []); - for (const t of this._tracks) if (!window.has(t)) t.cancelPreload(); + for (const t of this._tracks) if (!window.has(t)) t.unload(); } private _preloadAhead(from: Track | null | undefined): void { - this._cancelPreloadsOutsideWindow(from); + this._unloadOutsideWindow(from); if (!from) return; const cur = from; diff --git a/src/Track.ts b/src/Track.ts index 93cd0ba..f34dfb8 100644 --- a/src/Track.ts +++ b/src/Track.ts @@ -60,6 +60,8 @@ export class Track { readonly skipHEAD: boolean; /** Temporary holder between fetch and decode steps (unserializable — stays on Track class). */ private _pendingArrayBuffer: ArrayBuffer | null = null; + /** Bumped by unload(): a fetch or decode that finishes after it is dropped. */ + private _loadGeneration = 0; // ---- HTML5 Audio --------------------------------------------------------- readonly audio: HTMLAudioElement; @@ -236,15 +238,21 @@ export class Track { }), fetchAudio: fromPromise(async ({ input, signal }) => { const { resolvedUrl } = input as { resolvedUrl: string }; + const generation = this._loadGeneration; const res = await fetch(resolvedUrl, { signal }); if (!res.ok) throw new Error(`HTTP ${res.status} for ${resolvedUrl}`); - this._pendingArrayBuffer = await res.arrayBuffer(); + const bytes = await res.arrayBuffer(); + if (generation === this._loadGeneration) this._pendingArrayBuffer = bytes; }), decodeAudio: fromPromise(async () => { const buf = this._pendingArrayBuffer; this._pendingArrayBuffer = null; if (!buf || !this.ctx) throw new Error('No ArrayBuffer or AudioContext'); - this.audioBuffer = await this.ctx.decodeAudioData(buf); + const generation = this._loadGeneration; + const decoded = await this.ctx.decodeAudioData(buf); + // Unloaded mid-decode (which can't be aborted): drop the result. + if (generation !== this._loadGeneration) return; + this.audioBuffer = decoded; this._maybeComputeBufferAlignment(); }), }, @@ -407,21 +415,24 @@ export class Track { } /** - * Abort an in-flight Web Audio download, so the track can be preloaded again - * later from scratch. Only while the URL is being resolved or the file - * fetched: once decoding starts the bytes are already here, and the decode - * (which assigns audioBuffer itself) can't be aborted. Returns whether a - * download was cancelled. + * Let go of this track's Web Audio data, so a track out of the preload + * window doesn't hold memory (a decoded hour of audio is hundreds of MB): + * abort its download, drop a decode in progress when it finishes (decoding + * can't be aborted), or release its decoded buffer. It loads again from + * scratch if it comes back into the window. Never while it's playing, + * scheduled to play, or waiting for its buffer to play. Returns whether + * anything was let go. */ - cancelPreload(): boolean { - const snap = this._actor.getSnapshot(); - if (snap.context.webAudioLoadingState !== 'LOADING' || snap.context.isPlaying) return false; - const child = snap.children.fetchDecode as { getSnapshot(): { value: unknown } } | undefined; - const stage = child?.getSnapshot().value; - if (stage !== 'resolvingUrl' && stage !== 'fetching') return false; - this.queueRef.onDebug(`cancelPreload() track=${this.key} stage=${String(stage)}`); + unload(): boolean { + const { context } = this._actor.getSnapshot(); + const state = context.webAudioLoadingState; + if (state !== 'LOADING' && state !== 'LOADED') return false; + if (context.isPlaying || context.pendingPlay) return false; + this.queueRef.onDebug(`unload() track=${this.key} state=${state}`); + this._loadGeneration++; this._pendingArrayBuffer = null; - this._actor.send({ type: 'CANCEL_PRELOAD' }); + this.audioBuffer = null; + this._actor.send({ type: 'UNLOAD' }); return true; } diff --git a/src/machines/track.machine.ts b/src/machines/track.machine.ts index 2f15831..dc48286 100644 --- a/src/machines/track.machine.ts +++ b/src/machines/track.machine.ts @@ -69,8 +69,8 @@ export type TrackEvent = | { type: 'WEBAUDIO_ENDED' } | { type: 'URL_RESOLVED'; url: string } | { type: 'START_FETCH' } - // Abort an in-flight fetch (sent by Track only before decoding starts). - | { type: 'CANCEL_PRELOAD' } + // Let go of Web Audio data: abort a fetch, drop a decode, release a buffer. + | { type: 'UNLOAD' } | { type: 'SCHEDULE_GAPLESS'; when: number } | { type: 'CANCEL_GAPLESS' } | { type: 'LOOKAHEAD_REACHED' }; @@ -87,8 +87,10 @@ export function createTrackMachine(initialContext: TrackContext) { fetchDecode: fetchDecodeMachine, }, guards: { - canCancelPreload: ({ context }) => - context.webAudioLoadingState === 'LOADING' && !context.isPlaying, + canUnload: ({ context }) => + (context.webAudioLoadingState === 'LOADING' || context.webAudioLoadingState === 'LOADED') && + !context.isPlaying && + !context.pendingPlay, canPlayWebAudio: () => false, isWebAudioOnly: () => false, canStartFetch: ({ context }) => @@ -189,10 +191,11 @@ export function createTrackMachine(initialContext: TrackContext) { }), ], }, - // Stopping the child aborts its fetch. Never for a playing track: its - // decode is what lets it cross over to Web Audio. - CANCEL_PRELOAD: { - guard: 'canCancelPreload', + // Stopping the child aborts its fetch (Track drops a decode in flight and + // the buffer itself). Never for a playing, scheduled or waiting track: + // its decode is what lets it cross over to Web Audio. + UNLOAD: { + guard: 'canUnload', actions: ['stopFetch', 'resetLoadingState'], }, }, @@ -367,8 +370,8 @@ export function createTrackMachine(initialContext: TrackContext) { // ----------------------------------------------------------------- loading: { on: { - CANCEL_PRELOAD: { - guard: 'canCancelPreload', + UNLOAD: { + guard: 'canUnload', target: 'idle', actions: ['stopFetch', 'resetLoadingState'], }, diff --git a/tests/unit/preload-cancel.test.ts b/tests/unit/preload-cancel.test.ts index 49670be..c18e900 100644 --- a/tests/unit/preload-cancel.test.ts +++ b/tests/unit/preload-cancel.test.ts @@ -1,6 +1,7 @@ // --------------------------------------------------------------------------- -// In-flight downloads for tracks that leave the preload window are aborted, -// so they don't compete with the new next track for bandwidth. +// Tracks that leave the preload window are unloaded: in-flight downloads are +// aborted, so they don't compete with the new next track for bandwidth, and +// decoded buffers are released, so they don't hold memory. // --------------------------------------------------------------------------- import { describe, it, expect, vi } from 'vitest'; @@ -104,16 +105,59 @@ describe('cancelling displaced preloads', () => { expect(internal._tracks[1].webAudioLoadingState).toBe('LOADING'); }); - it('keeps decoded buffers for displaced tracks', async () => { + it('releases the decoded buffer of a track moved out of the window', async () => { const { q, internal } = await playingWithNextDownloading(['a', 'b', 'c'], []); const b = internal._tracks[1]; expect(b.isBufferLoaded).toBe(true); q.move('b', { after: 'c' }); await flush(); + expect(b.isBufferLoaded).toBe(false); + expect(b.webAudioLoadingState).toBe('NONE'); + expect(internal._tracks[1].key).toBe('c'); // c, now next, loads instead + expect(internal._tracks[1].webAudioLoadingState).toBe('LOADED'); + + q.move('b', { after: 'a' }); // back in the window: loads again + await flush(); expect(b.isBufferLoaded).toBe(true); expect(b.webAudioLoadingState).toBe('LOADED'); }); + it('drops a decode in progress when its track leaves the window', async () => { + const { q, internal } = await playingWithNextDownloading(['a', 'b', 'c'], ['c']); + // Hold b's decode open: decoding can't be aborted. + const ctx = (globalThis as Internal)._mockAudioContext; + let finish: (buf: AudioBuffer) => void = () => {}; + ctx.decodeAudioData.mockImplementationOnce( + () => new Promise((resolve) => (finish = resolve)) + ); + q.move('b', { after: 'c' }); + q.move('b', { after: 'a' }); // b unloads (it was LOADED), then starts again… + await flush(); + const b = internal._tracks[1]; + expect(b.key).toBe('b'); + expect(b.webAudioLoadingState).toBe('LOADING'); // …and is decoding + + q.move('b', { after: 'c' }); // out of the window mid-decode + await flush(); + expect(b.webAudioLoadingState).toBe('NONE'); + finish({ duration: 180 } as AudioBuffer); // the decode lands late + await flush(); + expect(b.isBufferLoaded).toBe(false); + expect(b.webAudioLoadingState).toBe('NONE'); + }); + + it('releases the track that just played once the queue moves on', async () => { + const { q, internal } = await playingWithNextDownloading(['a', 'b', 'c'], []); + const a = internal._tracks[0]; + expect(a.isBufferLoaded).toBe(true); + q.pause(); + internal.onTrackEnded(a); // a → b + await flush(); + expect(q.currentKey).toBe('b'); + expect(a.isBufferLoaded).toBe(false); + expect(internal._tracks[1].isBufferLoaded).toBe(true); // b, current, keeps its buffer + }); + it('never cancels the current track', async () => { const { q, internal, signals } = await playingWithNextDownloading(['a', 'b'], ['a']); expect(internal._currentTrack.webAudioLoadingState).toBe('LOADING'); diff --git a/tests/unit/queue.test.ts b/tests/unit/queue.test.ts index 5a51297..d34c2ea 100644 --- a/tests/unit/queue.test.ts +++ b/tests/unit/queue.test.ts @@ -930,9 +930,10 @@ describe('Queue next/previous/gotoTrack cancel stale gapless schedule', () => { q.gotoTrack(2, true); - // Track 1 should be back to idle (cancelled), buffer still loaded + // Track 1 should be back to idle (cancelled). It's behind the current + // track now, outside the preload window, so its buffer is released too. expect(q.tracks[1].machineState).toBe('idle'); - expect(q.tracks[1].webAudioLoadingState).toBe('LOADED'); + expect(q.tracks[1].webAudioLoadingState).toBe('NONE'); }); it('gotoTrack(_, false) cancels gapless without playing', async () => { @@ -1374,15 +1375,11 @@ describe('Queue preloading without prior AudioContext', () => { await new Promise((r) => setTimeout(r, 0)); await new Promise((r) => setTimeout(r, 0)); - // Track 1 should already be preloaded by gotoTrack()'s preload-ahead logic + // The window (the next 2) is preloaded by gotoTrack()'s preload-ahead logic… expect(tracks[1].isBufferLoaded).toBe(true); - - // Manually preload track 3 — should also work since ctx now exists - (tracks[3] as unknown as { preload(): void }).preload(); - await new Promise((r) => setTimeout(r, 0)); - await new Promise((r) => setTimeout(r, 0)); - - expect(tracks[3].isBufferLoaded).toBe(true); + expect(tracks[2].isBufferLoaded).toBe(true); + // …and nothing outside it. + expect(tracks[3].isBufferLoaded).toBe(false); }); }); From 0c9f5cf0cd0e03877fef2a05d49d77b467af3b4e Mon Sep 17 00:00:00 2001 From: Daniel Saewitz Date: Sat, 7 Nov 2026 23:05:34 -0500 Subject: [PATCH 2/6] Bump to 5.0.0-alpha.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 32e0437..47a58f6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gapless", - "version": "5.0.0-alpha.0", + "version": "5.0.0-alpha.1", "private": false, "description": "Gapless audio playback javascript plugin", "license": "MIT", From a7d1f3bdcfc02c64abd51116467634ba8dc937bb Mon Sep 17 00:00:00 2001 From: Daniel Saewitz Date: Tue, 10 Nov 2026 16:44:30 -0500 Subject: [PATCH 3/6] Abort a blocked play()'s downloads When the browser refused HTML5 play() (autoplay policy, NotAllowedError), gapless reported onPlayBlocked and the queue paused, but the track stayed in the html5 state with both downloads running: the Web Audio HEAD and GET started alongside play(), and the element, switched to preload=auto, kept buffering. Nothing cancelled them; unload() refuses the current track, and the element is internal. A page whose autoplay was blocked downloaded the whole first track anyway. A blocked play() now sends PLAY_BLOCKED to the track before onPlayBlocked runs. From html5 it returns to idle, as if play() had never been called: isPlaying cleared, progress loop stopped, the element released (source dropped and reattached with preload=none, which aborts its fetch without an error event), and a Web Audio load still in flight aborted, with any decode that finishes later dropped (the same bookkeeping as unload()). The seek target is kept, so the next play() resumes where it would have. The next play() starts both loads fresh. The queue's existing PAUSE then reaches an idle track, which ignores it, so the app sees a stopped queue inside its onPlayBlocked callback. --- src/Track.ts | 28 +++++++- src/machines/track.machine.ts | 34 ++++++++++ tests/setup.ts | 4 ++ tests/unit/play-blocked.test.ts | 110 ++++++++++++++++++++++++++++++++ 4 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 tests/unit/play-blocked.test.ts diff --git a/src/Track.ts b/src/Track.ts index f34dfb8..3394406 100644 --- a/src/Track.ts +++ b/src/Track.ts @@ -317,6 +317,8 @@ export class Track { this._seekAbort = new AbortController(); this.audio.currentTime = 0; }, + releaseHtml5Element: () => this._releaseHtml5Element(), + dropPendingDecode: () => this._dropPendingDecode(), resetTiming: () => { this._waRefCtxTime = 0; this._waRefTrackTime = 0; @@ -429,8 +431,7 @@ export class Track { if (state !== 'LOADING' && state !== 'LOADED') return false; if (context.isPlaying || context.pendingPlay) return false; this.queueRef.onDebug(`unload() track=${this.key} state=${state}`); - this._loadGeneration++; - this._pendingArrayBuffer = null; + this._dropPendingDecode(); this.audioBuffer = null; this._actor.send({ type: 'UNLOAD' }); return true; @@ -620,6 +621,8 @@ export class Track { if (promise) { promise.catch((err: unknown) => { if (err instanceof Error && err.name === 'NotAllowedError') { + // First, so the queue (and the app's callback) see a stopped track. + this._actor.send({ type: 'PLAY_BLOCKED' }); this.queueRef.onPlayBlocked(); } else if (err instanceof Error && err.name === 'AbortError') { // Browser aborted — element will recover on next play() @@ -630,6 +633,27 @@ export class Track { } } + /** A fetch or decode that finishes from now on is dropped (see unload()). */ + private _dropPendingDecode(): void { + this._loadGeneration++; + this._pendingArrayBuffer = null; + } + + /** + * Stop the element's download without an error event: drop its source + * (which aborts the fetch) and put it back unloaded, so the next play() + * starts it fresh. + */ + private _releaseHtml5Element(): void { + this.audio.pause(); + this._seekAbort.abort(); + this._seekAbort = new AbortController(); + this.audio.preload = 'none'; + this.audio.removeAttribute('src'); + this.audio.load(); + this.audio.src = this._trackUrl; + } + private _seekHtml5(target: number): void { if (!isFinite(target)) return; if (this.audio.preload !== 'auto') this.audio.preload = 'auto'; diff --git a/src/machines/track.machine.ts b/src/machines/track.machine.ts index dc48286..cd3afee 100644 --- a/src/machines/track.machine.ts +++ b/src/machines/track.machine.ts @@ -59,6 +59,9 @@ export type TrackEvent = | { type: 'PRELOAD' } | { type: 'BUFFER_LOADING' } | { type: 'PLAY' } + // The browser refused HTML5 play() (autoplay policy): nothing will play, so + // nothing should keep downloading. + | { type: 'PLAY_BLOCKED' } | { type: 'PLAY_WEBAUDIO' } | { type: 'PAUSE' } | { type: 'SEEK'; time: number } @@ -112,6 +115,8 @@ export function createTrackMachine(initialContext: TrackContext) { seekHtml5: () => {}, seekWebAudio: () => {}, resetHtml5Element: () => {}, + releaseHtml5Element: () => {}, + dropPendingDecode: () => {}, resetTiming: () => {}, notifyTrackEnded: () => {}, triggerFetchForPendingPlay: () => {}, @@ -306,6 +311,35 @@ export function createTrackMachine(initialContext: TrackContext) { PLAY: { actions: ['setIsPlaying', 'playHtml5', 'startProgressLoop'], }, + // Blocked before a sound was made: back to idle, as if play() had + // never been called. The element stops buffering, and a Web Audio + // download still in flight is aborted (a decoded buffer is kept: it + // costs nothing more). The position is kept for the next play(). + PLAY_BLOCKED: [ + { + guard: ({ context }: { context: TrackContext }) => + context.webAudioLoadingState === 'LOADING', + target: 'idle', + actions: [ + 'clearIsPlaying', + 'stopProgressLoop', + 'releaseHtml5Element', + 'stopFetch', + 'resetLoadingState', + 'dropPendingDecode', + 'reportProgress', + ], + }, + { + target: 'idle', + actions: [ + 'clearIsPlaying', + 'stopProgressLoop', + 'releaseHtml5Element', + 'reportProgress', + ], + }, + ], BUFFER_LOADING: { actions: 'setLoadingState', }, diff --git a/tests/setup.ts b/tests/setup.ts index f466163..f715666 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -171,6 +171,10 @@ export class MockAudioElement { load: Mock = vi.fn(); + removeAttribute = vi.fn((name: string) => { + if (name === 'src') this.src = ''; + }); + addEventListener = vi.fn( (type: string, cb: EventListenerOrEventListenerObject, opts?: AddEventListenerOptions) => { if (!this._listeners[type]) this._listeners[type] = []; diff --git a/tests/unit/play-blocked.test.ts b/tests/unit/play-blocked.test.ts new file mode 100644 index 0000000..d9e4a3f --- /dev/null +++ b/tests/unit/play-blocked.test.ts @@ -0,0 +1,110 @@ +// --------------------------------------------------------------------------- +// A play() the browser blocks (autoplay policy: HTML5 play() rejects with +// NotAllowedError) leaves nothing downloading: the Web Audio fetch is +// aborted and the element stops buffering. The next play() loads again. +// --------------------------------------------------------------------------- + +import { describe, it, expect, vi } from 'vitest'; +import { Queue } from '../../src/Queue'; +import type { Entry } from '../../src/types'; +import { MockAudioElement } from '../setup'; + +const flush = async (n = 20) => { + for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0)); +}; +const entry = (key: string): Entry => ({ key, url: `${key}.mp3`, skipHEAD: true }); + +// oxlint-disable-next-line typescript/no-explicit-any +type Internal = any; + +/** Every element's play() is refused, as under a blocking autoplay policy. */ +function blockAutoplay() { + class Blocked extends MockAudioElement { + play = vi.fn(() => Promise.reject(new DOMException('Not allowed', 'NotAllowedError'))); + } + vi.stubGlobal('Audio', Blocked); +} + +/** fetch that never resolves until aborted; records each request's signal. */ +function mockFetchHanging() { + const signals: AbortSignal[] = []; + const spy = vi.fn((_url: string, init?: RequestInit) => { + if (init?.signal) signals.push(init.signal); + return new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => + reject(new DOMException('Aborted', 'AbortError')) + ); + }); + }); + vi.stubGlobal('fetch', spy); + return { spy, signals }; +} + +describe('blocked play()', () => { + it('aborts the Web Audio download and stops the element buffering', async () => { + blockAutoplay(); + const net = mockFetchHanging(); + const onPlayBlocked = vi.fn(); + const q = new Queue({ onPlayBlocked, preloadNumTracks: 0 }); + q.setEntries([entry('a'), entry('b')], { play: false }); + + q.play(); + await flush(); + + expect(onPlayBlocked).toHaveBeenCalledTimes(1); + expect(net.signals.length).toBeGreaterThan(0); + expect(net.signals.every((s) => s.aborted)).toBe(true); + + const a = (q as Internal)._tracks[0]; + expect(a.machineState).toBe('idle'); + expect(a.isPlaying).toBe(false); + expect(a.webAudioLoadingState).toBe('NONE'); + expect(q.isPlaying).toBe(false); + // The element dropped its source (aborting its fetch) and won't refetch on its own. + expect(a.audio.removeAttribute).toHaveBeenCalledWith('src'); + expect(a.audio.load).toHaveBeenCalled(); + expect(a.audio.preload).toBe('none'); + expect(a.audio.src).toBe('a.mp3'); + }); + + it('the app sees a stopped queue inside onPlayBlocked', async () => { + blockAutoplay(); + mockFetchHanging(); + let playingInCallback: boolean | undefined; + let trackStateInCallback: string | undefined; + const q: Queue = new Queue({ + preloadNumTracks: 0, + onPlayBlocked: () => { + playingInCallback = q.isPlaying; + trackStateInCallback = (q as Internal)._tracks[0].machineState; + }, + }); + q.setEntries([entry('a')], { play: false }); + q.play(); + await flush(); + expect(playingInCallback).toBe(false); + expect(trackStateInCallback).toBe('idle'); + }); + + it('a later play() starts the load again', async () => { + blockAutoplay(); + const net = mockFetchHanging(); + const q = new Queue({ preloadNumTracks: 0 }); + q.setEntries([entry('a')], { play: false }); + q.play(); + await flush(); + const before = net.spy.mock.calls.length; + + vi.stubGlobal('Audio', MockAudioElement); // the visitor clicked: allowed now + const a = (q as Internal)._tracks[0]; + a.audio.play = vi.fn(() => Promise.resolve()); + q.play(); + await flush(); + + expect(a.audio.play).toHaveBeenCalled(); + expect(net.spy.mock.calls.length).toBeGreaterThan(before); + expect(net.signals.at(-1)?.aborted).toBe(false); + expect(a.webAudioLoadingState).toBe('LOADING'); + expect(a.isPlaying).toBe(true); + }); +}); From a24becec5820edc8b3f6a26afa5a5c7966a66513 Mon Sep 17 00:00:00 2001 From: Daniel Saewitz Date: Tue, 10 Nov 2026 16:44:30 -0500 Subject: [PATCH 4/6] Bump to 5.0.0-alpha.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 47a58f6..55ca0dd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gapless", - "version": "5.0.0-alpha.1", + "version": "5.0.0-alpha.2", "private": false, "description": "Gapless audio playback javascript plugin", "license": "MIT", From 269f7af4ee7130c82c206bb98fd87c0b11c92a5c Mon Sep 17 00:00:00 2001 From: Daniel Saewitz Date: Tue, 10 Nov 2026 16:48:00 -0500 Subject: [PATCH 5/6] Report HTML5 again when an unloaded track replays Nothing set playbackType back to HTML5. Before tracks could be unloaded that didn't matter: a track that had played on Web Audio kept its buffer, so it replayed on Web Audio. Now unload() can release that buffer, and replaying the track goes through HTML5 with playbackType still WEBAUDIO, which the queue reads in two places: - _preloadAhead's bandwidth guard (defer preloading while the current track is on HTML5 and still loading) didn't apply, so the next track downloaded alongside the current track's fresh fetch, delaying its crossover; - _cancelScheduledGapless skipped cancelling the HTML5 gain mute. The html5 state now sets playbackType to HTML5 on entry: it's HTML5 playback by definition, and both transitions into it get it. Reported by Codex review on #32. --- src/machines/track.machine.ts | 6 ++++++ tests/unit/preload-cancel.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/machines/track.machine.ts b/src/machines/track.machine.ts index cd3afee..53187a6 100644 --- a/src/machines/track.machine.ts +++ b/src/machines/track.machine.ts @@ -164,6 +164,9 @@ export function createTrackMachine(initialContext: TrackContext) { setPlaybackTypeWebAudio: assign({ playbackType: () => 'WEBAUDIO' as PlaybackType, }), + setPlaybackTypeHtml5: assign({ + playbackType: () => 'HTML5' as PlaybackType, + }), clearNotifiedLookahead: assign({ notifiedLookahead: () => false, }), @@ -298,6 +301,9 @@ export function createTrackMachine(initialContext: TrackContext) { // html5: HTML5 Audio is playing; WebAudio decode may be in progress // ----------------------------------------------------------------- html5: { + // HTML5 is the output here, whatever played before: a track that ran + // on Web Audio, was unloaded and plays again starts over on HTML5. + entry: 'setPlaybackTypeHtml5', on: { PAUSE: { actions: [ diff --git a/tests/unit/preload-cancel.test.ts b/tests/unit/preload-cancel.test.ts index c18e900..c621b9b 100644 --- a/tests/unit/preload-cancel.test.ts +++ b/tests/unit/preload-cancel.test.ts @@ -187,3 +187,26 @@ describe('cancelling displaced preloads', () => { expect(signals.get('b')?.aborted).toBe(true); }); }); + +describe('replaying an unloaded track', () => { + it('plays it through HTML5 again, and reports HTML5', async () => { + const q = new Queue({ preloadNumTracks: 0 }); + q.setEntries([entry('a')], { play: false }); + q.play(); + await flush(); // a decodes and crosses over to Web Audio + const a = (q as Internal)._tracks[0]; + expect(a.playbackType).toBe('WEBAUDIO'); + + q.pause(); + a.deactivate(); + expect(a.unload()).toBe(true); // buffer released, as when it leaves the window + a.activate(); + + mockFetchHanging(['a']); // the fresh download stays in flight + q.play(); + await flush(); + expect(a.machineState).toBe('html5'); + expect(a.playbackType).toBe('HTML5'); + expect(a.webAudioLoadingState).toBe('LOADING'); + }); +}); From 0d8f3f1d595678cbfe09e3c94a301025591a3bbc Mon Sep 17 00:00:00 2001 From: Daniel Saewitz Date: Tue, 10 Nov 2026 16:52:04 -0500 Subject: [PATCH 6/6] Release a finished source node when unloading its track unload() nulled audioBuffer, but a track that ended naturally on Web Audio still held its source node: WEBAUDIO_ENDED goes to idle without stopping it, and DEACTIVATE in idle doesn't either. The node's buffer is the decoded audio, so in ordinary sequential playback every finished track kept its decoded audio (hundreds of MB for a long track) after the queue unloaded it for leaving the preload window. unload() now also releases the source node through _stopSourceNode() (onended cleared, disconnected, dropped). unload() never runs on a playing or scheduled track, so the node it finds is a finished one. Reported by Codex review on #32. --- src/Track.ts | 3 +++ tests/unit/preload-cancel.test.ts | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/Track.ts b/src/Track.ts index 3394406..288b63d 100644 --- a/src/Track.ts +++ b/src/Track.ts @@ -433,6 +433,9 @@ export class Track { this.queueRef.onDebug(`unload() track=${this.key} state=${state}`); this._dropPendingDecode(); this.audioBuffer = null; + // A track that ended on Web Audio keeps its finished source node, whose + // buffer is the decoded audio: let it go too, or the memory stays held. + this._stopSourceNode(); this._actor.send({ type: 'UNLOAD' }); return true; } diff --git a/tests/unit/preload-cancel.test.ts b/tests/unit/preload-cancel.test.ts index c621b9b..1e50b7d 100644 --- a/tests/unit/preload-cancel.test.ts +++ b/tests/unit/preload-cancel.test.ts @@ -210,3 +210,24 @@ describe('replaying an unloaded track', () => { expect(a.webAudioLoadingState).toBe('LOADING'); }); }); + +describe('a track that finished on Web Audio', () => { + it('lets go of its finished source node, which holds the decoded buffer, once unloaded', async () => { + const q = new Queue({ preloadNumTracks: 0 }); + q.setEntries([entry('a'), entry('b')], { play: false }); + q.play(); + await flush(); // a decodes and plays on Web Audio + const a = (q as Internal)._tracks[0]; + const node = a.sourceNode; + expect(a.playbackType).toBe('WEBAUDIO'); + expect(node?.buffer).toBeTruthy(); + + // a ends; the queue moves on to b and unloads a, now outside the window. + node.simulateEnded(); + await flush(); + expect(a.webAudioLoadingState).toBe('NONE'); + expect(a.isBufferLoaded).toBe(false); + expect(a.sourceNode).toBeNull(); // the node's buffer is the decoded audio + expect(node.disconnect).toHaveBeenCalled(); + }); +});