IAudioRenderer.cs 14 KB

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