assemblyai 4.33.3 → 4.34.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.
Files changed (38) hide show
  1. package/dist/assemblyai.streaming.umd.js +1279 -3
  2. package/dist/assemblyai.streaming.umd.min.js +1 -1
  3. package/dist/assemblyai.umd.js +786 -3
  4. package/dist/assemblyai.umd.min.js +1 -1
  5. package/dist/browser.mjs +762 -4
  6. package/dist/bun.mjs +762 -4
  7. package/dist/deno.mjs +762 -4
  8. package/dist/exports/streaming.d.ts +7 -0
  9. package/dist/index.cjs +786 -3
  10. package/dist/index.mjs +778 -4
  11. package/dist/node.cjs +770 -3
  12. package/dist/node.mjs +762 -4
  13. package/dist/services/index.d.ts +2 -2
  14. package/dist/services/streaming/browser/dual-channel-capture.d.ts +66 -0
  15. package/dist/services/streaming/browser/worklets/pcm16-encoder.d.ts +19 -0
  16. package/dist/services/streaming/energy-vad.d.ts +35 -0
  17. package/dist/services/streaming/index.d.ts +4 -0
  18. package/dist/services/streaming/label-mapper.d.ts +44 -0
  19. package/dist/services/streaming/resampler.d.ts +22 -0
  20. package/dist/services/streaming/service.d.ts +69 -1
  21. package/dist/streaming.browser.mjs +1235 -4
  22. package/dist/streaming.cjs +1275 -3
  23. package/dist/streaming.mjs +1264 -4
  24. package/dist/types/streaming/dual-channel.d.ts +48 -0
  25. package/dist/types/streaming/index.d.ts +110 -1
  26. package/dist/workerd.mjs +762 -4
  27. package/package.json +1 -1
  28. package/src/exports/streaming.ts +7 -0
  29. package/src/services/index.ts +20 -1
  30. package/src/services/streaming/browser/dual-channel-capture.ts +177 -0
  31. package/src/services/streaming/browser/worklets/pcm16-encoder.ts +70 -0
  32. package/src/services/streaming/energy-vad.ts +75 -0
  33. package/src/services/streaming/index.ts +4 -0
  34. package/src/services/streaming/label-mapper.ts +128 -0
  35. package/src/services/streaming/resampler.ts +69 -0
  36. package/src/services/streaming/service.ts +385 -2
  37. package/src/types/streaming/dual-channel.ts +57 -0
  38. package/src/types/streaming/index.ts +110 -0
package/dist/browser.mjs CHANGED
@@ -1,3 +1,16 @@
1
+ /**
2
+ * Thrown when `DualChannelCapture` is constructed in a non-browser environment
3
+ * (no `globalThis.AudioContext`). The helper is intentionally surfaced from the
4
+ * main entrypoint so the import path is uniform across runtimes; the runtime
5
+ * guard moves to construction time.
6
+ */
7
+ class BrowserOnlyError extends Error {
8
+ constructor(message = "DualChannelCapture requires a browser environment (AudioContext is undefined).") {
9
+ super(message);
10
+ this.name = "BrowserOnlyError";
11
+ }
12
+ }
13
+
1
14
  const DEFAULT_FETCH_INIT = {
2
15
  cache: "no-store",
3
16
  };
@@ -15,7 +28,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
15
28
  defaultUserAgentString += navigator.userAgent;
16
29
  }
17
30
  const defaultUserAgent = {
18
- sdk: { name: "JavaScript", version: "4.33.3" },
31
+ sdk: { name: "JavaScript", version: "4.34.0" },
19
32
  };
