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/index.js CHANGED
@@ -5,13 +5,13 @@
5
5
  * batch, streaming with committed/tentative text, typed per-family extensions,
6
6
  * backend discovery, log routing, and cooperative cancellation.
7
7
  */
8
- import { native, setLogHandler, } from "./native.js";
8
+ import { backendState, callAsync, initialize, loadLibrary, nativeAsync, nativeReady, setLogHandler, } from "./native.js";
9
9
  import { resolveLibrary } from "./loader.js";
10
10
  import * as g from "./_generated.js";
11
11
  import { Aborted, Busy, exceptionForStatus, InvalidArgument, ModelLoadError, NotImplementedByModel, OutputRepetition, OutputTruncated, TranscribeError, UnsupportedRequest, } from "./errors.js";
12
12
  export * from "./types.js";
13
13
  export * from "./errors.js";
14
- export { setLogHandler };
14
+ export { backendState, initialize, setLogHandler };
15
15
  // ---- enum maps -------------------------------------------------------------
16
16
  const BACKENDS = {
17
17
  auto: g.TRANSCRIBE_BACKEND_AUTO,
@@ -68,6 +68,12 @@ const FEATURES = {
68
68
  instruct: g.TRANSCRIBE_FEATURE_INSTRUCT,
69
69
  transcript_prefix: g.TRANSCRIBE_FEATURE_TRANSCRIPT_PREFIX,
70
70
  };
71
+ const ROLES = {
72
+ asr: g.TRANSCRIBE_ROLE_ASR,
73
+ diarize: g.TRANSCRIBE_ROLE_DIARIZE,
74
+ langid: g.TRANSCRIBE_ROLE_LANGID,
75
+ vad: g.TRANSCRIBE_ROLE_VAD,
76
+ };
71
77
  // ---- helpers ---------------------------------------------------------------
72
78
  function lookup(map, key, what) {
73
79
  const v = map[key];
@@ -170,39 +176,37 @@ function deferFree(lock, fn, after) {
170
176
  after?.();
171
177
  });
172
178
  }
173
- function callAsync(fn, ...args) {
174
- return new Promise((resolve, reject) => fn.async(...args, (err, res) => err ? reject(err) : resolve(res)));
175
- }
176
179
  // Coerce caller PCM to a Float32Array. A Float32Array is returned AS-IS (no
177
180
  // copy): the buffer is borrowed across the async native call, which reads it on
178
181
  // a worker thread, so callers must not mutate it until the promise resolves
179
182
  // (documented on run/runBatch/feed). Other inputs already produce a fresh array.
