-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathspeechflow-node-a2a-compressor.ts
More file actions
322 lines (286 loc) · 12.4 KB
/
speechflow-node-a2a-compressor.ts
File metadata and controls
322 lines (286 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*
** SpeechFlow - Speech Processing Flow Graph
** Copyright (c) 2024-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
** Licensed under GPL 3.0 <https://spdx.org/licenses/GPL-3.0-only>
*/
/* standard dependencies */
import path from "node:path"
import Stream from "node:stream"
import { EventEmitter } from "node:events"
/* external dependencies */
import { GainNode, AudioWorkletNode } from "node-web-audio-api"
/* internal dependencies */
import SpeechFlowNode, { SpeechFlowChunk } from "./speechflow-node"
import * as util from "./speechflow-util"
/* internal types */
interface AudioCompressorConfig {
thresholdDb?: number
ratio?: number
attackMs?: number
releaseMs?: number
kneeDb?: number
makeupDb?: number
}
/* audio compressor class */
class AudioCompressor extends util.WebAudio {
/* internal state */
private type: "standalone" | "sidechain"
private mode: "compress" | "measure" | "adjust"
private config: Required<AudioCompressorConfig>
private compressorNode: AudioWorkletNode | null = null
private gainNode: GainNode | null = null
private _reduction = 0
private _reductionListener: ((event: MessageEvent) => void) | null = null
/* construct object */
constructor (
sampleRate: number,
channels: number,
type: "standalone" | "sidechain" = "standalone",
mode: "compress" | "measure" | "adjust" = "compress",
config: AudioCompressorConfig = {}
) {
super(sampleRate, channels)
/* store type and mode */
this.type = type
this.mode = mode
/* store configuration */
this.config = {
thresholdDb: config.thresholdDb ?? -23,
ratio: config.ratio ?? 4.0,
attackMs: config.attackMs ?? 10,
releaseMs: config.releaseMs ?? 50,
kneeDb: config.kneeDb ?? 6.0,
makeupDb: config.makeupDb ?? 0
}
}
/* setup object */
public async setup (): Promise<void> {
await super.setup()
/* add audio worklet module */
const url = path.resolve(__dirname, "speechflow-node-a2a-compressor-wt.js")
await this.audioContext.audioWorklet.addModule(url)
/* determine operation modes */
const needsCompressor = (this.type === "standalone" && this.mode === "compress")
|| (this.type === "sidechain" && this.mode === "measure")
const needsGain = (this.type === "standalone" && this.mode === "compress")
|| (this.type === "sidechain" && this.mode === "adjust")
/* create compressor worklet node */
if (needsCompressor) {
this.compressorNode = new AudioWorkletNode(this.audioContext, "compressor", {
numberOfInputs: 1,
numberOfOutputs: 1,
processorOptions: {
sampleRate: this.audioContext.sampleRate
}
})
}
/* listen for reduction updates from compressor worklet */
if (needsCompressor) {
this._reductionListener = (event: MessageEvent) => {
if (event.data?.type === "reduction")
this._reduction = event.data.reduction
}
this.compressorNode!.port.addEventListener("message", this._reductionListener)
this.compressorNode!.port.start()
}
/* create gain node */
if (needsGain)
this.gainNode = this.audioContext.createGain()
/* connect nodes (according to type and mode) */
if (this.type === "standalone" && this.mode === "compress") {
this.sourceNode!.connect(this.compressorNode!)
this.compressorNode!.connect(this.gainNode!)
this.gainNode!.connect(this.captureNode!)
}
else if (this.type === "sidechain" && this.mode === "measure") {
this.sourceNode!.connect(this.compressorNode!)
this.compressorNode!.connect(this.captureNode!)
}
else if (this.type === "sidechain" && this.mode === "adjust") {
this.sourceNode!.connect(this.gainNode!)
this.gainNode!.connect(this.captureNode!)
}
/* configure compressor worklet node */
const currentTime = this.audioContext.currentTime
if (needsCompressor) {
const params = this.compressorNode!.parameters as Map<string, AudioParam>
params.get("threshold")!.setValueAtTime(this.config.thresholdDb, currentTime)
params.get("ratio")!.setValueAtTime(this.config.ratio, currentTime)
params.get("attack")!.setValueAtTime(this.config.attackMs / 1000, currentTime)
params.get("release")!.setValueAtTime(this.config.releaseMs / 1000, currentTime)
params.get("knee")!.setValueAtTime(this.config.kneeDb, currentTime)
}
/* configure gain node */
if (needsGain) {
const gain = Math.pow(10, this.config.makeupDb / 20)
this.gainNode!.gain.setValueAtTime(gain, currentTime)
}
}
/* get the current gain reduction */
public getGainReduction (): number {
return this._reduction
}
/* set the current gain */
public setGain (decibel: number): void {
const gain = Math.pow(10, decibel / 20)
this.gainNode?.gain.setTargetAtTime(gain, this.audioContext.currentTime, 0.002)
}
/* destroy the compressor */
public async destroy (): Promise<void> {
/* destroy nodes */
if (this.compressorNode !== null) {
if (this._reductionListener !== null) {
this.compressorNode.port.removeEventListener("message", this._reductionListener)
this._reductionListener = null
}
this.compressorNode.disconnect()
this.compressorNode = null
}
if (this.gainNode !== null) {
this.gainNode.disconnect()
this.gainNode = null
}
/* destroy parent */
await super.destroy()
}
}
/* SpeechFlow node for compression in audio-to-audio passing */
export default class SpeechFlowNodeA2ACompressor extends SpeechFlowNode {
/* declare official node name */
public static name = "a2a-compressor"
/* internal state */
private closing = false
private compressor: AudioCompressor | null = null
private bus: EventEmitter | null = null
private intervalId: ReturnType<typeof setInterval> | null = null
/* construct node */
constructor (id: string, cfg: { [ id: string ]: any }, opts: { [ id: string ]: any }, args: any[]) {
super(id, cfg, opts, args)
/* declare node configuration parameters */
this.configure({
type: { type: "string", val: "standalone", match: /^(?:standalone|sidechain)$/ },
mode: { type: "string", val: "compress", match: /^(?:compress|measure|adjust)$/ },
bus: { type: "string", val: "compressor", match: /^.+$/ },
thresholdDb: { type: "number", val: -23, match: (n: number) => n <= 0 && n >= -100 },
ratio: { type: "number", val: 4.0, match: (n: number) => n >= 1 && n <= 20 },
attackMs: { type: "number", val: 10, match: (n: number) => n >= 0 && n <= 1000 },
releaseMs: { type: "number", val: 50, match: (n: number) => n >= 0 && n <= 1000 },
kneeDb: { type: "number", val: 6.0, match: (n: number) => n >= 0 && n <= 40 },
makeupDb: { type: "number", val: 0, match: (n: number) => n >= -24 && n <= 24 }
})
/* sanity check mode and role */
if (this.params.type === "standalone" && this.params.mode !== "compress")
throw new Error("type \"standalone\" implies mode \"compress\"")
if (this.params.type === "sidechain" && this.params.mode === "compress")
throw new Error("type \"sidechain\" implies mode \"measure\" or \"adjust\"")
/* declare node input/output format */
this.input = "audio"
this.output = "audio"
}
/* open node */
async open () {
/* clear destruction flag */
this.closing = false
/* setup compressor */
this.compressor = new AudioCompressor(
this.config.audioSampleRate,
this.config.audioChannels,
this.params.type,
this.params.mode, {
thresholdDb: this.params.thresholdDb,
ratio: this.params.ratio,
attackMs: this.params.attackMs,
releaseMs: this.params.releaseMs,
kneeDb: this.params.kneeDb,
makeupDb: this.params.makeupDb
}
)
await this.compressor.setup()
/* optionally establish sidechain processing */
if (this.params.type === "sidechain") {
this.bus = this.accessBus(this.params.bus)
if (this.params.mode === "measure") {
this.intervalId = setInterval(() => {
const decibel = this.compressor?.getGainReduction()
this.bus?.emit("sidechain-decibel", decibel)
}, 10)
}
else if (this.params.mode === "adjust") {
this.bus.on("sidechain-decibel", (decibel: number) => {
this.compressor?.setGain(decibel)
})
}
}
/* establish a transform stream */
const self = this
this.stream = new Stream.Transform({
readableObjectMode: true,
writableObjectMode: true,
decodeStrings: false,
transform (chunk: SpeechFlowChunk & { payload: Buffer }, encoding, callback) {
if (self.closing) {
callback(new Error("stream already destroyed"))
return
}
if (!Buffer.isBuffer(chunk.payload))
callback(new Error("invalid chunk payload type"))
else if (self.compressor === null)
callback(new Error("compressor not initialized"))
else {
/* compress chunk */
const payload = util.convertBufToI16(chunk.payload, self.config.audioLittleEndian)
self.compressor.process(payload).then((result) => {
if (self.closing) {
callback(new Error("stream already destroyed"))
return
}
if ((self.params.type === "standalone" && self.params.mode === "compress")
|| (self.params.type === "sidechain" && self.params.mode === "adjust")) {
/* take over compressed data */
const payload = util.convertI16ToBuf(result, self.config.audioLittleEndian)
const chunkNew = chunk.clone()
chunkNew.payload = payload
this.push(chunkNew)
}
else
this.push(chunk)
callback()
}).catch((error: unknown) => {
if (self.closing)
callback()
else
callback(util.ensureError(error, "compression failed"))
})
}
},
final (callback) {
callback()
}
})
}
/* close node */
async close () {
/* indicate closing */
this.closing = true
/* clear interval */
if (this.intervalId !== null) {
clearInterval(this.intervalId)
this.intervalId = null
}
/* destroy bus */
if (this.bus !== null) {
this.bus.removeAllListeners()
this.bus = null
}
/* destroy compressor */
if (this.compressor !== null) {
await this.compressor.destroy()
this.compressor = null
}
/* shutdown stream */
if (this.stream !== null) {
await util.destroyStream(this.stream)
this.stream = null
}
}
}