-
Notifications
You must be signed in to change notification settings - Fork 253
Expand file tree
/
Copy pathLocalAudioTrack.ts
More file actions
253 lines (224 loc) · 7.38 KB
/
LocalAudioTrack.ts
File metadata and controls
253 lines (224 loc) · 7.38 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
import { AudioTrackFeature } from '@livekit/protocol';
import { TrackEvent } from '../events';
import { computeBitrate, monitorFrequency } from '../stats';
import type { AudioSenderStats } from '../stats';
import type { LoggerOptions } from '../types';
import { isReactNative, isWeb, unwrapConstraint } from '../utils';
import LocalTrack from './LocalTrack';
import { Track } from './Track';
import type { AudioCaptureOptions } from './options';
import type { AudioProcessorOptions, TrackProcessor } from './processor/types';
import { constraintsForOptions, detectSilence } from './utils';
export default class LocalAudioTrack extends LocalTrack<Track.Kind.Audio> {
/** @internal */
stopOnMute: boolean = false;
private prevStats?: AudioSenderStats;
private isKrispNoiseFilterEnabled = false;
protected processor?: TrackProcessor<Track.Kind.Audio, AudioProcessorOptions> | undefined;
/**
* boolean indicating whether enhanced noise cancellation is currently being used on this track
*/
get enhancedNoiseCancellation() {
return this.isKrispNoiseFilterEnabled;
}
/**
*
* @param mediaTrack
* @param constraints MediaTrackConstraints that are being used when restarting or reacquiring tracks
* @param userProvidedTrack Signals to the SDK whether or not the mediaTrack should be managed (i.e. released and reacquired) internally by the SDK
*/
constructor(
mediaTrack: MediaStreamTrack,
constraints?: MediaTrackConstraints,
userProvidedTrack = true,
audioContext?: AudioContext,
loggerOptions?: LoggerOptions,
) {
super(mediaTrack, Track.Kind.Audio, constraints, userProvidedTrack, loggerOptions);
this.audioContext = audioContext;
this.checkForSilence();
}
async mute(): Promise<typeof this> {
const unlock = await this.muteLock.lock();
try {
if (this.isMuted) {
this.log.debug('Track already muted', this.logContext);
return this;
}
// disabled special handling as it will cause BT headsets to switch communication modes
if (this.source === Track.Source.Microphone && this.stopOnMute && !this.isUserProvided) {
this.log.debug('stopping mic track', this.logContext);
// also stop the track, so that microphone indicator is turned off
this._mediaStreamTrack.stop();
}
await super.mute();
return this;
} finally {
unlock();
}
}
async unmute(): Promise<typeof this> {
const unlock = await this.muteLock.lock();
try {
if (!this.isMuted) {
this.log.debug('Track already unmuted', this.logContext);
return this;
}
const deviceHasChanged =
this._constraints.deviceId &&
this._mediaStreamTrack.getSettings().deviceId !==
unwrapConstraint(this._constraints.deviceId);
if (
this.source === Track.Source.Microphone &&
(this.stopOnMute || this._mediaStreamTrack.readyState === 'ended' || deviceHasChanged) &&
!this.isUserProvided
) {
this.log.debug('reacquiring mic track', this.logContext);
await this.restartTrack();
}
await super.unmute();
return this;
} finally {
unlock();
}
}
async restartTrack(options?: AudioCaptureOptions) {
let constraints: MediaTrackConstraints | undefined;
if (options) {
const streamConstraints = constraintsForOptions({ audio: options });
if (typeof streamConstraints.audio !== 'boolean') {
constraints = streamConstraints.audio;
}
}
await this.restart(constraints);
}
protected async restart(constraints?: MediaTrackConstraints): Promise<typeof this> {
const track = await super.restart(constraints);
this.checkForSilence();
return track;
}
/* @internal */
startMonitor() {
if (!isWeb()) {
return;
}
if (this.monitorInterval) {
return;
}
this.monitorInterval = setInterval(() => {
this.monitorSender();
}, monitorFrequency);
}
protected monitorSender = async () => {
if (!this.sender) {
this._currentBitrate = 0;
return;
}
let stats: AudioSenderStats | undefined;
try {
stats = await this.getSenderStats();
} catch (e) {
this.log.error('could not get audio sender stats', { ...this.logContext, error: e });
return;
}
if (stats && this.prevStats) {
this._currentBitrate = computeBitrate(stats, this.prevStats);
}
this.prevStats = stats;
};
private handleKrispNoiseFilterEnable = () => {
this.isKrispNoiseFilterEnabled = true;
this.log.debug(`Krisp noise filter enabled`, this.logContext);
this.emit(
TrackEvent.AudioTrackFeatureUpdate,
this,
AudioTrackFeature.TF_ENHANCED_NOISE_CANCELLATION,
true,
);
};
private handleKrispNoiseFilterDisable = () => {
this.isKrispNoiseFilterEnabled = false;
this.log.debug(`Krisp noise filter disabled`, this.logContext);
this.emit(
TrackEvent.AudioTrackFeatureUpdate,
this,
AudioTrackFeature.TF_ENHANCED_NOISE_CANCELLATION,
false,
);
};
async setProcessor(processor: TrackProcessor<Track.Kind.Audio, AudioProcessorOptions>) {
const unlock = await this.processorLock.lock();
try {
if (!isReactNative() && !this.audioContext) {
throw Error(
'Audio context needs to be set on LocalAudioTrack in order to enable processors',
);
}
if (this.processor) {
await this.stopProcessor();
}
const processorOptions = {
kind: this.kind,
track: this._mediaStreamTrack,
// RN won't have or use AudioContext
audioContext: this.audioContext as AudioContext,
};
this.log.debug(`setting up audio processor ${processor.name}`, this.logContext);
await processor.init(processorOptions);
this.processor = processor;
if (this.processor.processedTrack) {
await this.sender?.replaceTrack(this.processor.processedTrack);
this.processor.processedTrack.addEventListener(
'enable-lk-krisp-noise-filter',
this.handleKrispNoiseFilterEnable,
);
this.processor.processedTrack.addEventListener(
'disable-lk-krisp-noise-filter',
this.handleKrispNoiseFilterDisable,
);
}
this.emit(TrackEvent.TrackProcessorUpdate, this.processor);
} finally {
unlock();
}
}
/**
* @internal
* @experimental
*/
setAudioContext(audioContext: AudioContext | undefined) {
this.audioContext = audioContext;
}
async getSenderStats(): Promise<AudioSenderStats | undefined> {
if (!this.sender?.getStats) {
return undefined;
}
const stats = await this.sender.getStats();
let audioStats: AudioSenderStats | undefined;
stats.forEach((v) => {
if (v.type === 'outbound-rtp') {
audioStats = {
type: 'audio',
streamId: v.id,
packetsSent: v.packetsSent,
packetsLost: v.packetsLost,
bytesSent: v.bytesSent,
timestamp: v.timestamp,
roundTripTime: v.roundTripTime,
jitter: v.jitter,
};
}
});
return audioStats;
}
async checkForSilence() {
const trackIsSilent = await detectSilence(this);
if (trackIsSilent) {
if (!this.isMuted) {
this.log.warn('silence detected on local audio track', this.logContext);
}
this.emit(TrackEvent.AudioSilenceDetected);
}
return trackIsSilent;
}
}