@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,317 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { readFile as nodeReadFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+
5
+ // No top-level import of `node-web-audio-api`: it is an optional dependency
6
+ // with a native binding, and importing it can fail on platforms without a
7
+ // prebuilt binary. Resolved lazily on first play; a failure surfaces as an
8
+ // engine 'error' event (the track is skipped with a hint, not a crash).
9
+ const loadWebAudio = () => createRequire(import.meta.url)('node-web-audio-api');
10
+
11
+ // Analysis tap. The whole file is decoded into an AudioBuffer, so the tap
12
+ // reads the decoded samples directly at the playback position — a wall-clock
13
+ // timer slices out whatever audio elapsed since the last tick (capped, so a
14
+ // stalled event loop skips stale audio instead of lagging the bars forever),
15
+ // interleaves L/R and emits float32 PCM. This mirrors the ffmpeg engine's
16
+ // AudioDataExtractor cadence (~86 updates/sec) so the visualizer ballistics
17
+ // transfer without recalibration.
18
+ const TAP_TICK_MS = 12;
19
+ const TAP_MAX_LAG_SECONDS = 0.25;
20
+
21
+ // node-web-audio-api's AudioContext constructor throws DeviceNotAvailable on
22
+ // systems without an output device and does not document a sampleRate
23
+ // fallback, so the 44100 request degrades to the device default.
24
+ const PREFERRED_SAMPLE_RATE = 44100;
25
+
26
+ // decodes at the context rate; duration = buffer.duration is sample-exact.
27
+ export class WebAudioEngine extends EventEmitter {
28
+ constructor({
29
+ loadModule = loadWebAudio,
30
+ readFile = nodeReadFile,
31
+ device,
32
+ } = {}) {
33
+ super();
34
+ this.loadModule = loadModule;
35
+ this.readFile = readFile;
36
+ // Accepted but unusable (issues/042): web-audio-api-rs has no device
37
+ // selection — a configured device only earns the debug note below.
38
+ this.device = device;
39
+
40
+ this.audio = null; // { AudioContext, AudioBufferSourceNode, GainNode }
41
+ this.context = null;
42
+ this.source = null;
43
+ this.gain = null;
44
+ this.buffer = null;
45
+ this.currentPath = null;
46
+
47
+ this.volume = 1;
48
+ this.playing = false;
49
+ this.paused = false;
50
+ this.duration = 0;
51
+
52
+ // Incremented on every stop/seek/restart: closures from a previous
53
+ // generation (decode, source onended, decode-completion) compare and
54
+ // drop themselves when stale.
55
+ this.epoch = 0;
56
+
57
+ // Where the current source was started: position =
58
+ // context.currentTime - startedAtTime + startOffset.
59
+ this.startedAtTime = 0;
60
+ this.startOffset = 0;
61
+ // Position snapshot while suspended (currentTime is frozen, but the
62
+ // snapshot makes pause/resume/seek arithmetic synchronous).
63
+ this.pausedPos = 0;
64
+ // Set when seek() targeted a suspended context: resume() must
65
+ // restart the source at pausedPos (a plain resume keeps it).
66
+ this.seekedWhilePaused = false;
67
+ // seek() that arrives before decode completes (Player applies a
68
+ // session-resume position right after play()) lands here.
69
+ this.pendingSeek = null;
70
+
71
+ this.tapTimer = null;
72
+ this.tapPos = 0;
73
+ this.deviceNoteShown = false;
74
+ }
75
+
76
+ get position() {
77
+ if (!this.playing || !this.context) return 0;
78
+ if (this.paused) return this.pausedPos;
79
+ if (!this.duration) return this.startOffset;
80
+ return Math.min(
81
+ this.duration,
82
+ this.context.currentTime - this.startedAtTime + this.startOffset,
83
+ );
84
+ }
85
+
86
+ setVolume(volume) {
87
+ this.volume = Math.max(0, Math.min(1, volume));
88
+ if (this.gain) {
89
+ this.gain.gain.value = this.volume;
90
+ }
91
+ return this.volume;
92
+ }
93
+
94
+ play(track) {
95
+ // Synchronous state flip: Player marks isPlaying right after play()
96
+ // returns and must not disagree with the engine while the decode
97
+ // promise is in flight. Decode failure surfaces later as 'error'.
98
+ this.currentPath = track.path;
99
+ this.epoch++;
100
+ const epoch = this.epoch;
101
+ this.playing = true;
102
+ this.paused = false;
103
+ this.buffer = null;
104
+ this.duration = 0;
105
+ this.startedAtTime = 0;
106
+ this.startOffset = 0;
107
+ this.pausedPos = 0;
108
+ this.pendingSeek = null;
109
+ this.tapPos = 0;
110
+
111
+ this._decodeCurrent(epoch);
112
+ }
113
+
114
+ async _decodeCurrent(epoch) {
115
+ try {
116
+ this._ensureContext();
117
+ if (epoch !== this.epoch) return;
118
+
119
+ const bytes = await this.readFile(this.currentPath);
120
+ if (epoch !== this.epoch) return;
121
+ const ab = bytes.buffer.slice(
122
+ bytes.byteOffset,
123
+ bytes.byteOffset + bytes.byteLength,
124
+ );
125
+
126
+ this.emit('debug', `webaudio: decoding ${this.currentPath}`);
127
+ const decoded = await this.context.decodeAudioData(ab);
128
+ if (epoch !== this.epoch) return;
129
+
130
+ this.buffer = decoded;
131
+ this.duration = decoded.duration;
132
+ this.emit('durationInfo', this.duration);
133
+ this._startSource(epoch, this.pendingSeek ?? 0);
134
+ this.pendingSeek = null;
135
+ this._startTap();
136
+ } catch (err) {
137
+ if (epoch !== this.epoch) return;
138
+ this.playing = false;
139
+ this.emit('error', err);
140
+ }
141
+ }
142
+
143
+ _ensureContext() {
144
+ if (this.context) return;
145
+ this.audio = this.loadModule();
146
+ if (this.device && !this.deviceNoteShown) {
147
+ this.deviceNoteShown = true;
148
+ this.emit(
149
+ 'debug',
150
+ 'webaudio: device selection unsupported (no device selection in web-audio-api-rs) — using default output',
151
+ );
152
+ }
153
+ const { AudioContext } = this.audio;
154
+ try {
155
+ this.context = new AudioContext({
156
+ sampleRate: PREFERRED_SAMPLE_RATE,
157
+ latencyHint: 'playback',
158
+ });
159
+ } catch {
160
+ // Device may not accept 44100 (or lack it entirely — the second
161
+ // attempt then throws for real and routes to 'error').
162
+ this.context = new AudioContext({ latencyHint: 'playback' });
163
+ }
164
+ this.gain = new this.audio.GainNode(this.context);
165
+ this.gain.gain.value = this.volume;
166
+ this.gain.connect(this.context.destination);
167
+ this.emit('format', {
168
+ float: true,
169
+ sampleRate: this.context.sampleRate,
170
+ });
171
+ this.emit('debug', `webaudio: context ${this.context.sampleRate}Hz`);
172
+ }
173
+
174
+ // stop the current source and start a fresh one at `offset`. The epoch
175
+ // bump is the caller's job (it distinguishes our own kills from natural
176
+ // ends in onended).
177
+ _startSource(epoch, offset) {
178
+ this._stopSource();
179
+ const source = new this.audio.AudioBufferSourceNode(this.context);
180
+ source.buffer = this.buffer;
181
+ source.connect(this.gain);
182
+ this.source = source;
183
+ this.startedAtTime = this.context.currentTime;
184
+ this.startOffset = offset;
185
+ source.onended = () => this._onSourceEnded(epoch);
186
+ source.start(0, offset);
187
+ }
188
+
189
+ _stopSource() {
190
+ if (!this.source) return;
191
+ const source = this.source;
192
+ this.source = null;
193
+ source.onended = null;
194
+ try {
195
+ source.stop();
196
+ } catch {
197
+ // start() not called yet / already stopped — nothing to do.
198
+ }
199
+ }
200
+
201
+ // Natural end only: every programmatic stop/seek bumped the epoch before
202
+ // killing the source, so a live epoch here means the buffer played out.
203
+ _onSourceEnded(epoch) {
204
+ if (epoch !== this.epoch || !this.playing) return;
205
+ this._stopTap();
206
+ this.paused = false;
207
+ this.playing = false;
208
+ this.emit('ended');
209
+ }
210
+
211
+ pause() {
212
+ if (!this.playing || this.paused || !this.context) return;
213
+ this.pausedPos = this.position;
214
+ this.paused = true;
215
+ this.context.suspend();
216
+ }
217
+
218
+ resume() {
219
+ if (!this.playing || !this.paused || !this.context) return;
220
+ this.paused = false;
221
+ this.context.resume();
222
+ // A seek while suspended moved pausedPos away from where the source
223
+ // actually sits — restart the source at the target. A plain resume
224
+ // keeps the source (currentTime froze with the context, so the
225
+ // position relationship survives suspension untouched).
226
+ if (this.seekedWhilePaused) {
227
+ this.seekedWhilePaused = false;
228
+ this.epoch++;
229
+ this._startSource(this.epoch, this.pausedPos);
230
+ }
231
+ }
232
+
233
+ // Clamp to [0, duration] happens in Player.seek (it knows the metadata
234
+ // duration). Before the decode has finished, the target is stashed and
235
+ // applied when the source starts (Player applies a session-resume seek
236
+ // immediately after play()).
237
+ seek(seconds) {
238
+ if (!this.playing) return;
239
+ // The tap re-anchors on both paths so the next tick doesn't read
240
+ // across the seek jump.
241
+ this.tapPos = seconds;
242
+ if (!this.buffer) {
243
+ this.pendingSeek = seconds;
244
+ this.pausedPos = seconds;
245
+ return;
246
+ }
247
+ this.epoch++;
248
+ if (this.paused) {
249
+ this.pausedPos = seconds;
250
+ this.seekedWhilePaused = true;
251
+ return;
252
+ }
253
+ this._startSource(this.epoch, seconds);
254
+ }
255
+
256
+ stop() {
257
+ this.epoch++;
258
+ this._stopSource();
259
+ this._stopTap();
260
+ this.buffer = null;
261
+ this.playing = false;
262
+ this.paused = false;
263
+ // Park the context: freezes the cpal render loop while idle; play()
264
+ // resumes it. Suspending also freezes currentTime, which keeps the
265
+ // position math consistent across idle periods.
266
+ if (this.context && this.context.state === 'running') {
267
+ this.context.suspend();
268
+ }
269
+ }
270
+
271
+ // ---- analysis tap ----
272
+
273
+ _startTap() {
274
+ this._stopTap();
275
+ this.tapPos = this.position;
276
+ this.tapTimer = setInterval(() => this._tapTick(), TAP_TICK_MS);
277
+ this.tapTimer.unref();
278
+ }
279
+
280
+ _stopTap() {
281
+ if (this.tapTimer) {
282
+ clearInterval(this.tapTimer);
283
+ this.tapTimer = null;
284
+ }
285
+ }
286
+
287
+ _tapTick() {
288
+ if (!this.playing || this.paused || !this.buffer) return;
289
+ const pos = this.position;
290
+ const rate = this.context.sampleRate;
291
+ let frames = Math.floor(pos * rate) - Math.floor(this.tapPos * rate);
292
+ if (frames <= 0) return;
293
+ // A stalled event loop must skip stale audio, not lag the bars
294
+ // forever (same trade as the ffmpeg extractor's staleness cap).
295
+ const maxLag = Math.ceil(rate * TAP_MAX_LAG_SECONDS);
296
+ if (frames > maxLag) {
297
+ this.tapPos = pos - maxLag / rate;
298
+ frames = maxLag;
299
+ }
300
+ const startFrame = Math.floor(this.tapPos * rate);
301
+ const available = Math.max(0, this.buffer.length - startFrame);
302
+ if (available <= 0) return;
303
+ frames = Math.min(frames, available);
304
+
305
+ const channels = Math.min(2, this.buffer.numberOfChannels);
306
+ const interleaved = new Float32Array(frames * 2);
307
+ const scratch = new Float32Array(frames);
308
+ for (let ch = 0; ch < channels; ch++) {
309
+ this.buffer.copyFromChannel(scratch, ch, startFrame);
310
+ for (let i = 0; i < frames; i++) {
311
+ interleaved[i * 2 + ch] = scratch[i];
312
+ }
313
+ }
314
+ this.emit('pcmData', Buffer.from(interleaved.buffer));
315
+ this.tapPos = this.tapPos + frames / rate;
316
+ }
317
+ }
package/src/index.js ADDED
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { mkdirSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { homedir } from 'node:os';
6
+ import './alsa-setup.js';
7
+ import { Command } from 'commander';
8
+ import { Browser } from './components/browser.js';
9
+ import { Config } from './components/config.js';
10
+ import { Library } from './components/library.js';
11
+ import { startMediaKeys } from './components/mediakeys.js';
12
+ import { startMpris } from './components/mpris.js';
13
+ import { Player } from './components/player.js';
14
+ import { Playlist } from './components/playlist.js';
15
+ import { restoreSession, saveSession } from './components/session.js';
16
+ import { CONFIG_FILE, LIBRARY_DB_FILE, STATE_DIR } from './constants.js';
17
+ import { startUI } from './ui/app.js';
18
+ import { AudioAnalyzer } from './utils/audioAnalyzer.js';
19
+ import { listOutputDevices } from './utils/audioDevices.js';
20
+ import { DBG } from './utils/debug.js';
21
+ import { fallbackDirectory, resolveDirectoryInput } from './utils/pathInput.js';
22
+ import { filterLoadable, readPlaylistFile } from './utils/playlistIO.js';
23
+
24
+ // Initialize the program
25
+ const program = new Command();
26
+
27
+ program
28
+ .name('mixshell')
29
+ .description('Console-based music player')
30
+ .version(createRequire(import.meta.url)('../package.json').version)
31
+ .option('-d, --directory <path>', 'specify media directory')
32
+ .option('-p, --playlist <path>', 'load playlist file')
33
+ .option('--debug', 'show the debug tab')
34
+ .option('--debug-log-path <path>', 'write debug output to this file')
35
+ .parse(process.argv);
36
+
37
+ const options = program.opts();
38
+
39
+ // Internal transport only: --debug-log-path is the user-facing way to set it.
40
+ if (options.debugLogPath)
41
+ process.env.MIXSHELL_DEBUG_FILE = options.debugLogPath;
42
+
43
+ // Initialize components
44
+ // All state lives in one directory (issues/030); create it before anything
45
+ // opens a file in it.
46
+ mkdirSync(STATE_DIR, { recursive: true });
47
+ DBG(
48
+ `state dir ${STATE_DIR} (config: ${CONFIG_FILE}, library: ${LIBRARY_DB_FILE})`,
49
+ );
50
+
51
+ const config = new Config();
52
+ config.load();
53
+
54
+ // Set directory from command line or use default from config. Resolve -d
55
+ // before the UI sees it, so a confirmed choice is never stored relative
56
+ // (issues/051); an unusable path still reaches the picker for a notice.
57
+ const requestedDirectory = options.directory || config.get('mediaDirectory');
58
+ const resolvedStart = requestedDirectory
59
+ ? resolveDirectoryInput(requestedDirectory, { base: process.cwd() })
60
+ : null;
61
+ const mediaDirectory = resolvedStart?.path || requestedDirectory;
62
+ const startDirectory = options.directory ? mediaDirectory : undefined;
63
+
64
+ // An unusable start directory falls back to the nearest readable ancestor
65
+ // for this session only (issues/054): never written back to the config, so
66
+ // the mount returning restores the stored path. Onboarding shows its own
67
+ // notice, so no startup toast is queued for the same problem.
68
+ let browserDirectory = mediaDirectory;
69
+ // Startup notices stay as data until the UI is up: the terminal attach
70
+ // wipes console lines (issues/063). The UI decides when to toast them —
71
+ // a first-run onboarding dialog owns the toast slot until it closes.
72
+ const startupNotices = [];
73
+ if (resolvedStart?.error) {
74
+ browserDirectory = fallbackDirectory(resolvedStart.path, {
75
+ home: homedir(),
76
+ });
77
+ if (!config.needsOnboarding()) {
78
+ startupNotices.push(
79
+ `Media directory unavailable: ${requestedDirectory} — showing ${browserDirectory}`,
80
+ );
81
+ }
82
+ DBG(`media directory fallback: ${resolvedStart.error} → ${browserDirectory}`);
83
+ }
84
+
85
+ // Initialize player and playlist
86
+ const playlist = new Playlist();
87
+ const analyzer = new AudioAnalyzer(config);
88
+ const player = new Player(playlist, config, analyzer);
89
+
90
+ // Load playlist if specified; otherwise restore the last session
91
+ // (issues/027) — an explicit -p wins over the stored queue. Restore happens
92
+ // before the UI inits so the playlist panel paints the restored queue.
93
+ // Format sniffed by extension (issues/028); dead/foreign entries skip with
94
+ // a count; loading never starts playback.
95
+ if (options.playlist) {
96
+ try {
97
+ const { tracks, skipped } = filterLoadable(
98
+ readPlaylistFile(options.playlist),
99
+ );
100
+ playlist.loadTracks(tracks);
101
+ if (skipped > 0) {
102
+ DBG(`playlist load: skipped ${skipped} dead/foreign entries`);
103
+ startupNotices.push(`Loaded ${tracks.length} tracks, skipped ${skipped}`);
104
+ }
105
+ } catch (error) {
106
+ DBG(`playlist load failed: ${error?.message ?? error}`);
107
+ startupNotices.push(
108
+ `Playlist load failed: ${options.playlist} — ${error?.message ?? error}`,
109
+ );
110
+ }
111
+ } else {
112
+ restoreSession({
113
+ player,
114
+ playlist,
115
+ onDropped: (dropped) => {
116
+ startupNotices.push(
117
+ `Restored ${playlist.length} tracks — ${dropped} missing files removed from the queue`,
118
+ );
119
+ },
120
+ });
121
+ }
122
+
123
+ // Keep the session file fresh between quits: track changes rewrite it with
124
+ // position 0 (the new track just started); a quit overwrites with the real
125
+ // position. Crash protection, cheap enough per issues/027.
126
+ playlist.on('trackChanged', () => {
127
+ saveSession({ player, playlist, position: 0 });
128
+ });
129
+
130
+ // Initialize browser with the media directory
131
+ const browser = new Browser(browserDirectory);
132
+
133
+ // Initialize the media library (SQLite index — issues/023)
134
+ const library = new Library({ config });
135
+
136
+ // Initialize UI with all components
137
+ const ui = await startUI({
138
+ player,
139
+ playlist,
140
+ browser,
141
+ config,
142
+ library,
143
+ analyzer,
144
+ debug: options.debug,
145
+ startDirectory,
146
+ startupNotices,
147
+ });
148
+
149
+ // Output device enumeration (issues/042): warm the session cache so the
150
+ // settings row can label the stored device with its friendly name. The
151
+ // helper never throws and only spawns probes on platforms where the
152
+ // speaker backend honours device strings (Linux).
153
+ listOutputDevices();
154
+
155
+ // Desktop integration (issues/029): MPRIS2 on Linux — media keys, playerctl,
156
+ // tray controls. Fire-and-forget: never blocks startup, and every failure
157
+ // path inside startMpris degrades to a null handle with one debug line.
158
+ startMpris({ player, playlist, quit: shutdown }).catch((error) =>
159
+ DBG(`mpris failed: ${error?.message ?? error}`),
160
+ );
161
+
162
+ // Media keys on macOS (issues/048): same contract as MPRIS — opt-in via the
163
+ // `mediaKeys` setting, fire-and-forget, and every failure path inside
164
+ // startMediaKeys degrades to a null handle with one debug line. The helper
165
+ // is a child process; process exit closes its stdin pipe and it exits on
166
+ // the EOF.
167
+ startMediaKeys({
168
+ player,
169
+ playlist,
170
+ enabled: config.get('mediaKeys') === true,
171
+ }).catch((error) => DBG(`mediakeys failed: ${error?.message ?? error}`));
172
+
173
+ // Scan the configured library directories on start if asked to
174
+ if (config.get('libraryScanOnStart') && library.isConfigured()) {
175
+ library.scan().catch(() => {});
176
+ }
177
+
178
+ // Shared teardown for Ctrl-C and MPRIS Quit (issues/029).
179
+ function shutdown() {
180
+ ui.cleanup();
181
+ player.stop();
182
+ config.save();
183
+ library.close();
184
+ process.exit(0);
185
+ }
186
+
187
+ // Handle process exit
188
+ process.on('SIGINT', shutdown);