transcribe-cpp 0.3.1 → 0.4.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/dist/native.d.ts CHANGED
@@ -1,24 +1,57 @@
1
1
  /**
2
- * Native bootstrap: resolve -> load -> bind -> verify ABI -> version-gate ->
3
- * init backends. The single choke point both the public API and tests go
4
- * through. Lazy and memoized: nothing loads until the first call.
2
+ * Native bootstrap, in two phases:
3
+ *
4
+ * 1. `loadLibrary()`: resolve -> (CUDA runtime preload) -> dlopen -> bind ->
5
+ * verify ABI -> version-gate -> install the log callback. Synchronous but
6
+ * GPU-free. Memoized on success; a failure is not cached.
7
+ *
8
+ * 2. Backend initialization: `transcribe_init_backends` builds the ggml
9
+ * backend registry, running each device's bootstrap (on Metal, the shader
10
+ * library compile, which can take seconds). `initialize()` runs it on a
11
+ * koffi async worker; concurrent callers share one attempt. A non-OK
12
+ * status is cached as `failed`: the C library documents it as not
13
+ * retryable in this process.
14
+ *
15
+ * Synchronous entry points that touch the registry go through `nativeReady()`.
16
+ * It initializes inline when uninitialized (blocking the caller, the pre-async
17
+ * behavior) and throws BackendInitializing while an async init is in flight.
18
+ * It must not wait for that init: the worker may be blocked delivering a log
19
+ * message to this (main) thread, so waiting would deadlock.
5
20
  */
6
21
  import { type Bound } from "./ffi.js";
7
22
  export interface Native extends Bound {
8
23
  libraryPath: string;
9
24
  provider: string | null;
25
+ /** Directory scanned for backend modules by `transcribe_init_backends`. */
26
+ artifactDir: string;
10
27
  abortProto: any;
11
28
  logProto: any;
12
29
  }
30
+ /** Lifecycle of the process-wide backend initialization. */
31
+ export type BackendState = "uninitialized" | "initializing" | "ready" | "failed";
13
32
  export type LogHandler = (level: number, message: string) => void;
14
- export declare function native(): Native;
33
+ /** Load and verify the native library without initializing any backend. */
34
+ export declare function loadLibrary(): Native;
35
+ export declare function callAsync<T = number>(fn: any, ...args: any[]): Promise<T>;
36
+ /** The current backend initialization state. Never loads or initializes anything. */
37
+ export declare function backendState(): BackendState;
38
+ /**
39
+ * Load the native library and initialize compute backends off the event loop.
40
+ * Idempotent; concurrent calls share one attempt. A backend init failure is
41
+ * permanent for the process; a library-load failure is not cached.
42
+ */
43
+ export declare function initialize(): Promise<void>;
44
+ /** Initialize (or join the in-flight init) and return the binding. */
45
+ export declare function nativeAsync(): Promise<Native>;
46
+ /** The binding with backends ready, for synchronous entry points. See module docs. */
47
+ export declare function nativeReady(): Native;
15
48
  /**
16
49
  * Route native (and ggml) diagnostics to `handler`, or pass null to disable.
17
50
  * The callback may fire from ggml worker threads; koffi marshals it to the
18
- * event-loop thread (proven by the M2 spike), so the handler runs on the main
19
- * thread. Exceptions thrown by the handler are swallowed (never re-enter C).
51
+ * event-loop thread, so the handler runs on the main thread. Exceptions thrown
52
+ * by the handler are swallowed (never re-enter C).
20
53
  *
21
- * The native callback is installed once during lazy bootstrap, before backend
54
+ * The native callback is installed once when the library loads, before backend
22
55
  * initialization. Later calls only swap this JS handler; they never call
23
56
  * transcribe_log_set again.
24
57
  */
