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