20
33
  if (typeof process !== "undefined") {
21
34
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -801,11 +814,216 @@ function dataUrlToBlob(dataUrl) {
801
814
  return new Blob([u8arr], { type: mime });
802
815
  }
803
816
 
817
+ /**
818
+ * Energy-based VAD with adaptive noise-floor tracking and hangover. Pure JS,
819
+ * no dependencies. Suitable for the "which physical channel is speaking" task
820
+ * because the channels are already physically separated at capture — the harder
821
+ * problem (speech vs. non-speech in the wild) is one a customer can swap in a
822
+ * DNN VAD for via the `createVad` parameter.
823
+ *
824
+ * Tuning notes:
825
+ * - thresholdRatio below 2 will treat anything above noise as speech (too sensitive).
826
+ * - thresholdRatio above 6 will miss quiet utterance onsets/offsets.
827
+ * - noiseFloorAlpha above 0.1 makes the floor track quickly (good for non-stationary
828
+ * background) but risks slowly adapting *up* to a sustained low voice.
829
+ */
830
+ class EnergyVad {
831
+ constructor(params = {}) {
832
+ this.hangoverRemaining = 0;
833
+ this.thresholdRatio = params.thresholdRatio ?? 3.0;
834
+ this.noiseFloorAlpha = params.noiseFloorAlpha ?? 0.05;
835
+ this.hangoverFrames = params.hangoverFrames ?? 10;
836
+ this.initialNoiseFloor = params.initialNoiseFloor ?? 1e-4;
837
+ this.noiseFloor = this.initialNoiseFloor;
838
+ }
839
+ process(frame) {
840
+ let sumSq = 0;
841
+ for (let i = 0; i < frame.length; i++) {
842
+ sumSq += frame[i] * frame[i];
843
+ }
844
+ const rms = frame.length > 0 ? Math.sqrt(sumSq / frame.length) : 0;
845
+ const threshold = this.noiseFloor * this.thresholdRatio;
846
+ let active = rms > threshold;
847
+ if (active) {
848
+ this.hangoverRemaining = this.hangoverFrames;
849
+ }
850
+ else if (this.hangoverRemaining > 0) {
851
+ this.hangoverRemaining--;
852
+ active = true;
853
+ // While in hangover, do not update noise floor — RMS may still reflect tail energy.
854
+ }
855
+ else {
856
+ this.noiseFloor =
857
+ this.noiseFloor * (1 - this.noiseFloorAlpha) +
858
+ rms * this.noiseFloorAlpha;
859
+ }
860
+ return { active, energy: rms };
861
+ }
862
+ reset() {
863
+ this.noiseFloor = this.initialNoiseFloor;
864
+ this.hangoverRemaining = 0;
865
+ }
866
+ }
867
+
868
+ /**
869
+ * Append-only ring buffer of VAD frames in stream-relative ms order.
870
+ * `pushFrame` is O(1) amortized; `framesInWindow` is O(n) over kept frames,
871
+ * which is fine for the per-word lookups we do (a 30 s window at 50 frames/s
872
+ * per channel × 2 channels = 3000 entries, scanned once per word).
873
+ *
874
+ * Runtime-agnostic — no DOM or Web Audio dependencies.
875
+ */
876
+ class VadTimeline {
877
+ constructor(windowMs) {
878
+ this.windowMs = windowMs;
879
+ this.frames = [];
880
+ this.head = 0;
881
+ }
882
+ pushFrame(frame) {
883
+ this.frames.push(frame);
884
+ const cutoff = frame.ts - this.windowMs;
885
+ while (this.head < this.frames.length &&
886
+ this.frames[this.head].ts < cutoff) {
887
+ this.head++;
888
+ }
889
+ if (this.head > 1024 && this.head * 2 > this.frames.length) {
890
+ this.frames = this.frames.slice(this.head);
891
+ this.head = 0;
892
+ }
893
+ }
894
+ framesInWindow(startMs, endMs) {
895
+ const out = [];
896
+ for (let i = this.head; i < this.frames.length; i++) {
897
+ const f = this.frames[i];
898
+ if (f.ts < startMs)
899
+ continue;
900
+ if (f.ts > endMs)
901
+ break;
902
+ out.push(f);
903
+ }
904
+ return out;
905
+ }
906
+ clear() {
907
+ this.frames = [];
908
+ this.head = 0;
909
+ }
910
+ }
911
+ /**
912
+ * Sum per-channel active RMS over a window. Returns a Map from channel name
913
+ * to total score. Channels with zero score are omitted.
914
+ */
915
+ function scoreChannels(frames) {
916
+ const scores = new Map();
917
+ for (const f of frames) {
918
+ if (!f.active)
919
+ continue;
920
+ scores.set(f.channel, (scores.get(f.channel) ?? 0) + f.rms);
921
+ }
922
+ return scores;
923
+ }
924
+ /**
925
+ * Decide which channel was dominant during a word's `[start, end]` window.
926
+ *
927
+ * - If no channel has any active VAD energy → `"unknown"`.
928
+ * - If the top channel beats the runner-up by at least `dominanceRatio` → top channel.
929
+ * - Else: top channel wins on absolute score; exact ties → `"unknown"`.
930
+ */
931
+ function attributeWord(word, timeline, params) {
932
+ const scores = scoreChannels(timeline.framesInWindow(word.start, word.end));
933
+ if (scores.size === 0)
934
+ return "unknown";
935
+ const sorted = [...scores.entries()].sort((a, b) => b[1] - a[1]);
936
+ if (sorted.length === 1)
937
+ return sorted[0][0];
938
+ const [topName, topScore] = sorted[0];
939
+ const [runnerName, runnerScore] = sorted[1];
940
+ if (topScore >= params.dominanceRatio * runnerScore)
941
+ return topName;
942
+ if (topScore > runnerScore)
943
+ return topName;
944
+ if (runnerScore > topScore)
945
+ return runnerName;
946
+ return "unknown";
947
+ }
948
+ /**
949
+ * Duration-weighted majority of word channels. `"unknown"` if there are no
950
+ * words, every word resolved to `"unknown"`, or two channels tie exactly.
951
+ */
952
+ function rollUpTurnChannel(words) {
953
+ const totals = new Map();
954
+ for (const w of words) {
955
+ if (!w.channel || w.channel === "unknown")
956
+ continue;
957
+ const dur = Math.max(0, w.end - w.start);
958
+ totals.set(w.channel, (totals.get(w.channel) ?? 0) + dur);
959
+ }
960
+ if (totals.size === 0)
961
+ return "unknown";
962
+ const sorted = [...totals.entries()].sort((a, b) => b[1] - a[1]);
963
+ if (sorted.length === 1)
964
+ return sorted[0][0];
965
+ const [topName, topMs] = sorted[0];
966
+ const [, runnerMs] = sorted[1];
967
+ if (topMs === runnerMs)
968
+ return "unknown";
969
+ return topName;
970
+ }
971
+ /**
972
+ * Mutate `turn` in place: write `turn.words[i].channel` for every word and set
973
+ * `turn.channel` to the duration-weighted rollup.
974
+ *
975
+ * Returns `void` because the transcriber owns the `TurnEvent` ref and forwards
976
+ * the same object to the customer listener — no need to allocate a copy.
977
+ */
978
+ function attributeTurn(turn, timeline, params) {
979
+ for (const w of turn.words) {
980
+ w.channel = attributeWord(w, timeline, params);
981
+ }
982
+ turn.channel = rollUpTurnChannel(turn.words);
983
+ }
984
+
985
+ /**
986
+ * View any `AudioData` (ArrayBuffer / ArrayBufferView / typed array) as a
987
+ * little-endian Int16 sample sequence without copying. Callers must guarantee
988
+ * the underlying byte length is even.
989
+ */
990
+ function toInt16View(audio) {
991
+ // AudioData is ArrayBufferLike per the public type, but in practice callers
992
+ // pass ArrayBuffer or a typed-array view. Handle both without copying.
993
+ if (audio instanceof Int16Array)
994
+ return audio;
995
+ if (ArrayBuffer.isView(audio)) {
996
+ const view = audio;
997
+ return new Int16Array(view.buffer, view.byteOffset, Math.floor(view.byteLength / 2));
998
+ }
999
+ return new Int16Array(audio);
1000
+ }
804
1001
  const defaultStreamingUrl$1 = "wss://streaming.assemblyai.com/v3/ws";
805
1002
  const terminateSessionMessage = `{"type":"Terminate"}`;
1003
+ /**
1004
+ * Per-send chunk cap in milliseconds for the dual-channel mixer. The streaming
1005
+ * server rejects audio messages longer than 1000 ms (`Input Duration Error`).
1006
+ * If a backlog accumulates (e.g. when a browser tab is backgrounded and
1007
+ * `setInterval` is throttled to ~1 Hz), `flushMix` loops and emits multiple
1008
+ * sends each ≤ this cap until the buffers drain.
1009
+ */
1010
+ const MAX_CHUNK_MS = 200;
1011
+ /**
1012
+ * Per-send minimum chunk size in milliseconds. The streaming server also
1013
+ * rejects audio messages shorter than 50 ms with the same
1014
+ * `Input Duration Error`, so the mixer waits until both per-channel buffers
1015
+ * have at least this much accumulated before emitting. Final-flush (close
1016
+ * path) bypasses this floor so the trailing partial buffer still gets sent.
1017
+ */
1018
+ const MIN_CHUNK_MS = 50;
806
1019
  class StreamingTranscriber {
807
1020
  constructor(params) {
808
1021
  this.listeners = {};
1022
+ // Dual-channel mode state (allocated only when params.channels is set).
1023
+ this.isDualChannel = false;
1024
+ this.vadFrameSamples = 0;
1025
+ this.minChunkSamples = 0;
1026
+ this.maxChunkSamples = 0;
809
1027
  this.params = {
810
1028
  ...params,
811
1029
  websocketBaseUrl: params.websocketBaseUrl || defaultStreamingUrl$1,
@@ -817,6 +1035,42 @@ class StreamingTranscriber {
817
1035
  if (!(this.token || this.apiKey)) {
818
1036
  throw new Error("API key or temporary token is required.");
819
1037
  }
1038
+ if (params.channels) {
1039
+ if (params.channels.length !== 2) {
1040
+ throw new Error("StreamingTranscriber.channels must have exactly 2 entries.");
1041
+ }
1042
+ const names = params.channels.map((c) => c.name);
1043
+ if (new Set(names).size !== names.length) {
1044
+ throw new Error("StreamingTranscriber.channels names must be unique.");
1045
+ }
1046
+ this.isDualChannel = true;
1047
+ this.channelNames = names;
1048
+ const att = params.channelAttribution ?? {};
1049
+ this.attributionParams = {
1050
+ dominanceRatio: att.dominanceRatio ?? 4,
1051
+ timelineWindowMs: att.timelineWindowMs ?? 30_000,
1052
+ createVad: att.createVad ?? (() => new EnergyVad()),
1053
+ flushIntervalMs: att.flushIntervalMs ?? 50,
1054
+ resolveUnknownChannelsMethod: att.resolveUnknownChannelsMethod ?? "window",
1055
+ resolutionWindowWords: att.resolutionWindowWords ?? 2,
1056
+ speakerHistoryMinRmsEvidence: att.speakerHistoryMinRmsEvidence ?? 0.5,
1057
+ speakerHistoryDominanceRatio: att.speakerHistoryDominanceRatio ?? 3,
1058
+ };
1059
+ if (this.attributionParams.resolveUnknownChannelsMethod ===
1060
+ "speaker-history") {
1061
+ this.speakerHistory = new Map();
1062
+ }
1063
+ // 20 ms VAD frames at the transcriber's target sample rate.
1064
+ this.vadFrameSamples = Math.max(1, Math.round(params.sampleRate * 0.02));
1065
+ this.minChunkSamples = Math.max(1, Math.round(params.sampleRate * (MIN_CHUNK_MS / 1000)));
1066
+ this.maxChunkSamples = Math.max(this.minChunkSamples, Math.round(params.sampleRate * (MAX_CHUNK_MS / 1000)));
1067
+ this.channelBuffers = new Map(names.map((n) => [n, []]));
1068
+ this.channelSamplesReceived = new Map(names.map((n) => [n, 0]));
1069
+ this.channelVadFloatBuffers = new Map(names.map((n) => [n, new Float32Array(this.vadFrameSamples)]));
1070
+ this.channelVadBufferIdx = new Map(names.map((n) => [n, 0]));
1071
+ this.channelVads = new Map(names.map((n) => [n, this.attributionParams.createVad(n)]));
1072
+ this.timeline = new VadTimeline(this.attributionParams.timelineWindowMs);
1073
+ }
820
1074
  }
821
1075
  connectionUrl() {
822
1076
  const url = new URL(this.params.websocketBaseUrl ?? "");
@@ -969,6 +1223,13 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
969
1223
  reason = StreamingErrorMessages[code];
970
1224
  }
971
1225
  }
1226
+ // Stop the flush timer when the socket is gone (server-initiated close,
1227
+ // network drop, etc.) — otherwise subsequent ticks call send() on a
1228
+ // closed socket and spam the error listener.
1229
+ if (this.flushTimer) {
1230
+ clearInterval(this.flushTimer);
1231
+ this.flushTimer = undefined;
1232
+ }
972
1233
  this.listeners.close?.(code, reason);
973
1234
  };
974
1235
  this.socket.onerror = (event) => {
@@ -995,6 +1256,19 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
995
1256
  break;
996
1257
  }
997
1258
  case "Turn": {
1259
+ if (this.isDualChannel && this.timeline && this.attributionParams) {
1260
+ attributeTurn(message, this.timeline, {
1261
+ dominanceRatio: this.attributionParams.dominanceRatio,
1262
+ });
1263
+ switch (this.attributionParams.resolveUnknownChannelsMethod) {
1264
+ case "window":
1265
+ this.resolveUnknownChannelsByWindow(message);
1266
+ break;
1267
+ case "speaker-history":
1268
+ this.resolveUnknownChannelsBySpeakerHistory(message);
1269
+ break;
1270
+ }
1271
+ }
998
1272
  this.listeners.turn?.(message);
999
1273
  break;
1000
1274
  }
@@ -1020,6 +1294,11 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1020
1294
  };
1021
1295
  });
