@trippnology/mixshell 0.0.0-stage → 0.7.1

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