aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Common/PreciseSleep/WindowsSleepEvent.cs
blob: 87c10d18edd8dabc88a1fec130d45d8fc565de3f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using Ryujinx.Common.SystemInterop;
using System;
using System.Runtime.Versioning;
using System.Threading;

namespace Ryujinx.Common.PreciseSleep
{
    /// <summary>
    /// A precise sleep event that uses Windows specific methods to increase clock resolution beyond 1ms,
    /// use the clock's phase for more precise waits, and potentially align timepoints with it.
    /// </summary>
    [SupportedOSPlatform("windows")]
    internal class WindowsSleepEvent : IPreciseSleepEvent
    {
        /// <summary>
        /// The clock can drift a bit, so add this to encourage the clock to still wait if the next tick is forecasted slightly before it.
        /// </summary>
        private const long ErrorBias = 50000;

        /// <summary>
        /// Allowed to be 0.05ms away from the clock granularity to reduce precision.
        /// </summary>
        private const long ClockAlignedBias = 50000;

        /// <summary>
        /// The fraction of clock granularity above the timepoint that will align it down to the lower timepoint.
        /// Currently set to the lower 1/4, so for 0.5ms granularity: 0.1ms would be rounded down, 0.2 ms would be rounded up.
        /// </summary>
        private const long ReverseTimePointFraction = 4;

        private readonly AutoResetEvent _waitEvent = new(false);
        private readonly WindowsGranularTimer _timer = WindowsGranularTimer.Instance;

        /// <summary>
        /// Set to true to disable timepoint realignment.
        /// </summary>
        public bool Precise { get; set; } = false;

        public long AdjustTimePoint(long timePoint, long timeoutNs)
        {
            if (Precise || timePoint == long.MaxValue)
            {
                return timePoint;
            }

            // Does the timeout align with the host clock?

            long granularity = _timer.GranularityNs;
            long misalignment = timeoutNs % granularity;

            if ((misalignment < ClockAlignedBias || misalignment > granularity - ClockAlignedBias) && timeoutNs > ClockAlignedBias)
            {
                // Inaccurate sleep for 0.5ms increments, typically.

                (long low, long high) = _timer.ReturnNearestTicks(timePoint);

                if (timePoint - low < _timer.GranularityTicks / ReverseTimePointFraction)
                {
                    timePoint = low;
                }
                else
                {
                    timePoint = high;
                }
            }

            return timePoint;
        }

        public bool SleepUntil(long timePoint)
        {
            return _timer.SleepUntilTimePoint(_waitEvent, timePoint + (ErrorBias * PerformanceCounter.TicksPerMillisecond) / 1_000_000);
        }

        public void Sleep()
        {
            _waitEvent.WaitOne();
        }

        public void Signal()
        {
            _waitEvent.Set();
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);

            _waitEvent.Dispose();
        }
    }
}