-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMetaVc.cs
More file actions
235 lines (188 loc) · 8.11 KB
/
MetaVc.cs
File metadata and controls
235 lines (188 loc) · 8.11 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
// This project referenced the following projects in its beginnings, which were created by Vatsal Ambastha:
// https://github.com/adrenak/univoice
// https://github.com/adrenak/univoice-unimic-input
// https://github.com/adrenak/unimic
// https://github.com/adrenak/univoice-audiosource-output
// This was created by Connor Myers (Metater):
// https://github.com/Metater
using System;
using MetaVoiceChat.Input;
using MetaVoiceChat.NetProviders;
using MetaVoiceChat.Opus;
using MetaVoiceChat.Output;
using MetaVoiceChat.Utils;
using UnityEngine;
namespace MetaVoiceChat
{
public class MetaVc : MonoBehaviour
{
private const string CodecTimeOverrunMessage = "Opus codec took too long this frame. It is recommended to decrease Opus complexity until this message is rare as long as you have a sensible max codec ms value chosen to maintain your desired fps.";
[Header("General")]
public VcAudioInput audioInput;
public VcAudioOutput audioOutput;
public VcConfig config;
[Header("Testing")]
[Tooltip("This plays back the voice of the local player.")]
public bool isEchoEnabled;
[Tooltip("This overwrites the audio input with a 200 Hz sine wave at 20% volume.")]
public bool isSineOverrideEnabled;
[Tooltip("The maximum time allowed per frame in milliseconds for all Opus encoding and decoding before giving a warning. This helps you ensure that the Opus codec is not limiting your fps. Disable the warnings by increasing this to its max.")]
[Range(0, 100)]
public float maxCodecMilliseconds = 50;
[Tooltip("This allows multiple codec time overrun warnings per frame.")]
public bool allowMultipleCodecWarningsPerFrame;
[Header("Serializable Reactive Properties")]
[Tooltip("This is the local player and they don't want to hear anyone else.")]
public MetaSerializableReactiveProperty<bool> isDeafened;
[Tooltip("This is the local player and they don't want anyone to hear them.")]
public MetaSerializableReactiveProperty<bool> isInputMuted;
[Tooltip("This is a remote player that the local player doesn't want to hear.")]
public MetaSerializableReactiveProperty<bool> isOutputMuted;
[Tooltip("This player is speaking or trying to speak.")]
public MetaSerializableReactiveProperty<bool> isSpeaking;
private INetProvider netProvider;
private bool isLocalPlayer;
private VcEncoder encoder;
private VcDecoder decoder;
private VcJitter jitter;
private readonly System.Diagnostics.Stopwatch stopwatch = new();
private double Timestamp => stopwatch.Elapsed.TotalSeconds;
private bool CannotSpeak => netProvider.IsLocalPlayerDeafened || isOutputMuted;
private bool ShouldLocalEcho => isLocalPlayer && isEchoEnabled;
private static readonly FrameStopwatch codecStopwatch = new();
private void Awake()
{
config.Init();
codecStopwatch.Reset();
}
public void StartClient(INetProvider netProvider, bool isLocalPlayer, int maxDataBytesPerPacket)
{
this.netProvider = netProvider;
this.isLocalPlayer = isLocalPlayer;
if (isLocalPlayer)
{
encoder = new(config, maxDataBytesPerPacket);
audioInput.OnFrameReady += SendFrame;
audioInput.StartLocalPlayer();
}
decoder = new(config);
jitter = new(config);
stopwatch.Start();
}
private void SendFrame(int index, float[] samples)
{
if (samples != null && isSineOverrideEnabled)
{
const float Amplitude = 0.2f;
float multiplier = Mathf.PI * (1.0f / 40.0f); // 200 Hz
for (int i = 0; i < samples.Length; i++)
{
samples[i] = Amplitude * Mathf.Sin(i * multiplier);
}
}
bool isSpeaking = samples != null;
this.isSpeaking.Value = isSpeaking;
bool shouldRelayEmpty;
if (isEchoEnabled)
{
shouldRelayEmpty = !isSpeaking;
}
else
{
shouldRelayEmpty = !isSpeaking || isDeafened || isInputMuted;
}
if (shouldRelayEmpty)
{
//if (isEchoEnabled)
//{
ReceiveFrame(index, Timestamp, additionalLatency: 0, ReadOnlySpan<byte>.Empty);
//}
netProvider.RelayFrame(index, Timestamp, ReadOnlySpan<byte>.Empty);
}
else
{
bool hasEncodedYet = encoder.HasEncodedYet;
codecStopwatch.Start();
var data = encoder.EncodeFrame(samples.AsSpan());
codecStopwatch.Stop(maxCodecMilliseconds, CodecTimeOverrunMessage, !hasEncodedYet, allowMultipleCodecWarningsPerFrame);
if (isEchoEnabled)
{
ReceiveFrame(index, Timestamp, additionalLatency: 0, data);
}
else
{
ReceiveFrame(index, Timestamp, additionalLatency: 0, ReadOnlySpan<byte>.Empty);
}
if (isDeafened || isInputMuted)
{
netProvider.RelayFrame(index, Timestamp, ReadOnlySpan<byte>.Empty);
}
else
{
netProvider.RelayFrame(index, Timestamp, data);
}
}
}
public void ReceiveFrame(int index, double timestamp, float additionalLatency, ReadOnlySpan<byte> data)
{
float targetLatency = (config.secondsPerFrame * config.outputMinBufferSize) + Time.deltaTime + additionalLatency;
if (!isLocalPlayer)
{
// Exponential backoff is an alternative to the current jitter calculation, but this works!
float jitter = this.jitter.Update(timestamp);
targetLatency += jitter;
}
if (data.Length == 0)
{
SetIsSpeaking(false);
audioOutput.ReceiveAndFilterFrame(index, null, targetLatency);
}
else
{
SetIsSpeaking(true);
if (CannotSpeak && !ShouldLocalEcho)
{
audioOutput.ReceiveAndFilterFrame(index, null, targetLatency);
}
else
{
bool hasDecodedYet = decoder.HasDecodedYet;
codecStopwatch.Start();
var samples = decoder.DecodeFrame(data);
codecStopwatch.Stop(maxCodecMilliseconds, CodecTimeOverrunMessage, !hasDecodedYet, allowMultipleCodecWarningsPerFrame);
if (samples.Length == config.samplesPerFrame)
{
var array = FixedLengthArrayPool<float>.Rent(samples.Length);
samples.CopyTo(array);
audioOutput.ReceiveAndFilterFrame(index, array, targetLatency);
FixedLengthArrayPool<float>.Return(array);
}
else
{
// Silently ignore the frame with invalid length
audioOutput.ReceiveAndFilterFrame(index, null, targetLatency);
}
}
}
}
public void StopClient()
{
if (isLocalPlayer)
{
encoder.Dispose();
audioInput.OnFrameReady -= SendFrame;
}
decoder.Dispose();
}
private void SetIsSpeaking(bool value)
{
if (isLocalPlayer/* && isEchoEnabled*/)
{
// If this is a local player, the only way to get here is echo being enabled
// Return because isSpeaking is already set in SendFrame for echo mode
return;
}
isSpeaking.Value = value;
}
}
}