assemblyai 4.33.2 → 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 +789 -3
  4. package/dist/assemblyai.umd.min.js +1 -1
  5. package/dist/browser.mjs +765 -4
  6. package/dist/bun.mjs +765 -4
  7. package/dist/deno.mjs +765 -4
  8. package/dist/exports/streaming.d.ts +7 -0
  9. package/dist/index.cjs +789 -3
  10. package/dist/index.mjs +781 -4
  11. package/dist/node.cjs +773 -3
  12. package/dist/node.mjs +765 -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 +112 -1
  26. package/dist/workerd.mjs +765 -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 +392 -2
  37. package/src/types/streaming/dual-channel.ts +57 -0
  38. package/src/types/streaming/index.ts +112 -0
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.2" },
36
+ sdk: { name: "JavaScript", version: "4.34.0" },
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 ?? "");
@@ -878,6 +1132,9 @@ class StreamingTranscriber {
878
1132
  if (this.params.interruptionDelay !== undefined) {
879
1133
  searchParams.set("interruption_delay", this.params.interruptionDelay.toString());
880
1134
  }
1135
+ if (this.params.turnLeftPadMs !== undefined) {
1136
+ searchParams.set("turn_left_pad_ms", this.params.turnLeftPadMs.toString());
1137
+ }
881
1138
  if (this.params.customerSupportAudioCapture) {
882
1139
  console.warn("`customerSupportAudioCapture=true` will record session audio. Only enable this when explicitly coordinating with AssemblyAI support.");
883
1140
  // The server's canonical wire name is `_customer_support_audio_capture`
@@ -940,6 +1197,13 @@ class StreamingTranscriber {
940
1197
  reason = StreamingErrorMessages[code];
941
1198
  }
942
1199
  }
1200
+ // Stop the flush timer when the socket is gone (server-initiated close,
1201
+ // network drop, etc.) — otherwise subsequent ticks call send() on a
1202
+ // closed socket and spam the error listener.
1203
+ if (this.flushTimer) {
1204
+ clearInterval(this.flushTimer);
1205
+ this.flushTimer = undefined;
1206
+ }
943
1207
  this.listeners.close?.(code, reason);
944
1208
  };
945
1209
  this.socket.onerror = (event) => {
@@ -966,6 +1230,19 @@ class StreamingTranscriber {
966
1230
  break;
967
1231
  }
968
1232
  case "Turn": {
1233
+ if (this.isDualChannel && this.timeline && this.attributionParams) {
1234
+ attributeTurn(message, this.timeline, {
1235
+ dominanceRatio: this.attributionParams.dominanceRatio,
1236
+ });
1237
+ switch (this.attributionParams.resolveUnknownChannelsMethod) {
1238
+ case "window":
1239
+ this.resolveUnknownChannelsByWindow(message);
1240
+ break;
1241
+ case "speaker-history":
1242
+ this.resolveUnknownChannelsBySpeakerHistory(message);
1243
+ break;
1244
+ }
1245
+ }
969
1246
  this.listeners.turn?.(message);
970
1247
  break;
971
1248
  }
@@ -991,6 +1268,11 @@ class StreamingTranscriber {
991
1268
  };
992
1269
  });
993
1270
  }
