assemblyai 4.33.3 → 4.34.4

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