File size: 8,313 Bytes
6ac63e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System;
using System.Runtime.InteropServices;
using UnityEngine;

public class TenVADRunner : IDisposable
{
#if UNITY_WEBGL && !UNITY_EDITOR
    [DllImport("__Internal")]
    private static extern int WebGLTenVad_Create(int hopSize, float threshold);

    [DllImport("__Internal")]
    private static extern int WebGLTenVad_Process(int instanceId, short[] audioData, int audioDataLength, out float outProbability, out int outFlag);

    [DllImport("__Internal")]
    private static extern int WebGLTenVad_Destroy(int instanceId);

    [DllImport("__Internal")]
    private static extern int WebGLTenVad_GetState();

    private const int WebGlStateLoading = 0;
    private const int WebGlStateError = -1;
    private const int WebGlPending = -2;

    private int webGlInstanceId;
    private readonly int webGlHopSize;
    private readonly float webGlThreshold;
#else
    private const string DllName = "ten_vad";

    [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
    private static extern int ten_vad_create(out IntPtr handle, UIntPtr hop_size, float threshold);

    [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
    private static extern int ten_vad_process(IntPtr handle, short[] audio_data, UIntPtr audio_data_length, out float out_probability, out int out_flag);

    [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
    private static extern int ten_vad_destroy(ref IntPtr handle);

    private IntPtr vadHandle = IntPtr.Zero;
#endif
    private bool isDisposed = false;
    private bool useFallbackVad = false;
    private readonly float fallbackThreshold;
    private float fallbackSmoothedProbability;

#if UNITY_WEBGL && !UNITY_EDITOR
    private const float FallbackRmsScale = 140f;
#else
    private const float FallbackRmsScale = 20f;
#endif
    private const float FallbackSmoothing = 0.35f;

    public TenVADRunner(UIntPtr hopSize, float threshold)
    {
        fallbackThreshold = Mathf.Clamp01(threshold);
        fallbackSmoothedProbability = 0f;

#if UNITY_WEBGL && !UNITY_EDITOR
        webGlHopSize = Math.Max(1, (int)hopSize.ToUInt64());
        webGlThreshold = threshold;
        TryInitializeWebGlVad();
#else
        try
        {
            int result = ten_vad_create(out vadHandle, hopSize, threshold);
            if (result != 0 || vadHandle == IntPtr.Zero)
            {
                EnableFallback($"Failed to create VAD Handle. (Error Code: {result})");
                return;
            }
        }
        catch (DllNotFoundException ex)
        {
            EnableFallback($"Native VAD library '{DllName}' was not found. {ex.Message}");
        }
        catch (EntryPointNotFoundException ex)
        {
            EnableFallback($"Native VAD entry point was not found. {ex.Message}");
        }
        catch (Exception ex)
        {
            EnableFallback($"Native VAD initialization failed. {ex.Message}");
        }
#endif        
    }

    public int Process(short[] audioData, out float probability, out int flag)
    {
        if (isDisposed)
        {
            throw new ObjectDisposedException(nameof(TenVADRunner), "The VAD instance has already been disposed.");
        }
        if (audioData == null || audioData.Length == 0)
        {
            probability = 0;
            flag = 0;
            return -1;
        }

        if (!useFallbackVad)
        {
#if UNITY_WEBGL && !UNITY_EDITOR
            if (webGlInstanceId <= 0)
            {
                if (!TryInitializeWebGlVad())
                    return ProcessWithFallback(audioData, out probability, out flag);
            }

            try
            {
                int result = WebGLTenVad_Process(webGlInstanceId, audioData, audioData.Length, out probability, out flag);
                if (result == 0)
                    return result;

                if (result == WebGlPending)
                    return ProcessWithFallback(audioData, out probability, out flag);

                int state = SafeGetWebGlState();
                EnableFallback($"WebGL ten_vad processing failed. result={result}, state={state}");
            }
            catch (Exception ex)
            {
                EnableFallback($"WebGL ten_vad processing bridge failed. {ex.Message}");
            }
#else
            if (vadHandle != IntPtr.Zero)
            {
                try
                {
                    int result = ten_vad_process(vadHandle, audioData, (UIntPtr)audioData.Length, out probability, out flag);
                    return result;
                }
                catch (DllNotFoundException ex)
                {
                    EnableFallback($"Native VAD library '{DllName}' disappeared at runtime. {ex.Message}");
                }
                catch (EntryPointNotFoundException ex)
                {
                    EnableFallback($"Native VAD entry point missing at runtime. {ex.Message}");
                }
                catch (Exception ex)
                {
                    EnableFallback($"Native VAD processing failed. {ex.Message}");
                }
            }
#endif
        }

        return ProcessWithFallback(audioData, out probability, out flag);
    }
    
    public void Dispose()
    {
        if (isDisposed)
            return;

#if UNITY_WEBGL && !UNITY_EDITOR
        if (!useFallbackVad && webGlInstanceId > 0)
        {
            try
            {
                WebGLTenVad_Destroy(webGlInstanceId);
            }
            catch (Exception)
            {
                // Ignore disposal failures for browser teardown.
            }

            webGlInstanceId = 0;
        }
#else
        if (!useFallbackVad && vadHandle != IntPtr.Zero)
        {
            try
            {
                ten_vad_destroy(ref vadHandle);
            }
            catch (Exception)
            {
                // Ignore disposal failures for native plugin teardown.
            }

            vadHandle = IntPtr.Zero;
        }
#endif

        isDisposed = true;
    }

    private void EnableFallback(string reason)
    {
        if (useFallbackVad)
            return;

        useFallbackVad = true;
#if UNITY_WEBGL && !UNITY_EDITOR
        webGlInstanceId = 0;
        Debug.LogWarning($"[TenVADRunner] Falling back to RMS VAD on WebGL. Reason: {reason}");
#else
        vadHandle = IntPtr.Zero;
        Debug.LogWarning($"[TenVADRunner] Falling back to simple RMS VAD. Reason: {reason}");
#endif
    }

    #if UNITY_WEBGL && !UNITY_EDITOR
    private bool TryInitializeWebGlVad()
    {
        if (webGlInstanceId > 0)
            return true;

        int createResult;
        try
        {
            createResult = WebGLTenVad_Create(webGlHopSize, webGlThreshold);
        }
        catch (Exception ex)
        {
            EnableFallback($"WebGL ten_vad bridge is unavailable. {ex.Message}");
            return false;
        }

        if (createResult > 0)
        {
            webGlInstanceId = createResult;
            return true;
        }

        if (createResult == WebGlPending || createResult == WebGlStateLoading)
        {
            return false;
        }

        int state = SafeGetWebGlState();
        if (state == WebGlStateError || createResult < 0)
        {
            EnableFallback($"WebGL ten_vad initialization failed. createResult={createResult}, state={state}");
        }
        return false;
    }

    private int SafeGetWebGlState()
    {
        try
        {
            return WebGLTenVad_GetState();
        }
        catch
        {
            return WebGlStateError;
        }
    }
    #endif

    private int ProcessWithFallback(short[] audioData, out float probability, out int flag)
    {
        double sumSquares = 0d;
        for (int i = 0; i < audioData.Length; i++)
        {
            float sample = audioData[i] / 32768f;
            sumSquares += sample * sample;
        }

        float rms = (float)Math.Sqrt(sumSquares / audioData.Length);
        float rawProbability = Mathf.Clamp01(rms * FallbackRmsScale);
        fallbackSmoothedProbability = Mathf.Lerp(fallbackSmoothedProbability, rawProbability, FallbackSmoothing);

        probability = fallbackSmoothedProbability;
        flag = probability >= fallbackThreshold ? 1 : 0;
        return 0;
    }
}