IAudioRenderer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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;
  7. using Ryujinx.HLE.Utilities;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Runtime.InteropServices;
  11. namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer
  12. {
  13. class IAudioRenderer : IpcService, IDisposable
  14. {
  15. //This is the amount of samples that are going to be appended
  16. //each time that RequestUpdateAudioRenderer is called. Ideally,
  17. //this value shouldn't be neither too small (to avoid the player
  18. //starving due to running out of samples) or too large (to avoid
  19. //high latency).
  20. private const int MixBufferSamplesCount = 960;
  21. private Dictionary<int, ServiceProcessRequest> m_Commands;
  22. public override IReadOnlyDictionary<int, ServiceProcessRequest> Commands => m_Commands;
  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. m_Commands = new Dictionary<int, ServiceProcessRequest>()
  38. {
  39. { 0, GetSampleRate },
  40. { 1, GetSampleCount },
  41. { 2, GetMixBufferCount },
  42. { 3, GetState },
  43. { 4, RequestUpdateAudioRenderer },
  44. { 5, StartAudioRenderer },
  45. { 6, StopAudioRenderer },
  46. { 7, QuerySystemEvent }
  47. };
  48. UpdateEvent = new KEvent(System);
  49. this.Memory = Memory;
  50. this.AudioOut = AudioOut;
  51. this.Params = Params;
  52. Track = AudioOut.OpenTrack(
  53. AudioConsts.HostSampleRate,
  54. AudioConsts.HostChannelsCount,
  55. AudioCallback);
  56. MemoryPools = CreateArray<MemoryPoolContext>(Params.EffectCount + Params.VoiceCount * 4);
  57. Voices = CreateArray<VoiceContext>(Params.VoiceCount);
  58. InitializeAudioOut();
  59. PlayState = PlayState.Stopped;
  60. }
  61. // GetSampleRate() -> u32
  62. public long GetSampleRate(ServiceCtx Context)
  63. {
  64. Context.ResponseData.Write(Params.SampleRate);
  65. return 0;
  66. }
  67. // GetSampleCount() -> u32
  68. public long GetSampleCount(ServiceCtx Context)
  69. {
  70. Context.ResponseData.Write(Params.SampleCount);
  71. return 0;
  72. }
  73. // GetMixBufferCount() -> u32
  74. public long GetMixBufferCount(ServiceCtx Context)
  75. {
  76. Context.ResponseData.Write(Params.MixCount);
  77. return 0;
  78. }
  79. // GetState() -> u32
  80. private long GetState(ServiceCtx Context)
  81. {
  82. Context.ResponseData.Write((int)PlayState);
  83. Logger.PrintStub(LogClass.ServiceAudio, $"Stubbed. Renderer State: {Enum.GetName(typeof(PlayState), PlayState)}");
  84. return 0;
  85. }
  86. private void AudioCallback()
  87. {
  88. UpdateEvent.ReadableEvent.Signal();
  89. }
  90. private static T[] CreateArray<T>(int Size) where T : new()
  91. {
  92. T[] Output = new T[Size];
  93. for (int Index = 0; Index < Size; Index++)
  94. {
  95. Output[Index] = new T();
  96. }
  97. return Output;
  98. }
  99. private void InitializeAudioOut()
  100. {
  101. AppendMixedBuffer(0);
  102. AppendMixedBuffer(1);
  103. AppendMixedBuffer(2);
  104. AudioOut.Start(Track);
  105. }
  106. public long 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. 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. UpdateAudio();
  158. UpdateDataHeader OutputHeader = new UpdateDataHeader();
  159. int UpdateHeaderSize = Marshal.SizeOf<UpdateDataHeader>();
  160. OutputHeader.Revision = IAudioRendererManager.RevMagic;
  161. OutputHeader.BehaviorSize = 0xb0;
  162. OutputHeader.MemoryPoolSize = (Params.EffectCount + Params.VoiceCount * 4) * 0x10;
  163. OutputHeader.VoiceSize = Params.VoiceCount * 0x10;
  164. OutputHeader.EffectSize = Params.EffectCount * 0x10;
  165. OutputHeader.SinkSize = Params.SinkCount * 0x20;
  166. OutputHeader.PerformanceManagerSize = 0x10;
  167. OutputHeader.TotalSize = UpdateHeaderSize +
  168. OutputHeader.BehaviorSize +
  169. OutputHeader.MemoryPoolSize +
  170. OutputHeader.VoiceSize +
  171. OutputHeader.EffectSize +
  172. OutputHeader.SinkSize +
  173. OutputHeader.PerformanceManagerSize;
  174. Writer.Write(OutputHeader);
  175. foreach (MemoryPoolContext MemoryPool in MemoryPools)
  176. {
  177. Writer.Write(MemoryPool.OutStatus);
  178. }
  179. foreach (VoiceContext Voice in Voices)
  180. {
  181. Writer.Write(Voice.OutStatus);
  182. }
  183. return 0;
  184. }
  185. public long StartAudioRenderer(ServiceCtx Context)
  186. {
  187. Logger.PrintStub(LogClass.ServiceAudio, "Stubbed.");
  188. PlayState = PlayState.Playing;
  189. return 0;
  190. }
  191. public long StopAudioRenderer(ServiceCtx Context)
  192. {
  193. Logger.PrintStub(LogClass.ServiceAudio, "Stubbed.");
  194. PlayState = PlayState.Stopped;
  195. return 0;
  196. }
  197. public long QuerySystemEvent(ServiceCtx Context)
  198. {
  199. if (Context.Process.HandleTable.GenerateHandle(UpdateEvent.ReadableEvent, out int Handle) != KernelResult.Success)
  200. {
  201. throw new InvalidOperationException("Out of handles!");
  202. }
  203. Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle);
  204. return 0;
  205. }
  206. private AdpcmDecoderContext GetAdpcmDecoderContext(long Position, long Size)
  207. {
  208. if (Size == 0)
  209. {
  210. return null;
  211. }
  212. AdpcmDecoderContext Context = new AdpcmDecoderContext();
  213. Context.Coefficients = new short[Size >> 1];
  214. for (int Offset = 0; Offset < Size; Offset += 2)
  215. {
  216. Context.Coefficients[Offset >> 1] = Memory.ReadInt16(Position + Offset);
  217. }
  218. return Context;
  219. }
  220. private void UpdateAudio()
  221. {
  222. long[] Released = AudioOut.GetReleasedBuffers(Track, 2);
  223. for (int Index = 0; Index < Released.Length; Index++)
  224. {
  225. AppendMixedBuffer(Released[Index]);
  226. }
  227. }
  228. private void AppendMixedBuffer(long Tag)
  229. {
  230. int[] MixBuffer = new int[MixBufferSamplesCount * AudioConsts.HostChannelsCount];
  231. foreach (VoiceContext Voice in Voices)
  232. {
  233. if (!Voice.Playing)
  234. {
  235. continue;
  236. }
  237. int OutOffset = 0;
  238. int PendingSamples = MixBufferSamplesCount;
  239. while (PendingSamples > 0)
  240. {
  241. int[] Samples = Voice.GetBufferData(Memory, PendingSamples, out int ReturnedSamples);
  242. if (ReturnedSamples == 0)
  243. {
  244. break;
  245. }
  246. PendingSamples -= ReturnedSamples;
  247. for (int Offset = 0; Offset < Samples.Length; Offset++)
  248. {
  249. int Sample = (int)(Samples[Offset] * Voice.Volume);
  250. MixBuffer[OutOffset++] += Sample;
  251. }
  252. }
  253. }
  254. AudioOut.AppendBuffer(Track, Tag, GetFinalBuffer(MixBuffer));
  255. }
  256. private static short[] GetFinalBuffer(int[] Buffer)
  257. {
  258. short[] Output = new short[Buffer.Length];
  259. for (int Offset = 0; Offset < Buffer.Length; Offset++)
  260. {
  261. Output[Offset] = DspUtils.Saturate(Buffer[Offset]);
  262. }
  263. return Output;
  264. }
  265. public void Dispose()
  266. {
  267. Dispose(true);
  268. }
  269. protected virtual void Dispose(bool Disposing)
  270. {
  271. if (Disposing)
  272. {
  273. AudioOut.CloseTrack(Track);
  274. }
  275. }
  276. }
  277. }