IAudioRenderer.cs 13 KB

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