package/dist/native.js CHANGED
@@ -1,18 +1,39 @@
1
1
  /**
2
- * Native bootstrap: resolve -> load -> bind -> verify ABI -> version-gate ->
3
- * init backends. The single choke point both the public API and tests go
4
- * through. Lazy and memoized: nothing loads until the first call.
2
+ * Native bootstrap, in two phases:
3
+ *
4
+ * 1. `loadLibrary()`: resolve -> (CUDA runtime preload) -> dlopen -> bind ->
5
+ * verify ABI -> version-gate -> install the log callback. Synchronous but
6
+ * GPU-free. Memoized on success; a failure is not cached.
7
+ *
8
+ * 2. Backend initialization: `transcribe_init_backends` builds the ggml
9
+ * backend registry, running each device's bootstrap (on Metal, the shader
10
+ * library compile, which can take seconds). `initialize()` runs it on a
11
+ * koffi async worker; concurrent callers share one attempt. A non-OK
12
+ * status is cached as `failed`: the C library documents it as not
13
+ * retryable in this process.
14
+ *
15
+ * Synchronous entry points that touch the registry go through `nativeReady()`.
16
+ * It initializes inline when uninitialized (blocking the caller, the pre-async
17
+ * behavior) and throws BackendInitializing while an async init is in flight.
18
+ * It must not wait for that init: the worker may be blocked delivering a log
19
+ * message to this (main) thread, so waiting would deadlock.
5
20
  */
6
21
  import { resolveLibrary } from "./loader.js";
7
22
  import { preloadCudaRuntime } from "./cuda.js";
8
23
  import { abortProto, bindLibrary, logProto } from "./ffi.js";
9
24
  import { verifyLayouts } from "./abi.js";
10
- import { BackendError, VersionMismatch } from "./errors.js";
25
+ import { BackendError, BackendInitializing, VersionMismatch } from "./errors.js";
11
26
  import { OUR_VERSION, baseVersion } from "./version.js";
12
27
  import * as g from "./_generated.js";
13
- let cached = null;
28
+ let lib = null;
29
+ let state = "uninitialized";
30
+ let initPromise = null; // set while an async init is in flight
31
+ let initError = null; // the cached bootstrap failure
14
32
  let logHandler = null;
15
33
  let logRegistered = null;
