@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,436 @@
1
+ import { EventEmitter } from 'node:events';
2
+
3
+ import { loadSpeaker } from '../engines/ffmpeg.js';
4
+ import { createAudioEngine } from '../engines/index.js';
5
+ import { markDeviceBroken, probeDevice } from '../utils/audioDevices.js';
6
+ import { readMetadata } from '../utils/id3.js';
7
+
8
+ // Effective output device (issues/042): MIXSHELL_AUDIO_DEVICE overrides the
9
+ // config so test/CLI workflows keep working; null/undefined = system default.
10
+ function resolveDevice(config) {
11
+ return process.env.MIXSHELL_AUDIO_DEVICE ?? config.get('audioDevice');
12
+ }
13
+
14
+ export class Player extends EventEmitter {
15
+ constructor(
16
+ playlist,
17
+ config,
18
+ analyzer = null,
19
+ { probeDevice: probe, speakerLoader = loadSpeaker } = {},
20
+ ) {
21
+ super();
22
+ this.playlist = playlist;
23
+ this.config = config;
24
+ this.engineName = config.get('audioEngine');
25
+ this.device = resolveDevice(config);
26
+ // Device gate (issues/047): play-time probe of the resolved device,
27
+ // injectable for tests.
28
+ this._probe = probe ?? probeDevice;
29
+ // Optional native sink (issues/067): injectable for tests; the real
30
+ // loader throws MODULE_NOT_FOUND when speaker failed to build.
31
+ this._speakerLoader = speakerLoader;
32
+ // speaker load canary: the native binding probes the literal ALSA
33
+ // "default" at require time and SIGABRTs the process when that open
34
+ // fails — regardless of the device we would then hand it. Canary
35
+ // "default" once before the first ffmpeg-engine speaker load;
36
+ // unusable → the webaudio engine takes over for the session.
37
+ this._forcedEngine = null;
38
+ this._defaultChecked = false;
39
+ // One deviceUnavailable toast per id per session.
40
+ this._deviceToasted = new Set();
41
+ this.engine = createAudioEngine(this.engineName, { device: this.device });
42
+ this.isPlaying = false;
43
+ this.isPaused = false;
44
+ this.volume = config.get('volume');
45
+ this.metadata = null;
46
+ this.duration = 0;
47
+ this.analyzer = analyzer;
48
+ // Mute (issues/029): engine gain goes to 0 directly — never through
49
+ // setVolume, which would persist 0 into the config (issues/027 owns
50
+ // volume persistence; mute itself does not survive a restart).
51
+ this.muted = false;
52
+ this.preMuteVolume = null;
53
+ // Session resume (issues/027): stored position for the restored
54
+ // track, applied on its first play — restoring never starts audio.
55
+ this.pendingResume = null;
56
+ this.volumeSaveTimer = null;
57
+ // Error resilience (issues/026): consecutive decode failures in one
58
+ // auto-advance chain. Reset on first engine data (a track that
59
+ // proved itself) and on user-driven track changes.
60
+ this.failCount = 0;
61
+
62
+ this.engine.setVolume(this.volume);
63
+
64
+ // Elapsed time reads the engine's PCM byte counter — no drift while
65
+ // the event loop stalls, frozen by construction while paused.
66
+ this.timer = setInterval(() => {
67
+ if (this.isPlaying && !this.isPaused) {
68
+ this.emit('timeUpdate', this.engine.position, this.duration);
69
+ }
70
+ }, 1000);
71
+
72
+ this.bindEngine();
73
+
74
+ // Listen for playlist track changes
75
+ this.playlist.on('trackChanged', () => {
76
+ if (this.isPlaying) {
77
+ this.stop();
78
+ this.play();
79
+ }
80
+ });
81
+
82
+ // Listen for the first track being added
83
+ this.playlist.on('firstTrackQueued', () => {
84
+ if (config.get('play_when_first_track_queued')) {
85
+ this.play();
86
+ }
87
+ });
88
+ }
89
+
90
+ // Rebuild the engine when the audioEngine config value changed since
91
+ // the current one was built (issues/021) — or when the output device
92
+ // changed (issues/042), same next-play contract, no live sink re-open.
93
+ // Called from play() — a switch takes effect on the next play, never
94
+ // mid-track (a paused track keeps its engine until the next full play).
95
+ // The old engine is idle by then (play() never swaps while isPaused),
96
+ // so dropping its listeners cannot strand events.
97
+ ensureEngine(device = resolveDevice(this.config)) {
98
+ const name = this._forcedEngine ?? this.config.get('audioEngine');
99
+ if (this.engineName === name && this.device === device) return;
100
+ this.stop();
101
+ this.engine.removeAllListeners();
102
+ this.engineName = name;
103
+ this.device = device;
104
+ this.engine = createAudioEngine(name, { device });
105
+ // Mute state rides the swap: the fresh engine must inherit the
106
+ // effective (post-mute) volume, not the persisted level.
107
+ this.engine.setVolume(this.muted ? 0 : this.volume);
108
+ this.bindEngine();
109
+ this.emit(
110
+ 'debug',
111
+ `Audio engine: ${name}${device ? ` (device: ${device})` : ''}`,
112
+ );
113
+ }
114
+
115
+ // Pre-play device gate (issues/047): an unplayable configured device
116
+ // must never reach the speaker backend — the ALSA library prints open
117
+ // errors straight to the terminal, ruining the TUI. Probed once per id
118
+ // (module-level cache, poisoned at runtime by open failures); ffmpeg
119
+ // only, since webaudio has no device selection. Broken → null (system
120
+ // default for this play) + one toast per id per session; undefined (no
121
+ // configured device) keeps ensureEngine's own synchronous resolution.
122
+ // speaker load canary (see _forcedEngine in the constructor): the
123
+ // binding's get_formats() opens the literal "default" device at require
124
+ // time and reads a NULL pcm when that open fails — an uncatchable
125
+ // SIGABRT that kills the app, whichever device was selected. Canary
126
+ // "default" once per session before the first speaker load; unusable →
127
+ // the ffmpeg engine cannot run on that system, so force the webaudio
128
+ // engine for the session and announce it (engineFallback event).
129
+ async _ensureSpeakerLoadable() {
130
+ const name = this._forcedEngine ?? this.config.get('audioEngine');
131
+ if (name !== 'ffmpeg' || this._defaultChecked) return;
132
+ this._defaultChecked = true;
133
+ const ok = await this._probe('default');
134
+ if (!ok) {
135
+ this._forcedEngine = 'webaudio';
136
+ this.emit(
137
+ 'debug',
138
+ 'audio: system default unusable — speaker load would abort; using webaudio for this session',
139
+ );
140
+ this.emit('engineFallback', 'ffmpeg');
141
+ return;
142
+ }
143
+ // The ALSA probe passed, so loading the binding cannot SIGABRT.
144
+ // A failed optional build (issues/067) is the other reason ffmpeg
145
+ // cannot run — fall back the same way, with a reason for the toast.
146
+ try {
147
+ this._speakerLoader();
148
+ } catch {
149
+ this._forcedEngine = 'webaudio';
150
+ this.emit(
151
+ 'debug',
152
+ 'audio: speaker module unavailable — using webaudio for this session',
153
+ );
154
+ this.emit('engineFallback', 'ffmpeg', 'speaker-unavailable');
155
+ }
156
+ }
157
+
158
+ async _resolveDeviceForPlay() {
159
+ const raw = resolveDevice(this.config);
160
+ const name = this._forcedEngine ?? this.config.get('audioEngine');
161
+ if (!raw || name !== 'ffmpeg') {
162
+ this.emit(
163
+ 'debug',
164
+ `device gate: raw=${raw ?? '(null=default)'} probe skipped`,
165
+ );
166
+ return raw;
167
+ }
168
+ const ok = await this._probe(raw);
169
+ this.emit('debug', `device gate: raw=${raw} probed=${ok}`);
170
+ if (ok) return raw;
171
+ this._notifyDeviceUnavailable(raw);
172
+ return null;
173
+ }
174
+
175
+ // Toasts an unavailable device id once per session (debug line every
176
+ // time): the pre-play gate (issues/047) and the runtime sink open
177
+ // failure below both land here. Also clears the config-sourced
178
+ // preference so the settings row shows what actually plays — a
179
+ // MIXSHELL_AUDIO_DEVICE override is session-only and must not rewrite
180
+ // the user's config. The play() retry re-resolves to the default.
181
+ _notifyDeviceUnavailable(id) {
182
+ if (
183
+ !process.env.MIXSHELL_AUDIO_DEVICE &&
184
+ resolveDevice(this.config) === id
185
+ ) {
186
+ this.config.set('audioDevice', null);
187
+ this.config.save();
188
+ }
189
+ this.emit('debug', `audio device unavailable, using default: ${id}`);
190
+ if (!this._deviceToasted.has(id)) {
191
+ this._deviceToasted.add(id);
192
+ this.emit('deviceUnavailable', id);
193
+ }
194
+ }
195
+
196
+ // One engine instance, reused across tracks: volume and wiring survive
197
+ // stop()/play() cycles by construction.
198
+ bindEngine() {
199
+ this.engine.on('pcmData', (data) => {
200
+ // First decoded bytes: the child proved itself, so the track is
201
+ // readable — the failure chain ends here (issues/026). This is
202
+ // the reset anchor, not the 'play' event, which fires before the
203
+ // engine has produced anything.
204
+ this.failCount = 0;
205
+ if (this.analyzer) {
206
+ this.analyzer.process(data);
207
+ }
208
+ });
209
+ this.engine.on('format', (format) => {
210
+ this.emit('debug', `Audio format: ${JSON.stringify(format)}`);
211
+ if (this.analyzer) {
212
+ this.analyzer.setFormat(format);
213
+ }
214
+ });
215
+ this.engine.on('ended', () => {
216
+ this.stop();
217
+ // auto=true: repeat 'one' replays the same track here instead
218
+ // of advancing (issues/037).
219
+ const nextTrack = this.playlist.next(true);
220
+ if (nextTrack) {
221
+ this.play();
222
+ }
223
+ });
224
+ this.engine.on('durationInfo', (seconds) => {
225
+ // Only fills in when metadata didn't provide a duration.
226
+ if (this.duration === 0) {
227
+ this.duration = seconds;
228
+ }
229
+ });
230
+ // Engine errors are playback failures, not process faults: report the
231
+ // track and advance, keeping the app alive (issues/026). The
232
+ // controller's last-resort handler only sees non-playback errors.
233
+ this.engine.on('error', (err) => {
234
+ // Selected-device open failure (issues/047): poison the probe
235
+ // cache, toast once, and retry the same track on the system
236
+ // default (play() stops the dead pipeline itself). The retry
237
+ // resolves no device, so a default-device failure falls through
238
+ // to the ordinary skipFailed chain — no loop.
239
+ if (err.device) {
240
+ markDeviceBroken(err.device);
241
+ this._notifyDeviceUnavailable(err.device);
242
+ this.play();
243
+ return;
244
+ }
245
+ this.skipFailed(err);
246
+ });
247
+ this.engine.on('debug', (msg) => this.emit('debug', msg));
248
+ }
249
+
250
+ get position() {
251
+ return this.engine.position;
252
+ }
253
+
254
+ async play() {
255
+ if (this.isPaused) {
256
+ return this.resume();
257
+ }
258
+
259
+ // Engine switch lands here (issues/021): the paused-tracked early
260
+ // return above keeps a paused track on its own engine.
261
+ await this._ensureSpeakerLoadable();
262
+ const device = await this._resolveDeviceForPlay();
263
+ this.ensureEngine(device);
264
+
265
+ // Stop any current playback
266
+ this.stop();
267
+
268
+ const track = this.playlist.current;
269
+ if (!track) return;
270
+
271
+ try {
272
+ this.metadata = await readMetadata(track.path);
273
+ this.emit('metadataUpdate', this.metadata);
274
+
275
+ this.duration = this.metadata.duration || 0;
276
+
277
+ this.engine.play(track);
278
+
279
+ this.isPlaying = true;
280
+ this.isPaused = false;
281
+
282
+ // First play of a restored track: jump to the stored position
283
+ // once via the engine's seek respawn (issues/027). Any other
284
+ // track invalidates the pending position.
285
+ const resume = this.pendingResume;
286
+ this.pendingResume = null;
287
+ const resumed = resume?.path === track.path;
288
+ if (resumed) this.seek(resume.position);
289
+
290
+ this.emit('play', track, { resume: resumed });
291
+ } catch (error) {
292
+ // Metadata/decode failure is a bad track, not a dead app
293
+ // (issues/026) — skip it like any engine error.
294
+ this.skipFailed(error);
295
+ }
296
+ }
297
+
298
+ pause() {
299
+ if (!this.isPlaying || this.isPaused) return;
300
+ this.engine.pause();
301
+ this.isPaused = true;
302
+ this.emit('pause');
303
+ }
304
+
305
+ resume() {
306
+ if (!this.isPlaying || !this.isPaused) return;
307
+ this.engine.resume();
308
+ this.isPaused = false;
309
+ this.emit('resume');
310
+ }
311
+
312
+ stop() {
313
+ this.engine.stop();
314
+ this.isPlaying = false;
315
+ this.isPaused = false;
316
+ this.emit('stop');
317
+ }
318
+
319
+ togglePlayPause() {
320
+ if (!this.isPlaying) {
321
+ this.play();
322
+ } else if (this.isPaused) {
323
+ this.resume();
324
+ } else {
325
+ this.pause();
326
+ }
327
+ }
328
+
329
+ next() {
330
+ // User-driven skip: a fresh track selection ends any failure chain
331
+ // (issues/026) — "consecutive" counts only auto-advances.
332
+ this.failCount = 0;
333
+ const nextTrack = this.playlist.next();
334
+ if (nextTrack && this.isPlaying) {
335
+ this.stop();
336
+ this.play();
337
+ }
338
+ }
339
+
340
+ previous() {
341
+ this.failCount = 0;
342
+ const previousTrack = this.playlist.previous();
343
+ if (previousTrack && this.isPlaying) {
344
+ this.stop();
345
+ this.play();
346
+ }
347
+ }
348
+
349
+ // A track failed to decode or play (issues/026): report it and advance
350
+ // exactly as if it had ended — repeat-off stops at the queue end, never
351
+ // wrapping. Consecutive failures across the whole queue stop playback
352
+ // with a count instead of cycling under repeat.
353
+ skipFailed(err) {
354
+ const track = this.playlist.current;
355
+ const wasPlaying = this.isPlaying;
356
+ this.stop();
357
+ this.failCount++;
358
+ this.emit('trackError', track, err);
359
+ const cap = this.playlist.length;
360
+ if (this.failCount >= cap) {
361
+ this.emit('playbackStalled', this.failCount);
362
+ return;
363
+ }
364
+ const nextTrack = this.playlist.next();
365
+ if (nextTrack && wasPlaying) {
366
+ this.play();
367
+ }
368
+ }
369
+
370
+ seek(seconds) {
371
+ if (!this.isPlaying) return;
372
+ const max = this.duration > 0 ? this.duration : seconds;
373
+ const clamped = Math.max(0, Math.min(seconds, max));
374
+ this.engine.seek(clamped);
375
+ // MPRIS needs the discontinuity signal (issues/029); the UI ignores it.
376
+ this.emit('seek', clamped);
377
+ // Immediate update so the display responds on the keypress. The
378
+ // clamped target, not engine.position: right after the respawn the
379
+ // engine's position still sits below the target while the sink
380
+ // refills (the lead correction is already baked into it).
381
+ this.emit('timeUpdate', clamped, this.duration);
382
+ }
383
+
384
+ setVolume(level) {
385
+ // Volume should be between 0 and 1
386
+ this.volume = Math.max(0, Math.min(1, level));
387
+ // Any explicit volume change lifts the mute (issues/029) — the new
388
+ // level is the user's intent, and the engine is set to it below.
389
+ if (this.muted) {
390
+ this.muted = false;
391
+ this.preMuteVolume = null;
392
+ this.emit('muteChange', false);
393
+ }
394
+ this.engine.setVolume(this.volume);
395
+ // Persist (issues/027): update the config immediately, debounce the
396
+ // disk write — volume keys fire in bursts.
397
+ this.config.set('volume', this.volume);
398
+ if (this.volumeSaveTimer) clearTimeout(this.volumeSaveTimer);
399
+ this.volumeSaveTimer = setTimeout(() => {
400
+ this.volumeSaveTimer = null;
401
+ this.config.save();
402
+ }, 500);
403
+ this.emit('volumeChange', this.volume);
404
+ return this.volume;
405
+ }
406
+
407
+ // Mute stores the pre-mute volume and applies the silence directly to
408
+ // the engine gain, keeping config (persisted volume) and MPRIS Volume
409
+ // (muted ? 0 : volume) consistent in both directions.
410
+ setMuted(muted) {
411
+ if (muted === this.muted) return this.muted;
412
+ this.muted = muted;
413
+ if (muted) {
414
+ this.preMuteVolume = this.volume;
415
+ this.engine.setVolume(0);
416
+ } else {
417
+ this.engine.setVolume(this.preMuteVolume ?? this.volume);
418
+ this.preMuteVolume = null;
419
+ }
420
+ this.emit('muteChange', this.muted);
421
+ return this.muted;
422
+ }
423
+
424
+ toggleMuted() {
425
+ return this.setMuted(!this.muted);
426
+ }
427
+
428
+ cleanup() {
429
+ if (this.volumeSaveTimer) {
430
+ clearTimeout(this.volumeSaveTimer);
431
+ this.config.save();
432
+ }
433
+ clearInterval(this.timer);
434
+ this.stop();
435
+ }
436
+ }