dsh-apk-vm 0.12.0 → 0.12.2

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.
package/lib/media.js ADDED
@@ -0,0 +1,820 @@
1
+ // lib/media.js
2
+ //
3
+ // Pure, dependency-free configuration/launch layer for the APK VM panel's
4
+ // virtual camera and virtual microphone controls.
5
+ //
6
+ // Design notes
7
+ // ------------
8
+ // * Everything here is data-in/data-out, so HTTP routes and the panel can
9
+ // validate configuration without touching a device. Invalid input throws an
10
+ // Error with an actionable message (same convention as
11
+ // normalizeRemoteProfile() in lib/remote.js).
12
+ // * The emulator has no "file as camera" mode. Custom camera content is only
13
+ // possible through the emulator's 3D virtual scene: a PNG/JPEG poster passed
14
+ // as `-virtualscene-poster <name>=<file>` is rendered by the emulator itself,
15
+ // works headless (Windows/Linux/macOS) and needs no host camera. Host webcams
16
+ // (`webcamN`) require a real host camera or a virtual camera device such as
17
+ // OBS Virtual Camera; they never work on a headless server.
18
+ // * Microphone input: `-allow-host-audio` lets the host's audio INPUT reach the
19
+ // guest (otherwise the emulator zeroes input), and `-no-audio` must be
20
+ // omitted for audio to work at all. For a "file microphone" on a Linux host,
21
+ // PulseAudio `module-pipe-source` plus an ffmpeg loop exposes any
22
+ // wav/mp3/ogg file as a microphone. The command builders below only RETURN
23
+ // shell strings; they never execute anything.
24
+ //
25
+ // Typical local wiring (Lead-owned route code):
26
+ // const media = mediaLaunchOptions({ camera, mic });
27
+ // new AndroidVm({
28
+ // ...opts,
29
+ // extraEmulatorArgs: media.extraEmulatorArgs,
30
+ // enableAudio: media.enableAudio,
31
+ // });
32
+ //
33
+ // Typical remote wiring (Lead-owned SSH code):
34
+ // const paths = remoteMediaPaths(stateDir);
35
+ // // 1. upload the poster with scp to: remotePosterPath(stateDir, poster.name)
36
+ // // 2. start a file microphone (Linux remote host, no sudo required):
37
+ // const start = buildPulseMicStartCommand({
38
+ // sourceName: paths.micSourceName,
39
+ // fifoPath: paths.fifoPath,
40
+ // pidFile: paths.pidFile,
41
+ // audioFilePath: remoteAudioPath(stateDir, 'voice.wav'),
42
+ // rate: 48000,
43
+ // channels: 1,
44
+ // });
45
+ // // 3. run the remote emulator with media.extraEmulatorArgs / enableAudio.
46
+ // // 4. stop with buildPulseMicStopCommand(...), inspect with
47
+ // // buildPulseMicStatusCommand(...).
48
+ //
49
+ // All remote helper paths live under /tmp/apk-vm-media/<sanitized stateDir> so
50
+ // they are stable across runs and never collide between VM instances.
51
+
52
+ import { promises as fsp } from 'node:fs';
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // Constants
56
+ // ---------------------------------------------------------------------------
57
+
58
+ /** Camera modes accepted by `-camera-back` / `-camera-front` (webcamN is extra). */
59
+ export const CAMERA_MODES = Object.freeze(['none', 'emulated', 'virtualscene']);
60
+ /** Highest supported host webcam index (emulator supports webcam0..webcam7). */
61
+ export const MAX_WEBCAM_INDEX = 7;
62
+ /** Maximum number of virtual-scene posters per camera configuration. */
63
+ export const MAX_POSTERS = 8;
64
+ /** Maximum accepted poster file size (the emulator decodes it at startup). */
65
+ export const MAX_POSTER_BYTES = 20 * 1024 * 1024;
66
+
67
+ /** Microphone modes: off (no input), host (host audio input), file (Linux loop). */
68
+ export const MIC_MODES = Object.freeze(['off', 'host', 'file']);
69
+ /** Emulator `-audio <backend>` values. Validated cross-platform on purpose:
70
+ * a panel running on Windows may configure a Linux emulator on a remote host. */
71
+ export const MIC_AUDIO_BACKENDS = Object.freeze(['none', 'pa', 'alsa', 'sdl', 'winmm', 'dsound']);
72
+ /** Sample rates a virtual microphone can be declared with. */
73
+ export const MIC_RATES = Object.freeze([8000, 16000, 44100, 48000]);
74
+ /** Remote media root (Linux host; the Lead uploads files there over SSH). */
75
+ export const REMOTE_MEDIA_ROOT = '/tmp/apk-vm-media';
76
+
77
+ const POSTER_NAME_RE = /^[A-Za-z0-9_-]{1,32}$/;
78
+ const WEBCAM_MODE_RE = /^webcam([0-7])$/;
79
+ const PULSE_SOURCE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
80
+ const AUDIO_FILE_EXT_RE = /\.(wav|mp3|ogg)$/i;
81
+ const MAX_PATH_LENGTH = 1000;
82
+ const MAX_FILE_NAME_LENGTH = 128;
83
+
84
+ // ---------------------------------------------------------------------------
85
+ // Small shared validation helpers
86
+ // ---------------------------------------------------------------------------
87
+
88
+ function asPlainObject(value, label) {
89
+ if (value === undefined || value === null || value === '') return {};
90
+ if (typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);
91
+ return value;
92
+ }
93
+
94
+ function trimmedString(value) {
95
+ return typeof value === 'string' ? value.trim() : '';
96
+ }
97
+
98
+ function jsonish(value) {
99
+ const text = typeof value === 'string' ? value : String(value == null ? '' : value);
100
+ return JSON.stringify(text.length > 80 ? `${text.slice(0, 80)}...` : text);
101
+ }
102
+
103
+ function assertFilePathValue(value, label) {
104
+ const text = trimmedString(value);
105
+ if (!text) throw new Error(`${label} is required`);
106
+ if (text.length > MAX_PATH_LENGTH) throw new Error(`${label} is longer than ${MAX_PATH_LENGTH} characters`);
107
+ if (/[\u0000-\u001f\u007f]/.test(text)) throw new Error(`${label} contains control characters`);
108
+ return text;
109
+ }
110
+
111
+ function assertPosterFilePath(value, label) {
112
+ const text = assertFilePathValue(value, label);
113
+ // `-virtualscene-poster` uses `name=file`; an unbracketed `=` in the path is
114
+ // ambiguous for the emulator's own parser, so reject it early.
115
+ if (text.includes('=')) throw new Error(`${label} must not contain "=" (part of the -virtualscene-poster name=file syntax)`);
116
+ return text;
117
+ }
118
+
119
+ function assertPosterName(value, label = 'poster name') {
120
+ const text = trimmedString(value);
121
+ if (!text) throw new Error(`${label} is required`);
122
+ if (!POSTER_NAME_RE.test(text)) throw new Error(`${label} must match [A-Za-z0-9_-]{1,32}`);
123
+ return text;
124
+ }
125
+
126
+ function assertAbsolutePosixPath(value, label) {
127
+ const text = assertFilePathValue(value, label);
128
+ if (!text.startsWith('/')) {
129
+ throw new Error(`${label} must be an absolute POSIX path on the remote Linux host`);
130
+ }
131
+ return text;
132
+ }
133
+
134
+ function optionalAbsolutePosixPath(value, label) {
135
+ if (value === undefined || value === null || value === '') return null;
136
+ return assertAbsolutePosixPath(value, label);
137
+ }
138
+
139
+ function posixDirname(filePath) {
140
+ const index = filePath.lastIndexOf('/');
141
+ if (index <= 0) return '/';
142
+ return filePath.slice(0, index);
143
+ }
144
+
145
+ function assertPulseSourceName(value) {
146
+ const text = trimmedString(value);
147
+ if (!text) throw new Error('mic sourceName is required');
148
+ if (!PULSE_SOURCE_NAME_RE.test(text)) {
149
+ throw new Error('mic sourceName must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}');
150
+ }
151
+ return text;
152
+ }
153
+
154
+ function normalizeMicRate(value) {
155
+ const number = typeof value === 'number' ? value : Number(trimmedString(value));
156
+ if (!MIC_RATES.includes(number)) {
157
+ throw new Error(`mic.rate must be one of ${MIC_RATES.join(', ')} (got ${jsonish(value)})`);
158
+ }
159
+ return number;
160
+ }
161
+
162
+ function normalizeMicChannels(value) {
163
+ const number = typeof value === 'number' ? value : Number(trimmedString(value));
164
+ if (!Number.isInteger(number) || number < 1 || number > 2) {
165
+ throw new Error(`mic.channels must be 1 or 2 (got ${jsonish(value)})`);
166
+ }
167
+ return number;
168
+ }
169
+
170
+ function normalizePlatform(value) {
171
+ const text = trimmedString(value).toLowerCase();
172
+ return text || process.platform;
173
+ }
174
+
175
+ function uniqueStrings(values) {
176
+ const seen = new Set();
177
+ const result = [];
178
+ for (const value of values) {
179
+ if (seen.has(value)) continue;
180
+ seen.add(value);
181
+ result.push(value);
182
+ }
183
+ return result;
184
+ }
185
+
186
+ function assertDistinctPaths(entries) {
187
+ const seen = new Map();
188
+ for (const [label, value] of entries) {
189
+ if (!value) continue;
190
+ if (seen.has(value)) throw new Error(`${label} must differ from ${seen.get(value)}`);
191
+ seen.set(value, label);
192
+ }
193
+ }
194
+
195
+ // ---------------------------------------------------------------------------
196
+ // Camera configuration
197
+ // ---------------------------------------------------------------------------
198
+
199
+ function normalizeCameraMode(value, label) {
200
+ if (value === undefined || value === null || value === '') return null;
201
+ if (typeof value !== 'string') throw new Error(`${label} must be a string`);
202
+ const text = value.trim().toLowerCase();
203
+ if (!text) return null;
204
+ if (CAMERA_MODES.includes(text)) return text;
205
+ if (WEBCAM_MODE_RE.test(text)) return text;
206
+ throw new Error(
207
+ `${label} must be one of none, emulated, virtualscene, webcam0..webcam7 (got ${jsonish(text)})`,
208
+ );
209
+ }
210
+
211
+ /**
212
+ * Normalize/validate a camera configuration (throws on invalid input).
213
+ *
214
+ * Input shape: `{ back?, front?, posters? }` where posters are
215
+ * `{ name, path }` entries. Missing/empty back/front mean "leave the emulator
216
+ * default in place" (no flag is emitted). The returned object is idempotent:
217
+ * passing it back in yields the same result.
218
+ *
219
+ * @returns {{back: string|null, front: string|null, posters: {name: string, path: string}[]}}
220
+ */
221
+ export function normalizeCameraConfig(input = {}) {
222
+ const source = asPlainObject(input, 'camera config');
223
+ const posters = source.posters === undefined || source.posters === null ? [] : source.posters;
224
+ if (!Array.isArray(posters)) throw new Error('camera.posters must be an array');
225
+ if (posters.length > MAX_POSTERS) throw new Error(`camera.posters supports at most ${MAX_POSTERS} entries`);
226
+
227
+ const camera = {
228
+ back: normalizeCameraMode(source.back, 'camera.back'),
229
+ front: normalizeCameraMode(source.front, 'camera.front'),
230
+ posters: [],
231
+ };
232
+ const seenNames = new Set();
233
+ for (let index = 0; index < posters.length; index += 1) {
234
+ const entry = posters[index];
235
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
236
+ throw new Error(`camera.posters[${index}] must be an object with {name, path}`);
237
+ }
238
+ const name = assertPosterName(entry.name, `camera.posters[${index}].name`);
239
+ const key = name.toLowerCase();
240
+ if (seenNames.has(key)) throw new Error(`duplicate poster name: ${jsonish(name)}`);
241
+ seenNames.add(key);
242
+ camera.posters.push({
243
+ name,
244
+ path: assertPosterFilePath(entry.path, `camera.posters[${index}].path`),
245
+ });
246
+ }
247
+ return camera;
248
+ }
249
+
250
+ // ---------------------------------------------------------------------------
251
+ // Poster file validation
252
+ // ---------------------------------------------------------------------------
253
+
254
+ /**
255
+ * Sniff an image format from its leading bytes.
256
+ * @param {Buffer|Uint8Array} bytes
257
+ * @returns {'png'|'jpeg'|null}
258
+ */
259
+ export function sniffImageFormat(bytes) {
260
+ if (!bytes || typeof bytes.length !== 'number' || bytes.length < 4) return null;
261
+ const pngSignature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
262
+ if (bytes.length >= pngSignature.length && pngSignature.every((byte, index) => bytes[index] === byte)) {
263
+ return 'png';
264
+ }
265
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'jpeg';
266
+ return null;
267
+ }
268
+
269
+ /**
270
+ * Validate a *local* poster file that is about to be uploaded to a remote host
271
+ * (or used by a local emulator): exists, is a regular file, size is sane, and
272
+ * the leading bytes are a PNG or JPEG signature.
273
+ *
274
+ * Filesystem and format problems are returned as `{ok:false, reason}`; only a
275
+ * structurally invalid path argument throws. `options.stat` / `options.readFile`
276
+ * can be injected for tests.
277
+ *
278
+ * @returns {Promise<{ok: true, path: string, format: 'png'|'jpeg', size: number}
279
+ * | {ok: false, path: string, reason: string, size?: number}>}
280
+ */
281
+ export async function checkPosterFile(filePath, options = {}) {
282
+ const opts = options && typeof options === 'object' ? options : {};
283
+ const target = assertFilePathValue(filePath, 'poster path');
284
+ const maxBytes = Number.isFinite(opts.maxBytes) && opts.maxBytes > 0 ? opts.maxBytes : MAX_POSTER_BYTES;
285
+ const stat = typeof opts.stat === 'function' ? opts.stat : fsp.stat;
286
+ const readFile = typeof opts.readFile === 'function' ? opts.readFile : fsp.readFile;
287
+
288
+ let stats;
289
+ try {
290
+ stats = await stat(target);
291
+ } catch (error) {
292
+ return { ok: false, path: target, reason: `poster file is not readable (${(error && error.code) || 'error'})` };
293
+ }
294
+ if (!stats || typeof stats.isFile !== 'function' || !stats.isFile()) {
295
+ return { ok: false, path: target, reason: 'poster path is not a regular file' };
296
+ }
297
+ if (!Number.isFinite(stats.size) || stats.size <= 0) {
298
+ return { ok: false, path: target, reason: 'poster file is empty' };
299
+ }
300
+ if (stats.size > maxBytes) {
301
+ return { ok: false, path: target, size: stats.size, reason: `poster file is larger than ${maxBytes} bytes` };
302
+ }
303
+ let bytes;
304
+ try {
305
+ bytes = await readFile(target);
306
+ } catch (error) {
307
+ return { ok: false, path: target, reason: `poster file is not readable (${(error && error.code) || 'error'})` };
308
+ }
309
+ const format = sniffImageFormat(bytes);
310
+ if (!format) {
311
+ return { ok: false, path: target, size: stats.size, reason: 'not a PNG or JPEG image (magic bytes mismatch)' };
312
+ }
313
+ return { ok: true, path: target, format, size: stats.size };
314
+ }
315
+
316
+ // ---------------------------------------------------------------------------
317
+ // Microphone configuration
318
+ // ---------------------------------------------------------------------------
319
+
320
+ /**
321
+ * Normalize/validate a microphone configuration (throws on invalid input).
322
+ *
323
+ * Input shape: `{mode: 'off'|'host'|'file', filePath?, backend?, channels?, rate?}`.
324
+ * Defaults: mode 'off', channels 1, rate 48000, backend unset (emulator's
325
+ * platform default). `filePath` is required in file mode and rejected in every
326
+ * other mode (a stale path is a configuration bug, not something to silently
327
+ * ignore).
328
+ *
329
+ * @returns {{mode: 'off'|'host'|'file', filePath: string|undefined,
330
+ * backend: string|undefined, channels: number, rate: number}}
331
+ */
332
+ export function normalizeMicConfig(input = {}) {
333
+ const source = asPlainObject(input, 'mic config');
334
+ const rawMode = trimmedString(source.mode).toLowerCase();
335
+ const mode = rawMode || 'off';
336
+ if (!MIC_MODES.includes(mode)) {
337
+ throw new Error(`mic.mode must be one of ${MIC_MODES.join(', ')} (got ${jsonish(mode)})`);
338
+ }
339
+
340
+ const channels = normalizeMicChannels(source.channels === undefined ? 1 : source.channels);
341
+ const rate = normalizeMicRate(source.rate === undefined ? 48000 : source.rate);
342
+
343
+ let backend;
344
+ if (source.backend !== undefined && source.backend !== null && source.backend !== '') {
345
+ const text = trimmedString(source.backend).toLowerCase();
346
+ if (!MIC_AUDIO_BACKENDS.includes(text)) {
347
+ throw new Error(`mic.backend must be one of ${MIC_AUDIO_BACKENDS.join(', ')} (got ${jsonish(text)})`);
348
+ }
349
+ backend = text;
350
+ }
351
+
352
+ let filePath;
353
+ if (mode === 'file') {
354
+ if (source.filePath === undefined || source.filePath === null || trimmedString(source.filePath) === '') {
355
+ throw new Error('mic.filePath is required when mic.mode is "file"');
356
+ }
357
+ filePath = assertFilePathValue(source.filePath, 'mic.filePath');
358
+ if (!AUDIO_FILE_EXT_RE.test(filePath)) {
359
+ throw new Error('mic.filePath must be a .wav, .mp3 or .ogg file');
360
+ }
361
+ } else if (source.filePath !== undefined && source.filePath !== null && trimmedString(source.filePath) !== '') {
362
+ throw new Error(`mic.filePath is only valid when mic.mode is "file" (mode is ${jsonish(mode)})`);
363
+ }
364
+
365
+ return { mode, filePath, backend, channels, rate };
366
+ }
367
+
368
+ // ---------------------------------------------------------------------------
369
+ // Emulator argv + launch options
370
+ // ---------------------------------------------------------------------------
371
+
372
+ function normalizeMediaConfigInput(config) {
373
+ if (config === undefined || config === null || config === '') return { camera: null, mic: null };
374
+ if (typeof config !== 'object' || Array.isArray(config)) {
375
+ throw new Error('media config must be an object with optional {camera, mic}');
376
+ }
377
+ return {
378
+ camera: config.camera === undefined || config.camera === null || config.camera === '' ? null : normalizeCameraConfig(config.camera),
379
+ mic: config.mic === undefined || config.mic === null || config.mic === '' ? null : normalizeMicConfig(config.mic),
380
+ };
381
+ }
382
+
383
+ function mediaArgsFromNormalized({ camera, mic }) {
384
+ const args = [];
385
+ if (camera) {
386
+ if (camera.back) args.push('-camera-back', camera.back);
387
+ if (camera.front) args.push('-camera-front', camera.front);
388
+ for (const poster of camera.posters) {
389
+ args.push('-virtualscene-poster', `${poster.name}=${poster.path}`);
390
+ }
391
+ }
392
+ if (mic && mic.mode !== 'off') {
393
+ // Required for host audio INPUT; without it the guest receives zeros.
394
+ args.push('-allow-host-audio');
395
+ if (mic.backend) args.push('-audio', mic.backend);
396
+ }
397
+ return args;
398
+ }
399
+
400
+ /**
401
+ * Compose the extra emulator argv for the configured virtual camera / mic.
402
+ *
403
+ * Deterministic order: `-camera-back`, `-camera-front`, one
404
+ * `-virtualscene-poster <name>=<path>` per poster, then mic flags
405
+ * (`-allow-host-audio` and, when configured, `-audio <backend>`).
406
+ *
407
+ * `-no-audio` is deliberately NOT emitted here: the launcher decides that via
408
+ * `enableAudio` (see mediaLaunchOptions()).
409
+ *
410
+ * @param {{camera?: object|string|null, mic?: object|string|null}} config raw or
411
+ * already-normalized config; `{}`/null yields `[]`.
412
+ * @returns {string[]}
413
+ */
414
+ export function buildEmulatorMediaArgs(config = {}) {
415
+ return mediaArgsFromNormalized(normalizeMediaConfigInput(config));
416
+ }
417
+
418
+ /**
419
+ * One-call helper for the launcher: returns both the extra argv for the
420
+ * emulator and whether audio must be enabled (`-no-audio` omitted).
421
+ *
422
+ * `enableAudio` is true exactly when a microphone is configured
423
+ * (mic.mode !== 'off'), matching the Lead's integration contract.
424
+ *
425
+ * @param {{camera?: object, mic?: object}} config
426
+ * @returns {{extraEmulatorArgs: string[], enableAudio: boolean}}
427
+ */
428
+ export function mediaLaunchOptions(config = {}) {
429
+ const normalized = normalizeMediaConfigInput(config);
430
+ return {
431
+ extraEmulatorArgs: mediaArgsFromNormalized(normalized),
432
+ enableAudio: Boolean(normalized.mic && normalized.mic.mode !== 'off'),
433
+ };
434
+ }
435
+
436
+ // ---------------------------------------------------------------------------
437
+ // Capability reporting (pure parsers; no device probing here)
438
+ // ---------------------------------------------------------------------------
439
+
440
+ /**
441
+ * Parse `emulator -webcam-list` output.
442
+ *
443
+ * Accepted shapes (the emulator has used both over the years):
444
+ * List of web cameras connected to the computer:
445
+ * Camera `webcam0` is connected to device `AndroidEmulatorVC0` on channel 0 using pixel format `BGR4`
446
+ * Camera `Integrated Camera` is connected to device `webcam0` on channel 1 using pixel format `MJPEG`
447
+ *
448
+ * @param {string} text
449
+ * @returns {{index: number, name: string}[]} sorted by index
450
+ */
451
+ export function parseWebcamList(text) {
452
+ if (typeof text !== 'string' || !text.trim()) return [];
453
+ const cameras = new Map();
454
+ const pattern = /camera\s+(?:`([^`]+)`|"([^"]+)"|'([^']+)'|([^\s]+))\s+is\s+connected\s+to\s+device\s+(?:`([^`]+)`|"([^"]+)"|'([^']+)'|([^\s]+))/i;
455
+ for (const line of text.split(/\r?\n/)) {
456
+ if (!line.trim()) continue;
457
+ const match = pattern.exec(line);
458
+ if (!match) continue;
459
+ const cameraLabel = (match[1] || match[2] || match[3] || match[4] || '').trim();
460
+ const device = (match[5] || match[6] || match[7] || match[8] || '').trim();
461
+ const deviceIndex = /^webcam(\d+)$/i.exec(device);
462
+ const labelIndex = /webcam(\d+)/i.exec(cameraLabel);
463
+ const rawIndex = deviceIndex ? deviceIndex[1] : labelIndex ? labelIndex[1] : null;
464
+ if (rawIndex === null) continue;
465
+ const index = Number(rawIndex);
466
+ if (!Number.isInteger(index) || index < 0 || index > MAX_WEBCAM_INDEX || cameras.has(index)) continue;
467
+ cameras.set(index, { index, name: cameraLabel || `webcam${index}` });
468
+ }
469
+ return [...cameras.values()].sort((left, right) => left.index - right.index);
470
+ }
471
+
472
+ /**
473
+ * Describe camera capabilities for a target platform.
474
+ *
475
+ * `virtualscene` works headless and is the recommended custom-content path;
476
+ * `webcamN` entries are added only when `emulator -webcam-list` reported them.
477
+ *
478
+ * @param {{platform?: string, webcamListText?: string}} input
479
+ * @returns {{platform: string, webcams: {index: number, name: string}[],
480
+ * modes: string[], note: string}}
481
+ */
482
+ export function cameraCapabilities(input = {}) {
483
+ const opts = input && typeof input === 'object' ? input : {};
484
+ const platform = normalizePlatform(opts.platform);
485
+ const webcams = parseWebcamList(opts.webcamListText);
486
+ const modes = [...CAMERA_MODES, ...webcams.map((camera) => `webcam${camera.index}`)];
487
+ const notes = [
488
+ 'Virtual-scene posters (-virtualscene-poster) are rendered by the emulator itself, so they work headless and need no host camera.',
489
+ 'webcamN modes require a real host camera, or a virtual camera device (for example OBS Virtual Camera) that the emulator can see.',
490
+ ];
491
+ notes.push(
492
+ webcams.length
493
+ ? `${webcams.length} host camera(s) detected via emulator -webcam-list.`
494
+ : 'No host cameras were reported by emulator -webcam-list; use virtualscene posters for custom camera content.',
495
+ );
496
+ return { platform, webcams, modes, note: notes.join(' ') };
497
+ }
498
+
499
+ function micBackendChoices(platform) {
500
+ switch (platform) {
501
+ case 'win32':
502
+ return ['none', 'sdl', 'winmm', 'dsound'];
503
+ case 'linux':
504
+ return ['none', 'pa', 'alsa', 'sdl'];
505
+ case 'darwin':
506
+ return ['none', 'sdl'];
507
+ default:
508
+ return ['none', 'sdl'];
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Describe microphone capabilities for a target platform.
514
+ *
515
+ * @param {{platform?: string, remote?: boolean}} input `remote:true` means the
516
+ * emulator runs on a remote Linux host reached over SSH.
517
+ * @returns {{platform: string, hostPassthrough: true, fileLoop: boolean,
518
+ * backendChoices: string[], note: string}}
519
+ */
520
+ export function micCapabilities(input = {}) {
521
+ const opts = input && typeof input === 'object' ? input : {};
522
+ const platform = normalizePlatform(opts.platform);
523
+ const remote = opts.remote === true;
524
+ const fileLoop = platform === 'linux' || remote;
525
+ const notes = [
526
+ 'Host audio input requires -allow-host-audio plus a microphone on the machine that runs the emulator; otherwise audio input is zeroed.',
527
+ '-no-audio must be omitted for any audio input (pass the enableAudio launch option).',
528
+ ];
529
+ notes.push(
530
+ fileLoop
531
+ ? 'File-loop microphones need a Linux host with PulseAudio (pactl) and ffmpeg; module-pipe-source needs no sudo and is created with buildPulseMicStartCommand().'
532
+ : 'File-loop microphones are only supported on a Linux host (including a remote Linux host over SSH); use mode "host" on this platform.',
533
+ );
534
+ return {
535
+ platform,
536
+ hostPassthrough: true,
537
+ fileLoop,
538
+ backendChoices: micBackendChoices(platform),
539
+ note: notes.join(' '),
540
+ };
541
+ }
542
+
543
+ // ---------------------------------------------------------------------------
544
+ // POSIX shell quoting + PulseAudio virtual microphone commands
545
+ // ---------------------------------------------------------------------------
546
+
547
+ /**
548
+ * Quote one argument for a POSIX `sh` command line using single quotes.
549
+ * Embedded single quotes become `'\''`, so no input can break out of the
550
+ * quoted string. Control characters are rejected.
551
+ *
552
+ * @param {unknown} value
553
+ * @param {string} [label]
554
+ * @returns {string}
555
+ */
556
+ export function quotePosix(value, label = 'command argument') {
557
+ const text = value === undefined || value === null ? '' : String(value);
558
+ if (!text) throw new Error(`${label} is empty`);
559
+ if (/[\u0000-\u001f\u007f]/.test(text)) throw new Error(`${label} contains control characters`);
560
+ return `'${text.replace(/'/g, `'\\''`)}'`;
561
+ }
562
+
563
+ /** Build the `pactl ... | grep -F ... | cut -f1` lookup shared by the builders. */
564
+ function unloadBySourceExpr(sourceName) {
565
+ const rawSourceArg = `source_name=${sourceName}`;
566
+ return (
567
+ `_apkvm_idx=$(pactl list short modules 2>/dev/null | grep -F ${quotePosix(rawSourceArg)} | cut -f1 | head -n 1); ` +
568
+ 'if [ -n "$_apkvm_idx" ]; then pactl unload-module "$_apkvm_idx" >/dev/null 2>&1 || true; fi'
569
+ );
570
+ }
571
+
572
+ /**
573
+ * Build the shell command that starts a *file-backed* PulseAudio microphone:
574
+ *
575
+ * 1. mkdir -p the FIFO/pid/log directories (best effort),
576
+ * 2. clean up a previous instance (kill pid, unload old pipe-source),
577
+ * 3. `mkfifo`, then loop the audio file through ffmpeg into the FIFO as raw
578
+ * s16le at the configured rate/channels (PID recorded in the pid file),
579
+ * 4. wait briefly, then `pactl load-module module-pipe-source` pointing at the
580
+ * FIFO so the guest sees a microphone.
581
+ *
582
+ * The command is a single line and never executed here; run it over SSH on the
583
+ * Linux host (see lib/remote.js runSshCommand). Requires ffmpeg + pactl on the
584
+ * remote host. No sudo is needed for module-pipe-source.
585
+ *
586
+ * @param {{sourceName: string, fifoPath: string, pidFile: string,
587
+ * audioFilePath: string, rate?: number, channels?: number, logFile?: string}} options
588
+ * @returns {string}
589
+ */
590
+ export function buildPulseMicStartCommand(options = {}) {
591
+ const opts = options && typeof options === 'object' ? options : {};
592
+ const sourceName = assertPulseSourceName(opts.sourceName);
593
+ const fifoPath = assertAbsolutePosixPath(opts.fifoPath, 'mic FIFO path');
594
+ const pidFile = assertAbsolutePosixPath(opts.pidFile, 'mic pid file path');
595
+ const audioFilePath = assertAbsolutePosixPath(opts.audioFilePath, 'mic audio file path');
596
+ const rate = opts.rate === undefined ? 48000 : normalizeMicRate(opts.rate);
597
+ const channels = opts.channels === undefined ? 1 : normalizeMicChannels(opts.channels);
598
+ const logFile =
599
+ opts.logFile === undefined || opts.logFile === ''
600
+ ? `${fifoPath}.ffmpeg.log`
601
+ : assertAbsolutePosixPath(opts.logFile, 'mic ffmpeg log path');
602
+ assertDistinctPaths([
603
+ ['mic FIFO path', fifoPath],
604
+ ['mic pid file path', pidFile],
605
+ ['mic audio file path', audioFilePath],
606
+ ['mic ffmpeg log path', logFile],
607
+ ]);
608
+
609
+ const quotedFifo = quotePosix(fifoPath);
610
+ const quotedPid = quotePosix(pidFile);
611
+ const quotedAudio = quotePosix(audioFilePath);
612
+ const quotedLog = quotePosix(logFile);
613
+ const directories = uniqueStrings([posixDirname(fifoPath), posixDirname(pidFile), posixDirname(logFile)]);
614
+
615
+ const statements = [
616
+ 'set -u',
617
+ `mkdir -p -- ${directories.map((directory) => quotePosix(directory)).join(' ')}`,
618
+ `if [ -f ${quotedPid} ]; then kill "$(cat ${quotedPid})" 2>/dev/null || true; rm -f ${quotedPid}; fi`,
619
+ unloadBySourceExpr(sourceName),
620
+ `rm -f ${quotedFifo}`,
621
+ `mkfifo ${quotedFifo} || exit 1`,
622
+ `chmod 600 ${quotedFifo} || true`,
623
+ `ffmpeg -nostdin -hide_banner -loglevel error -re -stream_loop -1 -i ${quotedAudio}` +
624
+ ` -f s16le -ar ${rate} -ac ${channels} - > ${quotedFifo} 2> ${quotedLog} & echo $! > ${quotedPid}`,
625
+ 'sleep 1',
626
+ `pactl load-module module-pipe-source ${quotePosix(`source_name=${sourceName}`)}` +
627
+ ` ${quotePosix(`file=${fifoPath}`)} ${quotePosix('format=s16le')}` +
628
+ ` ${quotePosix(`rate=${rate}`)} ${quotePosix(`channels=${channels}`)}`,
629
+ ];
630
+ return statements.join('; ');
631
+ }
632
+
633
+ /**
634
+ * Build the shell command that stops a file-backed PulseAudio microphone:
635
+ * kills the ffmpeg loop (TERM then KILL), removes the pid file and FIFO, and
636
+ * unloads the matching module-pipe-source by module index (best effort).
637
+ *
638
+ * `pidFile` / `fifoPath` are optional — when omitted, only the PulseAudio
639
+ * module is unloaded by source name.
640
+ *
641
+ * @param {{sourceName: string, pidFile?: string, fifoPath?: string}} options
642
+ * @returns {string}
643
+ */
644
+ export function buildPulseMicStopCommand(options = {}) {
645
+ const opts = options && typeof options === 'object' ? options : {};
646
+ const sourceName = assertPulseSourceName(opts.sourceName);
647
+ const pidFile = optionalAbsolutePosixPath(opts.pidFile, 'mic pid file path');
648
+ const fifoPath = optionalAbsolutePosixPath(opts.fifoPath, 'mic FIFO path');
649
+ assertDistinctPaths([
650
+ ['mic pid file path', pidFile],
651
+ ['mic FIFO path', fifoPath],
652
+ ]);
653
+
654
+ const statements = ['set -u'];
655
+ if (pidFile) {
656
+ const quotedPid = quotePosix(pidFile);
657
+ statements.push(
658
+ `if [ -f ${quotedPid} ]; then kill "$(cat ${quotedPid})" 2>/dev/null || true; sleep 1;` +
659
+ ` kill -9 "$(cat ${quotedPid})" 2>/dev/null || true; rm -f ${quotedPid}; fi`,
660
+ );
661
+ }
662
+ if (fifoPath) statements.push(`rm -f ${quotePosix(fifoPath)}`);
663
+ statements.push(unloadBySourceExpr(sourceName));
664
+ statements.push('true');
665
+ return statements.join('; ');
666
+ }
667
+
668
+ /**
669
+ * Build the shell command that reports virtual-microphone status: matching
670
+ * `pactl list short sources` line, ffmpeg pid state and FIFO presence.
671
+ *
672
+ * @param {{sourceName: string, pidFile?: string, fifoPath?: string}} options
673
+ * @returns {string}
674
+ */
675
+ export function buildPulseMicStatusCommand(options = {}) {
676
+ const opts = options && typeof options === 'object' ? options : {};
677
+ const sourceName = assertPulseSourceName(opts.sourceName);
678
+ const pidFile = optionalAbsolutePosixPath(opts.pidFile, 'mic pid file path');
679
+ const fifoPath = optionalAbsolutePosixPath(opts.fifoPath, 'mic FIFO path');
680
+
681
+ const statements = [
682
+ 'set -u',
683
+ `printf 'source: '; pactl list short sources 2>/dev/null | grep -F ${quotePosix(sourceName)} || echo '(not found)'`,
684
+ ];
685
+ if (pidFile) {
686
+ const quotedPid = quotePosix(pidFile);
687
+ statements.push(
688
+ `printf 'pidfile: '; if [ -f ${quotedPid} ]; then cat ${quotedPid};` +
689
+ ` kill -0 "$(cat ${quotedPid})" 2>/dev/null && echo ' (running)' || echo ' (stale)';` +
690
+ ` else echo '(missing)'; fi`,
691
+ );
692
+ }
693
+ if (fifoPath) {
694
+ const quotedFifo = quotePosix(fifoPath);
695
+ statements.push(`printf 'fifo: '; if [ -p ${quotedFifo} ]; then echo '(present)'; else echo '(missing)'; fi`);
696
+ }
697
+ statements.push('true');
698
+ return statements.join('; ');
699
+ }
700
+
701
+ // ---------------------------------------------------------------------------
702
+ // Remote media path convention
703
+ // ---------------------------------------------------------------------------
704
+
705
+ function fnv1aHex(text) {
706
+ let hash = 0x811c9dc5;
707
+ for (let index = 0; index < text.length; index += 1) {
708
+ hash ^= text.charCodeAt(index);
709
+ hash = Math.imul(hash, 0x01000193) >>> 0;
710
+ }
711
+ return hash.toString(16).padStart(8, '0');
712
+ }
713
+
714
+ /**
715
+ * Turn an arbitrary local state directory into a stable, shell-safe slug used
716
+ * in remote media paths. Deterministic: the same stateDir always maps to the
717
+ * same slug (the short hash suffix keeps distinct directories distinct even
718
+ * after sanitization).
719
+ *
720
+ * @param {string} stateDir
721
+ * @returns {string}
722
+ */
723
+ export function sanitizeMediaSlug(stateDir) {
724
+ const raw = String(stateDir === undefined || stateDir === null ? '' : stateDir).trim();
725
+ let base = raw
726
+ .replace(/[^A-Za-z0-9._-]+/g, '_')
727
+ .replace(/^[_ .-]+/, '')
728
+ .replace(/[_ .-]+$/, '')
729
+ .slice(0, 40)
730
+ .replace(/^[_ .-]+/, '')
731
+ .replace(/[_ .-]+$/, '');
732
+ if (!base) base = 'state';
733
+ return `${base}-${fnv1aHex(raw || base)}`;
734
+ }
735
+
736
+ /**
737
+ * Remote directory for one VM's media files:
738
+ * `/tmp/apk-vm-media/<sanitized stateDir>`.
739
+ *
740
+ * @param {string} stateDir
741
+ * @returns {string}
742
+ */
743
+ export function remoteMediaDir(stateDir) {
744
+ return `${REMOTE_MEDIA_ROOT}/${sanitizeMediaSlug(stateDir)}`;
745
+ }
746
+
747
+ /**
748
+ * Remote path where the Lead should upload a virtual-scene poster. The poster
749
+ * file name must follow the poster-name rules; `extension` is png/jpg/jpeg.
750
+ *
751
+ * Example: scp ./wall.png <host>:`remotePosterPath(stateDir, 'wall')`, then pass
752
+ * `{name: 'wall', path: remotePosterPath(stateDir, 'wall')}` to the emulator.
753
+ *
754
+ * @param {string} stateDir
755
+ * @param {string} posterName
756
+ * @param {'png'|'jpg'|'jpeg'} [extension]
757
+ * @returns {string}
758
+ */
759
+ export function remotePosterPath(stateDir, posterName, extension = 'png') {
760
+ const name = assertPosterName(posterName);
761
+ const ext = trimmedString(extension).toLowerCase() || 'png';
762
+ if (ext !== 'png' && ext !== 'jpg' && ext !== 'jpeg') {
763
+ throw new Error(`poster extension must be png, jpg or jpeg (got ${jsonish(ext)})`);
764
+ }
765
+ return `${remoteMediaDir(stateDir)}/posters/${name}.${ext}`;
766
+ }
767
+
768
+ /**
769
+ * Remote path where the Lead should upload an audio file used by a file-loop
770
+ * microphone. Only wav/mp3/ogg are accepted by normalizeMicConfig().
771
+ *
772
+ * @param {string} stateDir
773
+ * @param {string} fileName
774
+ * @returns {string}
775
+ */
776
+ export function remoteAudioPath(stateDir, fileName) {
777
+ const name = trimmedString(fileName);
778
+ if (!name) throw new Error('audio file name is required');
779
+ if (name.length > MAX_FILE_NAME_LENGTH) throw new Error(`audio file name is longer than ${MAX_FILE_NAME_LENGTH} characters`);
780
+ if (/[\u0000-\u001f\u007f]/.test(name)) throw new Error('audio file name contains control characters');
781
+ if (!/^[A-Za-z0-9._-]+$/.test(name) || !AUDIO_FILE_EXT_RE.test(name)) {
782
+ throw new Error('audio file name must match [A-Za-z0-9._-]+ and end in .wav, .mp3 or .ogg');
783
+ }
784
+ return `${remoteMediaDir(stateDir)}/audio/${name}`;
785
+ }
786
+
787
+ /**
788
+ * PulseAudio source name derived from the VM state directory. The name is
789
+ * stable per VM, matches PulseAudio's source-name rules, and is used to find
790
+ * and unload the module later.
791
+ *
792
+ * @param {string} stateDir
793
+ * @returns {string}
794
+ */
795
+ export function micSourceName(stateDir) {
796
+ return `apkvm_mic_${sanitizeMediaSlug(stateDir)}`;
797
+ }
798
+
799
+ /**
800
+ * Convenience bundle of the remote media paths for one VM. The Lead can use
801
+ * these directly with the command builders and scp uploads.
802
+ *
803
+ * @param {string} stateDir
804
+ * @returns {{stateDir: string, dir: string, postersDir: string,
805
+ * audioDir: string, micSourceName: string, fifoPath: string,
806
+ * pidFile: string, logFile: string}}
807
+ */
808
+ export function remoteMediaPaths(stateDir) {
809
+ const dir = remoteMediaDir(stateDir);
810
+ return {
811
+ stateDir: String(stateDir === undefined || stateDir === null ? '' : stateDir),
812
+ dir,
813
+ postersDir: `${dir}/posters`,
814
+ audioDir: `${dir}/audio`,
815
+ micSourceName: micSourceName(stateDir),
816
+ fifoPath: `${dir}/mic.fifo`,
817
+ pidFile: `${dir}/mic.pid`,
818
+ logFile: `${dir}/mic-ffmpeg.log`,
819
+ };
820
+ }