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
@@ -4,6 +4,19 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.assemblyai = {}));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
+ /**
8
+ * Thrown when `DualChannelCapture` is constructed in a non-browser environment
9
+ * (no `globalThis.AudioContext`). The helper is intentionally surfaced from the
10
+ * main entrypoint so the import path is uniform across runtimes; the runtime
11
+ * guard moves to construction time.
12
+ */
13
+ class BrowserOnlyError extends Error {
14
+ constructor(message = "DualChannelCapture requires a browser environment (AudioContext is undefined).") {
15
+ super(message);
16
+ this.name = "BrowserOnlyError";
17
+ }
18
+ }
19
+
7
20
  /******************************************************************************
8
21
  Copyright (c) Microsoft Corporation.
9
22
 
@@ -65,7 +78,7 @@
65
78
  defaultUserAgentString += navigator.userAgent;
66
79
  }
67
80
  const defaultUserAgent = {
68
- sdk: { name: "JavaScript", version: "4.33.3" },
81
+ sdk: { name: "JavaScript", version: "4.34.0" },
69
82
  };
70
83
  if (typeof process !== "undefined") {
71
84
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -888,11 +901,220 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
888
901
  return new Blob([u8arr], { type: mime });
889
902
  }
890
903
 
904
+ /**
905
+ * Energy-based VAD with adaptive noise-floor tracking and hangover. Pure JS,
906
+ * no dependencies. Suitable for the "which physical channel is speaking" task
907
+ * because the channels are already physically separated at capture — the harder
908
+ * problem (speech vs. non-speech in the wild) is one a customer can swap in a
909
+ * DNN VAD for via the `createVad` parameter.
910
+ *
911
+ * Tuning notes:
912
+ * - thresholdRatio below 2 will treat anything above noise as speech (too sensitive).
913
+ * - thresholdRatio above 6 will miss quiet utterance onsets/offsets.
914
+ * - noiseFloorAlpha above 0.1 makes the floor track quickly (good for non-stationary
915
+ * background) but risks slowly adapting *up* to a sustained low voice.
916
+ */
917
+ class EnergyVad {
918
+ constructor(params = {}) {
919
+ var _a, _b, _c, _d;
920
+ this.hangoverRemaining = 0;
921
+ this.thresholdRatio = (_a = params.thresholdRatio) !== null && _a !== void 0 ? _a : 3.0;
922
+ this.noiseFloorAlpha = (_b = params.noiseFloorAlpha) !== null && _b !== void 0 ? _b : 0.05;
923
+ this.hangoverFrames = (_c = params.hangoverFrames) !== null && _c !== void 0 ? _c : 10;
924
+ this.initialNoiseFloor = (_d = params.initialNoiseFloor) !== null && _d !== void 0 ? _d : 1e-4;
925
+ this.noiseFloor = this.initialNoiseFloor;
926
+ }
927
+ process(frame) {
928
+ let sumSq = 0;
929
+ for (let i = 0; i < frame.length; i++) {
930
+ sumSq += frame[i] * frame[i];
931
+ }
932
+ const rms = frame.length > 0 ? Math.sqrt(sumSq / frame.length) : 0;
933
+ const threshold = this.noiseFloor * this.thresholdRatio;
934
+ let active = rms > threshold;
935
+ if (active) {
936
+ this.hangoverRemaining = this.hangoverFrames;
937
+ }
938
+ else if (this.hangoverRemaining > 0) {
939
+ this.hangoverRemaining--;
940
+ active = true;
941
+ // While in hangover, do not update noise floor — RMS may still reflect tail energy.
942
+ }
943
+ else {
944
+ this.noiseFloor =
945
+ this.noiseFloor * (1 - this.noiseFloorAlpha) +
946
+ rms * this.noiseFloorAlpha;
947
+ }
948
+ return { active, energy: rms };
949
+ }
950
+ reset() {
951
+ this.noiseFloor = this.initialNoiseFloor;
952
+ this.hangoverRemaining = 0;
953
+ }
954
+ }
955
+
956
+ /**
957
+ * Append-only ring buffer of VAD frames in stream-relative ms order.
958
+ * `pushFrame` is O(1) amortized; `framesInWindow` is O(n) over kept frames,
959
+ * which is fine for the per-word lookups we do (a 30 s window at 50 frames/s
960
+ * per channel × 2 channels = 3000 entries, scanned once per word).
961
+ *
962
+ * Runtime-agnostic — no DOM or Web Audio dependencies.
963
+ */
964
+ class VadTimeline {
965
+ constructor(windowMs) {
966
+ this.windowMs = windowMs;
967
+ this.frames = [];
968
+ this.head = 0;
969
+ }
970
+ pushFrame(frame) {
971
+ this.frames.push(frame);
972
+ const cutoff = frame.ts - this.windowMs;
973
+ while (this.head < this.frames.length &&
974
+ this.frames[this.head].ts < cutoff) {
975
+ this.head++;
976
+ }
977
+ if (this.head > 1024 && this.head * 2 > this.frames.length) {
978
+ this.frames = this.frames.slice(this.head);
979
+ this.head = 0;
980
+ }
981
+ }
982
+ framesInWindow(startMs, endMs) {
983
+ const out = [];
984
+ for (let i = this.head; i < this.frames.length; i++) {
985
+ const f = this.frames[i];
986
+ if (f.ts < startMs)
987
+ continue;
988
+ if (f.ts > endMs)
989
+ break;
990
+ out.push(f);
991
+ }
992
+ return out;
993
+ }
994
+ clear() {
995
+ this.frames = [];
996
+ this.head = 0;
997
+ }
998
+ }
999
+ /**
1000
+ * Sum per-channel active RMS over a window. Returns a Map from channel name
1001
+ * to total score. Channels with zero score are omitted.
1002
+ */
1003
+ function scoreChannels(frames) {
1004
+ var _a;
1005
+ const scores = new Map();
1006
+ for (const f of frames) {
1007
+ if (!f.active)
1008
+ continue;
1009
+ scores.set(f.channel, ((_a = scores.get(f.channel)) !== null && _a !== void 0 ? _a : 0) + f.rms);
1010
+ }
1011
+ return scores;
1012
+ }
1013
+ /**
1014
+ * Decide which channel was dominant during a word's `[start, end]` window.
1015
+ *
1016
+ * - If no channel has any active VAD energy → `"unknown"`.
1017
+ * - If the top channel beats the runner-up by at least `dominanceRatio` → top channel.
1018
+ * - Else: top channel wins on absolute score; exact ties → `"unknown"`.
1019
+ */
1020
+ function attributeWord(word, timeline, params) {
1021
+ const scores = scoreChannels(timeline.framesInWindow(word.start, word.end));
1022
+ if (scores.size === 0)
1023
+ return "unknown";
1024
+ const sorted = [...scores.entries()].sort((a, b) => b[1] - a[1]);
1025
+ if (sorted.length === 1)
1026
+ return sorted[0][0];
1027
+ const [topName, topScore] = sorted[0];
1028
+ const [runnerName, runnerScore] = sorted[1];
1029
+ if (topScore >= params.dominanceRatio * runnerScore)
1030
+ return topName;
1031
+ if (topScore > runnerScore)
1032
+ return topName;
1033
+ if (runnerScore > topScore)
1034
+ return runnerName;
1035
+ return "unknown";
1036
+ }
1037
+ /**
1038
+ * Duration-weighted majority of word channels. `"unknown"` if there are no
1039
+ * words, every word resolved to `"unknown"`, or two channels tie exactly.
1040
+ */
1041
+ function rollUpTurnChannel(words) {
1042
+ var _a;
1043
+ const totals = new Map();
1044
+ for (const w of words) {
1045
+ if (!w.channel || w.channel === "unknown")
1046
+ continue;
1047
+ const dur = Math.max(0, w.end - w.start);
1048
+ totals.set(w.channel, ((_a = totals.get(w.channel)) !== null && _a !== void 0 ? _a : 0) + dur);
1049
+ }
1050
+ if (totals.size === 0)
1051
+ return "unknown";
1052
+ const sorted = [...totals.entries()].sort((a, b) => b[1] - a[1]);
1053
+ if (sorted.length === 1)
1054
+ return sorted[0][0];
1055
+ const [topName, topMs] = sorted[0];
1056
+ const [, runnerMs] = sorted[1];
1057
+ if (topMs === runnerMs)
1058
+ return "unknown";
1059
+ return topName;
1060
+ }
1061
+ /**
1062
+ * Mutate `turn` in place: write `turn.words[i].channel` for every word and set
1063
+ * `turn.channel` to the duration-weighted rollup.
1064
+ *
1065
+ * Returns `void` because the transcriber owns the `TurnEvent` ref and forwards
1066
+ * the same object to the customer listener — no need to allocate a copy.
1067
+ */
1068
+ function attributeTurn(turn, timeline, params) {
1069
+ for (const w of turn.words) {
1070
+ w.channel = attributeWord(w, timeline, params);
1071
+ }
1072
+ turn.channel = rollUpTurnChannel(turn.words);
1073
+ }
1074
+
1075
+ /**
1076
+ * View any `AudioData` (ArrayBuffer / ArrayBufferView / typed array) as a
1077
+ * little-endian Int16 sample sequence without copying. Callers must guarantee
1078
+ * the underlying byte length is even.
1079
+ */
1080
+ function toInt16View(audio) {
1081
+ // AudioData is ArrayBufferLike per the public type, but in practice callers
1082
+ // pass ArrayBuffer or a typed-array view. Handle both without copying.
1083
+ if (audio instanceof Int16Array)
1084
+ return audio;
1085
+ if (ArrayBuffer.isView(audio)) {
1086
+ const view = audio;
1087
+ return new Int16Array(view.buffer, view.byteOffset, Math.floor(view.byteLength / 2));
1088
+ }
1089
+ return new Int16Array(audio);
1090
+ }
891
1091
  const defaultStreamingUrl$1 = "wss://streaming.assemblyai.com/v3/ws";
