-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathVoiceChatTrackManager.cs
More file actions
322 lines (266 loc) · 12.6 KB
/
Copy pathVoiceChatTrackManager.cs
File metadata and controls
322 lines (266 loc) · 12.6 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
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
using Cysharp.Threading.Tasks;
using DCL.Audio;
using DCL.Diagnostics;
using DCL.NotificationsBus;
using DCL.NotificationsBus.NotificationTypes;
using DCL.Settings.Settings;
using DCL.Utilities.Extensions;
using LiveKit.Audio;
using LiveKit.Proto;
using LiveKit.Rooms;
using LiveKit.Rooms.Participants;
using LiveKit.Rooms.Streaming;
using LiveKit.Rooms.Streaming.Audio;
using LiveKit.Rooms.TrackPublications;
using LiveKit.Rooms.Tracks;
using LiveKit.Runtime.Scripts.Audio;
using RichTypes;
using System;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using Utility;
using Utility.Multithreading;
#if UNITY_STANDALONE_OSX
using DCL.VoiceChat.Permissions;
# endif
using AudioStreamInfo = LiveKit.Rooms.Streaming.Audio.AudioStreamInfo;
namespace DCL.VoiceChat
{
/// <summary>
/// Manages audio track publishing, subscribing, and lifecycle for voice chat.
/// </summary>
public class VoiceChatTrackManager : IDisposable
{
private const string TAG = nameof(VoiceChatTrackManager);
private readonly IRoom voiceChatRoom;
private readonly VoiceChatConfiguration configuration;
private readonly PlaybackSourcesHub playbackSourcesHub;
private readonly VoiceChatMicrophoneHandler microphoneHandler;
private readonly SemaphoreSlim semaphoreSlimMicrophone = new (1, 1);
private CancellationTokenSource? trackPublishingCts;
private bool isDisposed;
private MicrophoneTrack? microphoneTrack;
public Weak<MicrophoneRtcAudioSource> CurrentMicrophone => microphoneTrack?.Source ?? Weak<MicrophoneRtcAudioSource>.Null;
public IReadOnlyDictionary<StreamKey, (Weak<AudioStream> stream, LivekitAudioSource source)> RemoteStreams => playbackSourcesHub.Streams;
public VoiceChatTrackManager(
IRoom voiceChatRoom,
VoiceChatConfiguration configuration,
VoiceChatMicrophoneHandler microphoneHandler)
{
this.voiceChatRoom = voiceChatRoom;
this.configuration = configuration;
this.microphoneHandler = microphoneHandler;
playbackSourcesHub = new PlaybackSourcesHub(configuration.ChatAudioMixerGroup.EnsureNotNull());
}
public void Dispose()
{
if (isDisposed) return;
isDisposed = true;
UnpublishLocalTrack();
StopListeningToRemoteTracks();
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} Disposed");
semaphoreSlimMicrophone.Dispose();
}
public void ActiveStreamsInfo(List<StreamInfo<AudioStreamInfo>> output)
{
voiceChatRoom.AudioStreams.ListInfo(output);
}
/// <summary>
/// Publishes the local microphone track to the room.
/// Creates and starts the OptimizedMonoRtcAudioSource if needed.
/// </summary>
public async UniTaskVoid PublishLocalTrackAsync(CancellationToken ct)
{
using var _ = await semaphoreSlimMicrophone.LockAsync();
if (microphoneTrack.HasValue)
{
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} Local track already published");
return;
}
//Raise volume if its Windows because for some reason Mac Volume is way higher than Windows.
if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor)
configuration.AudioMixerGroup.audioMixer.SetFloat(nameof(AudioMixerExposedParam.Microphone_Volume), 13);
#if UNITY_STANDALONE_OSX
bool hasPermissions = await VoiceChatPermissions.GuardAsync(ct);
if (hasPermissions == false)
{
ReportHub.LogError(ReportCategory.VOICE_CHAT, "Microphone permissions were not granted by user, cannot publish local track");
return;
}
#endif
try
{
Result<MicrophoneSelection> reachable = VoiceChatSettings.ReachableSelection();
if (reachable.Success == false)
{
NotificationsBusController.Instance.AddNotification(new ServerErrorNotification("No Available Microphone"));
throw new Exception(reachable.ErrorMessage!);
}
Result<MicrophoneRtcAudioSource> result = MicrophoneRtcAudioSource.New(
reachable.Value,
(configuration.AudioMixerGroup.audioMixer, nameof(AudioMixerExposedParam.Microphone_Volume)),
configuration.microphonePlaybackToSpeakers
);
if (!result.Success) throw new Exception($"Couldn't create RTCAudioSource: {result.ErrorMessage}");
MicrophoneRtcAudioSource rtcAudioSource = result.Value;
rtcAudioSource.Start();
ITrack livekitMicrophoneTrack = voiceChatRoom.LocalTracks.CreateAudioTrack(
voiceChatRoom.Participants.LocalParticipant().Name,
rtcAudioSource
);
microphoneTrack = new MicrophoneTrack(livekitMicrophoneTrack, new Owned<MicrophoneRtcAudioSource>(rtcAudioSource));
microphoneHandler.Assign(microphoneTrack.Value.Source);
var options = new TrackPublishOptions
{
AudioEncoding = new AudioEncoding
{
MaxBitrate = 124000,
},
Source = TrackSource.SourceMicrophone,
};
voiceChatRoom.Participants.LocalParticipant().PublishTrack(microphoneTrack.Value.Track, options, ct);
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} Local track published successfully");
}
catch (Exception ex)
{
ReportHub.LogWarning(ReportCategory.VOICE_CHAT, $"{TAG} Failed to publish local track: {ex.Message}");
CleanupLocalTrack();
throw;
}
}
public void UnpublishLocalTrack()
{
if (microphoneTrack.HasValue)
try
{
voiceChatRoom.Participants.LocalParticipant().UnpublishTrack(microphoneTrack.Value.Track, true);
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} Local track unpublished");
}
catch (Exception ex) { ReportHub.LogWarning(ReportCategory.VOICE_CHAT, $"{TAG} Failed to unpublish local track: {ex.Message}"); }
finally { CleanupLocalTrack(); }
}
public void StartListeningToRemoteTracks()
{
try
{
playbackSourcesHub.Reset();
foreach (KeyValuePair<string, Participant> remoteParticipantIdentity in voiceChatRoom.Participants.RemoteParticipantIdentities())
{
foreach ((string sid, TrackPublication value) in remoteParticipantIdentity.Value.Tracks)
{
if (value.Kind == TrackKind.KindAudio)
{
Weak<AudioStream> stream = voiceChatRoom.AudioStreams.ActiveStream(new StreamKey(remoteParticipantIdentity.Key!, sid));
if (stream.Resource.Has)
{
playbackSourcesHub.AddOrReplaceStream(new StreamKey(remoteParticipantIdentity.Key!, sid), stream);
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} Added existing remote track from {remoteParticipantIdentity}");
}
}
}
}
playbackSourcesHub.Play();
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} Remote track listening started");
}
catch (Exception ex)
{
ReportHub.LogWarning(ReportCategory.VOICE_CHAT, $"{TAG} Failed to start listening to remote tracks: {ex.Message}");
throw;
}
}
public void StopListeningToRemoteTracks()
{
StopListeningToRemoteTracksAsync().Forget();
}
private async UniTaskVoid StopListeningToRemoteTracksAsync()
{
if (!PlayerLoopHelper.IsMainThread)
await UniTask.SwitchToMainThread();
try
{
playbackSourcesHub.Stop();
playbackSourcesHub.Reset();
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} Remote track listening stopped");
}
catch (Exception ex) { ReportHub.LogWarning(ReportCategory.VOICE_CHAT, $"{TAG} Failed to stop listening to remote tracks: {ex.Message}"); }
}
public void HandleTrackSubscribed(ITrack track, TrackPublication publication, Participant participant)
{
try
{
if (publication.Kind == TrackKind.KindAudio)
{
Weak<AudioStream> stream = voiceChatRoom.AudioStreams.ActiveStream(new StreamKey(participant.Identity, publication.Sid));
if (stream.Resource.Has)
{
playbackSourcesHub.AddOrReplaceStream(new StreamKey(participant.Identity, publication.Sid), stream);
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} New remote track subscribed from {participant.Identity}");
}
}
}
catch (Exception ex) { ReportHub.LogWarning(ReportCategory.VOICE_CHAT, $"{TAG} Failed to handle track subscription: {ex.Message}"); }
}
public void HandleTrackUnsubscribed(ITrack track, TrackPublication publication, Participant participant)
{
try
{
if (publication.Kind == TrackKind.KindAudio)
{
playbackSourcesHub.RemoveStream(new StreamKey(participant.Identity, publication.Sid));
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} Remote track unsubscribed from {participant.Identity}");
}
}
catch (Exception ex) { ReportHub.LogWarning(ReportCategory.VOICE_CHAT, $"{TAG} Failed to handle track unsubscription: {ex.Message}"); }
}
public void HandleLocalTrackPublished(TrackPublication publication, Participant participant)
{
try
{
if (publication.Kind != TrackKind.KindAudio) return;
if (!configuration.EnableLocalTrackPlayback) return;
Weak<AudioStream> stream = voiceChatRoom.AudioStreams.ActiveStream(new StreamKey(participant.Identity, publication.Sid));
if (stream.Resource.Has)
{
playbackSourcesHub.AddOrReplaceStream(new StreamKey(participant.Identity, publication.Sid), stream);
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} Local track added to playback (loopback enabled)");
}
}
catch (Exception ex) { ReportHub.LogWarning(ReportCategory.VOICE_CHAT, $"{TAG} Failed to handle local track published: {ex.Message}"); }
}
public void HandleLocalTrackUnpublished(TrackPublication publication, Participant participant)
{
try
{
if (publication.Kind != TrackKind.KindAudio) return;
if (!configuration.EnableLocalTrackPlayback) return;
playbackSourcesHub.RemoveStream(new StreamKey(participant.Identity, publication.Sid));
ReportHub.Log(ReportCategory.VOICE_CHAT, $"{TAG} Local track removed from playback");
}
catch (Exception ex) { ReportHub.LogWarning(ReportCategory.VOICE_CHAT, $"{TAG} Failed to handle local track unpublished: {ex.Message}"); }
}
private void CleanupLocalTrack()
{
microphoneTrack?.Dispose();
microphoneTrack = null;
trackPublishingCts?.SafeCancelAndDispose();
trackPublishingCts = null;
}
private readonly struct MicrophoneTrack : IDisposable
{
private readonly Owned<MicrophoneRtcAudioSource> source;
public ITrack Track { get; }
public Weak<MicrophoneRtcAudioSource> Source => source.Downgrade();
public MicrophoneTrack(ITrack track, Owned<MicrophoneRtcAudioSource> source)
{
Track = track;
this.source = source;
}
public void Dispose()
{
source.Dispose(out MicrophoneRtcAudioSource? inner);
inner?.Dispose();
}
}
}
}