IAudioRenderer.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. using ChocolArm64.Memory;
  2. using Ryujinx.Audio;
  3. using Ryujinx.Audio.Adpcm;
  4. using Ryujinx.Common.Logging;
  5. using Ryujinx.HLE.HOS.Ipc;
  6. using Ryujinx.HLE.HOS.Kernel;
  7. using Ryujinx.HLE.Utilities;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Runtime.InteropServices;
  11. using System.Runtime.Intrinsics;
  12. using System.Runtime.Intrinsics.X86;
  13. namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer
  14. {
  15. class IAudioRenderer : IpcService, IDisposable
  16. {
  17. //This is the amount of samples that are going to be appended
  18. //each time that RequestUpdateAudioRenderer is called. Ideally,
  19. //this value shouldn't be neither too small (to avoid the player
  20. //starving due to running out of samples) or too large (to avoid
  21. //high latency).
  22. private const int MixBufferSamplesCount = 960;
  23. private Dictionary<int, ServiceProcessRequest> m_Commands;
  24. public override IReadOnlyDictionary<int, ServiceProcessRequest> Commands => m_Commands;
  25. private KEvent UpdateEvent;
  26. private MemoryManager Memory;
  27. private IAalOutput AudioOut;
  28. private AudioRendererParameter Params;
  29. private MemoryPoolContext[] MemoryPools;
  30. private VoiceContext[] Voices;
  31. private int Track;
  32. private PlayState PlayState;
  33. public IAudioRenderer(
  34. Horizon System,
  35. MemoryManager Memory,
  36. IAalOutput AudioOut,
  37. AudioRendererParameter Params)
  38. {
  39. m_Commands = new Dictionary<int, ServiceProcessRequest>()
  40. {
  41. { 0, GetSampleRate },
  42. { 1, GetSampleCount },
  43. { 2, GetMixBufferCount },
  44. { 3, GetState },
  45. { 4, RequestUpdateAudioRenderer },
  46. { 5, StartAudioRenderer },
  47. { 6, StopAudioRenderer },
  48. { 7, QuerySystemEvent }
  49. };
  50. UpdateEvent = new KEvent(System);
  51. this.Memory = Memory;
  52. this.AudioOut = AudioOut;
  53. this.Params = Params;
  54. Track = AudioOut.OpenTrack(
  55. AudioConsts.HostSampleRate,
  56. AudioConsts.HostChannelsCount,
  57. AudioCallback);
  58. MemoryPools = CreateArray<MemoryPoolContext>(Params.EffectCount + Params.VoiceCount * 4);
  59. Voices = CreateArray<VoiceContext>(Params.VoiceCount);
  60. InitializeAudioOut();
  61. PlayState = PlayState.Stopped;
  62. }
  63. // GetSampleRate() -> u32
  64. public long GetSampleRate(ServiceCtx Context)
  65. {
  66. Context.ResponseData.Write(Params.SampleRate);
  67. return 0;
  68. }
  69. // GetSampleCount() -> u32
  70. public long GetSampleCount(ServiceCtx Context)
  71. {
  72. Context.ResponseData.Write(Params.SampleCount);
  73. return 0;
  74. }
  75. // GetMixBufferCount() -> u32
  76. public long GetMixBufferCount(ServiceCtx Context)
  77. {
  78. Context.ResponseData.Write(Params.MixCount);
  79. return 0;
  80. }
  81. // GetState() -> u32
  82. private long GetState(ServiceCtx Context)
  83. {
  84. Context.ResponseData.Write((int)PlayState);
  85. Logger.PrintStub(LogClass.ServiceAudio, $"Stubbed. Renderer State: {Enum.GetName(typeof(PlayState), PlayState)}");
  86. return 0;
  87. }
  88. private void AudioCallback()
  89. {
  90. UpdateEvent.ReadableEvent.Signal();
  91. }
  92. private static T[] CreateArray<T>(int Size) where T : new()
  93. {
  94. T[] Output = new T[Size];
  95. for (int Index = 0; Index < Size; Index++)
  96. {
  97. Output[Index] = new T();
  98. }
  99. return Output;
  100. }
  101. private void InitializeAudioOut()
  102. {
  103. AppendMixedBuffer(0);
  104. AppendMixedBuffer(1);
  105. AppendMixedBuffer(2);
  106. AudioOut.Start(Track);
  107. }
  108. public long RequestUpdateAudioRenderer(ServiceCtx Context)
  109. {
  110. long OutputPosition = Context.Request.ReceiveBuff[0].Position;
  111. long OutputSize = Context.Request.ReceiveBuff[0].Size;
  112. MemoryHelper.FillWithZeros(Context.Memory, OutputPosition, (int)OutputSize);
  113. long InputPosition = Context.Request.SendBuff[0].Position;
  114. StructReader Reader = new StructReader(Context.Memory, InputPosition);
  115. StructWriter Writer = new StructWriter(Context.Memory, OutputPosition);
  116. UpdateDataHeader InputHeader = Reader.Read<UpdateDataHeader>();
  117. Reader.Read<BehaviorIn>(InputHeader.BehaviorSize);
  118. MemoryPoolIn[] MemoryPoolsIn = Reader.Read<MemoryPoolIn>(InputHeader.MemoryPoolSize);
  119. for (int Index = 0; Index < MemoryPoolsIn.Length; Index++)
  120. {
  121. MemoryPoolIn MemoryPool = MemoryPoolsIn[Index];
  122. if (MemoryPool.State == MemoryPoolState.RequestAttach)
  123. {
  124. MemoryPools[Index].OutStatus.State = MemoryPoolState.Attached;
  125. }
  126. else if (MemoryPool.State == MemoryPoolState.RequestDetach)
  127. {
  128. MemoryPools[Index].OutStatus.State = MemoryPoolState.Detached;
  129. }
  130. }
  131. Reader.Read<VoiceChannelResourceIn>(InputHeader.VoiceResourceSize);
  132. VoiceIn[] VoicesIn = Reader.Read<VoiceIn>(InputHeader.VoiceSize);
  133. for (int Index = 0; Index < VoicesIn.Length; Index++)
  134. {
  135. VoiceIn Voice = VoicesIn[Index];
  136. VoiceContext VoiceCtx = Voices[Index];
  137. VoiceCtx.SetAcquireState(Voice.Acquired != 0);
  138. if (Voice.Acquired == 0)
  139. {
  140. continue;
  141. }
  142. if (Voice.FirstUpdate != 0)
  143. {
  144. VoiceCtx.AdpcmCtx = GetAdpcmDecoderContext(
  145. Voice.AdpcmCoeffsPosition,
  146. Voice.AdpcmCoeffsSize);
  147. VoiceCtx.SampleFormat = Voice.SampleFormat;
  148. VoiceCtx.SampleRate = Voice.SampleRate;
  149. VoiceCtx.ChannelsCount = Voice.ChannelsCount;
  150. VoiceCtx.SetBufferIndex(Voice.BaseWaveBufferIndex);
  151. }
  152. VoiceCtx.WaveBuffers[0] = Voice.WaveBuffer0;
  153. VoiceCtx.WaveBuffers[1] = Voice.WaveBuffer1;
  154. VoiceCtx.WaveBuffers[2] = Voice.WaveBuffer2;
  155. VoiceCtx.WaveBuffers[3] = Voice.WaveBuffer3;
  156. VoiceCtx.Volume = Voice.Volume;
  157. VoiceCtx.PlayState = Voice.PlayState;
  158. }
  159. UpdateAudio();
  160. UpdateDataHeader OutputHeader = new UpdateDataHeader();
  161. int UpdateHeaderSize = Marshal.SizeOf<UpdateDataHeader>();
  162. OutputHeader.Revision = IAudioRendererManager.RevMagic;
  163. OutputHeader.BehaviorSize = 0xb0;
  164. OutputHeader.MemoryPoolSize = (Params.EffectCount + Params.VoiceCount * 4) * 0x10;
  165. OutputHeader.VoiceSize = Params.VoiceCount * 0x10;
  166. OutputHeader.EffectSize = Params.EffectCount * 0x10;
  167. OutputHeader.SinkSize = Params.SinkCount * 0x20;
  168. OutputHeader.PerformanceManagerSize = 0x10;
  169. OutputHeader.TotalSize = UpdateHeaderSize +
  170. OutputHeader.BehaviorSize +
  171. OutputHeader.MemoryPoolSize +
  172. OutputHeader.VoiceSize +
  173. OutputHeader.EffectSize +
  174. OutputHeader.SinkSize +
  175. OutputHeader.PerformanceManagerSize;
  176. Writer.Write(OutputHeader);
  177. foreach (MemoryPoolContext MemoryPool in MemoryPools)
  178. {
  179. Writer.Write(MemoryPool.OutStatus);
  180. }
  181. foreach (VoiceContext Voice in Voices)
  182. {
  183. Writer.Write(Voice.OutStatus);
  184. }
  185. return 0;
  186. }
  187. public long StartAudioRenderer(ServiceCtx Context)
  188. {
  189. Logger.PrintStub(LogClass.ServiceAudio, "Stubbed.");
  190. PlayState = PlayState.Playing;
  191. return 0;
  192. }
  193. public long StopAudioRenderer(ServiceCtx Context)
  194. {
  195. Logger.PrintStub(LogClass.ServiceAudio, "Stubbed.");
  196. PlayState = PlayState.Stopped;
  197. return 0;
  198. }
  199. public long QuerySystemEvent(ServiceCtx Context)
  200. {
  201. if (Context.Process.HandleTable.GenerateHandle(UpdateEvent.ReadableEvent, out int Handle) != KernelResult.Success)
  202. {
  203. throw new InvalidOperationException("Out of handles!");
  204. }
  205. Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle);
  206. return 0;
  207. }
  208. private AdpcmDecoderContext GetAdpcmDecoderContext(long Position, long Size)
  209. {
  210. if (Size == 0)
  211. {
  212. return null;
  213. }
  214. AdpcmDecoderContext Context = new AdpcmDecoderContext();
  215. Context.Coefficients = new short[Size >> 1];
  216. for (int Offset = 0; Offset < Size; Offset += 2)
  217. {
  218. Context.Coefficients[Offset >> 1] = Memory.ReadInt16(Position + Offset);
  219. }
  220. return Context;
  221. }
  222. private void UpdateAudio()
  223. {
  224. long[] Released = AudioOut.GetReleasedBuffers(Track, 2);
  225. for (int Index = 0; Index < Released.Length; Index++)
  226. {
  227. AppendMixedBuffer(Released[Index]);
  228. }
  229. }
  230. private unsafe void AppendMixedBuffer(long Tag)
  231. {
  232. int[] MixBuffer = new int[MixBufferSamplesCount * AudioConsts.HostChannelsCount];
  233. foreach (VoiceContext Voice in Voices)
  234. {
  235. if (!Voice.Playing)
  236. {
  237. continue;
  238. }
  239. int OutOffset = 0;
  240. int PendingSamples = MixBufferSamplesCount;
  241. float Volume = Voice.Volume;
  242. while (PendingSamples > 0)
  243. {
  244. int[] Samples = Voice.GetBufferData(Memory, PendingSamples, out int ReturnedSamples);
  245. if (ReturnedSamples == 0)
  246. {
  247. break;
  248. }
  249. PendingSamples -= ReturnedSamples;
  250. for (int Offset = 0; Offset < Samples.Length; Offset++)
  251. {
  252. MixBuffer[OutOffset++] += (int)(Samples[Offset] * Voice.Volume);
  253. }
  254. }
  255. }
  256. AudioOut.AppendBuffer(Track, Tag, GetFinalBuffer(MixBuffer));
  257. }
  258. private unsafe static short[] GetFinalBuffer(int[] Buffer)
  259. {
  260. short[] Output = new short[Buffer.Length];
  261. int Offset = 0;
  262. // Perform Saturation using SSE2 if supported
  263. if (Sse2.IsSupported)
  264. {
  265. fixed (int* inptr = Buffer)
  266. fixed (short* outptr = Output)
  267. {
  268. for (; Offset + 32 <= Buffer.Length; Offset += 32)
  269. {
  270. // Unroll the loop a little to ensure the CPU pipeline
  271. // is always full.
  272. Vector128<int> block1A = Sse2.LoadVector128(inptr + Offset + 0);
  273. Vector128<int> block1B = Sse2.LoadVector128(inptr + Offset + 4);
  274. Vector128<int> block2A = Sse2.LoadVector128(inptr + Offset + 8);
  275. Vector128<int> block2B = Sse2.LoadVector128(inptr + Offset + 12);
  276. Vector128<int> block3A = Sse2.LoadVector128(inptr + Offset + 16);
  277. Vector128<int> block3B = Sse2.LoadVector128(inptr + Offset + 20);
  278. Vector128<int> block4A = Sse2.LoadVector128(inptr + Offset + 24);
  279. Vector128<int> block4B = Sse2.LoadVector128(inptr + Offset + 28);
  280. Vector128<short> output1 = Sse2.PackSignedSaturate(block1A, block1B);
  281. Vector128<short> output2 = Sse2.PackSignedSaturate(block2A, block2B);
  282. Vector128<short> output3 = Sse2.PackSignedSaturate(block3A, block3B);
  283. Vector128<short> output4 = Sse2.PackSignedSaturate(block4A, block4B);
  284. Sse2.Store(outptr + Offset + 0, output1);
  285. Sse2.Store(outptr + Offset + 8, output2);
  286. Sse2.Store(outptr + Offset + 16, output3);
  287. Sse2.Store(outptr + Offset + 24, output4);
  288. }
  289. }
  290. }
  291. // Process left overs
  292. for (; Offset < Buffer.Length; Offset++)
  293. {
  294. Output[Offset] = DspUtils.Saturate(Buffer[Offset]);
  295. }
  296. return Output;
  297. }
  298. public void Dispose()
  299. {
  300. Dispose(true);
  301. }
  302. protected virtual void Dispose(bool Disposing)
  303. {
  304. if (Disposing)
  305. {
  306. AudioOut.CloseTrack(Track);
  307. }
  308. }
  309. }
  310. }