892
1092
  const terminateSessionMessage = `{"type":"Terminate"}`;
1093
+ /**
1094
+ * Per-send chunk cap in milliseconds for the dual-channel mixer. The streaming
1095
+ * server rejects audio messages longer than 1000 ms (`Input Duration Error`).
1096
+ * If a backlog accumulates (e.g. when a browser tab is backgrounded and
1097
+ * `setInterval` is throttled to ~1 Hz), `flushMix` loops and emits multiple
1098
+ * sends each ≤ this cap until the buffers drain.
1099
+ */
1100
+ const MAX_CHUNK_MS = 200;
1101
+ /**
1102
+ * Per-send minimum chunk size in milliseconds. The streaming server also
1103
+ * rejects audio messages shorter than 50 ms with the same
1104
+ * `Input Duration Error`, so the mixer waits until both per-channel buffers
1105
+ * have at least this much accumulated before emitting. Final-flush (close
1106
+ * path) bypasses this floor so the trailing partial buffer still gets sent.
1107
+ */
1108
+ const MIN_CHUNK_MS = 50;
893
1109
  class StreamingTranscriber {
894
1110
  constructor(params) {
1111
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
895
1112
  this.listeners = {};
1113
+ // Dual-channel mode state (allocated only when params.channels is set).
1114
+ this.isDualChannel = false;
1115
+ this.vadFrameSamples = 0;
1116
+ this.minChunkSamples = 0;
1117
+ this.maxChunkSamples = 0;
896
1118
  this.params = Object.assign(Object.assign({}, params), { websocketBaseUrl: params.websocketBaseUrl || defaultStreamingUrl$1 });
897
1119
  if ("token" in params && params.token)
898
1120
  this.token = params.token;
@@ -901,6 +1123,42 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
901
1123
  if (!(this.token || this.apiKey)) {
902
1124
  throw new Error("API key or temporary token is required.");
903
1125
  }
1126
+ if (params.channels) {
1127
+ if (params.channels.length !== 2) {
1128
+ throw new Error("StreamingTranscriber.channels must have exactly 2 entries.");
1129
+ }
1130
+ const names = params.channels.map((c) => c.name);
1131
+ if (new Set(names).size !== names.length) {
1132
+ throw new Error("StreamingTranscriber.channels names must be unique.");
1133
+ }
1134
+ this.isDualChannel = true;
1135
+ this.channelNames = names;
1136
+ const att = (_a = params.channelAttribution) !== null && _a !== void 0 ? _a : {};
1137
+ this.attributionParams = {
1138
+ dominanceRatio: (_b = att.dominanceRatio) !== null && _b !== void 0 ? _b : 4,
1139
+ timelineWindowMs: (_c = att.timelineWindowMs) !== null && _c !== void 0 ? _c : 30000,
1140
+ createVad: (_d = att.createVad) !== null && _d !== void 0 ? _d : (() => new EnergyVad()),
1141
+ flushIntervalMs: (_e = att.flushIntervalMs) !== null && _e !== void 0 ? _e : 50,
1142
+ resolveUnknownChannelsMethod: (_f = att.resolveUnknownChannelsMethod) !== null && _f !== void 0 ? _f : "window",
1143
+ resolutionWindowWords: (_g = att.resolutionWindowWords) !== null && _g !== void 0 ? _g : 2,
1144
+ speakerHistoryMinRmsEvidence: (_h = att.speakerHistoryMinRmsEvidence) !== null && _h !== void 0 ? _h : 0.5,
1145
+ speakerHistoryDominanceRatio: (_j = att.speakerHistoryDominanceRatio) !== null && _j !== void 0 ? _j : 3,
1146
+ };
1147
+ if (this.attributionParams.resolveUnknownChannelsMethod ===
1148
+ "speaker-history") {
1149
+ this.speakerHistory = new Map();
1150
+ }
1151
+ // 20 ms VAD frames at the transcriber's target sample rate.
1152
+ this.vadFrameSamples = Math.max(1, Math.round(params.sampleRate * 0.02));
1153
+ this.minChunkSamples = Math.max(1, Math.round(params.sampleRate * (MIN_CHUNK_MS / 1000)));
1154
+ this.maxChunkSamples = Math.max(this.minChunkSamples, Math.round(params.sampleRate * (MAX_CHUNK_MS / 1000)));
1155
+ this.channelBuffers = new Map(names.map((n) => [n, []]));
1156
+ this.channelSamplesReceived = new Map(names.map((n) => [n, 0]));
1157
+ this.channelVadFloatBuffers = new Map(names.map((n) => [n, new Float32Array(this.vadFrameSamples)]));
1158
+ this.channelVadBufferIdx = new Map(names.map((n) => [n, 0]));
1159
+ this.channelVads = new Map(names.map((n) => [n, this.attributionParams.createVad(n)]));
1160
+ this.timeline = new VadTimeline(this.attributionParams.timelineWindowMs);
1161
+ }
904
1162
  }
905
1163
  connectionUrl() {
906
1164
  var _a, _b;
@@ -1054,6 +1312,13 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1054
1312
  reason = StreamingErrorMessages[code];
1055
1313
  }
1056
1314
  }
