IAudioRenderer.cs 15 KB

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