| 1 | using System.Buffers.Binary; |
| 2 | using System.Diagnostics; |
| 3 | using System.Runtime.CompilerServices; |
| 4 | using System.Runtime.InteropServices; |
| 5 | using System.Text.Json.Nodes; |
| 6 | |
| 7 | namespace Cage.GuestClipboard; |
| 8 | |
| 9 | |
| 10 | |
| 11 | internal static class WindowsAudioRpc |
| 12 | { |
| 13 | private static readonly SemaphoreSlim Slots = new(4, 4); |
| 14 | private const int SampleRate = 48000, Channels = 2, Samples = 960 * Channels; |
| 15 | [ModuleInitializer] internal static void Register() |
| 16 | { |
| 17 | if (GuestOperations.Names.Contains("audio") && Environment.OSVersion.Version.Build >= 20348) |
| 18 | GuestOperations.Register("audio", Run); |
| 19 | } |
| 20 | internal sealed class Target : IDisposable |
| 21 | { |
| 22 | internal Process Process { get; } |
| 23 | internal long Started { get; } |
| 24 | private readonly string executable; |
| 25 | private readonly int session; |
| 26 | internal Target(Process process, string path) |
| 27 | { |
| 28 | Process = process; Started = process.StartTime.ToUniversalTime().Ticks; executable = path; |
| 29 | using var current = System.Diagnostics.Process.GetCurrentProcess(); session = current.SessionId; |
| 30 | try { Validate(); } catch { Process.Dispose(); throw; } |
| 31 | } |
| 32 | internal void Validate() |
| 33 | { |
| 34 | if (!SessionGuard.Available() || !SessionGuard.OwnsProcess(Process) || Process.HasExited || Process.StartTime.ToUniversalTime().Ticks != Started || |
| 35 | Process.SessionId != session || |
| 36 | !string.Equals(Process.MainModule?.FileName, executable, StringComparison.OrdinalIgnoreCase)) |
| 37 | throw new InvalidDataException("audio_target_changed"); |
| 38 | } |
| 39 | public void Dispose() => Process.Dispose(); |
| 40 | } |
| 41 | internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available) |
| 42 | { |
| 43 | var request = await Protocol.Read(stream, 4096, token) ?? throw new EndOfStreamException(); |
| 44 | if (request.Count != 1 || request["action"]?.GetValue<string>() is not ("status" or "capture")) throw new InvalidDataException("audio_request_invalid"); |
| 45 | if (!available()) throw new InvalidDataException("requires_gui_login"); |
| 46 | if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("audio_capture_limit"); |
| 47 | var began = false; |
| 48 | try |
| 49 | { |
| 50 | |
| 51 | |
| 52 | await Task.Factory.StartNew(() => Worker(stream, request["action"]!.GetValue<string>(), token, available, () => began = true), |
| 53 | CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); |
| 54 | } |
| 55 | catch (Exception) when (began) { } |
| 56 | finally { Slots.Release(); } |
| 57 | } |
| 58 | private static void Worker(Stream output, string action, CancellationToken token, Func<bool> available, Action began) |
| 59 | { |
| 60 | if(action=="status"){StatusDiagnostic(output,token,available);return;} |
| 61 | Marshal.ThrowExceptionForHR(CoInitializeEx(0, 0)); |
| 62 | try |
| 63 | { |
| 64 | token.ThrowIfCancellationRequested(); if (!available()) throw new InvalidDataException("requires_gui_login"); |
| 65 | var endpoints = RenderEndpoints(); |
| 66 | using var process = Process.GetCurrentProcess(); |
| 67 | using var owner = new Target(Process.GetProcessById(process.Id), process.MainModule!.FileName!); |
| 68 | var sources = new List<Source>(); |
| 69 | try |
| 70 | { |
| 71 | sources.Add(new Source(new Target(Process.GetProcessById(owner.Process.Id), owner.Process.MainModule!.FileName!), token)); |
| 72 | RefreshClaude(sources, owner, token); |
| 73 | Protocol.Write(output, new JsonObject { ["ready"] = true, ["format"] = "s16le", ["sample_rate"] = SampleRate, |
| 74 | ["channels"] = Channels, ["render_endpoints"] = endpoints, ["requires_render_stream"] = true }, token).GetAwaiter().GetResult(); |
| 75 | began(); |
| 76 | var clock = Stopwatch.StartNew(); var next = 20L; var refresh = 1000L; |
| 77 | var mixed = new int[Samples]; var packet = new byte[Samples * 2]; |
| 78 | while (true) |
| 79 | { |
| 80 | token.ThrowIfCancellationRequested(); if (!available()) throw new InvalidDataException("requires_gui_login"); owner.Validate(); |
| 81 | for (var i = sources.Count - 1; i >= 0; i--) |
| 82 | { |
| 83 | try { sources[i].Drain(); } |
| 84 | catch (InvalidDataException) when (i != 0) { sources[i].Dispose(); sources.RemoveAt(i); refresh = 0; } |
| 85 | } |
| 86 | if (clock.ElapsedMilliseconds >= refresh) { RefreshClaude(sources, owner, token); refresh = clock.ElapsedMilliseconds + 1000; } |
| 87 | var remaining = next - clock.ElapsedMilliseconds; |
| 88 | if (remaining > 0 && token.WaitHandle.WaitOne((int)Math.Min(remaining, 20))) token.ThrowIfCancellationRequested(); |
| 89 | if (clock.ElapsedMilliseconds < next) continue; |
| 90 | Array.Clear(mixed); |
| 91 | foreach (var source in sources) { source.Target.Validate(); source.Mix(mixed); } |
| 92 | for (var i = 0; i < Samples; i++) BinaryPrimitives.WriteInt16LittleEndian(packet.AsSpan(i * 2), (short)Math.Clamp(mixed[i], short.MinValue, short.MaxValue)); |
| 93 | owner.Validate(); output.WriteAsync(packet, token).GetAwaiter().GetResult(); |
| 94 | next += 20; if (next < clock.ElapsedMilliseconds - 100) next = clock.ElapsedMilliseconds + 20; |
| 95 | } |
| 96 | } |
| 97 | finally { foreach (var source in sources) source.Dispose(); } |
| 98 | } |
| 99 | finally { CoUninitialize(); } |
| 100 | } |
| 101 | private static void StatusDiagnostic(Stream output,CancellationToken token,Func<bool> available) |
| 102 | { |
| 103 | var stage="com_initialize";bool initialized=false; |
| 104 | object? enumerator=null;IMMDeviceCollection? devices=null; |
| 105 | try |
| 106 | { |
| 107 | Marshal.ThrowExceptionForHR(CoInitializeEx(0,0));initialized=true; |
| 108 | token.ThrowIfCancellationRequested();if(!available())throw new InvalidDataException("requires_gui_login"); |
| 109 | stage="render_activate";enumerator=Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"))!); |
| 110 | stage="render_enumerate";Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)enumerator!).EnumAudioEndpoints(0,1,out devices)); |
| 111 | stage="render_count";Marshal.ThrowExceptionForHR(devices.GetCount(out var count)); |
| 112 | stage="audio_service";var audio=ServiceState("Audiosrv",out var audioCode); |
| 113 | stage="endpoint_service";var endpoint=ServiceState("AudioEndpointBuilder",out var endpointCode); |
| 114 | token.ThrowIfCancellationRequested();if(!available())throw new InvalidDataException("requires_gui_login"); |
| 115 | stage="status_emit"; |
| 116 | Protocol.Write(output,new JsonObject { ["supported"]=Environment.OSVersion.Version.Build>=20348,["format"]="s16le",["sample_rate"]=SampleRate,["channels"]=Channels,["render_endpoints"]=checked((int)count),["audio_service"]=audio,["endpoint_service"]=endpoint,["audio_service_native_code"]=audioCode.ToString("X8"),["endpoint_service_native_code"]=endpointCode.ToString("X8"),["requires_render_stream"]=true },token).GetAwaiter().GetResult(); |
| 117 | } |
| 118 | catch(Exception error) when(error is not OperationCanceledException) |
| 119 | { |
| 120 | Protocol.Write(output,new JsonObject { ["error"]="audio_status_unavailable",["stage"]=stage,["native_code"]=unchecked((uint)error.HResult).ToString("X8"),["exception_type"]=error.GetType().Name },token).GetAwaiter().GetResult(); |
| 121 | } |
| 122 | finally |
| 123 | { |
| 124 | if(devices!=null)Marshal.ReleaseComObject(devices); |
| 125 | if(enumerator!=null)Marshal.ReleaseComObject(enumerator); |
| 126 | if(initialized)CoUninitialize(); |
| 127 | } |
| 128 | } |
| 129 | internal static JsonObject ComponentStatus() |
| 130 | { |
| 131 | var supported=Environment.OSVersion.Version.Build>=20348; |
| 132 | if(!supported)return new JsonObject{["supported"]=false,["installed"]=false,["ready"]=false,["reason"]="audio_os_unsupported"}; |
| 133 | using var memory=new MemoryStream();StatusDiagnostic(memory,CancellationToken.None,SessionGuard.Available); |
| 134 | var state=JsonNode.Parse(memory.ToArray())as JsonObject??throw new InvalidDataException("audio_status_unavailable"); |
| 135 | var result=new JsonObject{["supported"]=true,["installed"]=true,["ready"]=false,["reason"]="audio_status_unavailable"}; |
| 136 | foreach(var field in new[]{"stage","native_code","audio_service_native_code","endpoint_service_native_code"}) |
| 137 | if(state[field]!=null)result[field]=state[field]!.DeepClone(); |
| 138 | if(state["supported"]?.GetValue<bool>()==true) |
| 139 | { |
| 140 | var services=state["audio_service"]?.GetValue<string>()=="running"&&state["endpoint_service"]?.GetValue<string>()=="running"; |
| 141 | var endpoints=(state["render_endpoints"]?.GetValue<int>()??0)>0; |
| 142 | result["ready"]=services&&endpoints;result["reason"]=!services?"audio_services_unavailable":!endpoints?"no_active_render_endpoint":""; |
| 143 | } |
| 144 | return result; |
| 145 | } |
| 146 | private static void RefreshClaude(List<Source> sources, Target owner, CancellationToken token) |
| 147 | { |
| 148 | var target = ClaudeWindowRpc.AudioTarget(); |
| 149 | if (target is null) return; |
| 150 | try |
| 151 | { |
| 152 | if (IsDescendant(target.Process, owner.Process) || sources.Any(s => s.Target.Process.Id == target.Process.Id && s.Target.Started == target.Started)) return; |
| 153 | for (var i = sources.Count - 1; i > 0; i--) { sources[i].Dispose(); sources.RemoveAt(i); } |
| 154 | sources.Add(new Source(target, token)); target = null; |
| 155 | } |
| 156 | finally { target?.Dispose(); } |
| 157 | } |
| 158 | private static bool IsDescendant(Process child, Process ancestor) |
| 159 | { |
| 160 | var seen = new HashSet<int>(); var pid = child.Id; var started = child.StartTime.ToUniversalTime(); |
| 161 | while (seen.Add(pid)) |
| 162 | { |
| 163 | if (pid == ancestor.Id) return started == ancestor.StartTime.ToUniversalTime(); |
| 164 | using var current = Process.GetProcessById(pid); |
| 165 | if (NtQueryInformationProcess(current.Handle, 0, out var basic, (uint)Marshal.SizeOf<ProcessBasic>(), out _) != 0) throw new InvalidDataException("audio_target_ancestry_unavailable"); |
| 166 | pid = checked((int)basic.Parent.ToInt64()); if (pid < 1) return false; |
| 167 | try { using var parent = Process.GetProcessById(pid); if (parent.StartTime.ToUniversalTime() > started) throw new InvalidDataException("audio_target_ancestry_unavailable"); started = parent.StartTime.ToUniversalTime(); } |
| 168 | catch (ArgumentException) { throw new InvalidDataException("audio_target_ancestry_unavailable"); } |
| 169 | } |
| 170 | return false; |
| 171 | } |
| 172 | private sealed class Source : IDisposable |
| 173 | { |
| 174 | internal Target Target { get; } |
| 175 | private IAudioClient? client; private IAudioCaptureClient? capture; |
| 176 | private readonly EventWaitHandle ready = new(false, EventResetMode.AutoReset); |
| 177 | private readonly short[] ring = new short[SampleRate * Channels / 5]; |
| 178 | private int read, count; private bool started; |
| 179 | internal Source(Target target, CancellationToken token) |
| 180 | { |
| 181 | Target = target; |
| 182 | try |
| 183 | { |
| 184 | target.Validate(); client = Activate(target.Process.Id); |
| 185 | token.ThrowIfCancellationRequested(); target.Validate(); |
| 186 | var format = new WaveFormat { Tag = 1, Channels = Channels, Rate = SampleRate, Average = SampleRate * Channels * 2, Align = Channels * 2, Bits = 16, Extra = 0 }; |
| 187 | Check(client.Initialize(0, 0x80000000u | 0x00020000u | 0x00040000u, 0, 0, ref format, 0)); |
| 188 | Check(client.SetEventHandle(ready.SafeWaitHandle.DangerousGetHandle())); |
| 189 | Check(client.GetBufferSize(out var frames)); if (frames is < 1 or > SampleRate) throw new InvalidDataException("audio_buffer_invalid"); |
| 190 | var id = typeof(IAudioCaptureClient).GUID; Check(client.GetService(ref id, out var service)); capture = (IAudioCaptureClient)service; |
| 191 | target.Validate(); Check(client.Start()); started = true; |
| 192 | } |
| 193 | catch { Dispose(); throw; } |
| 194 | } |
| 195 | internal void Drain() |
| 196 | { |
| 197 | Target.Validate(); ready.WaitOne(0); var batches = 0; |
| 198 | while (true) |
| 199 | { |
| 200 | Check(capture!.GetNextPacketSize(out var next)); if (next == 0) return; |
| 201 | if (++batches > 100 || next > SampleRate) throw new InvalidDataException("audio_buffer_invalid"); |
| 202 | Check(capture.GetBuffer(out var data, out var frames, out var flags, out _, out _)); |
| 203 | try |
| 204 | { |
| 205 | if (frames > SampleRate || (data == 0 && (flags & 2) == 0)) throw new InvalidDataException("audio_buffer_invalid"); |
| 206 | Target.Validate(); if ((flags & 1) != 0) { read = count = 0; } |
| 207 | var values = new short[checked((int)frames * Channels)]; if ((flags & 2) == 0) Marshal.Copy(data, values, 0, values.Length); |
| 208 | Target.Validate(); |
| 209 | foreach (var value in values) { if (count == ring.Length) { read = (read + 1) % ring.Length; count--; } ring[(read + count++) % ring.Length] = value; } |
| 210 | } |
| 211 | finally { Check(capture.ReleaseBuffer(frames)); } |
| 212 | } |
| 213 | } |
| 214 | internal void Mix(int[] output) |
| 215 | { |
| 216 | for (var i = 0; i < output.Length && count != 0; i++) { output[i] += ring[read]; read = (read + 1) % ring.Length; count--; } |
| 217 | } |
| 218 | public void Dispose() |
| 219 | { |
| 220 | if (started) { client?.Stop(); started = false; } |
| 221 | if (capture is not null) { Marshal.ReleaseComObject(capture); capture = null; } |
| 222 | if (client is not null) { Marshal.ReleaseComObject(client); client = null; } |
| 223 | ready.Dispose(); Target.Dispose(); |
| 224 | } |
| 225 | } |
| 226 | private static IAudioClient Activate(int pid) |
| 227 | { |
| 228 | var data = Marshal.AllocHGlobal(12); IActivateOperation? operation = null; |
| 229 | var callback = new Completion(); |
| 230 | try |
| 231 | { |
| 232 | Marshal.WriteInt32(data, 1); Marshal.WriteInt32(data, 4, pid); Marshal.WriteInt32(data, 8, 0); |
| 233 | var value = new Variant { Type = 65, Bytes = 12, Data = data }; var iid = typeof(IAudioClient).GUID; |
| 234 | Check(ActivateAudioInterfaceAsync("VAD\\Process_Loopback", ref iid, ref value, callback, out operation)); |
| 235 | var result = callback.Done.Task.GetAwaiter().GetResult(); Check(result.Result); return result.Client ?? throw new InvalidDataException("audio_activation_failed"); |
| 236 | } |
| 237 | finally { GC.KeepAlive(callback); if (operation is not null) Marshal.ReleaseComObject(operation); Marshal.FreeHGlobal(data); } |
| 238 | } |
| 239 | [ComVisible(true), ClassInterface(ClassInterfaceType.None)] private sealed class Completion : ICompletion, IAgile |
| 240 | { |
| 241 | internal readonly TaskCompletionSource<(int Result, IAudioClient? Client)> Done = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| 242 | public int ActivateCompleted(IActivateOperation operation) |
| 243 | { |
| 244 | try { var result = operation.GetActivateResult(out var activated, out var audio); if (result >= 0) result = activated; Done.TrySetResult((result, result >= 0 ? (IAudioClient)audio : null)); } |
| 245 | catch (Exception e) { Done.TrySetResult((Marshal.GetHRForException(e), null)); } |
| 246 | return 0; |
| 247 | } |
| 248 | } |
| 249 | private static int RenderEndpoints() |
| 250 | { |
| 251 | object? enumerator = null; IMMDeviceCollection? devices = null; |
| 252 | try { enumerator = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"))!); Check(((IMMDeviceEnumerator)enumerator!).EnumAudioEndpoints(0, 1, out devices)); Check(devices.GetCount(out var count)); return checked((int)count); } |
| 253 | catch (COMException) { return -1; } |
| 254 | finally { if (devices is not null) Marshal.ReleaseComObject(devices); if (enumerator is not null) Marshal.ReleaseComObject(enumerator); } |
| 255 | } |
| 256 | private static string ServiceState(string name,out uint code) |
| 257 | { |
| 258 | code=0;var manager = OpenSCManagerW(null, null, 1); if (manager == 0) { code=Win32Code();return "unknown"; } |
| 259 | try { var service = OpenServiceW(manager, name, 4); if (service == 0) { code=Win32Code();return "unknown"; } try { if(!QueryServiceStatusEx(service, 0, out var state, (uint)Marshal.SizeOf<ServiceStatus>(), out _)){code=Win32Code();return "unknown";}return state.Current==4?"running":"stopped"; } finally { CloseServiceHandle(service); } } |
| 260 | finally { CloseServiceHandle(manager); } |
| 261 | } |
| 262 | private static uint Win32Code() {var error=unchecked((uint)Marshal.GetLastWin32Error());return error==0?0x80004005:error|0x80070000;} |
| 263 | private static void Check(int hr) { if (hr < 0) throw new InvalidDataException("audio_native_" + unchecked((uint)hr).ToString("x8")); } |
| 264 | [StructLayout(LayoutKind.Sequential, Pack = 2)] private struct WaveFormat { public ushort Tag, Channels; public uint Rate, Average; public ushort Align, Bits, Extra; } |
| 265 | [StructLayout(LayoutKind.Explicit, Size = 24)] private struct Variant { [FieldOffset(0)] public ushort Type; [FieldOffset(8)] public uint Bytes; [FieldOffset(16)] public nint Data; } |
| 266 | [StructLayout(LayoutKind.Sequential)] private struct ProcessBasic { public nint Exit, Peb, Affinity, Priority, ID, Parent; } |
| 267 | [StructLayout(LayoutKind.Sequential)] private struct ServiceStatus { public uint Type, Current, Controls, Exit, ServiceExit, Checkpoint, Hint, PID, Flags; } |
| 268 | [ComImport, Guid("1CB9AD4C-DBFA-4C32-B178-C2F568A703B2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAudioClient |
| 269 | { |
| 270 | [PreserveSig] int Initialize(int mode, uint flags, long duration, long period, ref WaveFormat format, nint session); |
| 271 | [PreserveSig] int GetBufferSize(out uint frames); [PreserveSig] int GetStreamLatency(out long latency); [PreserveSig] int GetCurrentPadding(out uint padding); |
| 272 | [PreserveSig] int IsFormatSupported(int mode, nint format, out nint closest); [PreserveSig] int GetMixFormat(out nint format); [PreserveSig] int GetDevicePeriod(out long normal, out long minimum); |
| 273 | [PreserveSig] int Start(); [PreserveSig] int Stop(); [PreserveSig] int Reset(); [PreserveSig] int SetEventHandle(nint handle); |
| 274 | [PreserveSig] int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object service); |
| 275 | } |
| 276 | [ComImport, Guid("C8ADBD64-E71E-48A0-A4DE-185C395CD317"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAudioCaptureClient |
| 277 | { [PreserveSig] int GetBuffer(out nint data, out uint frames, out uint flags, out ulong device, out ulong clock); [PreserveSig] int ReleaseBuffer(uint frames); [PreserveSig] int GetNextPacketSize(out uint frames); } |
| 278 | [ComImport, Guid("72A22D78-CDE4-431D-B8CC-843A71199B6D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IActivateOperation |
| 279 | { [PreserveSig] int GetActivateResult(out int result, [MarshalAs(UnmanagedType.IUnknown)] out object audio); } |
| 280 | [ComVisible(true), Guid("41D949AB-9862-444A-80F6-C261334DA5EB"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface ICompletion |
| 281 | { [PreserveSig] int ActivateCompleted(IActivateOperation operation); } |
| 282 | [ComVisible(true), Guid("94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAgile { } |
| 283 | [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IMMDeviceEnumerator |
| 284 | { [PreserveSig] int EnumAudioEndpoints(int flow, uint state, out IMMDeviceCollection devices); } |
| 285 | [ComImport, Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IMMDeviceCollection |
| 286 | { [PreserveSig] int GetCount(out uint count); } |
| 287 | [DllImport("mmdevapi.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern int ActivateAudioInterfaceAsync(string device, ref Guid iid, ref Variant parameters, ICompletion callback, out IActivateOperation operation); |
| 288 | [DllImport("ole32.dll")] private static extern int CoInitializeEx(nint reserved, uint mode); [DllImport("ole32.dll")] private static extern void CoUninitialize(); |
| 289 | [DllImport("ntdll.dll")] private static extern int NtQueryInformationProcess(nint process, int kind, out ProcessBasic basic, uint bytes, out uint returned); |
| 290 | [DllImport("advapi32.dll", ExactSpelling=true,CharSet = CharSet.Unicode,SetLastError=true)] private static extern nint OpenSCManagerW(string? machine, string? database, uint rights); |
| 291 | [DllImport("advapi32.dll", ExactSpelling=true,CharSet = CharSet.Unicode,SetLastError=true)] private static extern nint OpenServiceW(nint manager, string name, uint rights); |
| 292 | [DllImport("advapi32.dll", ExactSpelling=true,SetLastError=true)] private static extern bool QueryServiceStatusEx(nint service, int level, out ServiceStatus state, uint bytes, out uint needed); |
| 293 | [DllImport("advapi32.dll")] private static extern bool CloseServiceHandle(nint handle); |
| 294 | } |