-
Notifications
You must be signed in to change notification settings - Fork 6
/
CumulativeVoiceActivityDetector.cs
334 lines (288 loc) · 12.1 KB
/
CumulativeVoiceActivityDetector.cs
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
323
324
325
326
327
328
329
330
331
332
333
334
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Threading;
using Cysharp.Threading.Tasks;
using UniRx;
using Unity.Logging;
namespace Mochineko.VoiceActivityDetection
{
/// <summary>
/// A voice activity detector that detects voice activity by cumulative and upper limited charge time.
/// </summary>
public sealed class CumulativeVoiceActivityDetector : IVoiceActivityDetector
{
private readonly IVoiceSource source;
private readonly IVoiceBuffer buffer;
private readonly float activeVolumeThreshold;
private readonly float activeChargeTimeRate;
private readonly float maxChargeTimeSeconds;
private readonly float minCumulatedTimeSeconds;
private readonly float maxCumulatedTimeSeconds;
private readonly ActiveState activeState;
private readonly InactivateState inactivateState;
private readonly IDisposable onSegmentReadDisposable;
private readonly CancellationTokenSource cancellationTokenSource = new();
private readonly ReactiveProperty<bool> voiceIsActive = new();
IReadOnlyReactiveProperty<bool> IVoiceActivityDetector.VoiceIsActive => voiceIsActive;
private readonly Subject<Unit> onVoiceLost = new();
/// <summary>
/// Event that is raised when short voice is lost.
/// </summary>
public IObservable<Unit> OnVoiceLost => onVoiceLost;
/// <summary>
/// Create a new instance of <see cref="CumulativeVoiceActivityDetector"/>.
/// </summary>
/// <param name="source">Voice source.</param>
/// <param name="buffer">Voice buffer.</param>
/// <param name="activeVolumeThreshold">Threshold of active volume (root mean square) of voice data.</param>
/// <param name="activeChargeTimeRate">Rate to charge time for active voice.</param>
/// <param name="maxChargeTimeSeconds">Maximum and initial charge time in seconds.</param>
/// <param name="minCumulatedTimeSeconds">Minimum of cumulated time in seconds to buffer.</param>
/// <param name="maxCumulatedTimeSeconds">Maximum of cumulated time in seconds to buffer.</param>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public CumulativeVoiceActivityDetector(
IVoiceSource source,
IVoiceBuffer buffer,
float activeVolumeThreshold,
float activeChargeTimeRate,
float maxChargeTimeSeconds,
float minCumulatedTimeSeconds,
float maxCumulatedTimeSeconds)
{
if (activeVolumeThreshold <= 0f)
{
throw new ArgumentOutOfRangeException(nameof(activeVolumeThreshold), activeVolumeThreshold,
"Must be greater than 0.");
}
if (activeChargeTimeRate <= 0f)
{
throw new ArgumentOutOfRangeException(nameof(activeChargeTimeRate), activeChargeTimeRate,
"Must be greater than 0.");
}
if (maxChargeTimeSeconds <= 0f)
{
throw new ArgumentOutOfRangeException(nameof(maxChargeTimeSeconds), maxChargeTimeSeconds,
"Must be greater than 0.");
}
if (minCumulatedTimeSeconds <= 0f)
{
throw new ArgumentOutOfRangeException(nameof(minCumulatedTimeSeconds),
minCumulatedTimeSeconds, "Must be greater than 0.");
}
if (maxCumulatedTimeSeconds <= 0f)
{
throw new ArgumentOutOfRangeException(nameof(maxCumulatedTimeSeconds),
maxCumulatedTimeSeconds, "Must be greater than 0.");
}
if (minCumulatedTimeSeconds > maxCumulatedTimeSeconds)
{
throw new ArgumentOutOfRangeException(nameof(minCumulatedTimeSeconds),
minCumulatedTimeSeconds, "Must be less than maxCumulatedTimeSeconds.");
}
this.source = source;
this.buffer = buffer;
this.activeVolumeThreshold = activeVolumeThreshold;
this.activeChargeTimeRate = activeChargeTimeRate;
this.maxChargeTimeSeconds = maxChargeTimeSeconds;
this.minCumulatedTimeSeconds = minCumulatedTimeSeconds;
this.maxCumulatedTimeSeconds = maxCumulatedTimeSeconds;
onSegmentReadDisposable = this.source
.OnSegmentRead
.Subscribe(OnSegmentReadAsync);
this.activeState = new ActiveState(this);
this.inactivateState = new InactivateState(this);
inactivateState.Enter();
}
void IDisposable.Dispose()
{
onSegmentReadDisposable.Dispose();
cancellationTokenSource.Cancel();
cancellationTokenSource.Dispose();
activeState.Exit();
inactivateState.Exit();
buffer.Dispose();
source.Dispose();
}
void IVoiceActivityDetector.SetDetectorActive(bool isActive)
{
source.SetSourceActive(isActive);
// Force to inactivate
if (!isActive && voiceIsActive.Value)
{
activeState.Exit();
inactivateState.Enter();
buffer.OnVoiceInactiveAsync(cancellationTokenSource.Token)
.Forget();
}
}
void IVoiceActivityDetector.Update()
{
source.Update();
}
private async void OnSegmentReadAsync(VoiceSegment segment)
{
var cancellationToken = cancellationTokenSource.Token;
if (voiceIsActive.Value)
{
var changeToInactive = await activeState.UpdateAsync(segment, cancellationToken);
if (changeToInactive)
{
// Change to InactivateState
activeState.Exit();
inactivateState.Enter();
await buffer.OnVoiceInactiveAsync(cancellationToken);
}
}
else
{
var changeToActive = await inactivateState.UpdateAsync(segment, cancellationToken);
if (changeToActive)
{
// Change to ActiveState
inactivateState.Exit();
activeState.Enter();
await buffer.OnVoiceActiveAsync(cancellationToken);
// NOTE: Add initial segment to queue in active state.
var __ = await activeState.UpdateAsync(segment, cancellationToken);
}
}
}
private sealed class ActiveState
{
private readonly CumulativeVoiceActivityDetector parent;
private readonly ConcurrentQueue<VoiceSegment> queue = new();
private float chargeTimeSeconds;
private float cumulatedTimeSeconds;
private float activeTimeSeconds;
public ActiveState(CumulativeVoiceActivityDetector parent)
{
this.parent = parent;
}
public void Enter()
{
Log.Debug("[VAD] Enter ActiveState.");
chargeTimeSeconds = parent.maxChargeTimeSeconds;
cumulatedTimeSeconds = 0f;
activeTimeSeconds = 0f;
}
public void Exit()
{
while (queue.TryDequeue(out var segment))
{
segment.Dispose();
}
}
/// <summary>
/// Add segment and update state.
/// Returns true if state is changed to inactive state.
/// </summary>
/// <param name="segment"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async UniTask<bool> UpdateAsync(
VoiceSegment segment,
CancellationToken cancellationToken)
{
var isActive = segment.Volume >= parent.activeVolumeThreshold;
var durationSeconds = segment.DurationSeconds;
cumulatedTimeSeconds += durationSeconds;
queue.Enqueue(segment);
// Spend
chargeTimeSeconds -= durationSeconds;
if (isActive)
{
activeTimeSeconds += durationSeconds;
// Charge
chargeTimeSeconds += durationSeconds * parent.activeChargeTimeRate;
}
if (chargeTimeSeconds > parent.maxChargeTimeSeconds)
{
// Limit
chargeTimeSeconds = parent.maxChargeTimeSeconds;
}
Log.Verbose("[VAD] Charge time: {0}, Cumulated time: {1}", chargeTimeSeconds, cumulatedTimeSeconds);
// Finish active state
if (cumulatedTimeSeconds >= parent.maxCumulatedTimeSeconds
|| chargeTimeSeconds <= 0f)
{
// NOTE: Quickly change to inactive state before buffering.
parent.voiceIsActive.Value = false;
var isEffectiveSegments = activeTimeSeconds >= parent.minCumulatedTimeSeconds;
if (isEffectiveSegments)
{
Log.Debug("[VAD] Effective segments: {0}", activeTimeSeconds);
// Write all segments in queue to buffer.
while (
queue.TryDequeue(out var dequeued)
&& !cancellationToken.IsCancellationRequested)
{
await parent.buffer.BufferAsync(dequeued, cancellationToken);
dequeued.Dispose();
}
}
else
{
// NOTE: Not effective segments are ignored.
Log.Debug("[VAD] Ignored segments: {0}", activeTimeSeconds);
// Clear queue
while (queue.TryDequeue(out var dequeued))
{
dequeued.Dispose();
}
parent.onVoiceLost.OnNext(Unit.Default);
}
// Change to InactivateState
return true;
}
else
{
// Stay ActiveState
return false;
}
}
}
private sealed class InactivateState
{
private readonly CumulativeVoiceActivityDetector parent;
public InactivateState(CumulativeVoiceActivityDetector parent)
{
this.parent = parent;
}
public void Enter()
{
Log.Debug("[VAD] Enter InactiveState.");
parent.voiceIsActive.Value = false;
}
public void Exit()
{
}
/// <summary>
/// Add segment and update state.
/// Returns true if state is changed to active state.
/// </summary>
/// <param name="segment"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public UniTask<bool> UpdateAsync(
VoiceSegment segment,
CancellationToken cancellationToken)
{
var isActive = segment.Volume >= parent.activeVolumeThreshold;
if (isActive)
{
// Change to ActiveState
parent.voiceIsActive.Value = true;
// NOTE: Not dispose segment to enqueue in ActiveState.
return UniTask.FromResult(true);
}
else
{
// Stay InactivateState
segment.Dispose();
return UniTask.FromResult(false);
}
}
}
}
}