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