34
+ // Registered once and never unregistered or re-installed: native code (including
35
+ // an in-flight backend init on a worker) may hold the pointer at any time. Only
36
+ // the JS target (`logHandler`) ever changes.
16
37
  function ensureLogCallback(bound) {
17
38
  if (logRegistered)
18
39
  return;
@@ -30,14 +51,18 @@ function ensureLogCallback(bound) {
30
51
  logRegistered = bound.koffi.register(thunk, bound.koffi.pointer(logProto()));
31
52
  bound.F.logSet(logRegistered, null);
32
53
  }
33
- export function native() {
34
- if (cached)
35
- return cached;
54
+ // ---- phase 1: library -------------------------------------------------------
55
+ /** Load and verify the native library without initializing any backend. */
56
+ export function loadLibrary() {
57
+ if (lib)
58
+ return lib;
36
59
  const resolved = resolveLibrary();
37
60
  // Bring-your-own CUDA runtime: if the selected provider advertises cuda,
38
61
  // preload cudart/cublas (the TS twin of the Python cu12 provider's prepare()
39
62
  // hook) BEFORE any dlopen, so the ggml-cuda module's DT_NEEDED sonames resolve
40
- // when initBackends loads it below. A no-op without cuda or the runtime dir.
63
+ // when backend init loads it. A no-op without cuda or the runtime dir. This
64
+ // is synchronous (koffi.load has no async form) and can be slow for a large
65
+ // cublas; it only runs for the opt-in CUDA package with the env var set.
41
66
  if (resolved.backends.includes("cuda"))
42
67
  preloadCudaRuntime();
43
68
  const bound = bindLibrary(resolved.libraryPath);
@@ -51,31 +76,138 @@ export function native() {
51
76
  // stable JS dispatch callback once, before backend init can create worker
52
77
  // threads; setLogHandler later only swaps the JS target.
53
78
  ensureLogCallback(bound);
54
- // Register backend modules package-local. On a compiled-in build this is a
55
- // near no-op; on a dynamic-backend bundle it scans the artifact dir.
56
- let st = bound.F.initBackends(resolved.artifactDir);
57
- if (st !== g.TRANSCRIBE_OK)
58
- st = bound.F.initBackendsDefault();
59
- if (st !== g.TRANSCRIBE_OK) {
60
- throw new BackendError(`transcribe_init_backends found no usable compute device in ${resolved.artifactDir}: ` +
61
- `${bound.F.statusString(st)} (status ${st})`);
62
- }
63
- cached = {
79
+ lib = {
64
80
  ...bound,
65
81
  libraryPath: resolved.libraryPath,
66
82
  provider: resolved.provider,
83
+ artifactDir: resolved.artifactDir,
67
84
  abortProto: abortProto(),
68
85
  logProto: logProto(),
69
86
  };
70
- return cached;
87
+ return lib;
88
+ }
89
+ // ---- phase 2: backends ------------------------------------------------------
90
+ export function callAsync(fn, ...args) {
91
+ return new Promise((resolve, reject) => fn.async(...args, (err, res) => (err ? reject(err) : resolve(res))));
92
+ }
93
+ function initFailure(n, st) {
94
+ return new BackendError(`transcribe_init_backends found no usable compute device in ${n.artifactDir}: ` +
95
+ `${n.F.statusString(st)} (status ${st})`, st);
96
+ }
97
+ /**
98
+ * The device count after init forces registry construction (and so every device
99
+ * bootstrap) even on paths that skip the module scan. Zero devices is a failure
100
+ * even after an OK init: the compiled-in default path doesn't check the count,
101
+ * and `transcribe_device_count` reports 0 if registry construction threw.
102
+ */
103
+ function requireDevices(st, count) {
104
+ return st === g.TRANSCRIBE_OK && count <= 0 ? g.TRANSCRIBE_ERR_BACKEND : st;
105
+ }
106
+ async function initAsync(n) {
107
+ let st = await callAsync(n.F.initBackends, n.artifactDir);
108
+ if (st !== g.TRANSCRIBE_OK)
109
+ st = await callAsync(n.F.initBackendsDefault);
110
+ if (st !== g.TRANSCRIBE_OK)
111
+ return st;
112
+ return requireDevices(st, await callAsync(n.F.deviceCount));
113
+ }
114
+ function initSync(n) {
115
+ let st = n.F.initBackends(n.artifactDir);
116
+ if (st !== g.TRANSCRIBE_OK)
117
+ st = n.F.initBackendsDefault();
118
+ if (st !== g.TRANSCRIBE_OK)
119
+ return st;
120
+ return requireDevices(st, n.F.deviceCount());
121
+ }
122
+ /** The current backend initialization state. Never loads or initializes anything. */
123
+ export function backendState() {
124
+ return state;
125
+ }
126
+ /**
127
+ * Load the native library and initialize compute backends off the event loop.
128
+ * Idempotent; concurrent calls share one attempt. A backend init failure is
129
+ * permanent for the process; a library-load failure is not cached.
130
+ */
131
+ export function initialize() {
132
+ if (state === "ready")
133
+ return Promise.resolve();
134
+ if (state === "failed")
135
+ return Promise.reject(initError);
136
+ if (initPromise)
137
+ return initPromise;
138
+ if (state === "initializing") {
139
+ // Re-entered from a log handler during a synchronous inline init.
140
+ return Promise.reject(inProgress());
141
+ }
142
+ let n;
143
+ try {
144
+ n = loadLibrary();
145
+ }
146
+ catch (e) {
147
+ return Promise.reject(e);
148
+ }
149
+ state = "initializing";
150
+ initPromise = initAsync(n).then((st) => {
151
+ initPromise = null;
152
+ if (st === g.TRANSCRIBE_OK) {
153
+ state = "ready";
154
+ return;
155
+ }
156
+ initError = initFailure(n, st);
157
+ state = "failed";
158
+ throw initError;
159
+ }, (e) => {
160
+ // koffi failed to dispatch a call: not a native bootstrap status, so the
161
+ // next call retries (transcribe_init_backends is idempotent).
162
+ initPromise = null;
163
+ state = "uninitialized";
164
+ throw e;
165
+ });
166
+ return initPromise;
167
+ }
168
+ /** Initialize (or join the in-flight init) and return the binding. */
169
+ export async function nativeAsync() {
170
+ await initialize();
171
+ return lib;
172
+ }
173
+ function inProgress() {
174
+ return new BackendInitializing("transcribe.cpp backend initialization is in progress; await initialize() " +
175
+ "(or use getAvailableBackendsAsync() / backendAvailableAsync()) instead of " +
176
+ "calling a synchronous backend query concurrently with it");
177
+ }
178
+ /** The binding with backends ready, for synchronous entry points. See module docs. */
179
+ export function nativeReady() {
180
+ if (state === "ready")
181
+ return lib;
182
+ if (state === "failed")
183
+ throw initError;
184
+ if (state === "initializing")
185
+ throw inProgress();
186
+ const n = loadLibrary();
187
+ state = "initializing"; // a re-entrant call from a log handler fails fast
188
+ let st;
189
+ try {
190
+ st = initSync(n);
191
+ }
192
+ catch (e) {
193
+ state = "uninitialized";
194
+ throw e;
195
+ }
196
+ if (st !== g.TRANSCRIBE_OK) {
197
+ initError = initFailure(n, st);
198
+ state = "failed";
199
+ throw initError;
200
+ }
201
+ state = "ready";
202
+ return n;
71
203
  }
72
204
  /**
73
205
  * Route native (and ggml) diagnostics to `handler`, or pass null to disable.
74
206
  * The callback may fire from ggml worker threads; koffi marshals it to the
75
- * event-loop thread (proven by the M2 spike), so the handler runs on the main
76
- * thread. Exceptions thrown by the handler are swallowed (never re-enter C).
207
+ * event-loop thread, so the handler runs on the main thread. Exceptions thrown
208
+ * by the handler are swallowed (never re-enter C).
77
209
  *
78
- * The native callback is installed once during lazy bootstrap, before backend
210
+ * The native callback is installed once when the library loads, before backend
79
211
  * initialization. Later calls only swap this JS handler; they never call
80
212
  * transcribe_log_set again.
81
213
  */
package/dist/types.d.ts CHANGED
@@ -169,7 +169,7 @@ export type BatchItem = {
169
169
  };
170
170
  export type CommitPolicy = "auto" | "on_finalize" | "stable_prefix";
171
171
  export type StreamState = "idle" | "active" | "finished" | "failed";
172
- export type ExtSlot = "run" | "stream";
172
+ export type ExtSlot = "run" | "stream" | "diarize_run";
173
173
  export interface StreamUpdate {
174
174
  resultChanged: boolean;
175
175
  isFinal: boolean;
@@ -238,9 +238,8 @@ export interface VoxtralRealtimeStreamOptions {
238
238
  * "very_high_latency" (~30 s lookahead) is the offline-file operating
239
239
  * point; "low_latency" (~1 s) is the real-time point. */
240
240
  export type SortformerPreset = "default" | "very_high_latency" | "high_latency" | "low_latency";
241
- /** Sortformer diarizer options (run slot). A run produces speaker
242
- * segments, no text. */
243
- export interface SortformerStreamOptions {
241
+ /** Sortformer options for {@link DiarizeOptions.family} (diarize_run slot). */
242
+ export interface SortformerDiarizeOptions {
244
243
  preset?: SortformerPreset;
245
244
  }
246
245
  export type FamilyExtension = ({
@@ -254,5 +253,114 @@ export type FamilyExtension = ({
254
253
  } & ParakeetBufferedStreamOptions) | ({
255
254
  kind: "voxtral";
256
255
  } & VoxtralRealtimeStreamOptions) | ({
257
- kind: "sortformer";
258
- } & SortformerStreamOptions);
256
+ kind: "sortformer_diarize";
257
+ } & SortformerDiarizeOptions);
258
+ /**
259
+ * What a model serves: "asr" (transcription), "diarize" (speaker turns),
260
+ * "langid" (language), "vad" (voice activity).
261
+ */
262
+ export type Role = "asr" | "diarize" | "langid" | "vad";
263
+ export interface DiarizeInfo {
264
+ /** Input PCM rate. */
265
+ sampleRate: number;
266
+ /** Speaker ids are in [1, maxSpeakers]. */
267
+ maxSpeakers: number;
268
+ }
269
+ export interface DiarizeSessionOptions {
270
+ /** CPU threads for CPU-side ops; 0 = library default. */
271
+ nThreads?: number;
272
+ }
273
+ export interface DiarizeOptions {
274
+ /** Cancel the run cooperatively. */
275
+ signal?: AbortSignal;
276
+ /** A diarize_run-slot family extension (e.g. sortformer_diarize). */
277
+ family?: FamilyExtension;
278
+ }
279
+ export interface LangIdInfo {
280
+ /** Input PCM rate. */
281
+ sampleRate: number;
282
+ /** Label indices are [0, nLabels). */
283
+ nLabels: number;
284
+ /** Shorter scored audio throws InputTooShort. */
285
+ minAudioMs: number;
286
+ /** Longer input is scored on its first maxAudioMs (30000). */
287
+ maxAudioMs: number;
288
+ }
289
+ export interface LangIdSessionOptions {
290
+ /** CPU threads for CPU-side ops; 0 = library default. */
291
+ nThreads?: number;
292
+ }
293
+ export interface LangIdOptions {
294
+ /** Cancel the run cooperatively. */
295
+ signal?: AbortSignal;
296
+ /**
297
+ * Restrict the decision to these codes or aliases. Omitted (or undefined /
298
+ * null) means every label; an empty array throws InvalidArgument; an
299
+ * unknown code throws UnsupportedRequest.
300
+ */
301
+ allowed?: readonly string[] | null;
302
+ }
303
+ /** One ranked label; `code` is the model's own label ("en", "iw"). */
304
+ export interface LangIdCandidate {
305
+ index: number;
306
+ code: string;
307
+ name: string;
308
+ /** Softmax renormalized over the allowed set. */
309
+ p: number;
310
+ logit: number;
311
+ }
312
+ export interface LangIdResult {
313
+ /**
314
+ * Every allowed label (duplicates once; every label when unrestricted),
315
+ * ranked by p, descending; ties keep label order.
316
+ */
317
+ candidates: LangIdCandidate[];
318
+ /** The top candidate's code, or null with no candidates. */
319
+ code: string | null;
320
+ /** Unrestricted probability inside the allowed set (1 when unrestricted). */
321
+ allowedMass: number;
322
+ }
323
+ export interface VadInfo {
324
+ /** Input PCM rate (16000). */
325
+ sampleRate: number;
326
+ /** Samples per probability (512 = 32 ms for Silero). */
327
+ frameSamples: number;
328
+ }
329
+ export interface VadSessionOptions {
330
+ /** CPU threads; 0 = library default. */
331
+ nThreads?: number;
332
+ }
333
+ /** Segmentation options for VadSession.run; omitted fields keep Silero's defaults. */
334
+ export interface VadOptions {
335
+ /** Cancel the run cooperatively. */
336
+ signal?: AbortSignal;
337
+ /** A frame with p >= threshold is speech (default 0.5). */
338
+ threshold?: number;
339
+ /** Inside speech, p < negThreshold is silence; negative (default) = max(threshold - 0.15, 0.01). */
340
+ negThreshold?: number;
341
+ /** Shorter segments are dropped (default 250). */
342
+ minSpeechMs?: number;
343
+ /** Silence this long ends a segment (default 100). */
344
+ minSilenceMs?: number;
345
+ /** Padding added to each side of a segment (default 30). */
346
+ speechPadMs?: number;
347
+ /** Longer segments are split; 0 (default) = no limit. */
348
+ maxSpeechMs?: number;
349
+ }
350
+ export interface VadFeedOptions {
351
+ /** Cancel the feed cooperatively. */
352
+ signal?: AbortSignal;
353
+ }
354
+ /** One speech segment, in samples of the run's input: [startSample, endSample). */
355
+ export interface VadSegment {
356
+ startSample: number;
357
+ endSample: number;
358
+ }
359
+ export interface VadResult {
360
+ /** Per-frame speech probabilities produced by this call (copied). */
361
+ probs: number[];
362
+ /** Stream frame index of probs[0]: 0 after run; frames scored before a feed / flush. */
363
+ firstFrame: number;
364
+ /** Speech segments; run only, empty after a feed or flush. */
365
+ segments: VadSegment[];
366
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "transcribe-cpp",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "TypeScript/Node.js bindings for transcribe.cpp — a C/C++ speech-to-text library built on ggml",
5
5
  "type": "module",
6
6
  "exports": {
@@ -51,11 +51,11 @@
51
51
  "koffi": "^3.0.2"
52
52
  },
53
53
  "optionalDependencies": {
54
- "@transcribe-cpp/darwin-arm64-metal": "0.3.1",
55
- "@transcribe-cpp/darwin-x64-cpu": "0.3.1",
56
- "@transcribe-cpp/linux-x64-cpu-vulkan": "0.3.1",
57
- "@transcribe-cpp/linux-arm64-cpu-vulkan": "0.3.1",
58
- "@transcribe-cpp/win32-x64-cpu-vulkan": "0.3.1"
54
+ "@transcribe-cpp/darwin-arm64-metal": "0.4.0",
55
+ "@transcribe-cpp/darwin-x64-cpu": "0.4.0",
56
+ "@transcribe-cpp/linux-x64-cpu-vulkan": "0.4.0",
57
+ "@transcribe-cpp/linux-arm64-cpu-vulkan": "0.4.0",
58
+ "@transcribe-cpp/win32-x64-cpu-vulkan": "0.4.0"
59
59
  },
60
60
  "devDependencies": {
61
61
  "@types/node": "^22.0.0",