183
+ // asFloat32 allows empty input (a VAD stream feed accepts 0 samples).
180
184
  function toFloat32(pcm) {
181
- let out;
185
+ const out = asFloat32(pcm);
186
+ if (out.length === 0)
187
+ throw new TranscribeError("PCM is empty");
188
+ return out;
189
+ }
190
+ function asFloat32(pcm) {
182
191
  if (pcm instanceof Float32Array)
183
- out = pcm;
184
- else if (Array.isArray(pcm))
185
- out = Float32Array.from(pcm);
186
- else if (pcm instanceof ArrayBuffer)
187
- out = new Float32Array(pcm);
188
- else if (ArrayBuffer.isView(pcm)) {
192
+ return pcm;
193
+ if (Array.isArray(pcm))
194
+ return Float32Array.from(pcm);
195
+ if (pcm instanceof ArrayBuffer)
196
+ return new Float32Array(pcm);
197
+ if (ArrayBuffer.isView(pcm)) {
189
198
  const b = pcm;
190
199
  if (b.byteLength % 4 !== 0) {
191
200
  throw new TranscribeError("PCM byte length must be a multiple of 4 (float32)");
192
201
  }
193
- out = new Float32Array(b.buffer, b.byteOffset, b.byteLength / 4);
202
+ return new Float32Array(b.buffer, b.byteOffset, b.byteLength / 4);
194
203
  }
195
- else {
196
- throw new TranscribeError("PCM must be a Float32Array, number[], ArrayBuffer, or Buffer");
197
- }
198
- if (out.length === 0)
199
- throw new TranscribeError("PCM is empty");
200
- return out;
204
+ throw new TranscribeError("PCM must be a Float32Array, number[], ArrayBuffer, or Buffer");
201
205
  }
202
206
  // koffi decodes int64 struct fields as bigint. We surface them as number for
203
- // ergonomics; the fields this is used on (millisecond timestamps, kv byte caps)
204
- // stay well under Number.MAX_SAFE_INTEGER, so the narrowing is lossless in
205
- // practice. Revisit if a field can exceed 2^53.
207
+ // ergonomics; the fields this is used on (millisecond timestamps, kv byte caps,
208
+ // sample / frame indices) stay well under Number.MAX_SAFE_INTEGER, so the
209
+ // narrowing is lossless in practice. Revisit if a field can exceed 2^53.
206
210
  function num(v) {
207
211
  return typeof v === "bigint" ? Number(v) : v;
208
212
  }
@@ -230,13 +234,12 @@ class Mutex {
230
234
  }
231
235
  // ---- module-level introspection -------------------------------------------
232
236
  //
233
- // Note: these (like every public entry point) trigger the lazy native bootstrap
234
- // on first call — they dlopen the library, verify the ABI, and init backends.
235
- // There is no way to probe the binding without loading the native library, with
236
- // one exception: `headerHash` below is the compile-time PUBLIC_HEADER_HASH and
237
- // is the value the binding *expects*, not one read from the loaded library.
237
+ // Native bootstrap is two-phase (see native.ts). `version()` and
238
+ // `libraryPath()` only load the library and never initialize a backend.
239
+ // `headerHash` is the compile-time PUBLIC_HEADER_HASH: the value the binding
240
+ // *expects*, not one read from the loaded library.
238
241
  export function version() {
239
- const n = native();
242
+ const n = loadLibrary();
240
243
  return {
241
244
  version: n.F.version(),
242
245
  commit: n.F.versionCommit(),
@@ -244,7 +247,7 @@ export function version() {
244
247
  };
245
248
  }
246
249
  export function libraryPath() {
247
- return native().libraryPath;
250
+ return loadLibrary().libraryPath;
248
251
  }
249
252
  /**
250
253
  * The directory holding the native library and its sibling ggml libs / backend
@@ -285,8 +288,12 @@ function deviceFromRaw(dev, handle, index = null) {
285
288
  DEVICE_HANDLES.set(info, handle);
286
289
  return info;
287
290
  }
291
+ /**
292
+ * Every registered compute device. Initializes backends on the calling thread
293
+ * if needed; throws `BackendInitializing` while {@link initialize} runs.
294
+ */
288
295
  export function getAvailableBackends() {
289
- const n = native();
296
+ const n = nativeReady();
290
297
  const count = n.F.deviceCount();
291
298
  const out = [];
292
299
  for (let i = 0; i < count; i++) {
@@ -300,9 +307,36 @@ export function getAvailableBackends() {
300
307
  }
301
308
  return out;
302
309
  }
310
+ /** {@link getAvailableBackends} without blocking the event loop. */
311
+ export async function getAvailableBackendsAsync() {
312
+ const n = await nativeAsync();
313
+ const count = n.F.deviceCount();
314
+ const out = [];
315
+ for (let i = 0; i < count; i++) {
316
+ const handle = n.F.deviceGet(i);
317
+ if (!handle)
318
+ continue;
319
+ const dev = {};
320
+ n.F.deviceInfoInit(dev);
321
+ const st = await callAsync(n.F.deviceGetInfo, handle, dev);
322
+ check(n, st, `reading backend device ${i}`);
323
+ out.push(deviceFromRaw(dev, handle, i));
324
+ }
325
+ return out;
326
+ }
327
+ /**
328
+ * Whether some registered device can satisfy `backend`. Same initialization
329
+ * behavior as {@link getAvailableBackends}.
330
+ */
303
331
  export function backendAvailable(backend) {
304
- const n = native();
305
- return n.F.backendAvailable(lookup(BACKENDS, backend, "backend"));
332
+ const raw = lookup(BACKENDS, backend, "backend");
333
+ return nativeReady().F.backendAvailable(raw);
334
+ }
335
+ /** {@link backendAvailable} without blocking the event loop. */
336
+ export async function backendAvailableAsync(backend) {
337
+ const raw = lookup(BACKENDS, backend, "backend");
338
+ const n = await nativeAsync();
339
+ return n.F.backendAvailable(raw);
306
340
  }
307
341
  function singleAccessors(n, h) {
308
342
  const F = n.F;
@@ -387,38 +421,44 @@ function materialize(n, acc) {
387
421
  wordIndex: t.word_index,
388
422
  });
389
423
  }
390
- const speakerSegments = [];
391
- for (let i = 0, c = acc.nSpeakerSegments(); i < c; i++) {
424
+ return {
425
+ text: acc.fullText() ?? "",
426
+ rawText: acc.rawText() ?? "",
427
+ language: acc.detectedLanguage() ?? "",
428
+ timestampKind: TIMESTAMP_NAMES[acc.returnedTimestampKind()] ?? "none",
429
+ segments,
430
+ speakerSegments: readSpeakerSegments(n, acc.nSpeakerSegments(), acc.getSpeakerSegment),
431
+ words,
432
+ tokens,
433
+ timings: readTimings(n, acc.getTimings),
434
+ };
435
+ }
436
+ // Shared by transcripts and the DIARIZE role's results.
437
+ function readSpeakerSegments(n, count, get) {
438
+ const out = [];
439
+ for (let i = 0; i < count; i++) {
392
440
  const s = {};
393
- F.speakerSegmentInit(s);
394
- check(n, acc.getSpeakerSegment(i, s), `reading speaker segment ${i}`);
395
- speakerSegments.push({
441
+ n.F.speakerSegmentInit(s);
442
+ check(n, get(i, s), `reading speaker segment ${i}`);
443
+ out.push({
396
444
  t0Ms: num(s.t0_ms),
397
445
  t1Ms: num(s.t1_ms),
398
446
  speakerId: s.speaker_id,
399
447
  p: s.p,
400
448
  });
401
449
  }
450
+ return out;
451
+ }
452
+ function readTimings(n, get) {
402
453
  const tm = {};
403
- F.timingsInit(tm);
404
- check(n, acc.getTimings(tm), "reading timings");
405
- const timings = {
454
+ n.F.timingsInit(tm);
455
+ check(n, get(tm), "reading timings");
456
+ return {
406
457
  loadMs: tm.load_ms,
407
458
  melMs: tm.mel_ms,
408
459
  encodeMs: tm.encode_ms,
409
460
  decodeMs: tm.decode_ms,
410
461
  };
411
- return {
412
- text: acc.fullText() ?? "",
413
- rawText: acc.rawText() ?? "",
414
- language: acc.detectedLanguage() ?? "",
415
- timestampKind: TIMESTAMP_NAMES[acc.returnedTimestampKind()] ?? "none",
416
- segments,
417
- speakerSegments,
418
- words,
419
- tokens,
420
- timings,
421
- };
422
462
  }
423
463
  // ---- family extensions -----------------------------------------------------
424
464
  const COMMIT_POLICIES = {
@@ -435,6 +475,7 @@ const STREAM_STATES = {
435
475
  const SLOT = {
436
476
  run: g.TRANSCRIBE_EXT_SLOT_RUN,
437
477
  stream: g.TRANSCRIBE_EXT_SLOT_STREAM,
478
+ diarize_run: g.TRANSCRIBE_EXT_SLOT_DIARIZE_RUN,
438
479
  };
439
480
  const FAMILY = {
440
481
  whisper: {
@@ -490,12 +531,14 @@ const FAMILY = {
490
531
  min_decode_interval_ms: o.minDecodeIntervalMs,
491
532
  }),
492
533
  },
493
- sortformer: {
494
- slot: "run",
495
- kind: g.TRANSCRIBE_EXT_KIND_SORTFORMER_STREAM,
496
- type: "transcribe_sortformer_stream_ext",
497
- init: "sortformerStreamExtInit",
498
- map: (o) => ({ preset: SORTFORMER_PRESET[o.preset] }),
534
+ sortformer_diarize: {
535
+ slot: "diarize_run",
536
+ kind: g.TRANSCRIBE_EXT_KIND_SORTFORMER_DIARIZE,
537
+ type: "transcribe_sortformer_diarize_ext",
538
+ init: "sortformerDiarizeExtInit",
539
+ map: (o) => ({
540
+ preset: o.preset === undefined ? undefined : lookup(SORTFORMER_PRESET, o.preset, "sortformer preset"),
541
+ }),
499
542
  },
500
543
  };
501
544
  const SORTFORMER_PRESET = {
@@ -508,7 +551,7 @@ const SORTFORMER_PRESET = {
508
551
  * Build a native ext-struct buffer for a family extension and return the koffi
509
552
  * pointer to assign to `params.family`. Validates the slot and that the model
510
553
  * accepts the kind. The returned buffer must be kept alive (held via the params
511
- * object) until the native call returns.
554
+ * object) until the native call returns, then freed by freeRunParams.
512
555
  */
513
556
  function buildFamily(n, modelHandle, family, slot) {
514
557
  const reg = FAMILY[family.kind];
@@ -527,7 +570,13 @@ function buildFamily(n, modelHandle, family, slot) {
527
570
  ext[k] = v;
528
571
  }
529
572
  const buf = n.koffi.alloc(n.T[reg.type], 1);
530
- n.koffi.encode(buf, n.T[reg.type], ext);
573
+ try {
574
+ n.koffi.encode(buf, n.T[reg.type], ext);
575
+ }
576
+ catch (e) {
577
+ n.koffi.free(buf);
578
+ throw e;
579
+ }
531
580
  return buf;
532
581
  }
533
582
  /** A string option as passed to C, which would silently cut it at a NUL. */
@@ -536,13 +585,20 @@ function cstr(value, name) {
536
585
  throw new InvalidArgument(`${name} contains a NUL character`);
537
586
  return value;
538
587
  }
539
- /** Free what #buildRunParams allocated; call once the native call returns. */
588
+ /**
589
+ * Free what #buildRunParams / buildFamily allocated into a params struct; call
590
+ * only once the native call has returned (never while a worker reads it).
591
+ */
540
592
  function freeRunParams(n, p) {
541
593
  if (p.vocabulary) {
542
594
  n.koffi.free(p.vocabulary);
543
595
  p.vocabulary = null;
544
596
  p.n_vocabulary = 0;
545
597
  }
598
+ if (p.family) {
599
+ n.koffi.free(p.family);
600
+ p.family = null;
601
+ }
546
602
  }
547
603
  function toStreamUpdate(u) {
548
604
  return {
@@ -568,32 +624,119 @@ function toStreamUpdate(u) {
568
624
  */
569
625
  const STREAM_TEARDOWN = new WeakMap();
570
626
  const SESSION_CONTROL = new WeakMap();
627
+ /**
628
+ * One native session handle under the model's compute rules, shared by Session,
629
+ * DiarizeSession, LangIdSession, and VadSession. Each holds it in a private
630
+ * field, so none of this is reachable from user code. `setAbort` is the role's
631
+ * set_abort_callback.
632
+ */
633
+ class SessionCore {
634
+ #n;
635
+ #h;
636
+ #lock; // shared with the model; serializes compute model-wide
637
+ #setAbort;
638
+ #inFlight = null; // set while a native call runs on a worker
639
+ #disposed = false;
640
+ constructor(n, handle, lock, setAbort) {
641
+ this.#n = n;
642
+ this.#h = handle;
643
+ this.#lock = lock;
644
+ this.#setAbort = setAbort;
645
+ }
646
+ get handle() {
647
+ if (this.#disposed)
648
+ throw new TranscribeError("session has been disposed");
649
+ return this.#h;
650
+ }
651
+ get disposed() {
652
+ return this.#disposed;
653
+ }
654
+ /** Reads touch the session; forbidden while a worker call is in flight. */
655
+ assertNotComputing(what) {
656
+ if (this.#inFlight) {
657
+ throw new TranscribeError(`cannot read ${what} while ${this.#inFlight} is in flight; await it first`);
658
+ }
659
+ }
660
+ /**
661
+ * Run `body` as this session's one native compute on the model-wide FIFO
662
+ * lock (it copies results out before release). Refuses a disposed session,
663
+ * then an active stream (Busy naming `busyOp`); null `busyOp` = that stream.
664
+ * Not `async`: refusals and `body`'s promise are returned as-is (no extra ticks).
665
+ */
666
+ exclusive(busyOp, body) {
667
+ return this.#lock.run(() => {
668
+ if (busyOp !== null && this.#disposed)
669
+ return Promise.reject(new TranscribeError("session has been disposed"));
670
+ if (busyOp !== null && this.#lock.streamActive)
671
+ return Promise.reject(busyError(busyOp));
672
+ return body(this.#call);
673
+ });
674
+ }
675
+ #call = (kind, signal, fn, ...args) => {
676
+ const cancel = this.#installAbort(signal);
677
+ this.#inFlight = kind;
678
+ return callAsync(fn, ...args).finally(() => {
679
+ if (this.#inFlight === kind)
680
+ this.#inFlight = null;
681
+ cancel?.();
682
+ });
683
+ };
684
+ /**
685
+ * Wire an AbortSignal to a native abort callback for one run. The callback is
686
+ * installed on *this session's* handle, but install/run/uninstall is only safe
687
+ * because every caller holds the model-wide #lock for the whole run — the lock,
688
+ * not the per-session handle, is what guarantees no run overlaps the window
689
+ * between setAbort(cb) and setAbort(null). A future change that relaxes the
690
+ * lock must keep this install/uninstall paired within one run.
691
+ */
692
+ #installAbort(signal) {
693
+ if (!signal)
694
+ return null;
695
+ const n = this.#n;
696
+ const flag = { aborted: signal.aborted };
697
+ const onAbort = () => {
698
+ flag.aborted = true;
699
+ };
700
+ signal.addEventListener("abort", onAbort, { once: true });
701
+ const cbPtr = n.koffi.register(() => flag.aborted, n.koffi.pointer(n.abortProto));
702
+ const h = this.#h; // still valid at cleanup: a mid-run dispose frees behind the lock
703
+ this.#setAbort(h, cbPtr, null);
704
+ return () => {
705
+ this.#setAbort(h, null, null);
706
+ n.koffi.unregister(cbPtr);
707
+ signal.removeEventListener("abort", onAbort);
708
+ };
709
+ }
710
+ /**
711
+ * Mark disposed now (use-after-dispose throws immediately) and free the
712
+ * native handle behind the model lock: a worker may still hold it, and a
713
+ * free mid-call is a use-after-free. Queuing on the FIFO lock runs the free
714
+ * (then `after`) once any in-flight and queued compute drains.
715
+ */
716
+ dispose(free, after) {
717
+ this.#disposed = true;
718
+ const h = this.#h;
719
+ this.#h = null;
720
+ deferFree(this.#lock, () => free(h), after);
721
+ }
722
+ }
571
723
  // ---- Session ---------------------------------------------------------------
572
724
  export class Session {
573
725
  #n;
574
- #h;
726
+ #core;
575
727
  #model; // keep the model alive while this session lives
576
728
  #lock; // shared with the model; serializes compute model-wide
577
729
  #untrack; // drop self from the model's session set
578
- #inFlight = null; // set while a native call runs on a worker
579
730
  #activeStream = null; // current wrapper for the session's native stream slot
580
- #disposed = false;
581
731
  /** @internal */
582
732
  constructor(n, model, handle, lock, untrack) {
583
733
  this.#n = n;
584
734
  this.#model = model;
585
- this.#h = handle;
735
+ this.#core = new SessionCore(n, handle, lock, n.F.setAbortCallback);
586
736
  this.#lock = lock;
587
737
  this.#untrack = untrack;
588
738
  SESSION_CONTROL.set(this, {
589
- enterCompute: (kind) => {
590
- this.#inFlight = kind;
591
- },
592
- leaveCompute: (kind) => {
593
- if (this.#inFlight === kind)
594
- this.#inFlight = null;
595
- },
596
- currentCompute: () => this.#inFlight,
739
+ core: this.#core,
597
740
  isCurrentStream: (stream) => this.#activeStream === stream,
598
741
  replaceCurrentStream: (stream) => {
599
742
  if (this.#activeStream && this.#activeStream !== stream) {
@@ -609,18 +752,10 @@ export class Session {
609
752
  }
610
753
  /** @internal */
611
754
  get handle() {
612
- if (this.#disposed)
613
- throw new TranscribeError("session has been disposed");
614
- return this.#h;
615
- }
616
- /** Reads touch the session; forbidden while a worker call is in flight. */
617
- #assertNotComputing(what) {
618
- if (this.#inFlight) {
619
- throw new TranscribeError(`cannot read session ${what} while ${this.#inFlight} is in flight; await it first`);
620
- }
755
+ return this.#core.handle;
621
756
  }
622
757
  get limits() {
623
- this.#assertNotComputing("limits");
758
+ this.#core.assertNotComputing("session limits");
624
759
  const n = this.#n;
625
760
  const l = {};
626
761
  n.F.sessionLimitsInit(l);
@@ -642,21 +777,8 @@ export class Session {
642
777
  const h = this.handle;
643
778
  const samples = toFloat32(pcm);
644
779
  const p = this.#buildRunParams(opts);
645
- return this.#lock.run(async () => {
646
- if (this.#disposed)
647
- throw new TranscribeError("session has been disposed");
648
- if (this.#lock.streamActive)
649
- throw busyError("run");
650
- const cancel = this.#installAbort(opts.signal);
651
- let status;
652
- this.#inFlight = "run()";
653
- try {
654
- status = await callAsync(F.run, h, samples, samples.length, p);
655
- }
656
- finally {
657
- this.#inFlight = null;
658
- cancel?.();
659
- }
780
+ return this.#core.exclusive("run", async (call) => {
781
+ const status = await call("run()", opts.signal, F.run, h, samples, samples.length, p);
660
782
  if (status === g.TRANSCRIBE_ERR_ABORTED ||
661
783
  status === g.TRANSCRIBE_ERR_OUTPUT_TRUNCATED ||
662
784
  status === g.TRANSCRIBE_ERR_OUTPUT_REPETITION) {
@@ -685,6 +807,16 @@ export class Session {
685
807
  const n = this.#n;
686
808
  const p = {};
687
809
  n.F.runParamsInit(p);
810
+ try {
811
+ this.#fillRunParams(n, p, opts);
812
+ }
813
+ catch (e) {
814
+ freeRunParams(n, p); // the caller never gets p, so free what was allocated
815
+ throw e;
816
+ }
817
+ return p;
818
+ }
819
+ #fillRunParams(n, p, opts) {
688
820
  p.task = lookup(TASKS, opts.task ?? "transcribe", "task");
689
821
  // Default "auto" mirrors the C transcribe_run_params_init default:
690
822
  // whisper resolves it to "segment" (its robust path), no-timestamp
@@ -701,8 +833,6 @@ export class Session {
701
833
  p.keep_special_tags = opts.keepSpecialTags;
702
834
  if (opts.specKDrafts !== undefined)
703
835
  p.spec_k_drafts = opts.specKDrafts;
704
- if (opts.family)
705
- p.family = buildFamily(n, this.#model.handle, opts.family, "run");
706
836
  if (opts.vocabulary !== undefined) {
707
837
  const terms = opts.vocabulary;
708
838
  if (!Array.isArray(terms) || !terms.every((t) => typeof t === "string"))
@@ -721,7 +851,8 @@ export class Session {
721
851
  p.prompt = cstr(opts.prompt, "prompt");
722
852
  if (opts.prefix !== undefined)
723
853
  p.prefix = cstr(opts.prefix, "prefix");
724
- return p;
854
+ if (opts.family)
855
+ p.family = buildFamily(n, this.#model.handle, opts.family, "run");
725
856
  }
726
857
  /**
727
858
  * Offline batch transcription; each item carries its own success/failure.
@@ -737,21 +868,8 @@ export class Session {
737
868
  const arrays = pcms.map(toFloat32);
738
869
  const counts = Int32Array.from(arrays, (a) => a.length);
739
870
  const p = this.#buildRunParams(opts);
740
- return this.#lock.run(async () => {
741
- if (this.#disposed)
742
- throw new TranscribeError("session has been disposed");
743
- if (this.#lock.streamActive)
744
- throw busyError("runBatch");
745
- const cancel = this.#installAbort(opts.signal);
746
- let status;
747
- this.#inFlight = "runBatch()";
748
- try {
749
- status = await callAsync(F.runBatch, h, arrays, counts, arrays.length, p);
750
- }
751
- finally {
752
- this.#inFlight = null;
753
- cancel?.();
754
- }
871
+ return this.#core.exclusive("runBatch", async (call) => {
872
+ const status = await call("runBatch()", opts.signal, F.runBatch, h, arrays, counts, arrays.length, p);
755
873
  // A batch returns OK even with per-utterance failures; only a top-level
756
874
  // error (or a whole-batch abort) is fatal here.
757
875
  if (status !== g.TRANSCRIBE_OK && status !== g.TRANSCRIBE_ERR_ABORTED) {
@@ -809,19 +927,20 @@ export class Session {
809
927
  });
810
928
  const sp = {};
811
929
  F.streamParamsInit(sp);
812
- sp.commit_policy = lookup(COMMIT_POLICIES, opts.commitPolicy ?? "auto", "commitPolicy");
813
- if (opts.stablePrefixAgreementN !== undefined) {
814
- sp.stable_prefix_agreement_n = opts.stablePrefixAgreementN;
930
+ try {
931
+ sp.commit_policy = lookup(COMMIT_POLICIES, opts.commitPolicy ?? "auto", "commitPolicy");
932
+ if (opts.stablePrefixAgreementN !== undefined) {
933
+ sp.stable_prefix_agreement_n = opts.stablePrefixAgreementN;
934
+ }
935
+ if (opts.family)
936
+ sp.family = buildFamily(n, this.#model.handle, opts.family, "stream");
815
937
  }
816
- if (opts.family)
817
- sp.family = buildFamily(n, this.#model.handle, opts.family, "stream");
818
- return this.#lock.run(async () => {
819
- // Recheck inside the lock: dispose() may have run after we captured `h`
820
- // but before this queued body — don't begin a stream on a dead session.
821
- if (this.#disposed)
822
- throw new TranscribeError("session has been disposed");
823
- if (this.#lock.streamActive)
824
- throw busyError("begin a stream");
938
+ catch (e) {
939
+ freeRunParams(n, rp); // sp holds nothing yet: buildFamily frees on throw
940
+ throw e;
941
+ }
942
+ // Begin is a synchronous native call, so no in-flight window (no call()).
943
+ return this.#core.exclusive("begin a stream", async () => {
825
944
  check(n, F.streamBegin(h, rp, sp), "transcribe_stream_begin");
826
945
  this.#lock.streamActive = true; // claim the lease for the whole stream lifetime
827
946
  // The Stream holds the Session (not a raw handle) so its calls fail fast
@@ -832,41 +951,19 @@ export class Session {
832
951
  throw new TranscribeError("session control is missing");
833
952
  control.replaceCurrentStream(stream);
834
953
  return stream;
835
- }).finally(() => freeRunParams(n, rp)); // begin copied the prompting strings
836
- }
837
- /**
838
- * Wire an AbortSignal to a native abort callback for one run. The callback is
839
- * installed on *this session's* handle, but install/run/uninstall is only safe
840
- * because every caller holds the model-wide #lock for the whole run — the lock,
841
- * not the per-session handle, is what guarantees no run overlaps the window
842
- * between setAbortCallback(cb) and setAbortCallback(null). A future change that
843
- * relaxes the lock must keep this install/uninstall paired within one run.
844
- */
845
- #installAbort(signal) {
846
- if (!signal)
847
- return null;
848
- const n = this.#n;
849
- const flag = { aborted: signal.aborted };
850
- const onAbort = () => {
851
- flag.aborted = true;
852
- };
853
- signal.addEventListener("abort", onAbort, { once: true });
854
- const cbPtr = n.koffi.register(() => flag.aborted, n.koffi.pointer(n.abortProto));
855
- n.F.setAbortCallback(this.handle, cbPtr, null);
856
- return () => {
857
- n.F.setAbortCallback(this.handle, null, null);
858
- n.koffi.unregister(cbPtr);
859
- signal.removeEventListener("abort", onAbort);
860
- };
954
+ }).finally(() => {
955
+ // begin copied the prompting strings and the family extension
956
+ freeRunParams(n, rp);
957
+ freeRunParams(n, sp);
958
+ });
861
959
  }
862
960
  get wasAborted() {
863
- this.#assertNotComputing("wasAborted");
961
+ this.#core.assertNotComputing("session wasAborted");
864
962
  return this.#n.F.wasAborted(this.handle);
865
963
  }
866
964
  dispose() {
867
- if (this.#disposed)
965
+ if (this.#core.disposed)
868
966
  return;
869
- this.#disposed = true;
870
967
  this.#untrack(this); // stop the model from holding a dead session
871
968
  // Deactivate any live stream NOW (its reset() no-ops, reads throw via the
872
969
  // disposed handle), but release its model lease only inside the deferred
@@ -876,15 +973,7 @@ export class Session {
876
973
  this.#activeStream = null;
877
974
  const teardown = stream ? STREAM_TEARDOWN.get(stream) : undefined;
878
975
  teardown?.deactivate();
879
- // Free behind the model lock: a run/feed worker may still hold this handle,
880
- // and sessionFree mid-call is a use-after-free. Queuing on the FIFO lock
881
- // runs the free after any in-flight (and queued) compute drains. The JS-side
882
- // guard is already synchronous (#disposed/handle), so use-after-dispose
883
- // still throws immediately; only the native free + lease release are deferred.
884
- const n = this.#n;
885
- const h = this.#h;
886
- this.#h = null;
887
- deferFree(this.#lock, () => n.F.sessionFree(h), () => teardown?.releaseLease());
976
+ this.#core.dispose(this.#n.F.sessionFree, () => teardown?.releaseLease());
888
977
  }
889
978
  [Symbol.dispose]() {
890
979
  this.dispose();
@@ -956,28 +1045,17 @@ export class Stream {
956
1045
  if (!this.#active)
957
1046
  throw new TranscribeError("stream has been reset");
958
1047
  const samples = toFloat32(pcm);
959
- return this.#lock.run(async () => {
1048
+ return this.#sessionControl.core.exclusive(null, async (call) => {
960
1049
  const u = {};
961
1050
  n.F.streamUpdateInit(u);
962
- // The native feed runs on a libuv worker. While it is in flight the
963
- // session must not be touched from the main thread — the C session API
964
- // is single-threaded (transcribe.h), and stream_get_text hands back
965
- // pointers the feed may free/realloc. Flag the owning session so every
966
- // result getter fails fast instead of racing into a use-after-free.
967
- this.#sessionControl.enterCompute("feed()/finalize()");
968
- try {
969
- const status = await callAsync(n.F.streamFeed, h, samples, samples.length, u);
970
- if (status !== g.TRANSCRIBE_OK) {
971
- // Native feed failures leave the stream in FAILED, which is no longer
972
- // an active stream in the C API. Keep the wrapper readable for
973
- // state/lastStatus, but free the model-wide compute slot.
974
- this.#releaseLease();
975
- }
976
- check(n, status, "transcribe_stream_feed");
977
- }
978
- finally {
979
- this.#sessionControl.leaveCompute("feed()/finalize()");
980
- }
1051
+ const status = await call("feed()/finalize()", undefined, n.F.streamFeed, h, samples, samples.length, u);
1052
+ // The lease follows the native stream: a feed refused before the family
1053
+ // hook (e.g. non-finite samples) leaves it ACTIVE, so keep the lease
1054
+ // (siblings stay Busy); a hook failure moves it to FAILED, no longer
1055
+ // active, so free the model-wide slot (state/lastStatus stay readable).
1056
+ if (status !== g.TRANSCRIBE_OK && n.F.streamGetState(h) !== g.TRANSCRIBE_STREAM_ACTIVE)
1057
+ this.#releaseLease();
1058
+ check(n, status, "transcribe_stream_feed");
981
1059
  return toStreamUpdate(u);
982
1060
  });
983
1061
  }
@@ -988,15 +1066,14 @@ export class Stream {
988
1066
  this.#assertCurrent("finalize stream");
989
1067
  if (!this.#active)
990
1068
  throw new TranscribeError("stream has been reset");
991
- return this.#lock.run(async () => {
1069
+ return this.#sessionControl.core.exclusive(null, async (call) => {
992
1070
  const u = {};
993
1071
  n.F.streamUpdateInit(u);
994
- this.#sessionControl.enterCompute("feed()/finalize()");
995
1072
  try {
996
- check(n, await callAsync(n.F.streamFinalize, h, u), "transcribe_stream_finalize");
1073
+ const status = await call("feed()/finalize()", undefined, n.F.streamFinalize, h, u);
1074
+ check(n, status, "transcribe_stream_finalize");
997
1075
  }
998
1076
  finally {
999
- this.#sessionControl.leaveCompute("feed()/finalize()");
1000
1077
  // Finalize ends the active stream (FINISHED on success, FAILED on
1001
1078
  // error), so the model is free again — release the lease either way.
1002
1079
  this.#releaseLease();
@@ -1004,22 +1081,11 @@ export class Stream {
1004
1081
  return toStreamUpdate(u);
1005
1082
  });
1006
1083
  }
1007
- /**
1008
- * Reads borrow session-owned snapshot memory, so they are forbidden while
1009
- * any worker call is computing on this session (concurrent use is undefined
1010
- * per transcribe.h). The natural await-then-read pattern is unaffected.
1011
- */
1012
- #assertNotComputing(what) {
1013
- const compute = this.#sessionControl.currentCompute();
1014
- if (compute) {
1015
- throw new TranscribeError(`cannot read stream ${what} while ${compute} is in flight; await it first`);
1016
- }
1017
- }
1018
1084
  /** Current text snapshot (copied at the boundary). */
1019
1085
  get text() {
1020
1086
  const h = this.#session.handle; // throws if the session was disposed
1021
1087
  this.#assertCurrent("read stream text");
1022
- this.#assertNotComputing("text");
1088
+ this.#sessionControl.core.assertNotComputing("stream text");
1023
1089
  const n = this.#n;
1024
1090
  const t = {};
1025
1091
  n.F.streamTextInit(t);
@@ -1036,7 +1102,7 @@ export class Stream {
1036
1102
  this.#assertCurrent("read stream snapshot");
1037
1103
  if (!this.#active)
1038
1104
  throw new TranscribeError("stream has been reset");
1039
- this.#assertNotComputing("snapshot");
1105
+ this.#sessionControl.core.assertNotComputing("stream snapshot");
1040
1106
  return materialize(this.#n, singleAccessors(this.#n, h));
1041
1107
  }
1042
1108
  get state() {
@@ -1044,13 +1110,13 @@ export class Stream {
1044
1110
  this.#assertCurrent("read stream state");
1045
1111
  if (!this.#active)
1046
1112
  return "idle"; // reset() returns to idle; native reset may still be queued
1047
- this.#assertNotComputing("state");
1113
+ this.#sessionControl.core.assertNotComputing("stream state");
1048
1114
  return STREAM_STATES[this.#n.F.streamGetState(h)] ?? "idle";
1049
1115
  }
1050
1116
  get revision() {
1051
1117
  const h = this.#session.handle; // throws if the session was disposed
1052
1118
  this.#assertCurrent("read stream revision");
1053
- this.#assertNotComputing("revision");
1119
+ this.#sessionControl.core.assertNotComputing("stream revision");
1054
1120
  return this.#n.F.streamRevision(h);
1055
1121
  }
1056
1122
  /**
@@ -1061,7 +1127,7 @@ export class Stream {
1061
1127
  get lastStatus() {
1062
1128
  const h = this.#session.handle; // throws if the session was disposed
1063
1129
  this.#assertCurrent("read stream lastStatus");
1064
- this.#assertNotComputing("lastStatus");
1130
+ this.#sessionControl.core.assertNotComputing("stream lastStatus");
1065
1131
  const n = this.#n;
1066
1132
  const status = n.F.streamLastStatus(h);
1067
1133
  if (status === g.TRANSCRIBE_OK)
@@ -1095,6 +1161,266 @@ export class Stream {
1095
1161
  this.reset();
1096
1162
  }
1097
1163
  }
1164
+ // ---- DiarizeSession --------------------------------------------------------
1165
+ /** A DIARIZE-role session: who spoke when. Same compute rules as Session. */
1166
+ export class DiarizeSession {
1167
+ #n;
1168
+ #core;
1169
+ #model; // keep the model alive while this session lives
1170
+ #untrack;
1171
+ /** @internal */
1172
+ constructor(n, model, handle, lock, untrack) {
1173
+ this.#n = n;
1174
+ this.#model = model;
1175
+ this.#core = new SessionCore(n, handle, lock, n.F.diarizeSetAbortCallback);
1176
+ this.#untrack = untrack;
1177
+ }
1178
+ /**
1179
+ * Diarize one recording; returns its speaker turns, grouped by speaker and
1180
+ * time-ordered within a speaker (turns of different speakers may overlap).
1181
+ * The input PCM is borrowed, not copied (see Session.run).
1182
+ */
1183
+ async run(pcm, opts = {}) {
1184
+ const n = this.#n;
1185
+ const F = n.F;
1186
+ const h = this.#core.handle;
1187
+ const samples = toFloat32(pcm);
1188
+ const p = {};
1189
+ F.diarizeParamsInit(p);
1190
+ if (opts.family)
1191
+ p.family = buildFamily(n, this.#model.handle, opts.family, "diarize_run");
1192
+ return this.#core.exclusive("diarize", async (call) => {
1193
+ const status = await call("run()", opts.signal, F.diarizeRun, h, samples, samples.length, p);
1194
+ check(n, status, "transcribe_diarize_run");
1195
+ return readSpeakerSegments(n, F.diarizeNSegments(h), (i, o) => F.diarizeGetSegment(h, i, o));
1196
+ }).finally(() => freeRunParams(n, p));
1197
+ }
1198
+ /** load_ms plus the last run's mel / encode time. */
1199
+ get timings() {
1200
+ this.#core.assertNotComputing("session timings");
1201
+ const h = this.#core.handle;
1202
+ return readTimings(this.#n, (o) => this.#n.F.diarizeGetTimings(h, o));
1203
+ }
1204
+ dispose() {
1205
+ if (this.#core.disposed)
1206
+ return;
1207
+ this.#untrack(this);
1208
+ this.#core.dispose(this.#n.F.diarizeSessionFree);
1209
+ }
1210
+ [Symbol.dispose]() {
1211
+ this.dispose();
1212
+ }
1213
+ }
1214
+ // ---- LangIdSession ---------------------------------------------------------
1215
+ /** A LANGID-role session: which language is spoken. Same compute rules as Session. */
1216
+ export class LangIdSession {
1217
+ #n;
1218
+ #core;
1219
+ #model; // keep the model alive while this session lives
1220
+ #untrack;
1221
+ /** @internal */
1222
+ constructor(n, model, handle, lock, untrack) {
1223
+ this.#n = n;
1224
+ this.#model = model;
1225
+ this.#core = new SessionCore(n, handle, lock, n.F.langidSetAbortCallback);
1226
+ this.#untrack = untrack;
1227
+ }
1228
+ /**
1229
+ * Identify the language of one clip; input longer than langidInfo.maxAudioMs
1230
+ * is scored on its first maxAudioMs. The input PCM is borrowed, not copied
1231
+ * (see Session.run).
1232
+ */
1233
+ async run(pcm, opts = {}) {
1234
+ const n = this.#n;
1235
+ const F = n.F;
1236
+ const h = this.#core.handle;
1237
+ const samples = toFloat32(pcm);
1238
+ const p = {};
1239
+ F.langidParamsInit(p);
1240
+ if (opts.allowed !== undefined && opts.allowed !== null) {
1241
+ const codes = opts.allowed;
1242
+ if (!Array.isArray(codes) || !codes.every((c) => typeof c === "string"))
1243
+ throw new InvalidArgument("allowed must be an array of strings");
1244
+ // NULL would mean "every label", the opposite of an empty list.
1245
+ if (codes.length === 0)
1246
+ throw new InvalidArgument("allowed is empty; omit it for every label");
1247
+ codes.forEach((c) => cstr(c, "allowed"));
1248
+ // Freed after the call returns (including async worker calls).
1249
+ const type = n.koffi.array("char *", codes.length);
1250
+ const arr = n.koffi.alloc(type, 1);
1251
+ n.koffi.encode(arr, type, codes);
1252
+ p.allowed = arr;
1253
+ p.n_allowed = codes.length;
1254
+ }
1255
+ return this.#core.exclusive("langid", async (call) => {
1256
+ const status = await call("run()", opts.signal, F.langidRun, h, samples, samples.length, p);
1257
+ check(n, status, "transcribe_langid_run");
1258
+ const res = {};
1259
+ F.langidResultInit(res);
1260
+ check(n, F.langidGetResult(h, res), "transcribe_langid_get_result");
1261
+ const candidates = [];
1262
+ for (let i = 0; i < res.n_candidates; i++) {
1263
+ const c = {};
1264
+ F.langidCandidateInit(c);
1265
+ check(n, F.langidGetCandidate(h, i, c), "transcribe_langid_get_candidate");
1266
+ candidates.push({
1267
+ index: c.index,
1268
+ code: c.code ?? "",
1269
+ name: c.name ?? "",
1270
+ p: c.p,
1271
+ logit: c.logit,
1272
+ });
1273
+ }
1274
+ return {
1275
+ candidates,
1276
+ code: candidates.length > 0 ? candidates[0].code : null,
1277
+ allowedMass: res.allowed_mass,
1278
+ };
1279
+ }).finally(() => {
1280
+ if (p.allowed) {
1281
+ n.koffi.free(p.allowed);
1282
+ p.allowed = null;
1283
+ }
1284
+ });
1285
+ }
1286
+ /** load_ms plus the last run's mel / encode time. */
1287
+ get timings() {
1288
+ this.#core.assertNotComputing("session timings");
1289
+ const h = this.#core.handle;
1290
+ return readTimings(this.#n, (o) => this.#n.F.langidGetTimings(h, o));
1291
+ }
1292
+ dispose() {
1293
+ if (this.#core.disposed)
1294
+ return;
1295
+ this.#untrack(this);
1296
+ this.#core.dispose(this.#n.F.langidSessionFree);
1297
+ }
1298
+ [Symbol.dispose]() {
1299
+ this.dispose();
1300
+ }
1301
+ }
1302
+ // ---- VadSession ------------------------------------------------------------
1303
+ // Copy the last call's probabilities and segments out of the session; call
1304
+ // inside exclusive(), since the next compute replaces them.
1305
+ function readVadResult(n, h) {
1306
+ const F = n.F;
1307
+ const res = {};
1308
+ F.vadResultInit(res);
1309
+ check(n, F.vadGetResult(h, res), "transcribe_vad_get_result");
1310
+ const ptr = res.n_probs > 0 ? F.vadProbs(h) : null;
1311
+ if (res.n_probs > 0 && !ptr)
1312
+ throw new TranscribeError("vad result has probabilities but no buffer");
1313
+ const probs = ptr ? Array.from(n.koffi.decode(ptr, "float", res.n_probs)) : [];
1314
+ const segments = [];
1315
+ for (let i = 0; i < res.n_segments; i++) {
1316
+ const s = {};
1317
+ F.vadSegmentInit(s);
1318
+ check(n, F.vadGetSegment(h, i, s), "transcribe_vad_get_segment");
1319
+ segments.push({ startSample: num(s.start_sample), endSample: num(s.end_sample) });
1320
+ }
1321
+ return { probs, firstFrame: num(res.first_frame), segments };
1322
+ }
1323
+ /**
1324
+ * A VAD-role session: where there is speech. Same compute rules as Session,
1325
+ * except a VAD stream is session state and does not take the stream lease.
1326
+ */
1327
+ export class VadSession {
1328
+ #n;
1329
+ #core;
1330
+ #model; // keep the model alive while this session lives
1331
+ #untrack;
1332
+ /** @internal */
1333
+ constructor(n, model, handle, lock, untrack) {
1334
+ this.#n = n;
1335
+ this.#model = model;
1336
+ this.#core = new SessionCore(n, handle, lock, n.F.vadSetAbortCallback);
1337
+ this.#untrack = untrack;
1338
+ }
1339
+ /**
1340
+ * Score one clip from a fresh state and segment it (resets any stream in
1341
+ * progress). The input PCM is borrowed, not copied (see Session.run).
1342
+ */
1343
+ async run(pcm, opts = {}) {
1344
+ const n = this.#n;
1345
+ const F = n.F;
1346
+ const h = this.#core.handle;
1347
+ const samples = toFloat32(pcm);
1348
+ const p = {};
1349
+ F.vadParamsInit(p);
1350
+ if (opts.threshold !== undefined)
1351
+ p.threshold = opts.threshold;
1352
+ if (opts.negThreshold !== undefined)
1353
+ p.neg_threshold = opts.negThreshold;
1354
+ if (opts.minSpeechMs !== undefined)
1355
+ p.min_speech_ms = opts.minSpeechMs;
1356
+ if (opts.minSilenceMs !== undefined)
1357
+ p.min_silence_ms = opts.minSilenceMs;
1358
+ if (opts.speechPadMs !== undefined)
1359
+ p.speech_pad_ms = opts.speechPadMs;
1360
+ if (opts.maxSpeechMs !== undefined)
1361
+ p.max_speech_ms = opts.maxSpeechMs;
1362
+ return this.#core.exclusive("run VAD", async (call) => {
1363
+ const status = await call("run()", opts.signal, F.vadRun, h, samples, samples.length, p);
1364
+ check(n, status, "transcribe_vad_run");
1365
+ return readVadResult(n, h);
1366
+ });
1367
+ }
1368
+ /**
1369
+ * Append audio to the stream and score every frame it completes; returns
1370
+ * those frames' probabilities (a partial frame waits for the next feed).
1371
+ * The chunk is borrowed, not copied (see Stream.feed); an empty chunk scores
1372
+ * nothing. An abort or processing error resets the stream (the next feed's
1373
+ * firstFrame is 0); invalid input leaves it unchanged.
1374
+ */
1375
+ async streamFeed(pcm, opts = {}) {
1376
+ const n = this.#n;
1377
+ const h = this.#core.handle;
1378
+ const samples = asFloat32(pcm);
1379
+ return this.#core.exclusive("feed the VAD stream", async (call) => {
1380
+ const status = await call("streamFeed()", opts.signal, n.F.vadStreamFeed, h, samples.length > 0 ? samples : null, samples.length);
1381
+ check(n, status, "transcribe_vad_stream_feed");
1382
+ return readVadResult(n, h);
1383
+ });
1384
+ }
1385
+ /**
1386
+ * End the stream: score the buffered partial frame (zero padded) and reset,
1387
+ * so the next feed's firstFrame is 0. A processing error also resets it.
1388
+ */
1389
+ async streamFlush(opts = {}) {
1390
+ const n = this.#n;
1391
+ const h = this.#core.handle;
1392
+ return this.#core.exclusive("flush the VAD stream", async (call) => {
1393
+ const status = await call("streamFlush()", opts.signal, n.F.vadStreamFlush, h);
1394
+ check(n, status, "transcribe_vad_stream_flush");
1395
+ return readVadResult(n, h);
1396
+ });
1397
+ }
1398
+ /**
1399
+ * Drop the stream without scoring (the next feed's firstFrame is 0); queued
1400
+ * behind any in-flight call.
1401
+ */
1402
+ async streamReset() {
1403
+ const h = this.#core.handle;
1404
+ return this.#core.exclusive(null, async () => {
1405
+ this.#n.F.vadStreamReset(h);
1406
+ });
1407
+ }
1408
+ /** load_ms plus the last call's encode / decode time. */
1409
+ get timings() {
1410
+ this.#core.assertNotComputing("session timings");
1411
+ const h = this.#core.handle;
1412
+ return readTimings(this.#n, (o) => this.#n.F.vadGetTimings(h, o));
1413
+ }
1414
+ dispose() {
1415
+ if (this.#core.disposed)
1416
+ return;
1417
+ this.#untrack(this);
1418
+ this.#core.dispose(this.#n.F.vadSessionFree);
1419
+ }
1420
+ [Symbol.dispose]() {
1421
+ this.dispose();
1422
+ }
1423
+ }
1098
1424
  // ---- Model -----------------------------------------------------------------
1099
1425
  export class TranscribeModel {
1100
1426
  #n;
@@ -1111,8 +1437,9 @@ export class TranscribeModel {
1111
1437
  LIVE_MODELS.add(this);
1112
1438
  ensureExitHook();
1113
1439
  }
1440
+ /** Load a GGUF model. Awaits {@link initialize}, so it never blocks the event loop. */
1114
1441
  static async load(path, opts = {}) {
1115
- const n = native();
1442
+ const n = await nativeAsync();
1116
1443
  const p = {};
1117
1444
  n.F.modelLoadParamsInit(p);
1118
1445
  if ("gpuDevice" in opts) {
@@ -1168,6 +1495,99 @@ export class TranscribeModel {
1168
1495
  session.dispose(); // untracks itself from #sessions
1169
1496
  }
1170
1497
  }
1498
+ /** The roles this model serves; ASR calls on a model without "asr" throw UnsupportedRole. */
1499
+ get roles() {
1500
+ const mask = this.#n.F.modelRoles(this.handle);
1501
+ return Object.keys(ROLES).filter((r) => mask & ROLES[r]);
1502
+ }
1503
+ /** Static facts of a "diarize" model; UnsupportedRole otherwise. */
1504
+ get diarizeInfo() {
1505
+ const n = this.#n;
1506
+ const info = {};
1507
+ n.F.diarizeInfoInit(info);
1508
+ check(n, n.F.diarizeGetInfo(this.handle, info), "reading diarize info");
1509
+ return { sampleRate: info.sample_rate, maxSpeakers: info.max_speakers };
1510
+ }
1511
+ /** Open a DIARIZE-role session; UnsupportedRole on a model without "diarize". */
1512
+ createDiarizeSession(opts = {}) {
1513
+ const n = this.#n;
1514
+ const p = {};
1515
+ n.F.diarizeSessionParamsInit(p);
1516
+ if (opts.nThreads !== undefined)
1517
+ p.n_threads = opts.nThreads;
1518
+ const out = [null];
1519
+ check(n, n.F.diarizeSessionInit(this.handle, p, out), "opening diarize session");
1520
+ if (!out[0])
1521
+ throw new TranscribeError("diarize session init returned a null handle");
1522
+ const session = new DiarizeSession(n, this, out[0], this.#lock, (s) => this.#sessions.delete(s));
1523
+ this.#sessions.add(session);
1524
+ return session;
1525
+ }
1526
+ /** Static facts of a "langid" model; UnsupportedRole otherwise. */
1527
+ get langidInfo() {
1528
+ const n = this.#n;
1529
+ const info = {};
1530
+ n.F.langidInfoInit(info);
1531
+ check(n, n.F.langidGetInfo(this.handle, info), "reading langid info");
1532
+ return {
1533
+ sampleRate: info.sample_rate,
1534
+ nLabels: info.n_labels,
1535
+ minAudioMs: info.min_audio_ms,
1536
+ maxAudioMs: info.max_audio_ms,
1537
+ };
1538
+ }
1539
+ /** [code, name] per label index of a "langid" model; UnsupportedRole otherwise. */
1540
+ get langidLabels() {
1541
+ const n = this.langidInfo.nLabels;
1542
+ const F = this.#n.F;
1543
+ const out = [];
1544
+ for (let i = 0; i < n; i++)
1545
+ out.push([F.langidLabelCode(this.handle, i) ?? "", F.langidLabelName(this.handle, i) ?? ""]);
1546
+ return out;
1547
+ }
1548
+ /** Label index of a code or alias ("he" and "iw" name the same label), or null. */
1549
+ langidLabelIndex(code) {
1550
+ const i = this.#n.F.langidLabelIndex(this.handle, cstr(code, "code"));
1551
+ return i >= 0 ? i : null;
1552
+ }
1553
+ /** Open a LANGID-role session; UnsupportedRole on a model without "langid". */
1554
+ createLangIdSession(opts = {}) {
1555
+ const n = this.#n;
1556
+ const p = {};
1557
+ n.F.langidSessionParamsInit(p);
1558
+ if (opts.nThreads !== undefined)
1559
+ p.n_threads = opts.nThreads;
1560
+ const out = [null];
1561
+ check(n, n.F.langidSessionInit(this.handle, p, out), "opening langid session");
1562
+ if (!out[0])
1563
+ throw new TranscribeError("langid session init returned a null handle");
1564
+ const session = new LangIdSession(n, this, out[0], this.#lock, (s) => this.#sessions.delete(s));
1565
+ this.#sessions.add(session);
1566
+ return session;
1567
+ }
1568
+ /** Static facts of a "vad" model; UnsupportedRole otherwise. */
1569
+ get vadInfo() {
1570
+ const n = this.#n;
1571
+ const info = {};
1572
+ n.F.vadInfoInit(info);
1573
+ check(n, n.F.vadGetInfo(this.handle, info), "reading vad info");
1574
+ return { sampleRate: info.sample_rate, frameSamples: info.frame_samples };
1575
+ }
1576
+ /** Open a VAD-role session; UnsupportedRole on a model without "vad". */
1577
+ createVadSession(opts = {}) {
1578
+ const n = this.#n;
1579
+ const p = {};
1580
+ n.F.vadSessionParamsInit(p);
1581
+ if (opts.nThreads !== undefined)
1582
+ p.n_threads = opts.nThreads;
1583
+ const out = [null];
1584
+ check(n, n.F.vadSessionInit(this.handle, p, out), "opening vad session");
1585
+ if (!out[0])
1586
+ throw new TranscribeError("vad session init returned a null handle");
1587
+ const session = new VadSession(n, this, out[0], this.#lock, (s) => this.#sessions.delete(s));
1588
+ this.#sessions.add(session);
1589
+ return session;
1590
+ }
1171
1591
  get capabilities() {
1172
1592
  const n = this.#n;
1173
1593
  const c = {};