1315
+ // Stop the flush timer when the socket is gone (server-initiated close,
1316
+ // network drop, etc.) — otherwise subsequent ticks call send() on a
1317
+ // closed socket and spam the error listener.
1318
+ if (this.flushTimer) {
1319
+ clearInterval(this.flushTimer);
1320
+ this.flushTimer = undefined;
1321
+ }
1057
1322
  (_b = (_a = this.listeners).close) === null || _b === void 0 ? void 0 : _b.call(_a, code, reason);
1058
1323
  };
1059
1324
  this.socket.onerror = (event) => {
@@ -1082,6 +1347,19 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1082
1347
  break;
1083
1348
  }
1084
1349
  case "Turn": {
1350
+ if (this.isDualChannel && this.timeline && this.attributionParams) {
1351
+ attributeTurn(message, this.timeline, {
1352
+ dominanceRatio: this.attributionParams.dominanceRatio,
1353
+ });
1354
+ switch (this.attributionParams.resolveUnknownChannelsMethod) {
1355
+ case "window":
1356
+ this.resolveUnknownChannelsByWindow(message);
1357
+ break;
1358
+ case "speaker-history":
1359
+ this.resolveUnknownChannelsBySpeakerHistory(message);
1360
+ break;
1361
+ }
1362
+ }
1085
1363
  (_f = (_e = this.listeners).turn) === null || _f === void 0 ? void 0 : _f.call(_e, message);
1086
1364
  break;
1087
1365
  }
