|
@@ -0,0 +1,155 @@
|
|
1
|
+import EventEmitter from 'events';
|
|
2
|
+import RTC from '../RTC/RTC';
|
|
3
|
+import { VAD_SCORE_PUBLISHED } from './DetectionEvents';
|
|
4
|
+
|
|
5
|
+/**
|
|
6
|
+ * Connects an audio JitsiLocalTrack to a vadProcessor using WebAudio ScriptProcessorNode.
|
|
7
|
+ * Once an object is created audio from the local track flows through the ScriptProcessorNode as raw PCM.
|
|
8
|
+ * The PCM is processed by the injected vad module and a voice activity detection score is obtained, the
|
|
9
|
+ * score is published to consumers via an EventEmitter.
|
|
10
|
+ * After work is done with this service the destroy method needs to be called for a proper cleanup.
|
|
11
|
+ */
|
|
12
|
+export default class TrackVADEmitter extends EventEmitter {
|
|
13
|
+ /**
|
|
14
|
+ * Constructor.
|
|
15
|
+ *
|
|
16
|
+ * @param {number} procNodeSampleRate - Sample rate of the ScriptProcessorNode. Possible values 256, 512, 1024,
|
|
17
|
+ * 2048, 4096, 8192, 16384. Passing other values will default to closes neighbor.
|
|
18
|
+ * @param {Object} vadProcessor - adapter that allows us to calculate VAD score
|
|
19
|
+ * for PCM samples.
|
|
20
|
+ * @param {Object} jitsiLocalTrack - JitsiLocalTrack corresponding to micDeviceId.
|
|
21
|
+ */
|
|
22
|
+ constructor(procNodeSampleRate, vadProcessor, jitsiLocalTrack) {
|
|
23
|
+ super();
|
|
24
|
+ this._procNodeSampleRate = procNodeSampleRate;
|
|
25
|
+ this._vadProcessor = vadProcessor;
|
|
26
|
+ this._localTrack = jitsiLocalTrack;
|
|
27
|
+ this._micDeviceId = jitsiLocalTrack.getDeviceId();
|
|
28
|
+ this._bufferResidue = new Float32Array([]);
|
|
29
|
+ this._audioContext = new AudioContext({ sampleRate: 44100 });
|
|
30
|
+
|
|
31
|
+ this._vadSampleSize = vadProcessor.getSampleLength();
|
|
32
|
+ this._onAudioProcess = this._onAudioProcess.bind(this);
|
|
33
|
+
|
|
34
|
+ this._initializeAudioContext();
|
|
35
|
+ this._connectAudioGraph();
|
|
36
|
+ }
|
|
37
|
+
|
|
38
|
+ /**
|
|
39
|
+ * Factory method that sets up all the necessary components for the creation of the TrackVADEmitter.
|
|
40
|
+ *
|
|
41
|
+ * @param {string} micDeviceId - Target microphone device id.
|
|
42
|
+ * @param {number} procNodeSampleRate - Sample rate of the proc node.
|
|
43
|
+ * @returns {Promise<TrackVADEmitter>} - Promise resolving in a new instance of TrackVADEmitter.
|
|
44
|
+ */
|
|
45
|
+ static create(micDeviceId, procNodeSampleRate, vadProcessor) {
|
|
46
|
+ return RTC.obtainAudioAndVideoPermissions({
|
|
47
|
+ devices: [ 'audio' ],
|
|
48
|
+ micDeviceId
|
|
49
|
+ }).then(localTrack => {
|
|
50
|
+ // We only expect one audio track when specifying a device id.
|
|
51
|
+ if (!localTrack[0]) {
|
|
52
|
+ throw new Error(`Failed to create jitsi local track for device id: ${micDeviceId}`);
|
|
53
|
+ }
|
|
54
|
+
|
|
55
|
+ return new TrackVADEmitter(procNodeSampleRate, vadProcessor, localTrack[0]);
|
|
56
|
+
|
|
57
|
+ // We have no exception handling at this point as there is nothing to clean up, the vadProcessor
|
|
58
|
+ // life cycle is handled by whoever created this instance.
|
|
59
|
+ });
|
|
60
|
+ }
|
|
61
|
+
|
|
62
|
+ /**
|
|
63
|
+ * Sets up the audio graph in the AudioContext.
|
|
64
|
+ *
|
|
65
|
+ * @returns {Promise<void>}
|
|
66
|
+ */
|
|
67
|
+ _initializeAudioContext() {
|
|
68
|
+ this._audioSource = this._audioContext.createMediaStreamSource(this._localTrack.stream);
|
|
69
|
+
|
|
70
|
+ // TODO AudioProcessingNode is deprecated check and replace with alternative.
|
|
71
|
+ // We don't need stereo for determining the VAD score so we create a single channel processing node.
|
|
72
|
+ this._audioProcessingNode = this._audioContext.createScriptProcessor(this._procNodeSampleRate, 1, 1);
|
|
73
|
+ this._audioProcessingNode.onaudioprocess = this._onAudioProcess;
|
|
74
|
+ }
|
|
75
|
+
|
|
76
|
+ /**
|
|
77
|
+ * TODO maybe move this logic to the VAD Processor.
|
|
78
|
+ * ScriptProcessorNode callback, the input parameters contains the PCM audio that is then sent to rnnoise.
|
|
79
|
+ * Rnnoise only accepts PCM samples of 480 bytes whereas the webaudio processor node can't sample at a multiple
|
|
80
|
+ * of 480 thus after each _onAudioProcess callback there will remain and PCM buffer residue equal
|
|
81
|
+ * to _procNodeSampleRate / 480 which will be added to the next sample buffer and so on.
|
|
82
|
+ *
|
|
83
|
+ * @param {AudioProcessingEvent} audioEvent - Audio event.
|
|
84
|
+ * @returns {void}
|
|
85
|
+ */
|
|
86
|
+ _onAudioProcess(audioEvent) {
|
|
87
|
+ // Prepend the residue PCM buffer from the previous process callback.
|
|
88
|
+ const inData = audioEvent.inputBuffer.getChannelData(0);
|
|
89
|
+ const completeInData = [ ...this._bufferResidue, ...inData ];
|
|
90
|
+ const sampleTimestamp = Date.now();
|
|
91
|
+
|
|
92
|
+ let i = 0;
|
|
93
|
+
|
|
94
|
+ for (; i + this._vadSampleSize < completeInData.length; i += this._vadSampleSize) {
|
|
95
|
+ const pcmSample = completeInData.slice(i, i + this._vadSampleSize);
|
|
96
|
+ const vadScore = this._vadProcessor.calculateAudioFrameVAD(pcmSample);
|
|
97
|
+
|
|
98
|
+ this.emit(VAD_SCORE_PUBLISHED, {
|
|
99
|
+ timestamp: sampleTimestamp,
|
|
100
|
+ score: vadScore,
|
|
101
|
+ deviceId: this._micDeviceId
|
|
102
|
+ });
|
|
103
|
+ }
|
|
104
|
+
|
|
105
|
+ this._bufferResidue = completeInData.slice(i, completeInData.length);
|
|
106
|
+ }
|
|
107
|
+
|
|
108
|
+ /**
|
|
109
|
+ * Connects the nodes in the AudioContext to start the flow of audio data.
|
|
110
|
+ *
|
|
111
|
+ * @returns {void}
|
|
112
|
+ */
|
|
113
|
+ _connectAudioGraph() {
|
|
114
|
+ this._audioSource.connect(this._audioProcessingNode);
|
|
115
|
+ this._audioProcessingNode.connect(this._audioContext.destination);
|
|
116
|
+ }
|
|
117
|
+
|
|
118
|
+ /**
|
|
119
|
+ * Disconnects the nodes in the AudioContext.
|
|
120
|
+ *
|
|
121
|
+ * @returns {void}
|
|
122
|
+ */
|
|
123
|
+ _disconnectAudioGraph() {
|
|
124
|
+ // Even thought we disconnect the processing node it seems that some callbacks remain queued,
|
|
125
|
+ // resulting in calls with and uninitialized context.
|
|
126
|
+ // eslint-disable-next-line no-empty-function
|
|
127
|
+ this._audioProcessingNode.onaudioprocess = () => {};
|
|
128
|
+ this._audioProcessingNode.disconnect();
|
|
129
|
+ this._audioSource.disconnect();
|
|
130
|
+ }
|
|
131
|
+
|
|
132
|
+ /**
|
|
133
|
+ * Cleanup potentially acquired resources.
|
|
134
|
+ *
|
|
135
|
+ * @returns {void}
|
|
136
|
+ */
|
|
137
|
+ _cleanupResources() {
|
|
138
|
+ this._disconnectAudioGraph();
|
|
139
|
+ this._localTrack.stopStream();
|
|
140
|
+ }
|
|
141
|
+
|
|
142
|
+ /**
|
|
143
|
+ * Destroy TrackVADEmitter instance (release resources and stop callbacks).
|
|
144
|
+ *
|
|
145
|
+ * @returns {void}
|
|
146
|
+ */
|
|
147
|
+ destroy() {
|
|
148
|
+ if (this._destroyed) {
|
|
149
|
+ return;
|
|
150
|
+ }
|
|
151
|
+
|
|
152
|
+ this._cleanupResources();
|
|
153
|
+ this._destroyed = true;
|
|
154
|
+ }
|
|
155
|
+}
|