@trippnology/mixshell 0.0.0-stage → 0.7.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/LICENSE +21 -0
- package/README.md +294 -2
- package/assets/mixshell-screenshot.png +0 -0
- package/package.json +73 -5
- package/src/alsa-pulse.conf +20 -0
- package/src/alsa-setup.js +15 -0
- package/src/components/browser.js +193 -0
- package/src/components/config.js +168 -0
- package/src/components/durations.js +151 -0
- package/src/components/library.js +679 -0
- package/src/components/mediakeys.js +222 -0
- package/src/components/mpris.js +309 -0
- package/src/components/player.js +412 -0
- package/src/components/playlist.js +335 -0
- package/src/components/session.js +96 -0
- package/src/constants.js +164 -0
- package/src/engines/ffmpeg.js +601 -0
- package/src/engines/index.js +14 -0
- package/src/engines/webaudio.js +317 -0
- package/src/index.js +188 -0
- package/src/mediakeys/macos-nowplaying.js +227 -0
- package/src/ui/app.js +56 -0
- package/src/ui/artPane.js +314 -0
- package/src/ui/confirmPrompt.js +34 -0
- package/src/ui/constants.js +133 -0
- package/src/ui/controller.js +1641 -0
- package/src/ui/dom.js +9 -0
- package/src/ui/goToPrompt.js +105 -0
- package/src/ui/index.html +78 -0
- package/src/ui/libraryPanel.js +415 -0
- package/src/ui/listView.js +209 -0
- package/src/ui/onboarding.js +353 -0
- package/src/ui/playlistPanel.js +207 -0
- package/src/ui/settingsPanel.js +473 -0
- package/src/ui/shortcuts.js +30 -0
- package/src/ui/splash.js +302 -0
- package/src/ui/style.css +532 -0
- package/src/ui/subtabs.js +31 -0
- package/src/ui/visualizer/bars.js +74 -0
- package/src/ui/visualizer/circles.js +64 -0
- package/src/ui/visualizer/color.js +61 -0
- package/src/ui/visualizer/cube.js +105 -0
- package/src/ui/visualizer/grid.js +68 -0
- package/src/ui/visualizer/index.js +65 -0
- package/src/ui/visualizer/onset.js +130 -0
- package/src/ui/visualizer/spectrum.js +34 -0
- package/src/ui/visualizer/vu.js +71 -0
- package/src/ui/visualizer/waveform.js +58 -0
- package/src/utils/audioAnalyzer.js +362 -0
- package/src/utils/audioDevices.js +222 -0
- package/src/utils/cellart.js +75 -0
- package/src/utils/debug.js +7 -0
- package/src/utils/durationProbe.js +48 -0
- package/src/utils/folderArt.js +46 -0
- package/src/utils/format.js +20 -0
- package/src/utils/id3.js +84 -0
- package/src/utils/pathInput.js +76 -0
- package/src/utils/playlistIO.js +176 -0
- package/src/utils/terminalGraphics.js +47 -0
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
2
|
+
import { EventEmitter } from 'node:events';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { Transform } from 'node:stream';
|
|
5
|
+
|
|
6
|
+
import ffmpeg from '@ffmpeg-installer/ffmpeg';
|
|
7
|
+
|
|
8
|
+
// No top-level `speaker` import: loading the native binding can open ALSA
|
|
9
|
+
// and abort the process on device-less systems. It is resolved lazily on
|
|
10
|
+
// first real playback; tests inject a fake sink instead.
|
|
11
|
+
const loadSpeaker = () => createRequire(import.meta.url)('speaker');
|
|
12
|
+
|
|
13
|
+
const STDERR_BUF_CHARS = 2000;
|
|
14
|
+
|
|
15
|
+
// s16le, 44100 Hz, 2 channels — the format the engine fixes by construction.
|
|
16
|
+
export const PCM_BYTES_PER_SECOND = 176400;
|
|
17
|
+
|
|
18
|
+
// `-nostdin` is load-bearing: without it ffmpeg consumes stdin and eats TUI
|
|
19
|
+
// keystrokes. `-ss` before `-i` seeks on input (fast). Output is always
|
|
20
|
+
// s16le/44100/2ch on stdout.
|
|
21
|
+
export function buildFfmpegArgs(filePath, seekSeconds = 0) {
|
|
22
|
+
const args = ['-nostdin'];
|
|
23
|
+
if (seekSeconds > 0) {
|
|
24
|
+
args.push('-ss', String(seekSeconds));
|
|
25
|
+
}
|
|
26
|
+
args.push(
|
|
27
|
+
'-i',
|
|
28
|
+
filePath,
|
|
29
|
+
'-f',
|
|
30
|
+
's16le',
|
|
31
|
+
'-ar',
|
|
32
|
+
'44100',
|
|
33
|
+
'-ac',
|
|
34
|
+
'2',
|
|
35
|
+
'pipe:1',
|
|
36
|
+
);
|
|
37
|
+
return args;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Analysis tap. ffmpeg decodes far faster than realtime, so stdout data
|
|
41
|
+
// arrives in backpressure quanta — up to seconds of audio in one burst —
|
|
42
|
+
// and slicing `audioData` synchronously in _transform made the analysis
|
|
43
|
+
// cadence match the bursts (~2-3 visible bar updates/sec no matter the
|
|
44
|
+
// render FPS). The audio path is a plain passthrough; analysis is
|
|
45
|
+
// position-addressed (issues/034): a 12ms timer reads the stream at the
|
|
46
|
+
// audible position, which is playing wall time by construction — the
|
|
47
|
+
// sink queue (the engine's learned `leadBytes`) is exactly the amount by
|
|
48
|
+
// which the arrival head runs ahead of the wall clock, so wall time in
|
|
49
|
+
// stream coordinates IS what is audible now, no matter how burstily
|
|
50
|
+
// bytes arrive. The pool (chunk deque, never concatenated) only has to
|
|
51
|
+
// span the arrival head's lead over the read pointer; _trim drops what
|
|
52
|
+
// the pointer has passed. Cadence is smooth by construction (gated by
|
|
53
|
+
// nothing but the timer) and sync is exact by construction (device and
|
|
54
|
+
// wall clocks share a rate; the ppm-level drift is invisible on bars).
|
|
55
|
+
// 2048 bytes is a multiple of every PCM stereo frame size (4 or 8
|
|
56
|
+
// bytes), so the read grid never splits a sample pair.
|
|
57
|
+
const ANALYSIS_SLICE_BYTES = 2048;
|
|
58
|
+
const ANALYSIS_SLICE_MS = 12;
|
|
59
|
+
// Memory bound, not a pacing gate: the pool normally holds only the
|
|
60
|
+
// arrival head's lead over the read pointer (~LEAD_MAX_MS at worst); the
|
|
61
|
+
// cap only matters if the pointer stalls (bars are cosmetic and must not
|
|
62
|
+
// hold memory forever).
|
|
63
|
+
const ANALYSIS_MAX_POOL_BYTES = PCM_BYTES_PER_SECOND * 3;
|
|
64
|
+
|
|
65
|
+
// Sink-latency sync (issues: visualizer ~1s ahead of the audio). The
|
|
66
|
+
// audible output lags the decode tap by everything buffered downstream —
|
|
67
|
+
// stream pipe highWaterMarks, the speaker's queue, the device buffer —
|
|
68
|
+
// which varies per machine/audio setup. The engine measures that lead
|
|
69
|
+
// directly (raw byte position minus wall-clock playing time) and uses it
|
|
70
|
+
// for the position clock and the 'ended' tail delay. The analysis tap
|
|
71
|
+
// needs no correction: reading at playing wall time already reads what
|
|
72
|
+
// is audible now, because the lead is by definition how far the arrival
|
|
73
|
+
// head is ahead of the wall clock (issues/034).
|
|
74
|
+
const LEAD_SAMPLE_MS = 250;
|
|
75
|
+
const LEAD_WARMUP_MS = 1500;
|
|
76
|
+
// τ ≈ 4s: heavy smoothing on purpose. The raw sample sawtooths with the
|
|
77
|
+
// decode-pipe/queue fill-drain cycle (±0.5s over a few seconds on
|
|
78
|
+
// PulseAudio setups) — chasing it wobbled the emit floor and the position
|
|
79
|
+
// clock, stalling and bursting the analysis cadence.
|
|
80
|
+
const LEAD_EMA = 0.06;
|
|
81
|
+
const LEAD_MAX_MS = 2000;
|
|
82
|
+
// Hysteresis: only apply moves ≥ ~140ms. Keeps the extractor floor and
|
|
83
|
+
// the position clock from tracking the sawtooth; the residual sync error
|
|
84
|
+
// is far below what the eye catches on bars.
|
|
85
|
+
const LEAD_UPDATE_BYTES = 24576;
|
|
86
|
+
|
|
87
|
+
// The speaker binding reports device-open failures with the code it passes
|
|
88
|
+
// to napi_throw_error (both the initialize and open paths use ERR_OPEN);
|
|
89
|
+
// write-phase errors carry a different code. The Player uses the tag to
|
|
90
|
+
// fall back to the system default device instead of skipping through the
|
|
91
|
+
// queue (issues/047).
|
|
92
|
+
function isSinkOpenError(err) {
|
|
93
|
+
return err?.code === 'ERR_OPEN';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export class AudioDataExtractor extends Transform {
|
|
97
|
+
constructor({ now = Date.now } = {}) {
|
|
98
|
+
super();
|
|
99
|
+
this._chunks = [];
|
|
100
|
+
this._bytes = 0;
|
|
101
|
+
this._timer = null;
|
|
102
|
+
this._now = now;
|
|
103
|
+
// Playing wall clock — the read pointer's drive. Accumulates only
|
|
104
|
+
// while unpaused (hold()/resumeClock() bracket engine pauses), so
|
|
105
|
+
// reads never run ahead of what is audible.
|
|
106
|
+
this._accMs = 0;
|
|
107
|
+
this._startedAt = null;
|
|
108
|
+
// Stream-coordinate counters: _inBytes arrived, _readPtr handed to
|
|
109
|
+
// analysis. _readPtr is monotonic — lead moves and clock quirks
|
|
110
|
+
// can never make it regress (a regression would duplicate
|
|
111
|
+
// material; a skip just loses a few ms of bars). (Not `_read`:
|
|
112
|
+
// that name is stream-machinery internal.)
|
|
113
|
+
this._inBytes = 0;
|
|
114
|
+
this._readPtr = 0;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Freeze the read clock (engine paused): analysis cadence holds with
|
|
118
|
+
// the audio instead of running ahead during silence.
|
|
119
|
+
hold() {
|
|
120
|
+
if (this._startedAt != null) {
|
|
121
|
+
this._accMs += this._now() - this._startedAt;
|
|
122
|
+
this._startedAt = null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
resumeClock() {
|
|
127
|
+
if (this._startedAt == null) this._startedAt = this._now();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
get _elapsedMs() {
|
|
131
|
+
const open = this._startedAt != null ? this._now() - this._startedAt : 0;
|
|
132
|
+
return this._accMs + open;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
_transform(chunk, _encoding, callback) {
|
|
136
|
+
this.push(chunk);
|
|
137
|
+
if (this._startedAt == null) this.resumeClock();
|
|
138
|
+
this._chunks.push(chunk);
|
|
139
|
+
this._bytes += chunk.length;
|
|
140
|
+
this._inBytes += chunk.length;
|
|
141
|
+
this._trim();
|
|
142
|
+
if (!this._timer) {
|
|
143
|
+
this._timer = setInterval(() => this._drain(), ANALYSIS_SLICE_MS);
|
|
144
|
+
this._timer.unref();
|
|
145
|
+
}
|
|
146
|
+
callback();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Drop material the read pointer has passed; fall back to the
|
|
150
|
+
// absolute cap if the pointer stalls. Keeps the pool base at/below
|
|
151
|
+
// _readPtr, which is the invariant _gather relies on.
|
|
152
|
+
_trim() {
|
|
153
|
+
const keep = Math.max(
|
|
154
|
+
this._readPtr,
|
|
155
|
+
this._inBytes - ANALYSIS_MAX_POOL_BYTES,
|
|
156
|
+
);
|
|
157
|
+
let excess = keep - (this._inBytes - this._bytes);
|
|
158
|
+
while (excess > 0 && this._chunks.length) {
|
|
159
|
+
const head = this._chunks[0];
|
|
160
|
+
if (head.length <= excess) {
|
|
161
|
+
this._chunks.shift();
|
|
162
|
+
this._bytes -= head.length;
|
|
163
|
+
excess -= head.length;
|
|
164
|
+
} else {
|
|
165
|
+
this._chunks[0] = head.subarray(excess);
|
|
166
|
+
this._bytes -= excess;
|
|
167
|
+
excess = 0;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
_drain() {
|
|
173
|
+
// Read target = the audible position in stream coordinates:
|
|
174
|
+
// playing wall time, rounded down to the 2048-byte read grid,
|
|
175
|
+
// clamped to what has actually arrived (slow decode or a cold
|
|
176
|
+
// first burst: read what exists now, catch up on later ticks —
|
|
177
|
+
// never wait, never skip). One gathered chunk per tick; a stalled
|
|
178
|
+
// event loop widens the next chunk and the analyzer's
|
|
179
|
+
// wall-time-normalized ballistics absorb the lump.
|
|
180
|
+
const target = Math.min(
|
|
181
|
+
Math.floor(
|
|
182
|
+
((this._elapsedMs / 1000) * PCM_BYTES_PER_SECOND) /
|
|
183
|
+
ANALYSIS_SLICE_BYTES,
|
|
184
|
+
) * ANALYSIS_SLICE_BYTES,
|
|
185
|
+
Math.floor(this._inBytes / ANALYSIS_SLICE_BYTES) * ANALYSIS_SLICE_BYTES,
|
|
186
|
+
);
|
|
187
|
+
if (target > this._readPtr) {
|
|
188
|
+
this.emit('audioData', this._gather(this._readPtr, target));
|
|
189
|
+
this._readPtr = target;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Gather stream range [from, to) from the deque as one buffer.
|
|
194
|
+
// Whole-chunk and view cases allocate nothing; only a range spanning
|
|
195
|
+
// chunk boundaries allocates (read-sized, a few KB). _trim keeps the
|
|
196
|
+
// pool base at/below _readPtr, so from is always inside the pool.
|
|
197
|
+
_gather(from, to) {
|
|
198
|
+
let skip = Math.max(0, from - (this._inBytes - this._bytes));
|
|
199
|
+
let need = to - from;
|
|
200
|
+
const parts = [];
|
|
201
|
+
for (let i = 0; need > 0 && i < this._chunks.length; i++) {
|
|
202
|
+
const chunk = this._chunks[i];
|
|
203
|
+
if (skip >= chunk.length) {
|
|
204
|
+
skip -= chunk.length;
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const take = Math.min(need, chunk.length - skip);
|
|
208
|
+
parts.push(
|
|
209
|
+
skip === 0 && take === chunk.length
|
|
210
|
+
? chunk
|
|
211
|
+
: chunk.subarray(skip, skip + take),
|
|
212
|
+
);
|
|
213
|
+
need -= take;
|
|
214
|
+
skip = 0;
|
|
215
|
+
}
|
|
216
|
+
return parts.length === 1 ? parts[0] : Buffer.concat(parts);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
_destroy(err, callback) {
|
|
220
|
+
if (this._timer) {
|
|
221
|
+
clearInterval(this._timer);
|
|
222
|
+
this._timer = null;
|
|
223
|
+
}
|
|
224
|
+
callback(err);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// int16 stereo gain: `Math.round(sample * volume)` clamped to
|
|
229
|
+
// [−32768, 32767]. Counts post-gain bytes pushed — the engine's position
|
|
230
|
+
// counter reads this. An odd trailing byte is held and emitted on flush
|
|
231
|
+
// untouched (a lone byte is not a sample).
|
|
232
|
+
export class GainTransform extends Transform {
|
|
233
|
+
constructor(volume = 1) {
|
|
234
|
+
super();
|
|
235
|
+
this.volume = volume;
|
|
236
|
+
this.bytesPushed = 0;
|
|
237
|
+
this._carry = null;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
setVolume(volume) {
|
|
241
|
+
this.volume = volume;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
_transform(chunk, _encoding, callback) {
|
|
245
|
+
let buf = chunk;
|
|
246
|
+
if (this._carry) {
|
|
247
|
+
buf = Buffer.concat([this._carry, chunk]);
|
|
248
|
+
this._carry = null;
|
|
249
|
+
}
|
|
250
|
+
if (buf.length % 2 !== 0) {
|
|
251
|
+
this._carry = buf.subarray(buf.length - 1);
|
|
252
|
+
buf = buf.subarray(0, buf.length - 1);
|
|
253
|
+
}
|
|
254
|
+
const out = Buffer.allocUnsafe(buf.length);
|
|
255
|
+
for (let i = 0; i < buf.length; i += 2) {
|
|
256
|
+
const sample = Math.round(buf.readInt16LE(i) * this.volume);
|
|
257
|
+
out.writeInt16LE(sample > 32767 ? 32767 : Math.max(sample, -32768), i);
|
|
258
|
+
}
|
|
259
|
+
this.push(out);
|
|
260
|
+
this.bytesPushed += out.length;
|
|
261
|
+
callback();
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
_flush(callback) {
|
|
265
|
+
if (this._carry) {
|
|
266
|
+
this.push(this._carry);
|
|
267
|
+
this.bytesPushed += this._carry.length;
|
|
268
|
+
this._carry = null;
|
|
269
|
+
}
|
|
270
|
+
callback();
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ffmpeg child-process backend. stdout is s16le PCM:
|
|
275
|
+
// child → AudioDataExtractor → GainTransform → Speaker.
|
|
276
|
+
// Position = (seek offset + post-gain bytes pushed − learned sink lead)
|
|
277
|
+
// ÷ byte rate — no wall clock in the byte counter; backpressure freezes
|
|
278
|
+
// the count while paused. The lead estimate is the only wall-clock input:
|
|
279
|
+
// it measures how far the pushed stream runs ahead of the audible output
|
|
280
|
+
// so the position clock and the 'ended' tail match what is heard. The
|
|
281
|
+
// analysis tap reads at playing wall time, which is the audible position
|
|
282
|
+
// by the same identity (issues/034).
|
|
283
|
+
export class FFmpegEngine extends EventEmitter {
|
|
284
|
+
constructor({
|
|
285
|
+
spawnFn = nodeSpawn,
|
|
286
|
+
Speaker: SinkClass,
|
|
287
|
+
device,
|
|
288
|
+
now = Date.now,
|
|
289
|
+
} = {}) {
|
|
290
|
+
super();
|
|
291
|
+
this.spawnFn = spawnFn;
|
|
292
|
+
this.SinkClass = SinkClass;
|
|
293
|
+
// Output device (issues/042): resolved by the Player (config
|
|
294
|
+
// `audioDevice`, MIXSHELL_AUDIO_DEVICE override) — undefined opens
|
|
295
|
+
// the backend default.
|
|
296
|
+
this.device = device;
|
|
297
|
+
this.child = null;
|
|
298
|
+
this.extractor = null;
|
|
299
|
+
this.gain = null;
|
|
300
|
+
this.sink = null;
|
|
301
|
+
this.currentPath = null;
|
|
302
|
+
this.volume = 1;
|
|
303
|
+
this.playing = false;
|
|
304
|
+
this.paused = false;
|
|
305
|
+
this.killed = false;
|
|
306
|
+
this.seekOffsetBytes = 0;
|
|
307
|
+
this.duration = 0;
|
|
308
|
+
this._stderrBuf = '';
|
|
309
|
+
this._now = now;
|
|
310
|
+
|
|
311
|
+
// Learned sink buffering (bytes), a device property — persists
|
|
312
|
+
// across tracks and seeks; each respawn merely re-verifies it.
|
|
313
|
+
this.leadBytes = 0;
|
|
314
|
+
this._leadEmaSec = 0;
|
|
315
|
+
// Wall-clock time actually spent unpaused on this track since the
|
|
316
|
+
// last respawn: _playElapsedMs accumulates when pause/teardown
|
|
317
|
+
// close out _playStartedAt. Frozen by construction while paused.
|
|
318
|
+
this._playElapsedMs = 0;
|
|
319
|
+
this._playStartedAt = null;
|
|
320
|
+
this._leadTimer = null;
|
|
321
|
+
this._endedTimer = null;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
get position() {
|
|
325
|
+
const pushed = this.seekOffsetBytes + (this.gain?.bytesPushed ?? 0);
|
|
326
|
+
// Subtract the learned lead: pushed bytes include everything still
|
|
327
|
+
// queued inside the speaker/device, none of which is audible yet.
|
|
328
|
+
// Clamped at 0 while a fresh pipeline is still filling the sink.
|
|
329
|
+
return Math.max(0, pushed - this.leadBytes) / PCM_BYTES_PER_SECOND;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
setVolume(volume) {
|
|
333
|
+
this.volume = Math.max(0, Math.min(1, volume));
|
|
334
|
+
if (this.gain) {
|
|
335
|
+
this.gain.setVolume(this.volume);
|
|
336
|
+
}
|
|
337
|
+
return this.volume;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
play(track) {
|
|
341
|
+
this._startTrack(track.path, 0, false);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
pause() {
|
|
345
|
+
if (!this.playing || this.paused) return;
|
|
346
|
+
// Detach the sink: backpressure propagates up and freezes the byte
|
|
347
|
+
// counter with it.
|
|
348
|
+
if (this.child?.stdout) {
|
|
349
|
+
this.child.stdout.unpipe(this.extractor);
|
|
350
|
+
}
|
|
351
|
+
this.gain.unpipe(this.sink);
|
|
352
|
+
this._closePlayClock();
|
|
353
|
+
this.extractor?.hold();
|
|
354
|
+
this.paused = true;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
resume() {
|
|
358
|
+
if (!this.playing || !this.paused) return;
|
|
359
|
+
if (this.child?.stdout) {
|
|
360
|
+
this.child.stdout.pipe(this.extractor);
|
|
361
|
+
}
|
|
362
|
+
this.gain.pipe(this.sink);
|
|
363
|
+
this._playStartedAt = this._now();
|
|
364
|
+
this.extractor?.resumeClock();
|
|
365
|
+
this.paused = false;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// Clamp to [0, duration] happens in Player.seek (it knows the metadata
|
|
369
|
+
// duration); the engine spawns with what it gets.
|
|
370
|
+
seek(seconds) {
|
|
371
|
+
if (!this.playing || !this.child) return;
|
|
372
|
+
this._startTrack(this.currentPath, seconds, this.paused);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
stop() {
|
|
376
|
+
this._teardown();
|
|
377
|
+
this.paused = false;
|
|
378
|
+
this.playing = false;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Shared by play() and seek(): SIGKILL any current child, rebuild the
|
|
382
|
+
// pipeline, spawn fresh. Paused state survives a seek (re-paused after
|
|
383
|
+
// the respawn).
|
|
384
|
+
_startTrack(path, seekSeconds, paused) {
|
|
385
|
+
this.currentPath = path;
|
|
386
|
+
this._stderrBuf = '';
|
|
387
|
+
this._teardown();
|
|
388
|
+
this.killed = false;
|
|
389
|
+
this.paused = false;
|
|
390
|
+
this.seekOffsetBytes = Math.round(seekSeconds * PCM_BYTES_PER_SECOND);
|
|
391
|
+
// Fresh play-clock window for the lead estimator.
|
|
392
|
+
this._playElapsedMs = 0;
|
|
393
|
+
this._playStartedAt = paused ? null : this._now();
|
|
394
|
+
this._leadTimer = setInterval(() => this._sampleLead(), LEAD_SAMPLE_MS);
|
|
395
|
+
this._leadTimer.unref();
|
|
396
|
+
// Pipeline failure (sink constructor throw) emits 'error' and aborts
|
|
397
|
+
// the track — no child is spawned for a pipeline that cannot play.
|
|
398
|
+
if (!this._startPipeline()) {
|
|
399
|
+
clearInterval(this._leadTimer);
|
|
400
|
+
this._leadTimer = null;
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
this._spawnChild(seekSeconds);
|
|
404
|
+
this.playing = true;
|
|
405
|
+
if (paused) {
|
|
406
|
+
this.pause();
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// SIGKILL the child, destroy the decode pipeline, end the sink last
|
|
411
|
+
// (the child must be gone before the speaker drains, or PCM keeps
|
|
412
|
+
// arriving at a dead pipe).
|
|
413
|
+
_teardown() {
|
|
414
|
+
this.killed = true;
|
|
415
|
+
if (this.child) {
|
|
416
|
+
this.child.kill('SIGKILL');
|
|
417
|
+
this.child = null;
|
|
418
|
+
}
|
|
419
|
+
this._closePlayClock();
|
|
420
|
+
if (this._leadTimer) {
|
|
421
|
+
clearInterval(this._leadTimer);
|
|
422
|
+
this._leadTimer = null;
|
|
423
|
+
}
|
|
424
|
+
if (this._endedTimer) {
|
|
425
|
+
clearTimeout(this._endedTimer);
|
|
426
|
+
this._endedTimer = null;
|
|
427
|
+
}
|
|
428
|
+
if (this.extractor) {
|
|
429
|
+
this.extractor.destroy();
|
|
430
|
+
this.extractor = null;
|
|
431
|
+
}
|
|
432
|
+
if (this.gain) {
|
|
433
|
+
this.gain.destroy();
|
|
434
|
+
this.gain = null;
|
|
435
|
+
}
|
|
436
|
+
if (this.sink) {
|
|
437
|
+
this.sink.end();
|
|
438
|
+
this.sink = null;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// Freeze the play-clock window: fold the open segment into the
|
|
443
|
+
// elapsed total. A no-op when nothing is playing.
|
|
444
|
+
_closePlayClock() {
|
|
445
|
+
if (this._playStartedAt != null) {
|
|
446
|
+
this._playElapsedMs += this._now() - this._playStartedAt;
|
|
447
|
+
this._playStartedAt = null;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// One lead sample every LEAD_SAMPLE_MS while playing: raw byte position
|
|
452
|
+
// minus wall-clock playing time = how far the pushed stream runs ahead
|
|
453
|
+
// of the audible output (stream pipes + speaker queue + device buffer).
|
|
454
|
+
// The EMA runs on its own state (_leadEmaSec — anchoring it on the
|
|
455
|
+
// applied value would deadlock below the apply hysteresis), is clamped
|
|
456
|
+
// to [0, LEAD_MAX_MS], warmup-gated (right after a respawn the sink is
|
|
457
|
+
// still filling and the raw sample reads low), and only moves
|
|
458
|
+
// leadBytes — the position clock and the 'ended' tail — in
|
|
459
|
+
// LEAD_UPDATE_BYTES steps. The analysis tap needs no lead: it reads at
|
|
460
|
+
// playing wall time, which is the audible position by the same
|
|
461
|
+
// identity (issues/034). Learned value survives tracks and seeks
|
|
462
|
+
// (device property).
|
|
463
|
+
_sampleLead() {
|
|
464
|
+
if (this._playStartedAt == null || !this.gain) return;
|
|
465
|
+
const playedMs = this._playElapsedMs + (this._now() - this._playStartedAt);
|
|
466
|
+
if (playedMs < LEAD_WARMUP_MS) return;
|
|
467
|
+
const rawSec =
|
|
468
|
+
(this.seekOffsetBytes + this.gain.bytesPushed) / PCM_BYTES_PER_SECOND;
|
|
469
|
+
const sampledSec = Math.max(
|
|
470
|
+
0,
|
|
471
|
+
Math.min(LEAD_MAX_MS / 1000, rawSec - playedMs / 1000),
|
|
472
|
+
);
|
|
473
|
+
this._leadEmaSec += (sampledSec - this._leadEmaSec) * LEAD_EMA;
|
|
474
|
+
const bytes = Math.round(this._leadEmaSec * PCM_BYTES_PER_SECOND);
|
|
475
|
+
if (Math.abs(bytes - this.leadBytes) >= LEAD_UPDATE_BYTES) {
|
|
476
|
+
this.leadBytes = bytes;
|
|
477
|
+
this.emit(
|
|
478
|
+
'debug',
|
|
479
|
+
`sync lead: ${Math.round((bytes / PCM_BYTES_PER_SECOND) * 1000)}ms`,
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
_startPipeline() {
|
|
485
|
+
// Real wall clock: the analysis reader reads at playing wall time;
|
|
486
|
+
// only the lead estimator above takes the injectable clock.
|
|
487
|
+
this.extractor = new AudioDataExtractor();
|
|
488
|
+
this.extractor.on('audioData', (data) => this.emit('pcmData', data));
|
|
489
|
+
this.extractor.on('debug', (msg) => this.emit('debug', msg));
|
|
490
|
+
this.gain = new GainTransform(this.volume);
|
|
491
|
+
|
|
492
|
+
// Format is fixed by construction — announce once, before data.
|
|
493
|
+
// sampleRate is explicit so the analyzer's ballistics
|
|
494
|
+
// normalization reads one way for both engines (issues/021).
|
|
495
|
+
this.emit('format', { float: false, sampleRate: 44100 });
|
|
496
|
+
|
|
497
|
+
// A synchronous constructor throw (speaker native binding failing to
|
|
498
|
+
// open a device, bad options) must not escape play() as an uncaught
|
|
499
|
+
// exception — route it through the same error event as every other
|
|
500
|
+
// sink failure (issues/026) so the track is skipped, not the app.
|
|
501
|
+
this.emit(
|
|
502
|
+
'debug',
|
|
503
|
+
`sink open: device=${this.device ?? '(none → backend default)'}`,
|
|
504
|
+
);
|
|
505
|
+
try {
|
|
506
|
+
const SinkClass = this.SinkClass ?? loadSpeaker();
|
|
507
|
+
this.sink = new SinkClass({
|
|
508
|
+
channels: 2,
|
|
509
|
+
sampleRate: 44100,
|
|
510
|
+
bitDepth: 16,
|
|
511
|
+
signed: true,
|
|
512
|
+
...(this.device && { device: this.device }),
|
|
513
|
+
});
|
|
514
|
+
} catch (err) {
|
|
515
|
+
// Tag open failures with the selected device (issues/047) so the
|
|
516
|
+
// Player can fall back to the system default instead of
|
|
517
|
+
// skipping the queue track by track.
|
|
518
|
+
err.device = this.device;
|
|
519
|
+
this.emit('error', err);
|
|
520
|
+
return false;
|
|
521
|
+
}
|
|
522
|
+
this.sink.on('error', (err) => {
|
|
523
|
+
if (this.killed) return;
|
|
524
|
+
this.emit('debug', `sink error: ${err?.code ?? '-'}: ${err?.message}`);
|
|
525
|
+
if (isSinkOpenError(err)) err.device = this.device;
|
|
526
|
+
this.emit('error', err);
|
|
527
|
+
});
|
|
528
|
+
this.emit('debug', 'sink opened OK');
|
|
529
|
+
return true;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
_spawnChild(seekSeconds) {
|
|
533
|
+
const args = buildFfmpegArgs(this.currentPath, seekSeconds);
|
|
534
|
+
this.emit('debug', `spawn: ffmpeg ${args.join(' ')}`);
|
|
535
|
+
const child = this.spawnFn(ffmpeg.path, args, {
|
|
536
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
537
|
+
});
|
|
538
|
+
this.child = child;
|
|
539
|
+
child.on('error', (err) => {
|
|
540
|
+
if (this.child === child && !this.killed) {
|
|
541
|
+
this.emit('error', err);
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
child.on('close', (code) => this._onClose(child, code));
|
|
545
|
+
if (child.stderr) {
|
|
546
|
+
child.stderr.setEncoding('utf8');
|
|
547
|
+
child.stderr.on('data', (data) => this._onStderr(data));
|
|
548
|
+
}
|
|
549
|
+
child.stdout.pipe(this.extractor).pipe(this.gain).pipe(this.sink);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
_onClose(child, code) {
|
|
553
|
+
if (this.child !== child) return; // stale child (seek/stop raced)
|
|
554
|
+
this.child = null;
|
|
555
|
+
if (this.killed) return;
|
|
556
|
+
this.playing = false;
|
|
557
|
+
if (code === 0) {
|
|
558
|
+
// The tail still queued in the speaker/device keeps playing for
|
|
559
|
+
// about the learned lead — hold 'ended' so auto-advance waits
|
|
560
|
+
// it out instead of cutting into the next track's start. A
|
|
561
|
+
// stop/seek during the tail cancels the timer via _teardown.
|
|
562
|
+
const delayMs = Math.round(
|
|
563
|
+
(this.leadBytes / PCM_BYTES_PER_SECOND) * 1000,
|
|
564
|
+
);
|
|
565
|
+
if (delayMs <= ANALYSIS_SLICE_MS) {
|
|
566
|
+
this.emit('ended');
|
|
567
|
+
} else {
|
|
568
|
+
this._endedTimer = setTimeout(() => {
|
|
569
|
+
this._endedTimer = null;
|
|
570
|
+
this.emit('ended');
|
|
571
|
+
}, delayMs);
|
|
572
|
+
this._endedTimer.unref();
|
|
573
|
+
}
|
|
574
|
+
} else {
|
|
575
|
+
const err = new Error(`ffmpeg exited with code ${code}`);
|
|
576
|
+
err.stderr = this._stderrBuf;
|
|
577
|
+
this.emit('error', err);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// stderr carries the `Duration:` line (used only when music-metadata
|
|
582
|
+
// gave 0) and the diagnostics attached to errors. Kept as a capped
|
|
583
|
+
// tail; the Duration regex re-runs on it per chunk (guard prevents
|
|
584
|
+
// re-emits).
|
|
585
|
+
_onStderr(data) {
|
|
586
|
+
this._stderrBuf = (this._stderrBuf + data).slice(-STDERR_BUF_CHARS);
|
|
587
|
+
this._tryDuration(this._stderrBuf);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
_tryDuration(text) {
|
|
591
|
+
const match = /Duration:\s*(\d+):(\d{2}):(\d{2}(?:\.\d+)?)/.exec(text);
|
|
592
|
+
if (match) {
|
|
593
|
+
const seconds =
|
|
594
|
+
Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3]);
|
|
595
|
+
if (seconds > 0 && seconds !== this.duration) {
|
|
596
|
+
this.duration = seconds;
|
|
597
|
+
this.emit('durationInfo', seconds);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { FFmpegEngine } from './ffmpeg.js';
|
|
2
|
+
import { WebAudioEngine } from './webaudio.js';
|
|
3
|
+
|
|
4
|
+
// Engine factory, keyed on the audioEngine config value. Unknown values
|
|
5
|
+
// fall back to ffmpeg. Importing webaudio.js is safe on every platform —
|
|
6
|
+
// the optional native binding (`node-web-audio-api`) is only resolved when
|
|
7
|
+
// the engine first plays, and a missing module surfaces as an 'error' event
|
|
8
|
+
// on that play, never at construction (issues/021).
|
|
9
|
+
export function createAudioEngine(name, { device } = {}) {
|
|
10
|
+
if (name === 'webaudio') {
|
|
11
|
+
return new WebAudioEngine({ device });
|
|
12
|
+
}
|
|
13
|
+
return new FFmpegEngine({ device });
|
|
14
|
+
}
|