@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,362 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import FFT from 'fft.js';
3
+
4
+ // Quality presets. The FFT size is the analysis window length: bass needs
5
+ // long windows (a 40Hz note spans 25ms of samples), so even "low" uses 256
6
+ // samples (~6ms). Larger windows give finer frequency resolution, coarser
7
+ // temporal resolution. Render detail (bar counts) lives on the visualizer
8
+ // side — this module knows nothing about bars.
9
+ export const QUALITY_PRESETS = {
10
+ low: { fftSize: 256 },
11
+ medium: { fftSize: 1024 },
12
+ high: { fftSize: 2048 },
13
+ };
14
+
15
+ const DEFAULT_FFT_SIZE = 1024; // 512 frequency bins
16
+
17
+ export class AudioAnalyzer extends EventEmitter {
18
+ constructor(config, { now = Date.now } = {}) {
19
+ super();
20
+ this.config = config;
21
+ this._now = now;
22
+ // Wall-clock anchor for ballistics: smoothing steps are scaled by
23
+ // the time actually elapsed since the last chunk, not by chunk
24
+ // count — the analysis tap can deliver windows in lumps (the
25
+ // extractor paces emission against sink behavior), and per-window
26
+ // steps would turn each lump into one huge visual jump.
27
+ this._lastProcessAt = null;
28
+
29
+ this.fftSize = DEFAULT_FFT_SIZE;
30
+ this.numBins = this.fftSize / 2;
31
+ this.fft = new FFT(this.fftSize);
32
+ this.hann = makeHann(this.fftSize);
33
+ this.fftOutput = this.fft.createComplexArray();
34
+ this.buffer = [];
35
+ this.smoothedBins = new Array(this.numBins).fill(0);
36
+
37
+ this.smoothedAmplitude = 0;
38
+ // Per-channel envelopes for the VU meter: same ballistics as the
39
+ // mono envelope, fed from per-channel RMS instead of the average.
40
+ this.smoothedAmplitudeL = 0;
41
+ this.smoothedAmplitudeR = 0;
42
+
43
+ this.smoothingFactor = this.config?.get('visualizerSmoothing') ?? 1;
44
+
45
+ // Spectrum off = amplitude-only mode feeding (VU): the FFT is skipped and the payload carries empty bins. The flag
46
+ // is mode-agnostic on purpose — the controller decides who needs
47
+ // bins; this module knows nothing about modes.
48
+ this.spectrumEnabled = true;
49
+
50
+ // The engine reports its PCM format ('format' event → setFormat)
51
+ // before the first data chunk; the ffmpeg engine fixes s16le/44100
52
+ // by construction, so this default is now a constant of our
53
+ // pipeline. The webaudio engine reports float32 and its actual
54
+ // context rate (issues/021).
55
+ this.detectedFormat = 'int16';
56
+ this.sampleRate = 44100;
57
+
58
+ this.updateQualitySettings();
59
+ }
60
+
61
+ // Definitive format from the decoder's 'format' event. Heuristic
62
+ // byte-sniffing misdetected: int16 samples of some sines read as valid
63
+ // float32 (e.g. 0x3E803E80 ≈ 0.25), turning whole tracks into noise.
64
+ // An explicit sampleRate (webaudio, issues/021) feeds the ballistics
65
+ // time-normalization below; windows/sec = sampleRate / fftSize.
66
+ setFormat(format) {
67
+ this.detectedFormat = format?.float ? 'float32' : 'int16';
68
+ const rate = format?.sampleRate;
69
+ if (Number.isFinite(rate) && rate > 0 && rate !== this.sampleRate) {
70
+ this.sampleRate = rate;
71
+ this.updateQualitySettings();
72
+ }
73
+ }
74
+
75
+ setSpectrumEnabled(enabled) {
76
+ this.spectrumEnabled = !!enabled;
77
+ }
78
+
79
+ // Update quality settings based on config
80
+ updateQualitySettings() {
81
+ const quality = this.config?.get('visualizerQuality') || 'medium';
82
+ const preset = QUALITY_PRESETS[quality] || QUALITY_PRESETS.medium;
83
+
84
+ // Only update if quality changed
85
+ if (preset.fftSize !== this.fftSize) {
86
+ this.fftSize = preset.fftSize;
87
+ this.numBins = this.fftSize / 2;
88
+ this.fft = new FFT(this.fftSize);
89
+ this.hann = makeHann(this.fftSize);
90
+ this.fftOutput = this.fft.createComplexArray();
91
+ this.smoothedBins = new Array(this.numBins).fill(0);
92
+ this.buffer = []; // Clear buffer to prevent size mismatch
93
+ }
94
+
95
+ // Update smoothing factor
96
+ this.smoothingFactor = this.config?.get('visualizerSmoothing') ?? 1;
97
+
98
+ // Time-normalized ballistics. The EMA steps once per completed
99
+ // window and windows/sec = sampleRate / fftSize (ffmpeg output is
100
+ // fixed s16le stereo at 44100; webaudio reports its actual
101
+ // context rate), so an unadjusted factor makes High's bars 8x slower in
102
+ // wall-clock terms than Low's (44100/256 ≈ 172 windows/s vs
103
+ // 44100/2048 ≈ 21.5). Geometric compensation —
104
+ // f_eff = 1 - (1 - f)^(scale · dtSec · windows/sec) — pins the time
105
+ // constant to the medium preset at the reference rate the smoothing
106
+ // setting was calibrated at AND to wall time (process() supplies
107
+ // dtSec): stepRate · ln(1 - f_eff) is then constant across
108
+ // fftSizes, sample rates, and lumped vs even window arrival.
109
+ this._windowsPerSec = this.sampleRate / this.fftSize;
110
+ const scale = (this.sampleRate / 44100) * (this.fftSize / 1024);
111
+ this._ballisticScale = scale;
112
+ // The smoothing setting maps onto responsiveness (higher =
113
+ // snappier): the tap reads at the audible position on a smooth
114
+ // timer (issues/034), so this factor engages on every window and
115
+ // the raw setting read sluggish at the old 0.3 default (~140ms
116
+ // attack τ; the shipped default is now 1 = Off). ×2/×3 puts 0.3's
117
+ // attack τ ≈ 60ms; release stays faster than attack (≥1.5×,
118
+ // test-pinned) so bars punch up and fall cleanly. Capped at 0.95 —
119
+ // base 1 means zero integration (raw per-window magnitudes,
120
+ // flickery) and rides the 0 ** 0 = 1 JS quirk on same-millisecond
121
+ // calls, so Off lands one notch short of truly raw.
122
+ this._attackBase = Math.min(0.95, this.smoothingFactor * 2);
123
+ this._releaseBase = Math.min(0.95, this.smoothingFactor * 3);
124
+ }
125
+
126
+ // Ballistic factor for one smoothing step spanning dtSec of wall time.
127
+ _ballisticStep(base, dtSec) {
128
+ const exponent = this._ballisticScale * dtSec * this._windowsPerSec;
129
+ return 1 - (1 - base) ** exponent;
130
+ }
131
+
132
+ /**
133
+ * Process audio data chunk
134
+ * @param {Buffer} chunk - PCM audio data from decoder
135
+ */
136
+ process(chunk) {
137
+ const { samples, sumSqL, sumSqR } = this.readSamples(chunk);
138
+ if (samples.length === 0) return;
139
+
140
+ // Wall time since the last chunk drives every smoothing step this
141
+ // call makes (see constructor). First call: one nominal window.
142
+ const now = this._now();
143
+ const dtSec =
144
+ this._lastProcessAt == null
145
+ ? this.fftSize / this.sampleRate
146
+ : Math.min(0.5, Math.max(0, (now - this._lastProcessAt) / 1000));
147
+ this._lastProcessAt = now;
148
+
149
+ // Calculate amplitude (RMS)
150
+ this.calculateAmplitude(samples, dtSec);
151
+ this.calculateChannelAmplitudes(sumSqL, sumSqR, samples.length, dtSec);
152
+
153
+ // Silent chunks (quiet passages / decoder padding) decay smoothly to
154
+ // zero instead of freezing the last analysis on screen. Bins fall
155
+ // faster than amplitude: log10 compression in the renderer makes
156
+ // slow bin decay read as bars stuck above the baseline. Decay rates
157
+ // are wall-time normalized like the ballistics below.
158
+ const maxSample = maxAbs(samples);
159
+ if (maxSample < 0.01) {
160
+ if (this.spectrumEnabled) {
161
+ const decay = 0.5 ** (dtSec * this._windowsPerSec);
162
+ for (let i = 0; i < this.numBins; i++) {
163
+ this.smoothedBins[i] *= decay;
164
+ }
165
+ }
166
+ this.smoothedAmplitude *= 0.8 ** (dtSec * this._windowsPerSec);
167
+ this.smoothedAmplitudeL *= 0.8 ** (dtSec * this._windowsPerSec);
168
+ this.smoothedAmplitudeR *= 0.8 ** (dtSec * this._windowsPerSec);
169
+ this.emitAnalysis();
170
+ return;
171
+ }
172
+ if (this.spectrumEnabled) {
173
+ // Analyze every full window in the chunk — the decoder hands us
174
+ // ~0.4s per chunk, so consuming one window per call would
175
+ // analyse audio that is seconds stale and leave the buffer
176
+ // growing forever. The chunk's wall time is divided evenly
177
+ // across the windows analyzed (counted up front, remainder
178
+ // carry included), so a lump of N windows in one chunk steps
179
+ // the ballistics exactly as much as N evenly spaced windows
180
+ // would. The remainder carry is UNCONDITIONAL — it must
181
+ // accumulate across calls regardless of whether this chunk
182
+ // completed a window, or sub-window chunks never reach a full
183
+ // window and the FFT path goes silent (issues/034 freeze).
184
+ const totalWindows =
185
+ Math.floor(samples.length / this.fftSize) +
186
+ Math.floor(
187
+ (this.buffer.length + (samples.length % this.fftSize)) / this.fftSize,
188
+ );
189
+ const dtPerWindow = dtSec / Math.max(1, totalWindows);
190
+ for (
191
+ let offset = 0;
192
+ offset + this.fftSize <= samples.length;
193
+ offset += this.fftSize
194
+ ) {
195
+ this.analyzeWindow(samples, offset, dtPerWindow);
196
+ }
197
+ // Carry the sub-window remainder across chunks
198
+ const start = samples.length - (samples.length % this.fftSize);
199
+ for (let i = start; i < samples.length; i++) {
200
+ this.buffer.push(samples[i]);
201
+ }
202
+ while (this.buffer.length >= this.fftSize) {
203
+ this.analyzeWindow(this.buffer, 0, dtPerWindow);
204
+ this.buffer.splice(0, this.fftSize);
205
+ }
206
+ }
207
+ this.emitAnalysis();
208
+ }
209
+
210
+ // One FFT over samples[offset, offset + fftSize): mean removal kills the
211
+ // DC offset, the Hann window controls spectral leakage. dtSec is this
212
+ // window's share of the chunk's wall time.
213
+ analyzeWindow(samples, offset, dtSec) {
214
+ const attack = this._ballisticStep(this._attackBase, dtSec);
215
+ const release = this._ballisticStep(this._releaseBase, dtSec);
216
+ const windowed = new Array(this.fftSize);
217
+ let mean = 0;
218
+ for (let i = 0; i < this.fftSize; i++) {
219
+ mean += samples[offset + i];
220
+ }
221
+ mean /= this.fftSize;
222
+ for (let i = 0; i < this.fftSize; i++) {
223
+ windowed[i] = (samples[offset + i] - mean) * this.hann[i];
224
+ }
225
+
226
+ this.fft.realTransform(this.fftOutput, windowed);
227
+
228
+ // Magnitude of each frequency bin, normalized so a full-scale sine
229
+ // reads ~0.5 regardless of fftSize. Ballistics are asymmetric —
230
+ // attack uses the configured smoothing, release runs faster (see
231
+ // updateQualitySettings) — so bars punch up with the music but
232
+ // fall fast enough to track it (log10 compression in the renderer
233
+ // makes symmetric decay read as sluggish). Both factors are
234
+ // time-normalized per fftSize in updateQualitySettings.
235
+ for (let i = 0; i < this.numBins; i++) {
236
+ const re = this.fftOutput[i * 2];
237
+ const im = this.fftOutput[i * 2 + 1];
238
+ const magnitude = Math.sqrt(re * re + im * im) / this.fftSize;
239
+ const factor = magnitude > this.smoothedBins[i] ? attack : release;
240
+ const smoothed = this.smoothedBins[i] * (1 - factor) + magnitude * factor;
241
+ this.smoothedBins[i] = Number.isFinite(smoothed) ? smoothed : 0;
242
+ }
243
+ }
244
+
245
+ emitAnalysis() {
246
+ const safe = (v) => (Number.isFinite(v) ? v : 0);
247
+ this.emit('analysis', {
248
+ frequencyBins: this.spectrumEnabled ? [...this.smoothedBins] : [],
249
+ amplitude: safe(this.smoothedAmplitude),
250
+ amplitudeL: safe(this.smoothedAmplitudeL),
251
+ amplitudeR: safe(this.smoothedAmplitudeR),
252
+ sampleRate: this.sampleRate,
253
+ });
254
+ }
255
+
256
+ // Convert a PCM chunk to mono samples in [-1, 1]. Stereo is averaged.
257
+ // Also returns per-channel sums of squares (per-frame, matching the
258
+ // mono samples 1:1) so the VU path needs no second pass.
259
+ readSamples(chunk) {
260
+ const samples = [];
261
+ let sumSqL = 0;
262
+ let sumSqR = 0;
263
+ const acc = (leftSample, rightSample) => {
264
+ const avgSample = (leftSample + rightSample) / 2;
265
+ if (Number.isFinite(avgSample)) {
266
+ samples.push(avgSample);
267
+ sumSqL += leftSample * leftSample;
268
+ sumSqR += rightSample * rightSample;
269
+ }
270
+ };
271
+ if (this.detectedFormat === 'float32') {
272
+ for (let i = 0; i + 8 <= chunk.length; i += 8) {
273
+ acc(chunk.readFloatLE(i), chunk.readFloatLE(i + 4));
274
+ }
275
+ } else {
276
+ for (let i = 0; i + 4 <= chunk.length; i += 4) {
277
+ acc(chunk.readInt16LE(i) / 32768, chunk.readInt16LE(i + 2) / 32768);
278
+ }
279
+ }
280
+ return { samples, sumSqL, sumSqR };
281
+ }
282
+
283
+ calculateAmplitude(samples, dtSec) {
284
+ if (samples.length === 0) return;
285
+
286
+ // Calculate RMS amplitude
287
+ let sum = 0;
288
+ for (const sample of samples) {
289
+ if (Number.isFinite(sample)) {
290
+ sum += sample * sample;
291
+ }
292
+ }
293
+ const rms = Math.sqrt(sum / samples.length);
294
+
295
+ // Scale and clamp amplitude
296
+ const normalizedAmplitude = Math.min(rms * 15, 1);
297
+
298
+ // Smooth the amplitude with the same asymmetric, wall-time
299
+ // normalized ballistics as the bins (analyzeWindow): attack at the
300
+ // configured smoothing, release faster. Waveform and
301
+ // VU render from this envelope, so symmetric smoothing here
302
+ // rounded off transients in those modes.
303
+ const factor =
304
+ normalizedAmplitude > this.smoothedAmplitude
305
+ ? this._ballisticStep(this._attackBase, dtSec)
306
+ : this._ballisticStep(this._releaseBase, dtSec);
307
+ const smoothed =
308
+ this.smoothedAmplitude * (1 - factor) + normalizedAmplitude * factor;
309
+ this.smoothedAmplitude = Number.isFinite(smoothed) ? smoothed : 0;
310
+ }
311
+
312
+ // Per-channel variant of calculateAmplitude: RMS from the caller's
313
+ // sums of squares over `frames` frames, same ballistics but a fixed
314
+ // VU-reference gain (×5 ≈ 0 VU at −16dBFS RMS; the mono envelope's
315
+ // ×15 saturates anything above RMS 0.067 and maxed the meter at
316
+ // moderate levels). No auto-gain: a VU meter is absolute — the
317
+ // renderer reads these envelopes raw. Independent envelopes — a
318
+ // hard-panned source lights one bar while the other falls to zero.
319
+ calculateChannelAmplitudes(sumSqL, sumSqR, frames, dtSec) {
320
+ if (!frames) return;
321
+ const step = (sumSq, current) => {
322
+ const rms = Math.sqrt(sumSq / frames);
323
+ const normalized = Math.min(rms * 5, 1);
324
+ const factor =
325
+ normalized > current
326
+ ? this._ballisticStep(this._attackBase, dtSec)
327
+ : this._ballisticStep(this._releaseBase, dtSec);
328
+ const smoothed = current * (1 - factor) + normalized * factor;
329
+ return Number.isFinite(smoothed) ? smoothed : 0;
330
+ };
331
+ this.smoothedAmplitudeL = step(sumSqL, this.smoothedAmplitudeL);
332
+ this.smoothedAmplitudeR = step(sumSqR, this.smoothedAmplitudeR);
333
+ }
334
+
335
+ reset() {
336
+ this.buffer = [];
337
+ this.smoothedBins = new Array(this.numBins).fill(0);
338
+ this.smoothedAmplitude = 0;
339
+ this.smoothedAmplitudeL = 0;
340
+ this.smoothedAmplitudeR = 0;
341
+ this.detectedFormat = 'int16';
342
+ this.sampleRate = 44100;
343
+ this._lastProcessAt = null;
344
+ this.updateQualitySettings();
345
+ }
346
+ }
347
+
348
+ function makeHann(size) {
349
+ return Array.from(
350
+ { length: size },
351
+ (_, n) => 0.5 * (1 - Math.cos((2 * Math.PI * n) / (size - 1))),
352
+ );
353
+ }
354
+
355
+ function maxAbs(samples) {
356
+ let max = 0;
357
+ for (let i = 0; i < samples.length; i++) {
358
+ const abs = Math.abs(samples[i]);
359
+ if (abs > max) max = abs;
360
+ }
361
+ return max;
362
+ }
@@ -0,0 +1,222 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ import { DBG } from './debug.js';
5
+
6
+ // Output device enumeration (issues/042). The `speaker` backend has no
7
+ // enumeration API, so this shells out to per-platform tools with a timeout.
8
+ // Reality check against speaker's bundled mpg123 output modules (verified in
9
+ // node_modules/speaker/deps/mpg123/src/output at implementation time):
10
+ // - Linux (alsa.c): `snd_pcm_open` receives `ao->device` verbatim — full
11
+ // ALSA device strings work, so this is the only platform where picking a
12
+ // device actually takes effect. Sources: `pactl list sinks` (PulseAudio/
13
+ // PipeWire — mapped to `pulse:<sink-name>` strings) merged with
14
+ // `aplay -l` (`hw:CARD=x,DEV=n` strings), the latter standing in alone
15
+ // on bare-ALSA systems where pactl is absent.
16
+ // - macOS (coreaudio.c): the module never reads `ao->device` — any device
17
+ // string is silently ignored, so `system_profiler SPAudioDataType`
18
+ // listing would only feed a broken picker. Documented default-only
19
+ // instead of shipping one (issues/042 reality check).
20
+ // - Windows (win32.c): matches the device against waveOut `szPname`
21
+ // (31-char truncated) and falls back to WaveMapper (= default) on no
22
+ // match. PowerShell CIM (`Win32_SoundDevice`) exposes PnP hardware
23
+ // names, not szPname, so no speaker-valid string is obtainable without
24
+ // native deps. Documented default-only.
25
+ // Enumeration failure or an empty result is a debug line, never an error.
26
+
27
+ const RUN_TIMEOUT_MS = 3000;
28
+
29
+ const execFileP = promisify(execFile);
30
+ const defaultRun = (cmd, args) =>
31
+ execFileP(cmd, args, { timeout: RUN_TIMEOUT_MS }).then((r) => r.stdout);
32
+
33
+ // Probe runner: unlike the enumeration pass, the probe needs stderr (the
34
+ // discriminator lives there), and forces the C locale so the error text it
35
+ // matches is locale-independent.
36
+ const probeRun = (cmd, args) =>
37
+ execFileP(cmd, args, {
38
+ timeout: RUN_TIMEOUT_MS,
39
+ env: { ...process.env, LC_ALL: 'C', LANG: 'C' },
40
+ });
41
+
42
+ // `pactl list sinks` (long form): the only pactl output that carries the
43
+ // friendly Description next to the technical Name. Each sink block starts
44
+ // at "Sink #<n>" and carries one Name: and one Description: line.
45
+ export function parsePactlSinks(stdout) {
46
+ const devices = [];
47
+ let name = null;
48
+ let description = null;
49
+ const flush = () => {
50
+ if (name !== null) {
51
+ devices.push({ id: `pulse:${name}`, name: description || name });
52
+ }
53
+ name = null;
54
+ description = null;
55
+ };
56
+ for (const line of stdout.split('\n')) {
57
+ if (/^Sink #/.test(line)) {
58
+ flush();
59
+ continue;
60
+ }
61
+ const nameMatch = line.match(/^\s*Name:\s*(.+)$/);
62
+ if (nameMatch && name === null) name = nameMatch[1].trim();
63
+ const descMatch = line.match(/^\s*Description:\s*(.+)$/);
64
+ if (descMatch && description === null) description = descMatch[1].trim();
65
+ }
66
+ flush();
67
+ return devices;
68
+ }
69
+
70
+ // `aplay -l` lines look like:
71
+ // card 0: PCH [HDA Intel PCH], device 0: ALC1220 Analog [ALC1220 Analog]
72
+ // The CARD=…,DEV=… form is used because card short names can contain spaces
73
+ // (which the positional `hw:PCH,0` form would split on).
74
+ const APLAY_LINE =
75
+ /^card (\d+): ([^:]+?) \[(.+?)\], device (\d+): (.+?)(?: \[(.+?)\])?$/;
76
+
77
+ export function parseAplayL(stdout) {
78
+ const devices = [];
79
+ for (const line of stdout.split('\n')) {
80
+ const match = line.match(APLAY_LINE);
81
+ if (!match) continue;
82
+ const [, , cardName, cardDesc, devNum, devName, devDesc] = match;
83
+ devices.push({
84
+ id: `hw:CARD=${cardName.trim()},DEV=${devNum}`,
85
+ name: `${(devDesc || devName).trim()} (${cardDesc.trim()})`,
86
+ });
87
+ }
88
+ return devices;
89
+ }
90
+
91
+ async function linuxDevices(run, probe) {
92
+ const devices = [];
93
+ try {
94
+ devices.push(...parsePactlSinks(await run('pactl', ['list', 'sinks'])));
95
+ } catch {
96
+ // No pactl (bare ALSA) — the aplay pass below stands in.
97
+ }
98
+ try {
99
+ devices.push(...parseAplayL(await run('aplay', ['-l'])));
100
+ } catch {
101
+ // No aplay either — keep whatever pactl produced.
102
+ }
103
+ // issues/047: drop devices the speaker backend cannot open — a broken
104
+ // `pulse:` PCM (missing pulseaudio-alsa) or unplugged hardware would
105
+ // otherwise print raw ALSA errors onto the TUI on every play attempt.
106
+ // Nothing passes (no working audio stack at all): keep the unfiltered
107
+ // list — an unusable picker hides less than an empty one, and the
108
+ // Player's runtime fallback still guards playback.
109
+ const usable = await Promise.all(devices.map((d) => probe(d.id)));
110
+ const passing = devices.filter((_, i) => usable[i]);
111
+ return passing.length ? passing : devices;
112
+ }
113
+
114
+ // One enumeration pass. Never throws: a probe failure and an empty result
115
+ // are debug lines, never errors. `probe` verifies each candidate device the
116
+ // way the speaker backend would open it (issues/047); the default uses a
117
+ // real aplay canary, tests inject a fake.
118
+ async function probe(platform, run, probeDeviceFn) {
119
+ try {
120
+ let devices = [];
121
+ if (platform === 'linux') {
122
+ devices = await linuxDevices(run, probeDeviceFn);
123
+ } else if (platform === 'darwin') {
124
+ DBG(
125
+ 'audio devices: speaker CoreAudio backend ignores device strings — default output only',
126
+ );
127
+ } else if (platform === 'win32') {
128
+ DBG(
129
+ 'audio devices: speaker winmm backend needs waveOut szPname (not enumerable without native deps) — default output only',
130
+ );
131
+ } else {
132
+ DBG(
133
+ `audio devices: no enumeration for platform ${platform} — default output only`,
134
+ );
135
+ }
136
+ if (!devices.length) {
137
+ DBG('audio devices: none detected — default output only');
138
+ }
139
+ return devices;
140
+ } catch (err) {
141
+ DBG(`audio device enumeration failed: ${err?.message ?? err}`);
142
+ return [];
143
+ }
144
+ }
145
+
146
+ // Session cache: device lists are stable within a run, and the settings row
147
+ // reads the cache synchronously for friendly labels.
148
+ let cache = null;
149
+ let cachePromise = null;
150
+
151
+ export function listOutputDevices({
152
+ platform = process.platform,
153
+ run = defaultRun,
154
+ probe: deviceProbe,
155
+ } = {}) {
156
+ const probeDeviceFn = deviceProbe ?? ((id) => probeDevice(id));
157
+ // Custom platform/runner (tests) bypass the cache so injected scenarios
158
+ // never poison it.
159
+ if (platform !== process.platform || run !== defaultRun) {
160
+ return probe(platform, run, probeDeviceFn);
161
+ }
162
+ if (cache) return Promise.resolve(cache);
163
+ cachePromise ??= probe(platform, run, probeDeviceFn).then((devices) => {
164
+ cache = devices;
165
+ return devices;
166
+ });
167
+ return cachePromise;
168
+ }
169
+
170
+ // Device-probe cache: id → boolean. Poisoned at runtime by the Player when
171
+ // the speaker backend itself fails to open an enumerated device
172
+ // (markDeviceBroken).
173
+ const probeCache = new Map();
174
+
175
+ // Open a device the way the speaker backend would — via aplay as an
176
+ // out-of-process canary, because the real open happens inside our process,
177
+ // where ALSA prints open errors straight to the terminal and ruins the TUI
178
+ // (issues/047). /dev/null is never valid WAV data, so aplay always exits
179
+ // nonzero; the discriminator is the failure phase: open-phase errors print
180
+ // "audio open error" (LC_ALL=C), while a device that opened fine fails
181
+ // later with read_header/read error. A missing aplay or a failure with no
182
+ // stderr counts as OK — never block a device on an unobservable probe.
183
+ // Returns true (usable) / false (broken).
184
+ export async function probeDevice(id, { run = probeRun } = {}) {
185
+ if (run === probeRun && probeCache.has(id)) {
186
+ return probeCache.get(id);
187
+ }
188
+ let stderr = '';
189
+ try {
190
+ const result = await run('aplay', ['-D', id, '/dev/null']);
191
+ stderr = result?.stderr ?? '';
192
+ } catch (err) {
193
+ stderr = err?.stderr ?? '';
194
+ }
195
+ const ok = !/audio open error/.test(String(stderr));
196
+ if (!ok) DBG(`audio device probe: ${id} failed: ${String(stderr).trim()}`);
197
+ if (run === probeRun) probeCache.set(id, ok);
198
+ return ok;
199
+ }
200
+
201
+ // Runtime counterpart: the speaker backend failed to open an enumerated
202
+ // device (mid-session unplug, suspended sink). Poison the cache so the
203
+ // next play() resolves to the system default without re-probing.
204
+ export function markDeviceBroken(id) {
205
+ probeCache.set(id, false);
206
+ DBG(`audio device probe: ${id} marked broken (speaker open failure)`);
207
+ }
208
+
209
+ // Clear a poisoned/unusable probe result so the next play() re-probes the
210
+ // device — used when the user re-picks it in settings (a replugged device
211
+ // heals instead of staying broken until restart).
212
+ export function resetDeviceProbe(id) {
213
+ probeCache.delete(id);
214
+ DBG(`audio device probe: ${id} cleared — will re-probe on next play`);
215
+ }
216
+
217
+ // Friendly label for a stored device id; unknown/stale ids (unplugged
218
+ // hardware, cache not yet warmed) fall back to null so callers show the
219
+ // raw stored string.
220
+ export function friendlyDeviceName(id) {
221
+ return cache?.find((d) => d.id === id)?.name ?? null;
222
+ }
@@ -0,0 +1,75 @@
1
+ import { CHARSETS } from '../constants.js';
2
+
3
+ // Quantize color channels to multiples of this to cut distinct colors.
4
+ const COLOR_STEP = 32;
5
+
6
+ function quantize(value) {
7
+ return Math.min(255, Math.round(value / COLOR_STEP) * COLOR_STEP);
8
+ }
9
+
10
+ // ID3 picture mime strings vary by writer (`jpg`, empty, wrong); fall back
11
+ // to a signature check over the raw bytes.
12
+ export function sniffImageMime(bytes) {
13
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
14
+ if (
15
+ b.length >= 4 &&
16
+ b[0] === 0x89 &&
17
+ b[1] === 0x50 &&
18
+ b[2] === 0x4e &&
19
+ b[3] === 0x47
20
+ ) {
21
+ return 'image/png';
22
+ }
23
+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) {
24
+ return 'image/jpeg';
25
+ }
26
+ if (b.length >= 3 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) {
27
+ return 'image/gif';
28
+ }
29
+ if (b.length >= 2 && b[0] === 0x42 && b[1] === 0x4d) {
30
+ return 'image/bmp';
31
+ }
32
+ return 'application/octet-stream';
33
+ }
34
+
35
+ // Aspect in cell space: an image at w:h px laid out on cells whose height
36
+ // is `ratio` × their width is w : h/ratio in cells. There is no universal
37
+ // ratio — the classic 8×16 cell gives 2, JetBrains Mono's natural line box
38
+ // gives ~2.2, and terminal line spacing pushes it further — so the ratio
39
+ // comes from the engine's `measureCell()` (see the controller; 2 is the
40
+ // fallback for a terminal that never answers the cell-size query).
41
+ export function cellAspect(width, height, ratio = 2) {
42
+ return { width: width, height: height / ratio };
43
+ }
44
+
45
+ // Map one-pixel-per-cell RGBA pixels (the caller drew the bitmap into a
46
+ // cols x rows 2d canvas — drawImage averages what each pixel covers) to
47
+ // charset cells. Returns rows of {ch, color} cells — color is a CSS rgb()
48
+ // string or null for transparent space.
49
+ export function sampleCells(imageData, charset = 'complex') {
50
+ const chars = CHARSETS[charset] || CHARSETS.complex;
51
+ const { width, height, data } = imageData;
52
+ const grid = [];
53
+
54
+ for (let y = 0; y < height; y++) {
55
+ const row = [];
56
+ for (let x = 0; x < width; x++) {
57
+ const i = (y * width + x) * 4;
58
+ if (data[i + 3] < 128) {
59
+ row.push({ ch: ' ', color: null });
60
+ continue;
61
+ }
62
+ const r = data[i];
63
+ const g = data[i + 1];
64
+ const b = data[i + 2];
65
+ const lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
66
+ row.push({
67
+ ch: chars[Math.round(lum * (chars.length - 1))],
68
+ color: `rgb(${quantize(r)},${quantize(g)},${quantize(b)})`,
69
+ });
70
+ }
71
+ grid.push(row);
72
+ }
73
+
74
+ return grid;
75
+ }
@@ -0,0 +1,7 @@
1
+ import { appendFileSync } from 'node:fs';
2
+
3
+ export const DBG = (msg) => {
4
+ if (process.env.MIXSHELL_DEBUG_FILE) {
5
+ appendFileSync(process.env.MIXSHELL_DEBUG_FILE, `${Date.now()} ${msg}\n`);
6
+ }
7
+ };