IAudioRenderer.cs 14 KB

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