Repository navigation
Expand file tree
/
Copy pathRdpManagedSession.Audio.cs
More file actions
122 lines (112 loc) · 4.58 KB
/
Copy pathRdpManagedSession.Audio.cs
File metadata and controls
122 lines (112 loc) · 4.58 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
using System.Threading.Channels;
using VelaShell.Rdp.Audio;
using VelaShell.Rdp.Channels;
namespace VelaShell.Rdp;
/// <summary>Optional audio diagnostics. Failures stop audio, while the desktop remains connected.</summary>
public interface IRdpAudioSource
{
/// <summary>Raised on a background thread; the last failure is replayed to late subscribers.</summary>
event Action<Exception>? AudioPlaybackFailed;
}
public sealed partial class RdpManagedSession : IRdpAudioSource
{
private Channel<(byte[] Data, long ReceivedAt)>? _audioQueue;
private CancellationTokenSource? _audioStop;
private Task? _audioWorker;
private long _audioQueuedBytes;
private readonly Lock _audioGate = new();
private Exception? _audioFailure;
private Action<Exception>? _audioHandlers;
public event Action<Exception>? AudioPlaybackFailed
{
add
{
Exception? failure;
lock (_audioGate)
{
_audioHandlers += value;
failure = _audioFailure;
}
if (failure is not null)
{
try { value?.Invoke(failure); } catch { /* Observers cannot interrupt audio cleanup. */ }
}
}
remove { lock (_audioGate) { _audioHandlers -= value; } }
}
internal void EnableAudio(bool playback, Func<IAudioOutput>? createOutput = null)
{
_audioQueue = Channel.CreateBounded<(byte[], long)>(new BoundedChannelOptions(128)
{
SingleReader = true,
FullMode = BoundedChannelFullMode.Wait
});
_audioStop = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token);
_audioWorker = Task.Run(async () =>
{
try
{
using var channel = new RdpsndChannel(
(pdu, ct) => Connection.SendVirtualChannelAsync("rdpsnd", pdu, ct),
playback ? (createOutput?.Invoke() ?? AudioOutput.Create(LogAudio)) : null, LogAudio);
while (true)
{
Task<bool> available = _audioQueue.Reader.WaitToReadAsync(_audioStop.Token).AsTask();
if (await Task.WhenAny(available, channel.PlaybackFailure).ConfigureAwait(false) == channel.PlaybackFailure)
{
throw await channel.PlaybackFailure.ConfigureAwait(false);
}
if (!await available.ConfigureAwait(false))
{
break;
}
while (_audioQueue.Reader.TryRead(out (byte[] Data, long ReceivedAt) message))
{
_ = Interlocked.Add(ref _audioQueuedBytes, -message.Data.Length);
await channel.ProcessAsync(message.Data, message.ReceivedAt, _audioStop.Token).ConfigureAwait(false);
}
}
await channel.DrainAsync().ConfigureAwait(false);
}
catch (OperationCanceledException) when (_audioStop.IsCancellationRequested) { }
catch (Exception ex) { FailAudio(ex); }
finally
{
while (_audioQueue.Reader.TryRead(out (byte[] Data, long ReceivedAt) pending))
{
_ = Interlocked.Add(ref _audioQueuedBytes, -pending.Data.Length);
}
}
});
}
internal void ReceiveAudio(byte[] data)
{
if (_audioStop?.IsCancellationRequested != false) { return; }
long queued = Interlocked.Add(ref _audioQueuedBytes, data.Length);
if (data.Length > ushort.MaxValue + 4 || queued > 1024 * 1024
|| _audioQueue?.Writer.TryWrite((data, Environment.TickCount64)) != true)
{
_ = Interlocked.Add(ref _audioQueuedBytes, -data.Length);
FailAudio(new IOException("RDP audio queue capacity exceeded; reconnect to resume audio."));
}
}
private void FailAudio(Exception error)
{
Action<Exception>? handlers;
lock (_audioGate)
{
if (_audioFailure is not null) { return; }
_audioFailure = error;
handlers = _audioHandlers;
}
_ = (_audioQueue?.Writer.TryComplete());
_audioStop?.Cancel();
LogAudio($"playback stopped: {error.Message}");
try { handlers?.Invoke(error); } catch { /* Audio errors must not stop the desktop. */ }
}
private void LogAudio(string message)
{
try { _driveLog?.Invoke($"RDPSND {message}"); }
catch { /* Diagnostics must not interrupt audio cleanup. */ }
}
}