1022
1296
  }
1297
+ /**
1298
+ * Returns a WritableStream that pumps PCM chunks into `sendAudio`. Single-channel
1299
+ * only — in dual-channel mode use `sendAudio(pcm, { channel })` directly, since
1300
+ * `WritableStream` has no place to carry a channel tag.
1301
+ */
1023
1302
  stream() {
1024
1303
  return new WritableStream({
1025
1304
  write: (chunk) => {
@@ -1027,8 +1306,235 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1027
1306
  },
1028
1307
  });
1029
1308
  }
1030
- sendAudio(audio) {
1031
- this.send(audio);
1309
+ /**
1310
+ * Send PCM audio.
1311
+ *
1312
+ * In single-channel mode, `audio` is forwarded directly to the WebSocket and
1313
+ * `options` is ignored.
1314
+ *
1315
+ * In dual-channel mode (when `channels` is configured), `options.channel` is
1316
+ * REQUIRED and must match one of the declared channel names. Per-channel PCM is
1317
+ * fed into that channel's VAD, accumulated into a per-channel ring buffer, and
1318
+ * a scheduled flush (`channelAttribution.flushIntervalMs`, default 50ms) mixes
1319
+ * the buffers into mono before sending to the WebSocket.
1320
+ */
1321
+ sendAudio(audio, options) {
1322
+ if (!this.isDualChannel) {
1323
+ this.send(audio);
1324
+ return;
1325
+ }
1326
+ if (!options?.channel) {
1327
+ throw new Error("StreamingTranscriber is in dual-channel mode; sendAudio requires { channel }.");
1328
+ }
1329
+ if (!this.channelNames.includes(options.channel)) {
1330
+ throw new Error(`Unknown channel "${options.channel}"; declared channels: ${this.channelNames.join(", ")}.`);
1331
+ }
1332
+ this.ingestChannelAudio(options.channel, audio);
1333
+ }
1334
+ ingestChannelAudio(name, audio) {
1335
+ const samples = toInt16View(audio);
1336
+ const buf = this.channelBuffers.get(name);
1337
+ const vadBuf = this.channelVadFloatBuffers.get(name);
1338
+ let vadIdx = this.channelVadBufferIdx.get(name);
1339
+ let received = this.channelSamplesReceived.get(name);
1340
+ const vad = this.channelVads.get(name);
1341
+ const sampleRate = this.params.sampleRate;
1342
+ const frameSize = this.vadFrameSamples;
1343
+ for (let i = 0; i < samples.length; i++) {
1344
+ const s = samples[i];
1345
+ buf.push(s);
1346
+ vadBuf[vadIdx++] = s / 0x8000;
1347
+ received++;
1348
+ if (vadIdx === frameSize) {
1349
+ const result = vad.process(vadBuf);
1350
+ const frame = {
1351
+ ts: (received / sampleRate) * 1000,
1352
+ channel: name,
1353
+ active: result.active,
1354
+ rms: result.energy,
1355
+ };
1356
+ this.timeline.pushFrame(frame);
1357
+ this.listeners.vad?.(frame);
1358
+ vadIdx = 0;
1359
+ }
1360
+ }
1361
+ this.channelVadBufferIdx.set(name, vadIdx);
1362
+ this.channelSamplesReceived.set(name, received);
1363
+ if (!this.flushTimer)
1364
+ this.startFlushTimer();
1365
+ }
1366
+ startFlushTimer() {
1367
+ this.flushTimer = setInterval(() => this.flushMix(), this.attributionParams.flushIntervalMs);
1368
+ }
1369
+ flushMix(force = false) {
1370
+ if (!this.channelNames || !this.channelBuffers)
1371
+ return;
1372
+ const bufs = this.channelNames.map((n) => this.channelBuffers.get(n));
1373
+ const divisor = bufs.length;
1374
+ // Loop so a backlog (e.g. accumulated while a browser tab was throttled in
1375
+ // the background) drains as multiple sends, each capped at MAX_CHUNK_MS.
1376
+ // Without the cap a single message could exceed the server's 1000 ms input
1377
+ // duration limit and be rejected with code 3007.
1378
+ for (;;) {
1379
+ let mixLen = Infinity;
1380
+ for (const b of bufs)
1381
+ if (b.length < mixLen)
1382
+ mixLen = b.length;
1383
+ if (!Number.isFinite(mixLen) || mixLen === 0)
1384
+ return;
1385
+ // The streaming server rejects audio messages shorter than 50 ms with
1386
+ // `Input Duration Error`. Wait until both per-channel buffers have at
1387
+ // least minChunkSamples worth queued before emitting. The `force` path
1388
+ // (final flush on close) bypasses this so the trailing partial buffer
1389
+ // still gets through.
1390
+ if (!force && mixLen < this.minChunkSamples)
1391
+ return;
1392
+ if (mixLen > this.maxChunkSamples)
1393
+ mixLen = this.maxChunkSamples;
1394
+ const out = new Int16Array(mixLen);
1395
+ for (let i = 0; i < mixLen; i++) {
1396
+ let sum = 0;
1397
+ for (let c = 0; c < divisor; c++)
1398
+ sum += bufs[c][i];
1399
+ const avg = Math.round(sum / divisor);
1400
+ out[i] = avg < -32768 ? -32768 : avg > 32767 ? 32767 : avg;
1401
+ }
1402
+ for (const b of bufs)
1403
+ b.splice(0, mixLen);
1404
+ try {
1405
+ this.send(out.buffer);
1406
+ }
1407
+ catch (err) {
1408
+ this.listeners.error?.(err);
1409
+ return;
1410
+ }
1411
+ }
1412
+ }
1413
+ /**
1414
+ * Fill in words whose per-word VAD attribution was `"unknown"` by looking
1415
+ * at the dominant non-`"unknown"` channel among ±N neighbors in the same
1416
+ * turn. Words with no non-`"unknown"` neighbors stay `"unknown"`. Confident
1417
+ * per-word VAD decisions are never modified.
1418
+ *
1419
+ * Local temporal heuristic — ignores `speaker_label`, so it works even when
1420
+ * AAI's diarization re-uses the same label for two physically distinct
1421
+ * voices. Each resolved word gets `channelResolved: true` so downstream
1422
+ * renderers can distinguish inferred channels from directly-measured ones.
1423
+ */
1424
+ resolveUnknownChannelsByWindow(turn) {
1425
+ if (!this.attributionParams)
1426
+ return;
1427
+ const window = this.attributionParams.resolutionWindowWords;
1428
+ const words = turn.words;
1429
+ let mutated = false;
1430
+ for (let i = 0; i < words.length; i++) {
1431
+ if (words[i].channel !== "unknown")
1432
+ continue;
1433
+ const tally = new Map();
1434
+ const lo = Math.max(0, i - window);
1435
+ const hi = Math.min(words.length - 1, i + window);
1436
+ for (let j = lo; j <= hi; j++) {
1437
+ if (j === i)
1438
+ continue;
1439
+ const ch = words[j].channel;
1440
+ if (!ch || ch === "unknown")
1441
+ continue;
1442
+ tally.set(ch, (tally.get(ch) ?? 0) + 1);
1443
+ }
1444
+ if (tally.size === 0)
1445
+ continue;
1446
+ // Pick the dominant neighbor channel. Ties → leave `"unknown"` (rare;
1447
+ // would require an equal count of mic and system neighbors).
1448
+ let top;
1449
+ let topCount = 0;
1450
+ let tied = false;
1451
+ for (const [name, count] of tally) {
1452
+ if (count > topCount) {
1453
+ top = name;
1454
+ topCount = count;
1455
+ tied = false;
1456
+ }
1457
+ else if (count === topCount) {
1458
+ tied = true;
1459
+ }
1460
+ }
1461
+ if (top && !tied) {
1462
+ words[i].channel = top;
1463
+ words[i].channelResolved = true;
1464
+ mutated = true;
1465
+ }
1466
+ }
1467
+ // Recompute the rollup only if any per-word channel changed.
1468
+ if (mutated)
1469
+ turn.channel = rollUpTurnChannel(words);
1470
+ }
1471
+ /**
1472
+ * Fill `"unknown"` words by looking up the speaker's session-wide channel
1473
+ * evidence. For each `speaker_label`, sums active VAD frame RMS per channel
1474
+ * across every word the speaker has uttered to date. A speaker is
1475
+ * "resolvable" if their total evidence clears
1476
+ * `speakerHistoryMinRmsEvidence` and their top channel exceeds the
1477
+ * runner-up by `speakerHistoryDominanceRatio`.
1478
+ *
1479
+ * Only touches `"unknown"` words. Confident per-word VAD decisions are
1480
+ * never modified. `speaker_label` is never modified.
1481
+ */
1482
+ resolveUnknownChannelsBySpeakerHistory(turn) {
1483
+ if (!this.timeline || !this.attributionParams || !this.speakerHistory)
1484
+ return;
1485
+ const minEvidence = this.attributionParams.speakerHistoryMinRmsEvidence;
1486
+ const dominanceRatio = this.attributionParams.speakerHistoryDominanceRatio;
1487
+ // 1. Accumulate evidence from this turn's words.
1488
+ for (const w of turn.words) {
1489
+ if (!w.speaker)
1490
+ continue;
1491
+ const frames = this.timeline.framesInWindow(w.start, w.end);
1492
+ let entry = this.speakerHistory.get(w.speaker);
1493
+ if (!entry) {
1494
+ entry = new Map();
1495
+ this.speakerHistory.set(w.speaker, entry);
1496
+ }
1497
+ for (const f of frames) {
1498
+ if (!f.active)
1499
+ continue;
1500
+ entry.set(f.channel, (entry.get(f.channel) ?? 0) + f.rms);
1501
+ }
1502
+ }
1503
+ // 2. Fill unknown words whose speakers have dominant evidence.
1504
+ let mutated = false;
1505
+ for (const w of turn.words) {
1506
+ if (w.channel !== "unknown" || !w.speaker)
1507
+ continue;
1508
+ const entry = this.speakerHistory.get(w.speaker);
1509
+ if (!entry || entry.size === 0)
1510
+ continue;
1511
+ let total = 0;
1512
+ let topName;
1513
+ let topScore = 0;
1514
+ let runnerScore = 0;
1515
+ for (const [name, score] of entry) {
1516
+ total += score;
1517
+ if (score > topScore) {
1518
+ runnerScore = topScore;
1519
+ topScore = score;
1520
+ topName = name;
1521
+ }
1522
+ else if (score > runnerScore) {
1523
+ runnerScore = score;
1524
+ }
1525
+ }
1526
+ if (total < minEvidence)
1527
+ continue;
1528
+ if (runnerScore > 0 && topScore < dominanceRatio * runnerScore)
1529
+ continue;
1530
+ if (topName) {
1531
+ w.channel = topName;
1532
+ w.channelResolved = true;
1533
+ mutated = true;
1534
+ }
1535
+ }
1536
+ if (mutated)
1537
+ turn.channel = rollUpTurnChannel(turn.words);
1032
1538
  }
1033
1539
  /**
1034
1540
  * Update the streaming configuration mid-stream.
@@ -1068,6 +1574,15 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1068
1574
  this.socket.send(data);
1069
1575
  }
1070
1576
  async close(waitForSessionTermination = true) {
1577
+ if (this.flushTimer) {
1578
+ clearInterval(this.flushTimer);
1579
+ this.flushTimer = undefined;
1580
+ // Best-effort: drain any final partial mix so the server gets the tail.
1581
+ // Bypass the 50ms floor here since this is the last flush; if the tail
1582
+ // is <50ms the server will reject that single message, but we'd lose
1583
+ // the audio either way.
1584
+ this.flushMix(true);
1585
+ }
1071
1586
  if (this.socket) {
1072
1587
  if (this.socket.readyState === this.socket.OPEN) {
1073
1588
  if (waitForSessionTermination) {
@@ -1119,6 +1634,249 @@ class StreamingTranscriberFactory extends BaseService {
1119
1634
  }
1120
1635
  }
1121
1636
 
1637
+ /**
1638
+ * AudioWorklet processor that ingests mono Float32 audio at the AudioContext's
1639
+ * native sample rate, resamples to `targetRate` (linear interpolation, stateful
1640
+ * across `process()` calls), packs to little-endian Int16 PCM, and posts
1641
+ * fixed-size chunks via `port.postMessage` with a running `samplesSent` counter.
1642
+ *
1643
+ * `samplesSent` is in **target-rate samples**, so the main thread can derive a
1644
+ * stream-relative timestamp = `samplesSent / targetRate * 1000` (ms) — the same
1645
+ * frame AAI uses for `StreamingWord.start` / `.end`.
1646
+ *
1647
+ * Defined as a string so it can be registered via a Blob URL — the SDK ships as
1648
+ * a single ESM file, so a separate `.js` worklet asset isn't viable.
1649
+ */
1650
+ const pcm16EncoderWorkletSource = `
1651
+ class Pcm16EncoderProcessor extends AudioWorkletProcessor {
1652
+ constructor(options) {
1653
+ super();
1654
+ const opts = (options && options.processorOptions) || {};
1655
+ this.targetRate = opts.targetRate || 16000;
1656
+ this.chunkMs = opts.chunkMs || 50;
1657
+ this.ratio = sampleRate / this.targetRate;
1658
+ this.chunkSize = Math.round(this.targetRate * this.chunkMs / 1000);
1659
+ this.buffer = new Int16Array(this.chunkSize);
1660
+ this.bufferIdx = 0;
1661
+ this.samplesSent = 0;
1662
+ this.lastSample = 0;
1663
+ this.fractional = 0;
1664
+ }
1665
+
1666
+ process(inputs) {
1667
+ const input = inputs[0];
1668
+ if (!input || input.length === 0 || !input[0] || input[0].length === 0) {
1669
+ return true;
1670
+ }
1671
+ const mono = input[0];
1672
+ let pos = this.fractional;
1673
+ while (pos < mono.length) {
1674
+ const i = Math.floor(pos);
1675
+ const frac = pos - i;
1676
+ const a = i === 0 ? this.lastSample : mono[i - 1];
1677
+ const b = mono[i];
1678
+ const sample = a + (b - a) * frac;
1679
+ const clamped = sample < -1 ? -1 : sample > 1 ? 1 : sample;
1680
+ this.buffer[this.bufferIdx++] = clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff;
1681
+ if (this.bufferIdx === this.chunkSize) {
1682
+ const out = new Int16Array(this.chunkSize);
1683
+ out.set(this.buffer);
1684
+ this.samplesSent += this.chunkSize;
1685
+ this.port.postMessage(
1686
+ { pcm: out.buffer, samplesSent: this.samplesSent },
1687
+ [out.buffer],
1688
+ );
1689
+ this.bufferIdx = 0;
1690
+ }
1691
+ pos += this.ratio;
1692
+ }
1693
+ this.lastSample = mono[mono.length - 1];
1694
+ this.fractional = pos - mono.length;
1695
+ return true;
1696
+ }
1697
+ }
1698
+ registerProcessor("aai-pcm16-encoder", Pcm16EncoderProcessor);
1699
+ `;
1700
+ const PCM16_ENCODER_PROCESSOR_NAME = "aai-pcm16-encoder";
1701
+
1702
+ const DEFAULT_TARGET_RATE = 16_000;
1703
+ const DEFAULT_CHUNK_MS = 50;
1704
+ const MIC_CHANNEL = "mic";
1705
+ const SYSTEM_CHANNEL = "system";
1706
+ /**
1707
+ * Browser-only adapter that pumps two `MediaStream`s into a `StreamingTranscriber`
1708
+ * configured for dual-channel mode. Each `MediaStream` runs through its own
1709
+ * `pcm16-encoder` AudioWorklet (resample to `targetSampleRate`, encode to Int16
1710
+ * PCM); each PCM chunk is forwarded via `transcriber.sendAudio(pcm, { channel })`.
1711
+ *
1712
+ * All dual-channel orchestration (mixing, VAD, per-word attribution) lives inside
1713
+ * `StreamingTranscriber` — this class is a pure I/O adapter. Non-browser runtimes
1714
+ * can replicate its job by pushing tagged PCM into `transcriber.sendAudio` directly.
1715
+ *
1716
+ * Caller responsibilities:
1717
+ * - **Echo cancellation** is set at `getUserMedia` time (`audio: { echoCancellation: true }`).
1718
+ * - **System-audio capture** is platform-dependent. Chrome's `getDisplayMedia({ audio: true })`
1719
+ * captures tab audio (and on Windows, full system audio when sharing the whole screen).
1720
+ * macOS requires a virtual loopback driver (e.g. BlackHole) to expose system audio at all.
1721
+ * - **Token auth.** Construct the transcriber with `token` — API-key auth is unsupported in browsers.
1722
+ * - **Stream ownership.** `stop()` tears down the AudioContext but does NOT stop the
1723
+ * `MediaStreamTrack`s passed in — callers own those.
1724
+ */
1725
+ class DualChannelCapture {
1726
+ constructor(params) {
1727
+ this.running = false;
1728
+ if (typeof globalThis.AudioContext === "undefined") {
1729
+ throw new BrowserOnlyError();
1730
+ }
1731
+ this.params = {
1732
+ micStream: params.micStream,
1733
+ systemStream: params.systemStream,
1734
+ transcriber: params.transcriber,
1735
+ targetSampleRate: params.targetSampleRate ?? DEFAULT_TARGET_RATE,
1736
+ };
1737
+ }
1738
+ on(event, listener) {
1739
+ if (event === "error")
1740
+ this.errorListener = listener;
1741
+ }
1742
+ /**
1743
+ * Wire the capture pipeline and start pumping tagged PCM into the transcriber.
1744
+ * The transcriber must already be connected. Returns once the worklet is
1745
+ * registered and the audio graph is live.
1746
+ */
1747
+ async start() {
1748
+ if (this.running) {
1749
+ throw new Error("DualChannelCapture already started");
1750
+ }
1751
+ this.context = new AudioContext();
1752
+ const blob = new Blob([pcm16EncoderWorkletSource], {
1753
+ type: "application/javascript",
1754
+ });
1755
+ const url = URL.createObjectURL(blob);
1756
+ try {
1757
+ await this.context.audioWorklet.addModule(url);
1758
+ }
1759
+ finally {
1760
+ URL.revokeObjectURL(url);
1761
+ }
1762
+ this.micSource = this.context.createMediaStreamSource(this.params.micStream);
1763
+ this.sysSource = this.context.createMediaStreamSource(this.params.systemStream);
1764
+ this.micEncoder = this.makeEncoder(MIC_CHANNEL);
1765
+ this.sysEncoder = this.makeEncoder(SYSTEM_CHANNEL);
1766
+ this.micSource.connect(this.micEncoder);
1767
+ this.sysSource.connect(this.sysEncoder);
1768
+ this.running = true;
1769
+ }
1770
+ makeEncoder(channel) {
1771
+ const node = new AudioWorkletNode(this.context, PCM16_ENCODER_PROCESSOR_NAME, {
1772
+ numberOfInputs: 1,
1773
+ numberOfOutputs: 0,
1774
+ channelCount: 1,
1775
+ channelCountMode: "explicit",
1776
+ channelInterpretation: "speakers",
1777
+ processorOptions: {
1778
+ targetRate: this.params.targetSampleRate,
1779
+ chunkMs: DEFAULT_CHUNK_MS,
1780
+ },
1781
+ });
1782
+ node.port.onmessage = (e) => {
1783
+ try {
1784
+ this.params.transcriber.sendAudio(e.data.pcm, { channel });
1785
+ }
1786
+ catch (err) {
1787
+ this.errorListener?.(err);
1788
+ }
1789
+ };
1790
+ return node;
1791
+ }
1792
+ /**
1793
+ * Tear down internal nodes and close the AudioContext. Does NOT stop the
1794
+ * caller-provided MediaStream tracks — they remain available for preview UI,
1795
+ * recording, etc. Idempotent.
1796
+ */
1797
+ async stop() {
1798
+ if (!this.running)
1799
+ return;
1800
+ this.running = false;
1801
+ try {
1802
+ this.micEncoder?.port.close();
1803
+ this.sysEncoder?.port.close();
1804
+ this.micEncoder?.disconnect();
1805
+ this.sysEncoder?.disconnect();
1806
+ this.micSource?.disconnect();
1807
+ this.sysSource?.disconnect();
1808
+ }
1809
+ catch {
1810
+ // Disconnecting already-disconnected nodes throws in some browsers; ignore.
1811
+ }
1812
+ if (this.context && this.context.state !== "closed") {
1813
+ await this.context.close();
1814
+ }
1815
+ this.context = undefined;
1816
+ this.micSource = undefined;
1817
+ this.sysSource = undefined;
1818
+ this.micEncoder = undefined;
1819
+ this.sysEncoder = undefined;
1820
+ }
1821
+ }
1822
+
1823
+ /**
1824
+ * Linear-interpolation resampler for streaming Float32 audio. Stateful across
1825
+ * `process()` calls so chunk boundaries don't introduce phase discontinuities:
1826
+ * the last input sample and a fractional read position are carried over.
1827
+ *
1828
+ * Linear interpolation is good enough for ASR ingest — the downstream
1829
+ * StreamingTranscriber band-limits at the target rate anyway, and a polyphase
1830
+ * filter would be overkill in the AudioWorklet hot path. If a customer needs
1831
+ * higher quality they can supply their own VadDetector + bypass the encoder.
1832
+ */
1833
+ class LinearResampler {
1834
+ constructor(sourceRate, targetRate) {
1835
+ this.sourceRate = sourceRate;
1836
+ this.targetRate = targetRate;
1837
+ this.lastSample = 0;
1838
+ this.fractional = 0;
1839
+ if (sourceRate <= 0 || targetRate <= 0) {
1840
+ throw new Error("sourceRate and targetRate must be positive");
1841
+ }
1842
+ this.ratio = sourceRate / targetRate;
1843
+ }
1844
+ process(input) {
1845
+ if (this.sourceRate === this.targetRate) {
1846
+ return input;
1847
+ }
1848
+ // Worst-case output length; we'll slice to actual.
1849
+ const out = new Float32Array(Math.ceil(input.length / this.ratio) + 1);
1850
+ let outIdx = 0;
1851
+ let pos = this.fractional;
1852
+ while (pos < input.length) {
1853
+ const i = Math.floor(pos);
1854
+ const frac = pos - i;
1855
+ const a = i === 0 ? this.lastSample : input[i - 1];
1856
+ const b = input[i];
1857
+ out[outIdx++] = a + (b - a) * frac;
1858
+ pos += this.ratio;
1859
+ }
1860
+ this.lastSample = input[input.length - 1] ?? this.lastSample;
1861
+ this.fractional = pos - input.length;
1862
+ return out.subarray(0, outIdx);
1863
+ }
1864
+ reset() {
1865
+ this.lastSample = 0;
1866
+ this.fractional = 0;
1867
+ }
1868
+ }
1869
+ /** Convert Float32 PCM (-1..1) to little-endian Int16 PCM. */
1870
+ function float32ToPcm16(input) {
1871
+ const out = new ArrayBuffer(input.length * 2);
1872
+ const view = new DataView(out);
1873
+ for (let i = 0; i < input.length; i++) {
1874
+ const clamped = Math.max(-1, Math.min(1, input[i]));
1875
+ view.setInt16(i * 2, clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, true);
1876
+ }
1877
+ return out;
1878
+ }
1879
+
1122
1880
  const defaultBaseUrl = "https://api.assemblyai.com";
1123
1881
  const defaultStreamingUrl = "https://streaming.assemblyai.com";
1124
1882
  class AssemblyAI {
@@ -1142,4 +1900,4 @@ class AssemblyAI {
1142
1900
  }
1143
1901
  }
1144
1902
 
1145
- export { AssemblyAI, FileService, LemurService, RealtimeService, RealtimeServiceFactory, RealtimeTranscriber, RealtimeTranscriberFactory, StreamingTranscriber, TranscriptService };
1903
+ export { AssemblyAI, BrowserOnlyError, DualChannelCapture, EnergyVad, FileService, LemurService, LinearResampler, RealtimeService, RealtimeServiceFactory, RealtimeTranscriber, RealtimeTranscriberFactory, StreamingTranscriber, TranscriptService, VadTimeline, attributeTurn, attributeWord, float32ToPcm16, rollUpTurnChannel };