@@ -1107,6 +1385,11 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1107
1385
  };
1108
1386
  });
1109
1387
  }
1388
+ /**
1389
+ * Returns a WritableStream that pumps PCM chunks into `sendAudio`. Single-channel
1390
+ * only — in dual-channel mode use `sendAudio(pcm, { channel })` directly, since
1391
+ * `WritableStream` has no place to carry a channel tag.
1392
+ */
1110
1393
  stream() {
1111
1394
  return new WritableStream({
1112
1395
  write: (chunk) => {
@@ -1114,8 +1397,239 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1114
1397
  },
1115
1398
  });
1116
1399
  }
1117
- sendAudio(audio) {
1118
- this.send(audio);
1400
+ /**
1401
+ * Send PCM audio.
1402
+ *
1403
+ * In single-channel mode, `audio` is forwarded directly to the WebSocket and
1404
+ * `options` is ignored.
1405
+ *
1406
+ * In dual-channel mode (when `channels` is configured), `options.channel` is
1407
+ * REQUIRED and must match one of the declared channel names. Per-channel PCM is
1408
+ * fed into that channel's VAD, accumulated into a per-channel ring buffer, and
1409
+ * a scheduled flush (`channelAttribution.flushIntervalMs`, default 50ms) mixes
1410
+ * the buffers into mono before sending to the WebSocket.
1411
+ */
1412
+ sendAudio(audio, options) {
1413
+ if (!this.isDualChannel) {
1414
+ this.send(audio);
1415
+ return;
1416
+ }
1417
+ if (!(options === null || options === void 0 ? void 0 : options.channel)) {
1418
+ throw new Error("StreamingTranscriber is in dual-channel mode; sendAudio requires { channel }.");
1419
+ }
1420
+ if (!this.channelNames.includes(options.channel)) {
1421
+ throw new Error(`Unknown channel "${options.channel}"; declared channels: ${this.channelNames.join(", ")}.`);
1422
+ }
1423
+ this.ingestChannelAudio(options.channel, audio);
1424
+ }
1425
+ ingestChannelAudio(name, audio) {
1426
+ var _a, _b;
1427
+ const samples = toInt16View(audio);
1428
+ const buf = this.channelBuffers.get(name);
1429
+ const vadBuf = this.channelVadFloatBuffers.get(name);
1430
+ let vadIdx = this.channelVadBufferIdx.get(name);
1431
+ let received = this.channelSamplesReceived.get(name);
1432
+ const vad = this.channelVads.get(name);
1433
+ const sampleRate = this.params.sampleRate;
1434
+ const frameSize = this.vadFrameSamples;
1435
+ for (let i = 0; i < samples.length; i++) {
1436
+ const s = samples[i];
1437
+ buf.push(s);
1438
+ vadBuf[vadIdx++] = s / 0x8000;
1439
+ received++;
1440
+ if (vadIdx === frameSize) {
1441
+ const result = vad.process(vadBuf);
1442
+ const frame = {
1443
+ ts: (received / sampleRate) * 1000,
1444
+ channel: name,
1445
+ active: result.active,
1446
+ rms: result.energy,
1447
+ };
1448
+ this.timeline.pushFrame(frame);
1449
+ (_b = (_a = this.listeners).vad) === null || _b === void 0 ? void 0 : _b.call(_a, frame);
1450
+ vadIdx = 0;
1451
+ }
1452
+ }
1453
+ this.channelVadBufferIdx.set(name, vadIdx);
1454
+ this.channelSamplesReceived.set(name, received);
1455
+ if (!this.flushTimer)
1456
+ this.startFlushTimer();
1457
+ }
1458
+ startFlushTimer() {
1459
+ this.flushTimer = setInterval(() => this.flushMix(), this.attributionParams.flushIntervalMs);
1460
+ }
1461
+ flushMix(force = false) {
1462
+ var _a, _b;
1463
+ if (!this.channelNames || !this.channelBuffers)
1464
+ return;
1465
+ const bufs = this.channelNames.map((n) => this.channelBuffers.get(n));
1466
+ const divisor = bufs.length;
1467
+ // Loop so a backlog (e.g. accumulated while a browser tab was throttled in
1468
+ // the background) drains as multiple sends, each capped at MAX_CHUNK_MS.
1469
+ // Without the cap a single message could exceed the server's 1000 ms input
1470
+ // duration limit and be rejected with code 3007.
1471
+ for (;;) {
1472
+ let mixLen = Infinity;
1473
+ for (const b of bufs)
1474
+ if (b.length < mixLen)
1475
+ mixLen = b.length;
1476
+ if (!Number.isFinite(mixLen) || mixLen === 0)
1477
+ return;
1478
+ // The streaming server rejects audio messages shorter than 50 ms with
1479
+ // `Input Duration Error`. Wait until both per-channel buffers have at
1480
+ // least minChunkSamples worth queued before emitting. The `force` path
1481
+ // (final flush on close) bypasses this so the trailing partial buffer
1482
+ // still gets through.
1483
+ if (!force && mixLen < this.minChunkSamples)
1484
+ return;
1485
+ if (mixLen > this.maxChunkSamples)
1486
+ mixLen = this.maxChunkSamples;
1487
+ const out = new Int16Array(mixLen);
1488
+ for (let i = 0; i < mixLen; i++) {
1489
+ let sum = 0;
1490
+ for (let c = 0; c < divisor; c++)
1491
+ sum += bufs[c][i];
1492
+ const avg = Math.round(sum / divisor);
1493
+ out[i] = avg < -32768 ? -32768 : avg > 32767 ? 32767 : avg;
1494
+ }
1495
+ for (const b of bufs)
1496
+ b.splice(0, mixLen);
1497
+ try {
1498
+ this.send(out.buffer);
1499
+ }
1500
+ catch (err) {
1501
+ (_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1502
+ return;
1503
+ }
1504
+ }
1505
+ }
1506
+ /**
1507
+ * Fill in words whose per-word VAD attribution was `"unknown"` by looking
1508
+ * at the dominant non-`"unknown"` channel among ±N neighbors in the same
1509
+ * turn. Words with no non-`"unknown"` neighbors stay `"unknown"`. Confident
1510
+ * per-word VAD decisions are never modified.
1511
+ *
1512
+ * Local temporal heuristic — ignores `speaker_label`, so it works even when
1513
+ * AAI's diarization re-uses the same label for two physically distinct
1514
+ * voices. Each resolved word gets `channelResolved: true` so downstream
1515
+ * renderers can distinguish inferred channels from directly-measured ones.
1516
+ */
1517
+ resolveUnknownChannelsByWindow(turn) {
1518
+ var _a;
1519
+ if (!this.attributionParams)
1520
+ return;
1521
+ const window = this.attributionParams.resolutionWindowWords;
1522
+ const words = turn.words;
1523
+ let mutated = false;
1524
+ for (let i = 0; i < words.length; i++) {
1525
+ if (words[i].channel !== "unknown")
1526
+ continue;
1527
+ const tally = new Map();
1528
+ const lo = Math.max(0, i - window);
1529
+ const hi = Math.min(words.length - 1, i + window);
1530
+ for (let j = lo; j <= hi; j++) {
1531
+ if (j === i)
1532
+ continue;
1533
+ const ch = words[j].channel;
1534
+ if (!ch || ch === "unknown")
1535
+ continue;
1536
+ tally.set(ch, ((_a = tally.get(ch)) !== null && _a !== void 0 ? _a : 0) + 1);
1537
+ }
1538
+ if (tally.size === 0)
1539
+ continue;
1540
+ // Pick the dominant neighbor channel. Ties → leave `"unknown"` (rare;
1541
+ // would require an equal count of mic and system neighbors).
1542
+ let top;
1543
+ let topCount = 0;
1544
+ let tied = false;
1545
+ for (const [name, count] of tally) {
1546
+ if (count > topCount) {
1547
+ top = name;
1548
+ topCount = count;
1549
+ tied = false;
1550
+ }
1551
+ else if (count === topCount) {
1552
+ tied = true;
1553
+ }
1554
+ }
1555
+ if (top && !tied) {
1556
+ words[i].channel = top;
1557
+ words[i].channelResolved = true;
1558
+ mutated = true;
1559
+ }
1560
+ }
1561
+ // Recompute the rollup only if any per-word channel changed.
1562
+ if (mutated)
1563
+ turn.channel = rollUpTurnChannel(words);
1564
+ }
1565
+ /**
1566
+ * Fill `"unknown"` words by looking up the speaker's session-wide channel
1567
+ * evidence. For each `speaker_label`, sums active VAD frame RMS per channel
1568
+ * across every word the speaker has uttered to date. A speaker is
1569
+ * "resolvable" if their total evidence clears
1570
+ * `speakerHistoryMinRmsEvidence` and their top channel exceeds the
1571
+ * runner-up by `speakerHistoryDominanceRatio`.
1572
+ *
1573
+ * Only touches `"unknown"` words. Confident per-word VAD decisions are
1574
+ * never modified. `speaker_label` is never modified.
1575
+ */
1576
+ resolveUnknownChannelsBySpeakerHistory(turn) {
1577
+ var _a;
1578
+ if (!this.timeline || !this.attributionParams || !this.speakerHistory)
1579
+ return;
1580
+ const minEvidence = this.attributionParams.speakerHistoryMinRmsEvidence;
1581
+ const dominanceRatio = this.attributionParams.speakerHistoryDominanceRatio;
1582
+ // 1. Accumulate evidence from this turn's words.
1583
+ for (const w of turn.words) {
1584
+ if (!w.speaker)
1585
+ continue;
1586
+ const frames = this.timeline.framesInWindow(w.start, w.end);
1587
+ let entry = this.speakerHistory.get(w.speaker);
1588
+ if (!entry) {
1589
+ entry = new Map();
1590
+ this.speakerHistory.set(w.speaker, entry);
1591
+ }
1592
+ for (const f of frames) {
1593
+ if (!f.active)
1594
+ continue;
1595
+ entry.set(f.channel, ((_a = entry.get(f.channel)) !== null && _a !== void 0 ? _a : 0) + f.rms);
1596
+ }
1597
+ }
1598
+ // 2. Fill unknown words whose speakers have dominant evidence.
1599
+ let mutated = false;
1600
+ for (const w of turn.words) {
1601
+ if (w.channel !== "unknown" || !w.speaker)
1602
+ continue;
1603
+ const entry = this.speakerHistory.get(w.speaker);
1604
+ if (!entry || entry.size === 0)
1605
+ continue;
1606
+ let total = 0;
1607
+ let topName;
1608
+ let topScore = 0;
1609
+ let runnerScore = 0;
1610
+ for (const [name, score] of entry) {
1611
+ total += score;
1612
+ if (score > topScore) {
1613
+ runnerScore = topScore;
1614
+ topScore = score;
1615
+ topName = name;
1616
+ }
1617
+ else if (score > runnerScore) {
1618
+ runnerScore = score;
1619
+ }
1620
+ }
1621
+ if (total < minEvidence)
1622
+ continue;
1623
+ if (runnerScore > 0 && topScore < dominanceRatio * runnerScore)
1624
+ continue;
1625
+ if (topName) {
1626
+ w.channel = topName;
1627
+ w.channelResolved = true;
1628
+ mutated = true;
1629
+ }
1630
+ }
1631
+ if (mutated)
1632
+ turn.channel = rollUpTurnChannel(turn.words);
1119
1633
  }
1120
1634
  /**
1121
1635
  * Update the streaming configuration mid-stream.
@@ -1153,6 +1667,15 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1153
1667
  close() {
1154
1668
  return __awaiter(this, arguments, void 0, function* (waitForSessionTermination = true) {
1155
1669
  var _a;
1670
+ if (this.flushTimer) {
1671
+ clearInterval(this.flushTimer);
1672
+ this.flushTimer = undefined;
1673
+ // Best-effort: drain any final partial mix so the server gets the tail.
1674
+ // Bypass the 50ms floor here since this is the last flush; if the tail
1675
+ // is <50ms the server will reject that single message, but we'd lose
1676
+ // the audio either way.
1677
+ this.flushMix(true);
1678
+ }
1156
1679
  if (this.socket) {
1157
1680
  if (this.socket.readyState === this.socket.OPEN) {
1158
1681
  if (waitForSessionTermination) {
@@ -1207,6 +1730,257 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1207
1730
  }
1208
1731
  }
1209
1732
 
1733
+ /**
1734
+ * AudioWorklet processor that ingests mono Float32 audio at the AudioContext's
1735
+ * native sample rate, resamples to `targetRate` (linear interpolation, stateful
1736
+ * across `process()` calls), packs to little-endian Int16 PCM, and posts
1737
+ * fixed-size chunks via `port.postMessage` with a running `samplesSent` counter.
1738
+ *
1739
+ * `samplesSent` is in **target-rate samples**, so the main thread can derive a
1740
+ * stream-relative timestamp = `samplesSent / targetRate * 1000` (ms) — the same
1741
+ * frame AAI uses for `StreamingWord.start` / `.end`.
1742
+ *
1743
+ * Defined as a string so it can be registered via a Blob URL — the SDK ships as
1744
+ * a single ESM file, so a separate `.js` worklet asset isn't viable.
1745
+ */
1746
+ const pcm16EncoderWorkletSource = `
1747
+ class Pcm16EncoderProcessor extends AudioWorkletProcessor {
1748
+ constructor(options) {
1749
+ super();
1750
+ const opts = (options && options.processorOptions) || {};
1751
+ this.targetRate = opts.targetRate || 16000;
1752
+ this.chunkMs = opts.chunkMs || 50;
1753
+ this.ratio = sampleRate / this.targetRate;
1754
+ this.chunkSize = Math.round(this.targetRate * this.chunkMs / 1000);
1755
+ this.buffer = new Int16Array(this.chunkSize);
1756
+ this.bufferIdx = 0;
1757
+ this.samplesSent = 0;
1758
+ this.lastSample = 0;
1759
+ this.fractional = 0;
1760
+ }
1761
+
1762
+ process(inputs) {
1763
+ const input = inputs[0];
1764
+ if (!input || input.length === 0 || !input[0] || input[0].length === 0) {
1765
+ return true;
1766
+ }
1767
+ const mono = input[0];
1768
+ let pos = this.fractional;
1769
+ while (pos < mono.length) {
1770
+ const i = Math.floor(pos);
1771
+ const frac = pos - i;
1772
+ const a = i === 0 ? this.lastSample : mono[i - 1];
1773
+ const b = mono[i];
1774
+ const sample = a + (b - a) * frac;
1775
+ const clamped = sample < -1 ? -1 : sample > 1 ? 1 : sample;
1776
+ this.buffer[this.bufferIdx++] = clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff;
1777
+ if (this.bufferIdx === this.chunkSize) {
1778
+ const out = new Int16Array(this.chunkSize);
1779
+ out.set(this.buffer);
1780
+ this.samplesSent += this.chunkSize;
1781
+ this.port.postMessage(
1782
+ { pcm: out.buffer, samplesSent: this.samplesSent },
1783
+ [out.buffer],
1784
+ );
1785
+ this.bufferIdx = 0;
1786
+ }
1787
+ pos += this.ratio;
1788
+ }
1789
+ this.lastSample = mono[mono.length - 1];
1790
+ this.fractional = pos - mono.length;
1791
+ return true;
1792
+ }
1793
+ }
1794
+ registerProcessor("aai-pcm16-encoder", Pcm16EncoderProcessor);
1795
+ `;
1796
+ const PCM16_ENCODER_PROCESSOR_NAME = "aai-pcm16-encoder";
1797
+
1798
+ const DEFAULT_TARGET_RATE = 16000;
1799
+ const DEFAULT_CHUNK_MS = 50;
1800
+ const MIC_CHANNEL = "mic";
1801
+ const SYSTEM_CHANNEL = "system";
1802
+ /**
1803
+ * Browser-only adapter that pumps two `MediaStream`s into a `StreamingTranscriber`
1804
+ * configured for dual-channel mode. Each `MediaStream` runs through its own
1805
+ * `pcm16-encoder` AudioWorklet (resample to `targetSampleRate`, encode to Int16
1806
+ * PCM); each PCM chunk is forwarded via `transcriber.sendAudio(pcm, { channel })`.
1807
+ *
1808
+ * All dual-channel orchestration (mixing, VAD, per-word attribution) lives inside
1809
+ * `StreamingTranscriber` — this class is a pure I/O adapter. Non-browser runtimes
1810
+ * can replicate its job by pushing tagged PCM into `transcriber.sendAudio` directly.
1811
+ *
1812
+ * Caller responsibilities:
1813
+ * - **Echo cancellation** is set at `getUserMedia` time (`audio: { echoCancellation: true }`).
1814
+ * - **System-audio capture** is platform-dependent. Chrome's `getDisplayMedia({ audio: true })`
1815
+ * captures tab audio (and on Windows, full system audio when sharing the whole screen).
1816
+ * macOS requires a virtual loopback driver (e.g. BlackHole) to expose system audio at all.
1817
+ * - **Token auth.** Construct the transcriber with `token` — API-key auth is unsupported in browsers.
1818
+ * - **Stream ownership.** `stop()` tears down the AudioContext but does NOT stop the
1819
+ * `MediaStreamTrack`s passed in — callers own those.
1820
+ */
1821
+ class DualChannelCapture {
1822
+ constructor(params) {
1823
+ var _a;
1824
+ this.running = false;
1825
+ if (typeof globalThis.AudioContext === "undefined") {
1826
+ throw new BrowserOnlyError();
1827
+ }
1828
+ this.params = {
1829
+ micStream: params.micStream,
1830
+ systemStream: params.systemStream,
1831
+ transcriber: params.transcriber,
1832
+ targetSampleRate: (_a = params.targetSampleRate) !== null && _a !== void 0 ? _a : DEFAULT_TARGET_RATE,
1833
+ };
1834
+ }
1835
+ on(event, listener) {
1836
+ if (event === "error")
1837
+ this.errorListener = listener;
1838
+ }
1839
+ /**
1840
+ * Wire the capture pipeline and start pumping tagged PCM into the transcriber.
1841
+ * The transcriber must already be connected. Returns once the worklet is
1842
+ * registered and the audio graph is live.
1843
+ */
1844
+ start() {
1845
+ return __awaiter(this, void 0, void 0, function* () {
1846
+ if (this.running) {
1847
+ throw new Error("DualChannelCapture already started");
1848
+ }
1849
+ this.context = new AudioContext();
1850
+ const blob = new Blob([pcm16EncoderWorkletSource], {
1851
+ type: "application/javascript",
1852
+ });
1853
+ const url = URL.createObjectURL(blob);
1854
+ try {
1855
+ yield this.context.audioWorklet.addModule(url);
1856
+ }
1857
+ finally {
1858
+ URL.revokeObjectURL(url);
1859
+ }
1860
+ this.micSource = this.context.createMediaStreamSource(this.params.micStream);
1861
+ this.sysSource = this.context.createMediaStreamSource(this.params.systemStream);
1862
+ this.micEncoder = this.makeEncoder(MIC_CHANNEL);
1863
+ this.sysEncoder = this.makeEncoder(SYSTEM_CHANNEL);
1864
+ this.micSource.connect(this.micEncoder);
1865
+ this.sysSource.connect(this.sysEncoder);
1866
+ this.running = true;
1867
+ });
1868
+ }
1869
+ makeEncoder(channel) {
1870
+ const node = new AudioWorkletNode(this.context, PCM16_ENCODER_PROCESSOR_NAME, {
1871
+ numberOfInputs: 1,
1872
+ numberOfOutputs: 0,
1873
+ channelCount: 1,
1874
+ channelCountMode: "explicit",
1875
+ channelInterpretation: "speakers",
1876
+ processorOptions: {
1877
+ targetRate: this.params.targetSampleRate,
1878
+ chunkMs: DEFAULT_CHUNK_MS,
1879
+ },
1880
+ });
1881
+ node.port.onmessage = (e) => {
1882
+ var _a;
1883
+ try {
1884
+ this.params.transcriber.sendAudio(e.data.pcm, { channel });
1885
+ }
1886
+ catch (err) {
1887
+ (_a = this.errorListener) === null || _a === void 0 ? void 0 : _a.call(this, err);
1888
+ }
1889
+ };
1890
+ return node;
1891
+ }
1892
+ /**
1893
+ * Tear down internal nodes and close the AudioContext. Does NOT stop the
1894
+ * caller-provided MediaStream tracks — they remain available for preview UI,
1895
+ * recording, etc. Idempotent.
1896
+ */
1897
+ stop() {
1898
+ return __awaiter(this, void 0, void 0, function* () {
1899
+ var _a, _b, _c, _d, _e, _f;
1900
+ if (!this.running)
1901
+ return;
1902
+ this.running = false;
1903
+ try {
1904
+ (_a = this.micEncoder) === null || _a === void 0 ? void 0 : _a.port.close();
1905
+ (_b = this.sysEncoder) === null || _b === void 0 ? void 0 : _b.port.close();
1906
+ (_c = this.micEncoder) === null || _c === void 0 ? void 0 : _c.disconnect();
1907
+ (_d = this.sysEncoder) === null || _d === void 0 ? void 0 : _d.disconnect();
1908
+ (_e = this.micSource) === null || _e === void 0 ? void 0 : _e.disconnect();
1909
+ (_f = this.sysSource) === null || _f === void 0 ? void 0 : _f.disconnect();
1910
+ }
1911
+ catch (_g) {
1912
+ // Disconnecting already-disconnected nodes throws in some browsers; ignore.
1913
+ }
1914
+ if (this.context && this.context.state !== "closed") {
1915
+ yield this.context.close();
1916
+ }
1917
+ this.context = undefined;
1918
+ this.micSource = undefined;
1919
+ this.sysSource = undefined;
1920
+ this.micEncoder = undefined;
1921
+ this.sysEncoder = undefined;
1922
+ });
1923
+ }
1924
+ }
1925
+
1926
+ /**
1927
+ * Linear-interpolation resampler for streaming Float32 audio. Stateful across
1928
+ * `process()` calls so chunk boundaries don't introduce phase discontinuities:
1929
+ * the last input sample and a fractional read position are carried over.
1930
+ *
1931
+ * Linear interpolation is good enough for ASR ingest — the downstream
1932
+ * StreamingTranscriber band-limits at the target rate anyway, and a polyphase
1933
+ * filter would be overkill in the AudioWorklet hot path. If a customer needs
1934
+ * higher quality they can supply their own VadDetector + bypass the encoder.
1935
+ */
1936
+ class LinearResampler {
1937
+ constructor(sourceRate, targetRate) {
1938
+ this.sourceRate = sourceRate;
1939
+ this.targetRate = targetRate;
1940
+ this.lastSample = 0;
1941
+ this.fractional = 0;
1942
+ if (sourceRate <= 0 || targetRate <= 0) {
1943
+ throw new Error("sourceRate and targetRate must be positive");
1944
+ }
1945
+ this.ratio = sourceRate / targetRate;
1946
+ }
1947
+ process(input) {
1948
+ var _a;
1949
+ if (this.sourceRate === this.targetRate) {
1950
+ return input;
1951
+ }
1952
+ // Worst-case output length; we'll slice to actual.
1953
+ const out = new Float32Array(Math.ceil(input.length / this.ratio) + 1);
1954
+ let outIdx = 0;
1955
+ let pos = this.fractional;
1956
+ while (pos < input.length) {
1957
+ const i = Math.floor(pos);
1958
+ const frac = pos - i;
1959
+ const a = i === 0 ? this.lastSample : input[i - 1];
1960
+ const b = input[i];
1961
+ out[outIdx++] = a + (b - a) * frac;
1962
+ pos += this.ratio;
1963
+ }
1964
+ this.lastSample = (_a = input[input.length - 1]) !== null && _a !== void 0 ? _a : this.lastSample;
1965
+ this.fractional = pos - input.length;
1966
+ return out.subarray(0, outIdx);
1967
+ }
1968
+ reset() {
1969
+ this.lastSample = 0;
1970
+ this.fractional = 0;
1971
+ }
1972
+ }
1973
+ /** Convert Float32 PCM (-1..1) to little-endian Int16 PCM. */
1974
+ function float32ToPcm16(input) {
1975
+ const out = new ArrayBuffer(input.length * 2);
1976
+ const view = new DataView(out);
1977
+ for (let i = 0; i < input.length; i++) {
1978
+ const clamped = Math.max(-1, Math.min(1, input[i]));
1979
+ view.setInt16(i * 2, clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, true);
1980
+ }
1981
+ return out;
1982
+ }
1983
+
1210
1984
  const defaultBaseUrl = "https://api.assemblyai.com";
1211
1985
  const defaultStreamingUrl = "https://streaming.assemblyai.com";
1212
1986
  class AssemblyAI {
@@ -1228,13 +2002,22 @@ Learn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/c
1228
2002
  }
1229
2003
 
1230
2004
  exports.AssemblyAI = AssemblyAI;
2005
+ exports.BrowserOnlyError = BrowserOnlyError;
2006
+ exports.DualChannelCapture = DualChannelCapture;
2007
+ exports.EnergyVad = EnergyVad;
1231
2008
  exports.FileService = FileService;
1232
2009
  exports.LemurService = LemurService;
2010
+ exports.LinearResampler = LinearResampler;
1233
2011
  exports.RealtimeService = RealtimeService;
1234
2012
  exports.RealtimeServiceFactory = RealtimeServiceFactory;
1235
2013
  exports.RealtimeTranscriber = RealtimeTranscriber;
1236
2014
  exports.RealtimeTranscriberFactory = RealtimeTranscriberFactory;
1237
2015
  exports.StreamingTranscriber = StreamingTranscriber;
1238
2016
  exports.TranscriptService = TranscriptService;
2017
+ exports.VadTimeline = VadTimeline;
2018
+ exports.attributeTurn = attributeTurn;
2019
+ exports.attributeWord = attributeWord;
2020
+ exports.float32ToPcm16 = float32ToPcm16;
2021
+ exports.rollUpTurnChannel = rollUpTurnChannel;
1239
2022
 
1240
2023
  }));