IAudioRenderer.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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.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 KEvent _updateEvent;
  24. private IMemoryManager _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. IMemoryManager 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. AudioConsts.HostSampleRate,
  43. AudioConsts.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.MixCount);
  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. reader.Read<BehaviorIn>(inputHeader.BehaviorSize);
  112. MemoryPoolIn[] memoryPoolsIn = reader.Read<MemoryPoolIn>(inputHeader.MemoryPoolSize);
  113. for (int index = 0; index < memoryPoolsIn.Length; index++)
  114. {
  115. MemoryPoolIn memoryPool = memoryPoolsIn[index];
  116. if (memoryPool.State == MemoryPoolState.RequestAttach)
  117. {
  118. _memoryPools[index].OutStatus.State = MemoryPoolState.Attached;
  119. }
  120. else if (memoryPool.State == MemoryPoolState.RequestDetach)
  121. {
  122. _memoryPools[index].OutStatus.State = MemoryPoolState.Detached;
  123. }
  124. }
  125. reader.Read<VoiceChannelResourceIn>(inputHeader.VoiceResourceSize);
  126. VoiceIn[] voicesIn = reader.Read<VoiceIn>(inputHeader.VoiceSize);
  127. for (int index = 0; index < voicesIn.Length; index++)
  128. {
  129. VoiceIn voice = voicesIn[index];
  130. VoiceContext voiceCtx = _voices[index];
  131. voiceCtx.SetAcquireState(voice.Acquired != 0);
  132. if (voice.Acquired == 0)
  133. {
  134. continue;
  135. }
  136. if (voice.FirstUpdate != 0)
  137. {
  138. voiceCtx.AdpcmCtx = GetAdpcmDecoderContext(
  139. voice.AdpcmCoeffsPosition,
  140. voice.AdpcmCoeffsSize);
  141. voiceCtx.SampleFormat = voice.SampleFormat;
  142. voiceCtx.SampleRate = voice.SampleRate;
  143. voiceCtx.ChannelsCount = voice.ChannelsCount;
  144. voiceCtx.SetBufferIndex(voice.BaseWaveBufferIndex);
  145. }
  146. voiceCtx.WaveBuffers[0] = voice.WaveBuffer0;
  147. voiceCtx.WaveBuffers[1] = voice.WaveBuffer1;
  148. voiceCtx.WaveBuffers[2] = voice.WaveBuffer2;
  149. voiceCtx.WaveBuffers[3] = voice.WaveBuffer3;
  150. voiceCtx.Volume = voice.Volume;
  151. voiceCtx.PlayState = voice.PlayState;
  152. }
  153. UpdateAudio();
  154. UpdateDataHeader outputHeader = new UpdateDataHeader();
  155. int updateHeaderSize = Marshal.SizeOf<UpdateDataHeader>();
  156. outputHeader.Revision = IAudioRendererManager.RevMagic;
  157. outputHeader.BehaviorSize = 0xb0;
  158. outputHeader.MemoryPoolSize = (_params.EffectCount + _params.VoiceCount * 4) * 0x10;
  159. outputHeader.VoiceSize = _params.VoiceCount * 0x10;
  160. outputHeader.EffectSize = _params.EffectCount * 0x10;
  161. outputHeader.SinkSize = _params.SinkCount * 0x20;
  162. outputHeader.PerformanceManagerSize = 0x10;
  163. outputHeader.TotalSize = updateHeaderSize +
  164. outputHeader.BehaviorSize +
  165. outputHeader.MemoryPoolSize +
  166. outputHeader.VoiceSize +
  167. outputHeader.EffectSize +
  168. outputHeader.SinkSize +
  169. outputHeader.PerformanceManagerSize;
  170. writer.Write(outputHeader);
  171. foreach (MemoryPoolContext memoryPool in _memoryPools)
  172. {
  173. writer.Write(memoryPool.OutStatus);
  174. }
  175. foreach (VoiceContext voice in _voices)
  176. {
  177. writer.Write(voice.OutStatus);
  178. }
  179. return ResultCode.Success;
  180. }
  181. [Command(5)]
  182. // Start()
  183. public ResultCode StartAudioRenderer(ServiceCtx context)
  184. {
  185. Logger.PrintStub(LogClass.ServiceAudio);
  186. _playState = PlayState.Playing;
  187. return ResultCode.Success;
  188. }
  189. [Command(6)]
  190. // Stop()
  191. public ResultCode StopAudioRenderer(ServiceCtx context)
  192. {
  193. Logger.PrintStub(LogClass.ServiceAudio);
  194. _playState = PlayState.Stopped;
  195. return ResultCode.Success;
  196. }
  197. [Command(7)]
  198. // QuerySystemEvent() -> handle<copy, event>
  199. public ResultCode 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 ResultCode.Success;
  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 void AppendMixedBuffer(long tag)
  231. {
  232. int[] mixBuffer = new int[MixBufferSamplesCount * AudioConsts.HostChannelsCount];
  233. foreach (VoiceContext voice in _voices)
  234. {
  235. if (!voice.Playing || voice.CurrentWaveBuffer.Size == 0)
  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. }