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