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