SurfaceFlinger.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. using Ryujinx.Common.Configuration;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Gpu;
  5. using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvMap;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Threading;
  11. namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
  12. {
  13. class SurfaceFlinger : IConsumerListener, IDisposable
  14. {
  15. private const int TargetFps = 60;
  16. private Switch _device;
  17. private Dictionary<long, Layer> _layers;
  18. private bool _isRunning;
  19. private Thread _composerThread;
  20. private Stopwatch _chrono;
  21. private ManualResetEvent _event = new ManualResetEvent(false);
  22. private AutoResetEvent _nextFrameEvent = new AutoResetEvent(true);
  23. private long _ticks;
  24. private long _ticksPerFrame;
  25. private long _spinTicks;
  26. private long _1msTicks;
  27. private int _swapInterval;
  28. private readonly object Lock = new object();
  29. public long RenderLayerId { get; private set; }
  30. private class Layer
  31. {
  32. public int ProducerBinderId;
  33. public IGraphicBufferProducer Producer;
  34. public BufferItemConsumer Consumer;
  35. public BufferQueueCore Core;
  36. public long Owner;
  37. }
  38. private class TextureCallbackInformation
  39. {
  40. public Layer Layer;
  41. public BufferItem Item;
  42. }
  43. public SurfaceFlinger(Switch device)
  44. {
  45. _device = device;
  46. _layers = new Dictionary<long, Layer>();
  47. RenderLayerId = 0;
  48. _composerThread = new Thread(HandleComposition)
  49. {
  50. Name = "SurfaceFlinger.Composer"
  51. };
  52. _chrono = new Stopwatch();
  53. _chrono.Start();
  54. _ticks = 0;
  55. _spinTicks = Stopwatch.Frequency / 500;
  56. _1msTicks = Stopwatch.Frequency / 1000;
  57. UpdateSwapInterval(1);
  58. _composerThread.Start();
  59. }
  60. private void UpdateSwapInterval(int swapInterval)
  61. {
  62. _swapInterval = swapInterval;
  63. // If the swap interval is 0, Game VSync is disabled.
  64. if (_swapInterval == 0)
  65. {
  66. _nextFrameEvent.Set();
  67. _ticksPerFrame = 1;
  68. }
  69. else
  70. {
  71. _ticksPerFrame = Stopwatch.Frequency / (TargetFps / _swapInterval);
  72. }
  73. }
  74. public IGraphicBufferProducer OpenLayer(long pid, long layerId)
  75. {
  76. bool needCreate;
  77. lock (Lock)
  78. {
  79. needCreate = GetLayerByIdLocked(layerId) == null;
  80. }
  81. if (needCreate)
  82. {
  83. CreateLayerFromId(pid, layerId);
  84. }
  85. return GetProducerByLayerId(layerId);
  86. }
  87. public IGraphicBufferProducer CreateLayer(long pid, out long layerId)
  88. {
  89. layerId = 1;
  90. lock (Lock)
  91. {
  92. foreach (KeyValuePair<long, Layer> pair in _layers)
  93. {
  94. if (pair.Key >= layerId)
  95. {
  96. layerId = pair.Key + 1;
  97. }
  98. }
  99. }
  100. CreateLayerFromId(pid, layerId);
  101. return GetProducerByLayerId(layerId);
  102. }
  103. private void CreateLayerFromId(long pid, long layerId)
  104. {
  105. lock (Lock)
  106. {
  107. Logger.Info?.Print(LogClass.SurfaceFlinger, $"Creating layer {layerId}");
  108. BufferQueueCore core = BufferQueue.CreateBufferQueue(_device, pid, out BufferQueueProducer producer, out BufferQueueConsumer consumer);
  109. core.BufferQueued += () =>
  110. {
  111. _nextFrameEvent.Set();
  112. };
  113. _layers.Add(layerId, new Layer
  114. {
  115. ProducerBinderId = HOSBinderDriverServer.RegisterBinderObject(producer),
  116. Producer = producer,
  117. Consumer = new BufferItemConsumer(_device, consumer, 0, -1, false, this),
  118. Core = core,
  119. Owner = pid
  120. });
  121. }
  122. }
  123. public bool CloseLayer(long layerId)
  124. {
  125. lock (Lock)
  126. {
  127. Layer layer = GetLayerByIdLocked(layerId);
  128. if (layer != null)
  129. {
  130. HOSBinderDriverServer.UnregisterBinderObject(layer.ProducerBinderId);
  131. }
  132. bool removed = _layers.Remove(layerId);
  133. // If the layer was removed and the current in use, we need to change the current layer in use.
  134. if (removed && RenderLayerId == layerId)
  135. {
  136. // If no layer is availaible, reset to default value.
  137. if (_layers.Count == 0)
  138. {
  139. SetRenderLayer(0);
  140. }
  141. else
  142. {
  143. SetRenderLayer(_layers.Last().Key);
  144. }
  145. }
  146. return removed;
  147. }
  148. }
  149. public void SetRenderLayer(long layerId)
  150. {
  151. lock (Lock)
  152. {
  153. RenderLayerId = layerId;
  154. }
  155. }
  156. private Layer GetLayerByIdLocked(long layerId)
  157. {
  158. foreach (KeyValuePair<long, Layer> pair in _layers)
  159. {
  160. if (pair.Key == layerId)
  161. {
  162. return pair.Value;
  163. }
  164. }
  165. return null;
  166. }
  167. public IGraphicBufferProducer GetProducerByLayerId(long layerId)
  168. {
  169. lock (Lock)
  170. {
  171. Layer layer = GetLayerByIdLocked(layerId);
  172. if (layer != null)
  173. {
  174. return layer.Producer;
  175. }
  176. }
  177. return null;
  178. }
  179. private void HandleComposition()
  180. {
  181. _isRunning = true;
  182. long lastTicks = _chrono.ElapsedTicks;
  183. while (_isRunning)
  184. {
  185. long ticks = _chrono.ElapsedTicks;
  186. if (_swapInterval == 0)
  187. {
  188. Compose();
  189. _device.System?.SignalVsync();
  190. _nextFrameEvent.WaitOne(17);
  191. lastTicks = ticks;
  192. }
  193. else
  194. {
  195. _ticks += ticks - lastTicks;
  196. lastTicks = ticks;
  197. if (_ticks >= _ticksPerFrame)
  198. {
  199. Compose();
  200. _device.System?.SignalVsync();
  201. // Apply a maximum bound of 3 frames to the tick remainder, in case some event causes Ryujinx to pause for a long time or messes with the timer.
  202. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame * 3);
  203. }
  204. // Sleep if possible. If the time til the next frame is too low, spin wait instead.
  205. long diff = _ticksPerFrame - (_ticks + _chrono.ElapsedTicks - ticks);
  206. if (diff > 0)
  207. {
  208. if (diff < _spinTicks)
  209. {
  210. do
  211. {
  212. // SpinWait is a little more HT/SMT friendly than aggressively updating/checking ticks.
  213. // The value of 5 still gives us quite a bit of precision (~0.0003ms variance at worst) while waiting a reasonable amount of time.
  214. Thread.SpinWait(5);
  215. ticks = _chrono.ElapsedTicks;
  216. _ticks += ticks - lastTicks;
  217. lastTicks = ticks;
  218. } while (_ticks < _ticksPerFrame);
  219. }
  220. else
  221. {
  222. _event.WaitOne((int)(diff / _1msTicks));
  223. }
  224. }
  225. }
  226. }
  227. }
  228. public void Compose()
  229. {
  230. lock (Lock)
  231. {
  232. // TODO: support multilayers (& multidisplay ?)
  233. if (RenderLayerId == 0)
  234. {
  235. return;
  236. }
  237. Layer layer = GetLayerByIdLocked(RenderLayerId);
  238. Status acquireStatus = layer.Consumer.AcquireBuffer(out BufferItem item, 0);
  239. if (acquireStatus == Status.Success)
  240. {
  241. // If device vsync is disabled, reflect the change.
  242. if (!_device.EnableDeviceVsync)
  243. {
  244. if (_swapInterval != 0)
  245. {
  246. UpdateSwapInterval(0);
  247. }
  248. }
  249. else if (item.SwapInterval != _swapInterval)
  250. {
  251. UpdateSwapInterval(item.SwapInterval);
  252. }
  253. PostFrameBuffer(layer, item);
  254. }
  255. else if (acquireStatus != Status.NoBufferAvailaible && acquireStatus != Status.InvalidOperation)
  256. {
  257. throw new InvalidOperationException();
  258. }
  259. }
  260. }
  261. private void PostFrameBuffer(Layer layer, BufferItem item)
  262. {
  263. int frameBufferWidth = item.GraphicBuffer.Object.Width;
  264. int frameBufferHeight = item.GraphicBuffer.Object.Height;
  265. int nvMapHandle = item.GraphicBuffer.Object.Buffer.Surfaces[0].NvMapHandle;
  266. if (nvMapHandle == 0)
  267. {
  268. nvMapHandle = item.GraphicBuffer.Object.Buffer.NvMapId;
  269. }
  270. ulong bufferOffset = (ulong)item.GraphicBuffer.Object.Buffer.Surfaces[0].Offset;
  271. NvMapHandle map = NvMapDeviceFile.GetMapFromHandle(layer.Owner, nvMapHandle);
  272. ulong frameBufferAddress = map.Address + bufferOffset;
  273. Format format = ConvertColorFormat(item.GraphicBuffer.Object.Buffer.Surfaces[0].ColorFormat);
  274. int bytesPerPixel =
  275. format == Format.B5G6R5Unorm ||
  276. format == Format.R4G4B4A4Unorm ? 2 : 4;
  277. int gobBlocksInY = 1 << item.GraphicBuffer.Object.Buffer.Surfaces[0].BlockHeightLog2;
  278. // Note: Rotation is being ignored.
  279. Rect cropRect = item.Crop;
  280. bool flipX = item.Transform.HasFlag(NativeWindowTransform.FlipX);
  281. bool flipY = item.Transform.HasFlag(NativeWindowTransform.FlipY);
  282. AspectRatio aspectRatio = _device.Configuration.AspectRatio;
  283. bool isStretched = aspectRatio == AspectRatio.Stretched;
  284. ImageCrop crop = new ImageCrop(
  285. cropRect.Left,
  286. cropRect.Right,
  287. cropRect.Top,
  288. cropRect.Bottom,
  289. flipX,
  290. flipY,
  291. isStretched,
  292. aspectRatio.ToFloatX(),
  293. aspectRatio.ToFloatY());
  294. TextureCallbackInformation textureCallbackInformation = new TextureCallbackInformation
  295. {
  296. Layer = layer,
  297. Item = item
  298. };
  299. _device.Gpu.Window.EnqueueFrameThreadSafe(
  300. layer.Owner,
  301. frameBufferAddress,
  302. frameBufferWidth,
  303. frameBufferHeight,
  304. 0,
  305. false,
  306. gobBlocksInY,
  307. format,
  308. bytesPerPixel,
  309. crop,
  310. AcquireBuffer,
  311. ReleaseBuffer,
  312. textureCallbackInformation);
  313. if (item.Fence.FenceCount == 0)
  314. {
  315. _device.Gpu.Window.SignalFrameReady();
  316. _device.Gpu.GPFifo.Interrupt();
  317. }
  318. else
  319. {
  320. item.Fence.RegisterCallback(_device.Gpu, () =>
  321. {
  322. _device.Gpu.Window.SignalFrameReady();
  323. _device.Gpu.GPFifo.Interrupt();
  324. });
  325. }
  326. }
  327. private void ReleaseBuffer(object obj)
  328. {
  329. ReleaseBuffer((TextureCallbackInformation)obj);
  330. }
  331. private void ReleaseBuffer(TextureCallbackInformation information)
  332. {
  333. AndroidFence fence = AndroidFence.NoFence;
  334. information.Layer.Consumer.ReleaseBuffer(information.Item, ref fence);
  335. }
  336. private void AcquireBuffer(GpuContext ignored, object obj)
  337. {
  338. AcquireBuffer((TextureCallbackInformation)obj);
  339. }
  340. private void AcquireBuffer(TextureCallbackInformation information)
  341. {
  342. information.Item.Fence.WaitForever(_device.Gpu);
  343. }
  344. public static Format ConvertColorFormat(ColorFormat colorFormat)
  345. {
  346. return colorFormat switch
  347. {
  348. ColorFormat.A8B8G8R8 => Format.R8G8B8A8Unorm,
  349. ColorFormat.X8B8G8R8 => Format.R8G8B8A8Unorm,
  350. ColorFormat.R5G6B5 => Format.B5G6R5Unorm,
  351. ColorFormat.A8R8G8B8 => Format.B8G8R8A8Unorm,
  352. ColorFormat.A4B4G4R4 => Format.R4G4B4A4Unorm,
  353. _ => throw new NotImplementedException($"Color Format \"{colorFormat}\" not implemented!"),
  354. };
  355. }
  356. public void Dispose()
  357. {
  358. _isRunning = false;
  359. foreach (Layer layer in _layers.Values)
  360. {
  361. layer.Core.PrepareForExit();
  362. }
  363. }
  364. public void OnFrameAvailable(ref BufferItem item)
  365. {
  366. _device.Statistics.RecordGameFrameTime();
  367. }
  368. public void OnFrameReplaced(ref BufferItem item)
  369. {
  370. _device.Statistics.RecordGameFrameTime();
  371. }
  372. public void OnBuffersReleased() {}
  373. }
  374. }