1271
+ /**
1272
+ * Returns a WritableStream that pumps PCM chunks into `sendAudio`. Single-channel
1273
+ * only — in dual-channel mode use `sendAudio(pcm, { channel })` directly, since
1274
+ * `WritableStream` has no place to carry a channel tag.
1275
+ */
994
1276
  stream() {
995
1277
  return new WritableStream({
996
1278
  write: (chunk) => {
@@ -998,8 +1280,235 @@ class StreamingTranscriber {
998
1280
  },
999
1281
  });
1000
1282
  }
1001
- sendAudio(audio) {
1002
- this.send(audio);
1283
+ /**
1284
+ * Send PCM audio.
1285
+ *
1286
+ * In single-channel mode, `audio` is forwarded directly to the WebSocket and
1287
+ * `options` is ignored.
1288
+ *
1289
+ * In dual-channel mode (when `channels` is configured), `options.channel` is
1290
+ * REQUIRED and must match one of the declared channel names. Per-channel PCM is
1291
+ * fed into that channel's VAD, accumulated into a per-channel ring buffer, and
1292
+ * a scheduled flush (`channelAttribution.flushIntervalMs`, default 50ms) mixes
1293
+ * the buffers into mono before sending to the WebSocket.
1294
+ */
1295
+ sendAudio(audio, options) {
1296
+ if (!this.isDualChannel) {
1297
+ this.send(audio);
1298
+ return;
1299
+ }
1300
+ if (!options?.channel) {
1301
+ throw new Error("StreamingTranscriber is in dual-channel mode; sendAudio requires { channel }.");
1302
+ }
1303
+ if (!this.channelNames.includes(options.channel)) {
1304
+ throw new Error(`Unknown channel "${options.channel}"; declared channels: ${this.channelNames.join(", ")}.`);
1305
+ }
1306
+ this.ingestChannelAudio(options.channel, audio);
1307
+ }
1308
+ ingestChannelAudio(name, audio) {
1309
+ const samples = toInt16View(audio);
1310
+ const buf = this.channelBuffers.get(name);
1311
+ const vadBuf = this.channelVadFloatBuffers.get(name);
1312
+ let vadIdx = this.channelVadBufferIdx.get(name);
1313
+ let received = this.channelSamplesReceived.get(name);
1314
+ const vad = this.channelVads.get(name);
1315
+ const sampleRate = this.params.sampleRate;
1316
+ const frameSize = this.vadFrameSamples;
1317
+ for (let i = 0; i < samples.length; i++) {
1318
+ const s = samples[i];
1319
+ buf.push(s);
1320
+ vadBuf[vadIdx++] = s / 0x8000;
1321
+ received++;
1322
+ if (vadIdx === frameSize) {
1323
+ const result = vad.process(vadBuf);
1324
+ const frame = {
1325
+ ts: (received / sampleRate) * 1000,
1326
+ channel: name,
1327
+ active: result.active,
1328
+ rms: result.energy,
1329
+ };
1330
+ this.timeline.pushFrame(frame);
1331
+ this.listeners.vad?.(frame);
1332
+ vadIdx = 0;
1333
+ }
1334
+ }
1335
+ this.channelVadBufferIdx.set(name, vadIdx);
1336
+ this.channelSamplesReceived.set(name, received);
1337
+ if (!this.flushTimer)
1338
+ this.startFlushTimer();
1339
+ }
1340
+ startFlushTimer() {
1341
+ this.flushTimer = setInterval(() => this.flushMix(), this.attributionParams.flushIntervalMs);
1342
+ }
1343
+ flushMix(force = false) {
1344
+ if (!this.channelNames || !this.channelBuffers)
1345
+ return;
1346
+ const bufs = this.channelNames.map((n) => this.channelBuffers.get(n));
1347
+ const divisor = bufs.length;
1348
+ // Loop so a backlog (e.g. accumulated while a browser tab was throttled in
1349
+ // the background) drains as multiple sends, each capped at MAX_CHUNK_MS.
1350
+ // Without the cap a single message could exceed the server's 1000 ms input
1351
+ // duration limit and be rejected with code 3007.
1352
+ for (;;) {
1353
+ let mixLen = Infinity;
1354
+ for (const b of bufs)
1355
+ if (b.length < mixLen)
1356
+ mixLen = b.length;
1357
+ if (!Number.isFinite(mixLen) || mixLen === 0)
1358
+ return;
1359
+ // The streaming server rejects audio messages shorter than 50 ms with
1360
+ // `Input Duration Error`. Wait until both per-channel buffers have at
1361
+ // least minChunkSamples worth queued before emitting. The `force` path
1362
+ // (final flush on close) bypasses this so the trailing partial buffer
1363
+ // still gets through.
1364
+ if (!force && mixLen < this.minChunkSamples)
1365
+ return;
1366
+ if (mixLen > this.maxChunkSamples)
1367
+ mixLen = this.maxChunkSamples;
1368
+ const out = new Int16Array(mixLen);
1369
+ for (let i = 0; i < mixLen; i++) {
1370
+ let sum = 0;
1371
+ for (let c = 0; c < divisor; c++)
1372
+ sum += bufs[c][i];
1373
+ const avg = Math.round(sum / divisor);
1374
+ out[i] = avg < -32768 ? -32768 : avg > 32767 ? 32767 : avg;
1375
+ }
1376
+ for (const b of bufs)
1377
+ b.splice(0, mixLen);
1378
+ try {
1379
+ this.send(out.buffer);
1380
+ }
1381
+ catch (err) {
1382
+ this.listeners.error?.(err);
1383
+ return;
1384
+ }
1385
+ }
1386
+ }
1387
+ /**
1388
+ * Fill in words whose per-word VAD attribution was `"unknown"` by looking
1389
+ * at the dominant non-`"unknown"` channel among ±N neighbors in the same
1390
+ * turn. Words with no non-`"unknown"` neighbors stay `"unknown"`. Confident
1391
+ * per-word VAD decisions are never modified.
1392
+ *
1393
+ * Local temporal heuristic — ignores `speaker_label`, so it works even when
1394
+ * AAI's diarization re-uses the same label for two physically distinct
1395
+ * voices. Each resolved word gets `channelResolved: true` so downstream
1396
+ * renderers can distinguish inferred channels from directly-measured ones.
1397
+ */
1398
+ resolveUnknownChannelsByWindow(turn) {
1399
+ if (!this.attributionParams)
1400
+ return;
1401
+ const window = this.attributionParams.resolutionWindowWords;
1402
+ const words = turn.words;
1403
+ let mutated = false;
1404
+ for (let i = 0; i < words.length; i++) {
1405
+ if (words[i].channel !== "unknown")
1406
+ continue;
1407
+ const tally = new Map();
1408
+ const lo = Math.max(0, i - window);
1409
+ const hi = Math.min(words.length - 1, i + window);
1410
+ for (let j = lo; j <= hi; j++) {
1411
+ if (j === i)
1412
+ continue;
1413
+ const ch = words[j].channel;
1414
+ if (!ch || ch === "unknown")
1415
+ continue;
1416
+ tally.set(ch, (tally.get(ch) ?? 0) + 1);
1417
+ }
1418
+ if (tally.size === 0)
1419
+ continue;
1420
+ // Pick the dominant neighbor channel. Ties → leave `"unknown"` (rare;
1421
+ // would require an equal count of mic and system neighbors).
1422
+ let top;
1423
+ let topCount = 0;
1424
+ let tied = false;
1425
+ for (const [name, count] of tally) {
1426
+ if (count > topCount) {
1427
+ top = name;
1428
+ topCount = count;
1429
+ tied = false;
1430
+ }
1431
+ else if (count === topCount) {
1432
+ tied = true;
1433
+ }
1434
+ }
1435
+ if (top && !tied) {
1436
+ words[i].channel = top;
1437
+ words[i].channelResolved = true;
1438
+ mutated = true;
1439
+ }
1440
+ }
1441
+ // Recompute the rollup only if any per-word channel changed.
1442
+ if (mutated)
1443
+ turn.channel = rollUpTurnChannel(words);
1444
+ }
1445
+ /**
1446
+ * Fill `"unknown"` words by looking up the speaker's session-wide channel
1447
+ * evidence. For each `speaker_label`, sums active VAD frame RMS per channel
1448
+ * across every word the speaker has uttered to date. A speaker is
1449
+ * "resolvable" if their total evidence clears
1450
+ * `speakerHistoryMinRmsEvidence` and their top channel exceeds the
1451
+ * runner-up by `speakerHistoryDominanceRatio`.
1452
+ *
1453
+ * Only touches `"unknown"` words. Confident per-word VAD decisions are
1454
+ * never modified. `speaker_label` is never modified.
1455
+ */
1456
+ resolveUnknownChannelsBySpeakerHistory(turn) {
1457
+ if (!this.timeline || !this.attributionParams || !this.speakerHistory)
1458
+ return;
1459
+ const minEvidence = this.attributionParams.speakerHistoryMinRmsEvidence;
1460
+ const dominanceRatio = this.attributionParams.speakerHistoryDominanceRatio;
1461
+ // 1. Accumulate evidence from this turn's words.
1462
+ for (const w of turn.words) {
1463
+ if (!w.speaker)
1464
+ continue;
1465
+ const frames = this.timeline.framesInWindow(w.start, w.end);
1466
+ let entry = this.speakerHistory.get(w.speaker);
1467
+ if (!entry) {
1468
+ entry = new Map();
1469
+ this.speakerHistory.set(w.speaker, entry);
1470
+ }
1471
+ for (const f of frames) {
1472
+ if (!f.active)
1473
+ continue;
1474
+ entry.set(f.channel, (entry.get(f.channel) ?? 0) + f.rms);
1475
+ }
1476
+ }
1477
+ // 2. Fill unknown words whose speakers have dominant evidence.
1478
+ let mutated = false;
1479
+ for (const w of turn.words) {
1480
+ if (w.channel !== "unknown" || !w.speaker)
1481
+ continue;
1482
+ const entry = this.speakerHistory.get(w.speaker);
1483
+ if (!entry || entry.size === 0)
1484
+ continue;
1485
+ let total = 0;
1486
+ let topName;
1487
+ let topScore = 0;
1488
+ let runnerScore = 0;
1489
+ for (const [name, score] of entry) {
1490
+ total += score;
1491
+ if (score > topScore) {
1492
+ runnerScore = topScore;
1493
+ topScore = score;
1494
+ topName = name;
1495
+ }
1496
+ else if (score > runnerScore) {
1497
+ runnerScore = score;
1498
+ }
1499
+ }
1500
+ if (total < minEvidence)
1501
+ continue;
1502
+ if (runnerScore > 0 && topScore < dominanceRatio * runnerScore)
1503
+ continue;
1504
+ if (topName) {
1505
+ w.channel = topName;
1506
+ w.channelResolved = true;
1507
+ mutated = true;
1508
+ }
1509
+ }
1510
+ if (mutated)
1511
+ turn.channel = rollUpTurnChannel(turn.words);
1003
1512
  }
1004
1513
  /**
1005
1514
  * Update the streaming configuration mid-stream.
@@ -1039,6 +1548,15 @@ class StreamingTranscriber {
1039
1548
  this.socket.send(data);
1040
1549
  }
1041
1550
  async close(waitForSessionTermination = true) {
1551
+ if (this.flushTimer) {
1552
+ clearInterval(this.flushTimer);
1553
+ this.flushTimer = undefined;
1554
+ // Best-effort: drain any final partial mix so the server gets the tail.
1555
+ // Bypass the 50ms floor here since this is the last flush; if the tail
1556
+ // is <50ms the server will reject that single message, but we'd lose
1557
+ // the audio either way.
1558
+ this.flushMix(true);
1559
+ }
1042
1560
  if (this.socket) {
1043
1561
  if (this.socket.readyState === this.socket.OPEN) {
1044
1562
  if (waitForSessionTermination) {
@@ -1090,6 +1608,249 @@ class StreamingTranscriberFactory extends BaseService {
1090
1608
  }
1091
1609
  }
1092
1610
 
1611
+ /**
1612
+ * AudioWorklet processor that ingests mono Float32 audio at the AudioContext's
1613
+ * native sample rate, resamples to `targetRate` (linear interpolation, stateful
1614
+ * across `process()` calls), packs to little-endian Int16 PCM, and posts
1615
+ * fixed-size chunks via `port.postMessage` with a running `samplesSent` counter.
1616
+ *
1617
+ * `samplesSent` is in **target-rate samples**, so the main thread can derive a
1618
+ * stream-relative timestamp = `samplesSent / targetRate * 1000` (ms) — the same
1619
+ * frame AAI uses for `StreamingWord.start` / `.end`.
1620
+ *
1621
+ * Defined as a string so it can be registered via a Blob URL — the SDK ships as
1622
+ * a single ESM file, so a separate `.js` worklet asset isn't viable.
1623
+ */
1624
+ const pcm16EncoderWorkletSource = `
1625
+ class Pcm16EncoderProcessor extends AudioWorkletProcessor {
1626
+ constructor(options) {
1627
+ super();
1628
+ const opts = (options && options.processorOptions) || {};
1629
+ this.targetRate = opts.targetRate || 16000;
1630
+ this.chunkMs = opts.chunkMs || 50;
1631
+ this.ratio = sampleRate / this.targetRate;
1632
+ this.chunkSize = Math.round(this.targetRate * this.chunkMs / 1000);
1633
+ this.buffer = new Int16Array(this.chunkSize);
1634
+ this.bufferIdx = 0;
1635
+ this.samplesSent = 0;
1636
+ this.lastSample = 0;
1637
+ this.fractional = 0;
1638
+ }
1639
+
1640
+ process(inputs) {
1641
+ const input = inputs[0];
1642
+ if (!input || input.length === 0 || !input[0] || input[0].length === 0) {
1643
+ return true;
1644
+ }
1645
+ const mono = input[0];
1646
+ let pos = this.fractional;
1647
+ while (pos < mono.length) {
1648
+ const i = Math.floor(pos);
1649
+ const frac = pos - i;
1650
+ const a = i === 0 ? this.lastSample : mono[i - 1];
1651
+ const b = mono[i];
1652
+ const sample = a + (b - a) * frac;
1653
+ const clamped = sample < -1 ? -1 : sample > 1 ? 1 : sample;
1654
+ this.buffer[this.bufferIdx++] = clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff;
1655
+ if (this.bufferIdx === this.chunkSize) {
1656
+ const out = new Int16Array(this.chunkSize);
1657
+ out.set(this.buffer);
1658
+ this.samplesSent += this.chunkSize;
1659
+ this.port.postMessage(
1660
+ { pcm: out.buffer, samplesSent: this.samplesSent },
1661
+ [out.buffer],
1662
+ );
1663
+ this.bufferIdx = 0;
1664
+ }
1665
+ pos += this.ratio;
1666
+ }
1667
+ this.lastSample = mono[mono.length - 1];
1668
+ this.fractional = pos - mono.length;
1669
+ return true;
1670
+ }
1671
+ }
1672
+ registerProcessor("aai-pcm16-encoder", Pcm16EncoderProcessor);
1673
+ `;
1674
+ const PCM16_ENCODER_PROCESSOR_NAME = "aai-pcm16-encoder";
1675
+
1676
+ const DEFAULT_TARGET_RATE = 16_000;
1677
+ const DEFAULT_CHUNK_MS = 50;
1678
+ const MIC_CHANNEL = "mic";
1679
+ const SYSTEM_CHANNEL = "system";
1680
+ /**
1681
+ * Browser-only adapter that pumps two `MediaStream`s into a `StreamingTranscriber`
1682
+ * configured for dual-channel mode. Each `MediaStream` runs through its own
1683
+ * `pcm16-encoder` AudioWorklet (resample to `targetSampleRate`, encode to Int16
1684
+ * PCM); each PCM chunk is forwarded via `transcriber.sendAudio(pcm, { channel })`.
1685
+ *
1686
+ * All dual-channel orchestration (mixing, VAD, per-word attribution) lives inside
1687
+ * `StreamingTranscriber` — this class is a pure I/O adapter. Non-browser runtimes
1688
+ * can replicate its job by pushing tagged PCM into `transcriber.sendAudio` directly.
1689
+ *
1690
+ * Caller responsibilities:
1691
+ * - **Echo cancellation** is set at `getUserMedia` time (`audio: { echoCancellation: true }`).
1692
+ * - **System-audio capture** is platform-dependent. Chrome's `getDisplayMedia({ audio: true })`
1693
+ * captures tab audio (and on Windows, full system audio when sharing the whole screen).
1694
+ * macOS requires a virtual loopback driver (e.g. BlackHole) to expose system audio at all.
1695
+ * - **Token auth.** Construct the transcriber with `token` — API-key auth is unsupported in browsers.
1696
+ * - **Stream ownership.** `stop()` tears down the AudioContext but does NOT stop the
1697
+ * `MediaStreamTrack`s passed in — callers own those.
1698
+ */
1699
+ class DualChannelCapture {
1700
+ constructor(params) {
1701
+ this.running = false;
1702
+ if (typeof globalThis.AudioContext === "undefined") {
1703
+ throw new BrowserOnlyError();
1704
+ }
1705
+ this.params = {
1706
+ micStream: params.micStream,
1707
+ systemStream: params.systemStream,
1708
+ transcriber: params.transcriber,
1709
+ targetSampleRate: params.targetSampleRate ?? DEFAULT_TARGET_RATE,
1710
+ };
1711
+ }
1712
+ on(event, listener) {
1713
+ if (event === "error")
1714
+ this.errorListener = listener;
1715
+ }
1716
+ /**
1717
+ * Wire the capture pipeline and start pumping tagged PCM into the transcriber.
1718
+ * The transcriber must already be connected. Returns once the worklet is
1719
+ * registered and the audio graph is live.
1720
+ */
1721
+ async start() {
1722
+ if (this.running) {
1723
+ throw new Error("DualChannelCapture already started");
1724
+ }
1725
+ this.context = new AudioContext();
1726
+ const blob = new Blob([pcm16EncoderWorkletSource], {
1727
+ type: "application/javascript",
1728
+ });
1729
+ const url = URL.createObjectURL(blob);
1730
+ try {
1731
+ await this.context.audioWorklet.addModule(url);
1732
+ }
1733
+ finally {
1734
+ URL.revokeObjectURL(url);
1735
+ }
1736
+ this.micSource = this.context.createMediaStreamSource(this.params.micStream);
1737
+ this.sysSource = this.context.createMediaStreamSource(this.params.systemStream);
1738
+ this.micEncoder = this.makeEncoder(MIC_CHANNEL);
1739
+ this.sysEncoder = this.makeEncoder(SYSTEM_CHANNEL);
1740
+ this.micSource.connect(this.micEncoder);
1741
+ this.sysSource.connect(this.sysEncoder);
1742
+ this.running = true;
1743
+ }
1744
+ makeEncoder(channel) {
1745
+ const node = new AudioWorkletNode(this.context, PCM16_ENCODER_PROCESSOR_NAME, {
1746
+ numberOfInputs: 1,
1747
+ numberOfOutputs: 0,
1748
+ channelCount: 1,
1749
+ channelCountMode: "explicit",
1750
+ channelInterpretation: "speakers",
1751
+ processorOptions: {
1752
+ targetRate: this.params.targetSampleRate,
1753
+ chunkMs: DEFAULT_CHUNK_MS,
1754
+ },
1755
+ });
1756
+ node.port.onmessage = (e) => {
1757
+ try {
1758
+ this.params.transcriber.sendAudio(e.data.pcm, { channel });
1759
+ }
1760
+ catch (err) {
1761
+ this.errorListener?.(err);
1762
+ }
1763
+ };
1764
+ return node;
1765
+ }
1766
+ /**
1767
+ * Tear down internal nodes and close the AudioContext. Does NOT stop the
1768
+ * caller-provided MediaStream tracks — they remain available for preview UI,
1769
+ * recording, etc. Idempotent.
1770
+ */
1771
+ async stop() {
1772
+ if (!this.running)
1773
+ return;
1774
+ this.running = false;
1775
+ try {
1776
+ this.micEncoder?.port.close();
1777
+ this.sysEncoder?.port.close();
1778
+ this.micEncoder?.disconnect();
1779
+ this.sysEncoder?.disconnect();
1780
+ this.micSource?.disconnect();
1781
+ this.sysSource?.disconnect();
1782
+ }
1783
+ catch {
1784
+ // Disconnecting already-disconnected nodes throws in some browsers; ignore.
1785
+ }
1786
+ if (this.context && this.context.state !== "closed") {
1787
+ await this.context.close();
1788
+ }
1789
+ this.context = undefined;
1790
+ this.micSource = undefined;
1791
+ this.sysSource = undefined;
1792
+ this.micEncoder = undefined;
1793
+ this.sysEncoder = undefined;
1794
+ }
1795
+ }
1796
+
1797
+ /**
1798
+ * Linear-interpolation resampler for streaming Float32 audio. Stateful across
1799
+ * `process()` calls so chunk boundaries don't introduce phase discontinuities:
1800
+ * the last input sample and a fractional read position are carried over.
1801
+ *
1802
+ * Linear interpolation is good enough for ASR ingest — the downstream
1803
+ * StreamingTranscriber band-limits at the target rate anyway, and a polyphase
1804
+ * filter would be overkill in the AudioWorklet hot path. If a customer needs
1805
+ * higher quality they can supply their own VadDetector + bypass the encoder.
1806
+ */
1807
+ class LinearResampler {
1808
+ constructor(sourceRate, targetRate) {
1809
+ this.sourceRate = sourceRate;
1810
+ this.targetRate = targetRate;
1811
+ this.lastSample = 0;
1812
+ this.fractional = 0;
1813
+ if (sourceRate <= 0 || targetRate <= 0) {
1814
+ throw new Error("sourceRate and targetRate must be positive");
1815
+ }
1816
+ this.ratio = sourceRate / targetRate;
1817
+ }
1818
+ process(input) {
1819
+ if (this.sourceRate === this.targetRate) {
1820
+ return input;
1821
+ }
1822
+ // Worst-case output length; we'll slice to actual.
1823
+ const out = new Float32Array(Math.ceil(input.length / this.ratio) + 1);
1824
+ let outIdx = 0;
1825
+ let pos = this.fractional;
1826
+ while (pos < input.length) {
1827
+ const i = Math.floor(pos);
1828
+ const frac = pos - i;
1829
+ const a = i === 0 ? this.lastSample : input[i - 1];
1830
+ const b = input[i];
1831
+ out[outIdx++] = a + (b - a) * frac;
1832
+ pos += this.ratio;
1833
+ }
1834
+ this.lastSample = input[input.length - 1] ?? this.lastSample;
1835
+ this.fractional = pos - input.length;
1836
+ return out.subarray(0, outIdx);
1837
+ }
1838
+ reset() {
1839
+ this.lastSample = 0;
1840
+ this.fractional = 0;
1841
+ }
1842
+ }
1843
+ /** Convert Float32 PCM (-1..1) to little-endian Int16 PCM. */
1844
+ function float32ToPcm16(input) {
1845
+ const out = new ArrayBuffer(input.length * 2);
1846
+ const view = new DataView(out);
1847
+ for (let i = 0; i < input.length; i++) {
1848
+ const clamped = Math.max(-1, Math.min(1, input[i]));
1849
+ view.setInt16(i * 2, clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, true);
1850
+ }
1851
+ return out;
1852
+ }
1853
+
1093
1854
  const defaultBaseUrl = "https://api.assemblyai.com";
1094
1855
  const defaultStreamingUrl = "https://streaming.assemblyai.com";
1095
1856
  class AssemblyAI {
@@ -1113,4 +1874,4 @@ class AssemblyAI {
1113
1874
  }
1114
1875
  }
1115
1876
 
1116
- export { AssemblyAI, FileService, LemurService, RealtimeService, RealtimeServiceFactory, RealtimeTranscriber, RealtimeTranscriberFactory, StreamingTranscriber, TranscriptService };
1877
+ export { AssemblyAI, BrowserOnlyError, DualChannelCapture, EnergyVad, FileService, LemurService, LinearResampler, RealtimeService, RealtimeServiceFactory, RealtimeTranscriber, RealtimeTranscriberFactory, StreamingTranscriber, TranscriptService, VadTimeline, attributeTurn, attributeWord, float32ToPcm16, rollUpTurnChannel };