NvFlinger.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. using ChocolArm64.Memory;
  2. using Ryujinx.Core.Logging;
  3. using Ryujinx.Core.OsHle.Handles;
  4. using Ryujinx.Core.OsHle.Services.Nv;
  5. using Ryujinx.Graphics.Gal;
  6. using Ryujinx.Graphics.Gpu;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Text;
  11. using System.Threading;
  12. using static Ryujinx.Core.OsHle.Services.Android.Parcel;
  13. namespace Ryujinx.Core.OsHle.Services.Android
  14. {
  15. class NvFlinger : IDisposable
  16. {
  17. private delegate long ServiceProcessParcel(ServiceCtx Context, BinaryReader ParcelReader);
  18. private Dictionary<(string, int), ServiceProcessParcel> Commands;
  19. private KEvent ReleaseEvent;
  20. private IGalRenderer Renderer;
  21. private const int BufferQueueCount = 0x40;
  22. private const int BufferQueueMask = BufferQueueCount - 1;
  23. [Flags]
  24. private enum HalTransform
  25. {
  26. FlipX = 1 << 0,
  27. FlipY = 1 << 1,
  28. Rotate90 = 1 << 2
  29. }
  30. private enum BufferState
  31. {
  32. Free,
  33. Dequeued,
  34. Queued,
  35. Acquired
  36. }
  37. private struct Rect
  38. {
  39. public int Top;
  40. public int Left;
  41. public int Right;
  42. public int Bottom;
  43. }
  44. private struct BufferEntry
  45. {
  46. public BufferState State;
  47. public HalTransform Transform;
  48. public Rect Crop;
  49. public GbpBuffer Data;
  50. }
  51. private BufferEntry[] BufferQueue;
  52. private ManualResetEvent WaitBufferFree;
  53. private bool Disposed;
  54. public NvFlinger(IGalRenderer Renderer, KEvent ReleaseEvent)
  55. {
  56. Commands = new Dictionary<(string, int), ServiceProcessParcel>()
  57. {
  58. { ("android.gui.IGraphicBufferProducer", 0x1), GbpRequestBuffer },
  59. { ("android.gui.IGraphicBufferProducer", 0x3), GbpDequeueBuffer },
  60. { ("android.gui.IGraphicBufferProducer", 0x4), GbpDetachBuffer },
  61. { ("android.gui.IGraphicBufferProducer", 0x7), GbpQueueBuffer },
  62. { ("android.gui.IGraphicBufferProducer", 0x8), GbpCancelBuffer },
  63. { ("android.gui.IGraphicBufferProducer", 0x9), GbpQuery },
  64. { ("android.gui.IGraphicBufferProducer", 0xa), GbpConnect },
  65. { ("android.gui.IGraphicBufferProducer", 0xb), GbpDisconnect },
  66. { ("android.gui.IGraphicBufferProducer", 0xe), GbpPreallocBuffer }
  67. };
  68. this.Renderer = Renderer;
  69. this.ReleaseEvent = ReleaseEvent;
  70. BufferQueue = new BufferEntry[0x40];
  71. WaitBufferFree = new ManualResetEvent(false);
  72. }
  73. public long ProcessParcelRequest(ServiceCtx Context, byte[] ParcelData, int Code)
  74. {
  75. using (MemoryStream MS = new MemoryStream(ParcelData))
  76. {
  77. BinaryReader Reader = new BinaryReader(MS);
  78. MS.Seek(4, SeekOrigin.Current);
  79. int StrSize = Reader.ReadInt32();
  80. string InterfaceName = Encoding.Unicode.GetString(Reader.ReadBytes(StrSize * 2));
  81. long Remainder = MS.Position & 0xf;
  82. if (Remainder != 0)
  83. {
  84. MS.Seek(0x10 - Remainder, SeekOrigin.Current);
  85. }
  86. MS.Seek(0x50, SeekOrigin.Begin);
  87. if (Commands.TryGetValue((InterfaceName, Code), out ServiceProcessParcel ProcReq))
  88. {
  89. Context.Ns.Log.PrintDebug(LogClass.ServiceVi, $"{InterfaceName} {ProcReq.Method.Name}");
  90. return ProcReq(Context, Reader);
  91. }
  92. else
  93. {
  94. throw new NotImplementedException($"{InterfaceName} {Code}");
  95. }
  96. }
  97. }
  98. private long GbpRequestBuffer(ServiceCtx Context, BinaryReader ParcelReader)
  99. {
  100. int Slot = ParcelReader.ReadInt32();
  101. using (MemoryStream MS = new MemoryStream())
  102. {
  103. BinaryWriter Writer = new BinaryWriter(MS);
  104. BufferEntry Entry = BufferQueue[Slot];
  105. int BufferCount = 1; //?
  106. long BufferSize = Entry.Data.Size;
  107. Writer.Write(BufferCount);
  108. Writer.Write(BufferSize);
  109. Entry.Data.Write(Writer);
  110. Writer.Write(0);
  111. return MakeReplyParcel(Context, MS.ToArray());
  112. }
  113. }
  114. private long GbpDequeueBuffer(ServiceCtx Context, BinaryReader ParcelReader)
  115. {
  116. //TODO: Errors.
  117. int Format = ParcelReader.ReadInt32();
  118. int Width = ParcelReader.ReadInt32();
  119. int Height = ParcelReader.ReadInt32();
  120. int GetTimestamps = ParcelReader.ReadInt32();
  121. int Usage = ParcelReader.ReadInt32();
  122. int Slot = GetFreeSlotBlocking(Width, Height);
  123. return MakeReplyParcel(Context, Slot, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  124. }
  125. private long GbpQueueBuffer(ServiceCtx Context, BinaryReader ParcelReader)
  126. {
  127. Context.Ns.Statistics.RecordGameFrameTime();
  128. //TODO: Errors.
  129. int Slot = ParcelReader.ReadInt32();
  130. int Unknown4 = ParcelReader.ReadInt32();
  131. int Unknown8 = ParcelReader.ReadInt32();
  132. int Unknownc = ParcelReader.ReadInt32();
  133. int Timestamp = ParcelReader.ReadInt32();
  134. int IsAutoTimestamp = ParcelReader.ReadInt32();
  135. int CropTop = ParcelReader.ReadInt32();
  136. int CropLeft = ParcelReader.ReadInt32();
  137. int CropRight = ParcelReader.ReadInt32();
  138. int CropBottom = ParcelReader.ReadInt32();
  139. int ScalingMode = ParcelReader.ReadInt32();
  140. int Transform = ParcelReader.ReadInt32();
  141. int StickyTransform = ParcelReader.ReadInt32();
  142. int Unknown34 = ParcelReader.ReadInt32();
  143. int Unknown38 = ParcelReader.ReadInt32();
  144. int IsFenceValid = ParcelReader.ReadInt32();
  145. int Fence0Id = ParcelReader.ReadInt32();
  146. int Fence0Value = ParcelReader.ReadInt32();
  147. int Fence1Id = ParcelReader.ReadInt32();
  148. int Fence1Value = ParcelReader.ReadInt32();
  149. BufferQueue[Slot].Transform = (HalTransform)Transform;
  150. BufferQueue[Slot].Crop.Top = CropTop;
  151. BufferQueue[Slot].Crop.Left = CropLeft;
  152. BufferQueue[Slot].Crop.Right = CropRight;
  153. BufferQueue[Slot].Crop.Bottom = CropBottom;
  154. BufferQueue[Slot].State = BufferState.Queued;
  155. SendFrameBuffer(Context, Slot);
  156. return MakeReplyParcel(Context, 1280, 720, 0, 0, 0);
  157. }
  158. private long GbpDetachBuffer(ServiceCtx Context, BinaryReader ParcelReader)
  159. {
  160. return MakeReplyParcel(Context, 0);
  161. }
  162. private long GbpCancelBuffer(ServiceCtx Context, BinaryReader ParcelReader)
  163. {
  164. //TODO: Errors.
  165. int Slot = ParcelReader.ReadInt32();
  166. BufferQueue[Slot].State = BufferState.Free;
  167. return MakeReplyParcel(Context, 0);
  168. }
  169. private long GbpQuery(ServiceCtx Context, BinaryReader ParcelReader)
  170. {
  171. return MakeReplyParcel(Context, 0, 0);
  172. }
  173. private long GbpConnect(ServiceCtx Context, BinaryReader ParcelReader)
  174. {
  175. return MakeReplyParcel(Context, 1280, 720, 0, 0, 0);
  176. }
  177. private long GbpDisconnect(ServiceCtx Context, BinaryReader ParcelReader)
  178. {
  179. return MakeReplyParcel(Context, 0);
  180. }
  181. private long GbpPreallocBuffer(ServiceCtx Context, BinaryReader ParcelReader)
  182. {
  183. int Slot = ParcelReader.ReadInt32();
  184. int BufferCount = ParcelReader.ReadInt32();
  185. if (BufferCount > 0)
  186. {
  187. long BufferSize = ParcelReader.ReadInt64();
  188. BufferQueue[Slot].State = BufferState.Free;
  189. BufferQueue[Slot].Data = new GbpBuffer(ParcelReader);
  190. }
  191. return MakeReplyParcel(Context, 0);
  192. }
  193. private long MakeReplyParcel(ServiceCtx Context, params int[] Ints)
  194. {
  195. using (MemoryStream MS = new MemoryStream())
  196. {
  197. BinaryWriter Writer = new BinaryWriter(MS);
  198. foreach (int Int in Ints)
  199. {
  200. Writer.Write(Int);
  201. }
  202. return MakeReplyParcel(Context, MS.ToArray());
  203. }
  204. }
  205. private long MakeReplyParcel(ServiceCtx Context, byte[] Data)
  206. {
  207. long ReplyPos = Context.Request.ReceiveBuff[0].Position;
  208. long ReplySize = Context.Request.ReceiveBuff[0].Size;
  209. byte[] Reply = MakeParcel(Data, new byte[0]);
  210. AMemoryHelper.WriteBytes(Context.Memory, ReplyPos, Reply);
  211. return 0;
  212. }
  213. private void SendFrameBuffer(ServiceCtx Context, int Slot)
  214. {
  215. int FbWidth = 1280;
  216. int FbHeight = 720;
  217. NvMap Map = GetNvMap(Context, Slot);
  218. NvMapFb MapFb = (NvMapFb)INvDrvServices.NvMapsFb.GetData(Context.Process, 0);
  219. long CpuAddr = Map.CpuAddress;
  220. long GpuAddr = Map.GpuAddress;
  221. if (MapFb.HasBufferOffset(Slot))
  222. {
  223. CpuAddr += MapFb.GetBufferOffset(Slot);
  224. //TODO: Enable once the frame buffers problems are fixed.
  225. //GpuAddr += MapFb.GetBufferOffset(Slot);
  226. }
  227. BufferQueue[Slot].State = BufferState.Acquired;
  228. Rect Crop = BufferQueue[Slot].Crop;
  229. int RealWidth = FbWidth;
  230. int RealHeight = FbHeight;
  231. float XSign = BufferQueue[Slot].Transform.HasFlag(HalTransform.FlipX) ? -1 : 1;
  232. float YSign = BufferQueue[Slot].Transform.HasFlag(HalTransform.FlipY) ? -1 : 1;
  233. float ScaleX = 1;
  234. float ScaleY = 1;
  235. float OffsX = 0;
  236. float OffsY = 0;
  237. if (Crop.Right != 0 &&
  238. Crop.Bottom != 0)
  239. {
  240. //Who knows if this is right, I was never good with math...
  241. RealWidth = Crop.Right - Crop.Left;
  242. RealHeight = Crop.Bottom - Crop.Top;
  243. if (BufferQueue[Slot].Transform.HasFlag(HalTransform.Rotate90))
  244. {
  245. ScaleY = (float)FbHeight / RealHeight;
  246. ScaleX = (float)FbWidth / RealWidth;
  247. OffsY = ((-(float)Crop.Left / Crop.Right) + ScaleX - 1) * -XSign;
  248. OffsX = ((-(float)Crop.Top / Crop.Bottom) + ScaleY - 1) * -YSign;
  249. }
  250. else
  251. {
  252. ScaleX = (float)FbWidth / RealWidth;
  253. ScaleY = (float)FbHeight / RealHeight;
  254. OffsX = ((-(float)Crop.Left / Crop.Right) + ScaleX - 1) * XSign;
  255. OffsY = ((-(float)Crop.Top / Crop.Bottom) + ScaleY - 1) * -YSign;
  256. }
  257. }
  258. ScaleX *= XSign;
  259. ScaleY *= YSign;
  260. float Rotate = 0;
  261. if (BufferQueue[Slot].Transform.HasFlag(HalTransform.Rotate90))
  262. {
  263. Rotate = -MathF.PI * 0.5f;
  264. }
  265. Renderer.SetFrameBufferTransform(ScaleX, ScaleY, Rotate, OffsX, OffsY);
  266. //TODO: Support double buffering here aswell, it is broken for GPU
  267. //frame buffers because it seems to be completely out of sync.
  268. if (Context.Ns.Gpu.Engine3d.IsFrameBufferPosition(GpuAddr))
  269. {
  270. //Frame buffer is rendered to by the GPU, we can just
  271. //bind the frame buffer texture, it's not necessary to read anything.
  272. Renderer.SetFrameBuffer(GpuAddr);
  273. }
  274. else
  275. {
  276. //Frame buffer is not set on the GPU registers, in this case
  277. //assume that the app is manually writing to it.
  278. Texture Texture = new Texture(CpuAddr, FbWidth, FbHeight);
  279. byte[] Data = TextureReader.Read(Context.Memory, Texture);
  280. Renderer.SetFrameBuffer(Data, FbWidth, FbHeight);
  281. }
  282. Context.Ns.Gpu.Renderer.QueueAction(() => ReleaseBuffer(Slot));
  283. }
  284. private NvMap GetNvMap(ServiceCtx Context, int Slot)
  285. {
  286. int NvMapHandle = BitConverter.ToInt32(BufferQueue[Slot].Data.RawData, 0x4c);
  287. if (!BitConverter.IsLittleEndian)
  288. {
  289. byte[] RawValue = BitConverter.GetBytes(NvMapHandle);
  290. Array.Reverse(RawValue);
  291. NvMapHandle = BitConverter.ToInt32(RawValue, 0);
  292. }
  293. return INvDrvServices.NvMaps.GetData<NvMap>(Context.Process, NvMapHandle);
  294. }
  295. private void ReleaseBuffer(int Slot)
  296. {
  297. BufferQueue[Slot].State = BufferState.Free;
  298. ReleaseEvent.WaitEvent.Set();
  299. lock (WaitBufferFree)
  300. {
  301. WaitBufferFree.Set();
  302. }
  303. }
  304. private int GetFreeSlotBlocking(int Width, int Height)
  305. {
  306. int Slot;
  307. do
  308. {
  309. lock (WaitBufferFree)
  310. {
  311. if ((Slot = GetFreeSlot(Width, Height)) != -1)
  312. {
  313. break;
  314. }
  315. if (Disposed)
  316. {
  317. break;
  318. }
  319. WaitBufferFree.Reset();
  320. }
  321. WaitBufferFree.WaitOne();
  322. }
  323. while (!Disposed);
  324. return Slot;
  325. }
  326. private int GetFreeSlot(int Width, int Height)
  327. {
  328. lock (BufferQueue)
  329. {
  330. for (int Slot = 0; Slot < BufferQueue.Length; Slot++)
  331. {
  332. if (BufferQueue[Slot].State != BufferState.Free)
  333. {
  334. continue;
  335. }
  336. GbpBuffer Data = BufferQueue[Slot].Data;
  337. if (Data.Width == Width &&
  338. Data.Height == Height)
  339. {
  340. BufferQueue[Slot].State = BufferState.Dequeued;
  341. return Slot;
  342. }
  343. }
  344. }
  345. return -1;
  346. }
  347. public void Dispose()
  348. {
  349. Dispose(true);
  350. }
  351. protected virtual void Dispose(bool Disposing)
  352. {
  353. if (Disposing && !Disposed)
  354. {
  355. Disposed = true;
  356. lock (WaitBufferFree)
  357. {
  358. WaitBufferFree.Set();
  359. }
  360. WaitBufferFree.Dispose();
  361. }
  362. }
  363. }
  364. }