system-loopback 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # system-loopback (Node.js & Electron)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Zero-`node-gyp` Node.js & Electron binding powered by `koffi` over `libsystem_loopback`.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import { SystemLoopback } from 'system-loopback';
9
+
10
+ const lb = new SystemLoopback({ excludePid: process.pid });
11
+ const pcm = lb.readF32(4800); // Float32Array in [-1.0, 1.0]
12
+ lb.close();
13
+ ```
14
+
15
+ ## Electron Packaging Checklist
16
+
17
+ 1. **Keep polling off the renderer UI thread**: run `SystemLoopback` inside a Node `worker_threads` worker or the Electron main process, and transfer `Float32Array.buffer` over IPC/MessagePort.
18
+ 2. **Unpack native binaries from `app.asar`** (`electron-builder`):
19
+ ```json
20
+ {
21
+ "build": {
22
+ "asarUnpack": ["**/system-loopback/prebuilds/**"]
23
+ }
24
+ }
25
+ ```
26
+ 3. **macOS 14.2+ signing & privacy**:
27
+ - Add `NSAudioCaptureUsageDescription` to your macOS `Info.plist`.
28
+ - Ensure `libsystem_loopback.dylib` is codesigned along with your Electron `.app` bundle.
@@ -0,0 +1,38 @@
1
+ export declare const EXPECTED_ABI_VERSION = 1;
2
+ export declare enum LoopbackStatus {
3
+ OK = 0,
4
+ UNSUPPORTED = -1,
5
+ PERMISSION_DENIED = -2,
6
+ DEVICE_NOT_FOUND = -3,
7
+ INIT_FAILED = -4,
8
+ DEVICE_LOST = -5,
9
+ INVALID_ARG = -6
10
+ }
11
+ export declare class LoopbackError extends Error {
12
+ readonly status: LoopbackStatus;
13
+ constructor(status: LoopbackStatus, detail?: string);
14
+ }
15
+ export interface LoopbackOptions {
16
+ deviceName?: string;
17
+ sampleRateHint?: number;
18
+ excludePid?: number;
19
+ autoStart?: boolean;
20
+ libraryPath?: string;
21
+ }
22
+ export declare function abiVersion(libraryPath?: string): number;
23
+ export declare function backendName(libraryPath?: string): string;
24
+ export declare class SystemLoopback {
25
+ private readonly api;
26
+ private handle;
27
+ private closed;
28
+ readonly sampleRate: number;
29
+ readonly channels: number;
30
+ readonly backend: string;
31
+ constructor(options?: LoopbackOptions);
32
+ start(): void;
33
+ stop(): void;
34
+ availableFrames(): number;
35
+ /** Non-blocking read of up to maxFrames mono float32 samples in [-1.0, 1.0]. */
36
+ readF32(maxFrames?: number): Float32Array;
37
+ close(): void;
38
+ }
package/dist/index.js ADDED
@@ -0,0 +1,149 @@
1
+ import koffi from 'koffi';
2
+ import { resolveLibraryPath } from './loader.js';
3
+ export const EXPECTED_ABI_VERSION = 1;
4
+ export var LoopbackStatus;
5
+ (function (LoopbackStatus) {
6
+ LoopbackStatus[LoopbackStatus["OK"] = 0] = "OK";
7
+ LoopbackStatus[LoopbackStatus["UNSUPPORTED"] = -1] = "UNSUPPORTED";
8
+ LoopbackStatus[LoopbackStatus["PERMISSION_DENIED"] = -2] = "PERMISSION_DENIED";
9
+ LoopbackStatus[LoopbackStatus["DEVICE_NOT_FOUND"] = -3] = "DEVICE_NOT_FOUND";
10
+ LoopbackStatus[LoopbackStatus["INIT_FAILED"] = -4] = "INIT_FAILED";
11
+ LoopbackStatus[LoopbackStatus["DEVICE_LOST"] = -5] = "DEVICE_LOST";
12
+ LoopbackStatus[LoopbackStatus["INVALID_ARG"] = -6] = "INVALID_ARG";
13
+ })(LoopbackStatus || (LoopbackStatus = {}));
14
+ export class LoopbackError extends Error {
15
+ status;
16
+ constructor(status, detail = '') {
17
+ const label = LoopbackStatus[status] ?? 'UNKNOWN';
18
+ super(detail ? `${label} (${status}): ${detail}` : `${label} (${status})`);
19
+ this.name = 'LoopbackError';
20
+ this.status = status;
21
+ }
22
+ }
23
+ const SlbConfig = koffi.struct('slb_config_t', {
24
+ struct_size: 'uint32',
25
+ device_name: 'str',
26
+ sample_rate_hint: 'uint32',
27
+ exclude_pid: 'uint32',
28
+ flags: 'uint32',
29
+ });
30
+ const apiCache = new Map();
31
+ function loadApi(explicitPath) {
32
+ const libPath = resolveLibraryPath(explicitPath);
33
+ const cached = apiCache.get(libPath);
34
+ if (cached)
35
+ return cached;
36
+ const lib = koffi.load(libPath);
37
+ const api = {
38
+ slb_abi_version: lib.func('uint32 slb_abi_version()'),
39
+ slb_backend_name: lib.func('str slb_backend_name()'),
40
+ slb_config_init: lib.func('void slb_config_init(_Out_ slb_config_t* cfg)'),
41
+ slb_create_ex: lib.func('int slb_create_ex(const slb_config_t* cfg, _Out_ int* out_sample_rate, _Out_ int* out_channels, _Out_ void** out_handle)'),
42
+ slb_start: lib.func('int slb_start(void* handle)'),
43
+ slb_available_frames: lib.func('int slb_available_frames(void* handle)'),
44
+ slb_read_f32: lib.func('int slb_read_f32(void* handle, _Out_ float* out_buf, int max_frames)'),
45
+ slb_last_error: lib.func('str slb_last_error(void* handle)'),
46
+ slb_stop: lib.func('void slb_stop(void* handle)'),
47
+ slb_destroy: lib.func('void slb_destroy(void* handle)'),
48
+ };
49
+ const abi = api.slb_abi_version();
50
+ if (abi !== EXPECTED_ABI_VERSION) {
51
+ throw new Error(`Incompatible libsystem_loopback ABI: expected v${EXPECTED_ABI_VERSION}, got v${abi}`);
52
+ }
53
+ apiCache.set(libPath, api);
54
+ return api;
55
+ }
56
+ export function abiVersion(libraryPath) {
57
+ return loadApi(libraryPath).slb_abi_version();
58
+ }
59
+ export function backendName(libraryPath) {
60
+ return loadApi(libraryPath).slb_backend_name();
61
+ }
62
+ export class SystemLoopback {
63
+ api;
64
+ handle = null;
65
+ closed = false;
66
+ sampleRate;
67
+ channels;
68
+ backend;
69
+ constructor(options = {}) {
70
+ this.api = loadApi(options.libraryPath);
71
+ this.backend = this.api.slb_backend_name();
72
+ const cfg = {
73
+ struct_size: koffi.sizeof(SlbConfig),
74
+ device_name: options.deviceName ?? null,
75
+ sample_rate_hint: options.sampleRateHint ?? 0,
76
+ exclude_pid: options.excludePid ?? 0,
77
+ flags: 0,
78
+ };
79
+ const rateOut = new Int32Array(1);
80
+ const chOut = new Int32Array(1);
81
+ const handleOut = [null];
82
+ const rc = this.api.slb_create_ex(cfg, rateOut, chOut, handleOut);
83
+ if (rc !== LoopbackStatus.OK || !handleOut[0]) {
84
+ const msg = this.api.slb_last_error(null);
85
+ throw new LoopbackError(rc, msg);
86
+ }
87
+ this.handle = handleOut[0];
88
+ this.sampleRate = rateOut[0] || 48000;
89
+ this.channels = chOut[0] || 1;
90
+ if (options.autoStart !== false) {
91
+ try {
92
+ this.start();
93
+ }
94
+ catch (err) {
95
+ this.close();
96
+ throw err;
97
+ }
98
+ }
99
+ }
100
+ start() {
101
+ if (this.closed || !this.handle) {
102
+ throw new LoopbackError(LoopbackStatus.INVALID_ARG, 'Stream is closed');
103
+ }
104
+ const rc = this.api.slb_start(this.handle);
105
+ if (rc !== LoopbackStatus.OK) {
106
+ throw new LoopbackError(rc, this.api.slb_last_error(this.handle));
107
+ }
108
+ }
109
+ stop() {
110
+ if (!this.closed && this.handle) {
111
+ this.api.slb_stop(this.handle);
112
+ }
113
+ }
114
+ availableFrames() {
115
+ if (this.closed || !this.handle)
116
+ return 0;
117
+ const n = this.api.slb_available_frames(this.handle);
118
+ if (n < 0) {
119
+ throw new LoopbackError(n, this.api.slb_last_error(this.handle));
120
+ }
121
+ return n;
122
+ }
123
+ /** Non-blocking read of up to maxFrames mono float32 samples in [-1.0, 1.0]. */
124
+ readF32(maxFrames = 4800) {
125
+ if (this.closed || !this.handle)
126
+ return new Float32Array(0);
127
+ const buf = new Float32Array(maxFrames);
128
+ const n = this.api.slb_read_f32(this.handle, buf, maxFrames);
129
+ if (n < 0) {
130
+ throw new LoopbackError(n, this.api.slb_last_error(this.handle));
131
+ }
132
+ return n === maxFrames ? buf : buf.subarray(0, n);
133
+ }
134
+ close() {
135
+ if (this.closed)
136
+ return;
137
+ this.closed = true;
138
+ if (this.handle) {
139
+ const h = this.handle;
140
+ this.handle = null;
141
+ try {
142
+ this.api.slb_stop(h);
143
+ }
144
+ finally {
145
+ this.api.slb_destroy(h);
146
+ }
147
+ }
148
+ }
149
+ }
@@ -0,0 +1,13 @@
1
+ export declare function platformInfo(): {
2
+ tag: string;
3
+ filename: string;
4
+ };
5
+ /**
6
+ * Resolve libsystem_loopback across:
7
+ * 1. Explicit path or SLB_LIBRARY_PATH env override
8
+ * 2. Electron asarUnpack path (app.asar.unpacked)
9
+ * 3. Bundled prebuilds/<platform-arch>/
10
+ * 4. Monorepo dist/native/<platform-arch>/
11
+ * 5. System dynamic library search path
12
+ */
13
+ export declare function resolveLibraryPath(explicitPath?: string): string;
package/dist/loader.js ADDED
@@ -0,0 +1,53 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
5
+ export function platformInfo() {
6
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
7
+ if (process.platform === 'darwin') {
8
+ return { tag: `darwin-${arch}`, filename: 'libsystem_loopback.dylib' };
9
+ }
10
+ if (process.platform === 'win32') {
11
+ return { tag: `win32-${arch}`, filename: 'system_loopback.dll' };
12
+ }
13
+ if (process.platform === 'linux') {
14
+ return { tag: `linux-${arch}`, filename: 'libsystem_loopback.so' };
15
+ }
16
+ throw new Error(`Unsupported platform: ${process.platform}`);
17
+ }
18
+ /**
19
+ * Resolve libsystem_loopback across:
20
+ * 1. Explicit path or SLB_LIBRARY_PATH env override
21
+ * 2. Electron asarUnpack path (app.asar.unpacked)
22
+ * 3. Bundled prebuilds/<platform-arch>/
23
+ * 4. Monorepo dist/native/<platform-arch>/
24
+ * 5. System dynamic library search path
25
+ */
26
+ export function resolveLibraryPath(explicitPath) {
27
+ if (explicitPath) {
28
+ if (fs.existsSync(explicitPath))
29
+ return explicitPath;
30
+ throw new Error(`Explicit system_loopback library not found: ${explicitPath}`);
31
+ }
32
+ const envPath = process.env.SLB_LIBRARY_PATH;
33
+ if (envPath) {
34
+ if (fs.existsSync(envPath))
35
+ return envPath;
36
+ throw new Error(`SLB_LIBRARY_PATH does not exist: ${envPath}`);
37
+ }
38
+ const { tag, filename } = platformInfo();
39
+ const pkgRoot = path.resolve(__dirname, '..');
40
+ const rawCandidates = [
41
+ path.join(pkgRoot, 'prebuilds', tag, filename),
42
+ path.resolve(pkgRoot, '..', '..', 'dist', 'native', tag, filename),
43
+ ];
44
+ for (const candidate of rawCandidates) {
45
+ // When packaged inside Electron app.asar, OS dlopen must target app.asar.unpacked.
46
+ const unpacked = candidate.replace(/app\.asar([/\\])/i, 'app.asar.unpacked$1');
47
+ if (fs.existsSync(unpacked))
48
+ return unpacked;
49
+ if (fs.existsSync(candidate))
50
+ return candidate;
51
+ }
52
+ return filename;
53
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "system-loopback",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Zero-driver cross-platform system audio loopback capture for Node.js and Electron (macOS Core Audio Tap, Windows WASAPI, Linux PipeWire/PulseAudio).",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "prebuilds",
17
+ "README.md"
18
+ ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/huangjunsen0406/system-loopback.git",
22
+ "directory": "bindings/node"
23
+ },
24
+ "homepage": "https://github.com/huangjunsen0406/system-loopback#readme",
25
+ "bugs": {
26
+ "url": "https://github.com/huangjunsen0406/system-loopback/issues"
27
+ },
28
+ "scripts": {
29
+ "build": "tsc -p tsconfig.json",
30
+ "typecheck": "tsc --noEmit -p tsconfig.json"
31
+ },
32
+ "dependencies": {
33
+ "koffi": "^2.9.0"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^22.0.0",
37
+ "typescript": "^5.6.0"
38
+ },
39
+ "keywords": [
40
+ "audio",
41
+ "loopback",
42
+ "electron",
43
+ "aec",
44
+ "coreaudio",
45
+ "wasapi",
46
+ "pulseaudio",
47
+ "pipewire",
48
+ "voice-ai"
49
+ ],
50
+ "license": "MIT"
51
+ }