From 72ee3570b794762eae864f2cd266741f3775c8de Mon Sep 17 00:00:00 2001 From: "J. Ritchie Carroll" Date: Thu, 5 Nov 2026 15:23:29 -0500 Subject: [PATCH] Fix simulated timestamps for frame rates above 1,000 fps Millisecond aligned wall-clock timestamps (Ticks.AlignToMillisecondDistribution) cannot represent every frame slot above 1,000 frames per second. At 3,000 fps file replay with SimulateTimestamp produced only about 2,000 distinct timestamps per second, with some slots used twice, so downstream consumers aligning to a 3,000-slot grid lost about a third of the frames. - Add SimulatedTimestampGenerator: anchors to the wall clock on the first frame, then advances a frame counter across the full-resolution sub-second distribution so every slot is used once and frames are exactly one period apart; re-anchors to the wall clock if drift exceeds MaximumDrift. - MultiProtocolFrameParser: use the generator for captured-frame replay timing when DefinedFrameRate > 1,000 (the existing behavior is unchanged at or below 1,000 fps), reset it on Start, report resyncs in Status, and use sub-second alignment for injected simulated timestamps. - ReplayTimer: add an optional catch-up window (100 ms for high frame rates) so scheduler jitter at sub-millisecond periods does not lower replay throughput below the defined frame rate. The default of zero keeps the previous behavior. - Add SimulatedTimestampGeneratorTest unit tests. Co-Authored-By: Claude Opus 5.5 --- .../MultiProtocolFrameParser.cs | 42 ++- src/Gemstone.PhasorProtocols/ReplayTimer.cs | 29 +- .../SimulatedTimestampGenerator.cs | 210 ++++++++++++ .../SimulatedTimestampGeneratorTest.cs | 308 ++++++++++++++++++ 4 files changed, 578 insertions(+), 11 deletions(-) create mode 100644 src/Gemstone.PhasorProtocols/SimulatedTimestampGenerator.cs create mode 100644 src/UnitTests/SimulatedTimestampGeneratorTest.cs diff --git a/src/Gemstone.PhasorProtocols/MultiProtocolFrameParser.cs b/src/Gemstone.PhasorProtocols/MultiProtocolFrameParser.cs index 4429f0b42c..82401630e3 100644 --- a/src/Gemstone.PhasorProtocols/MultiProtocolFrameParser.cs +++ b/src/Gemstone.PhasorProtocols/MultiProtocolFrameParser.cs @@ -1307,6 +1307,16 @@ private void SharedClient_SendDataException(object? sender, EventArgs /// public const int DefaultDefinedFrameRate = 30; + /// + /// Specifies how far file replay pacing can fall behind and still catch up when the + /// exceeds 1,000 frames per second. + /// + /// + /// At sub-millisecond frame periods ordinary scheduler jitter regularly makes a frame late. Catching up + /// keeps replay throughput at the defined frame rate so counter-based simulated timestamps stay near real time. + /// + public static readonly TimeSpan HighFrameRateReplayCatchUpWindow = TimeSpan.FromMilliseconds(100.0D); + /// /// Specifies the default value for the property. /// @@ -1507,6 +1517,7 @@ private void SharedClient_SendDataException(object? sender, EventArgs private IPAddress? m_receiveFromAddress; private IPAddress? m_multicastServerAddress; private ReplayTimer? m_replayTimer; + private SimulatedTimestampGenerator? m_timestampGenerator; private PrecisionInputTimer? m_inputTimer; private LongSynchronizedOperation? m_readNextBuffer; private SharedTimer? m_rateCalcTimer; @@ -2274,6 +2285,9 @@ public string Status if (m_inputTimer is not null) status.AppendLine($" Timer resynchronizations: {m_inputTimer.Resynchronizations:N0}"); + if (m_timestampGenerator is not null) + status.AppendLine($" Timestamp resyncs (sim.): {m_timestampGenerator.Resynchronizations:N0}"); + if (ReplayStartTime > DateTime.MinValue || ReplayStopTime < DateTime.MaxValue) { status.AppendLine($" Replay start time: {ReplayStartTime:yyyy-MM-dd HH:mm:ss.fff}"); @@ -2400,6 +2414,9 @@ public void Start() m_lastParsingExceptionTime = 0L; m_parsingExceptionCount = 0; + // Simulated timestamps re-anchor to the wall clock on restart + m_timestampGenerator?.Reset(); + try { // Parse connection string to check for special parameters @@ -3635,24 +3652,41 @@ private void m_commandChannel_ReceiveDataException(object? sender, EventArgs SimulatedTimestampGenerator.MaximumMillisecondFrameRate; + if (m_inputTimer is null) { if (m_replayTimer?.DefinedFrameRate != m_definedFrameRate) - m_replayTimer = new ReplayTimer(m_definedFrameRate); + m_replayTimer = new ReplayTimer(m_definedFrameRate, highFrameRate ? HighFrameRateReplayCatchUpWindow : TimeSpan.Zero); m_replayTimer.WaitNext(); - - return Ticks.AlignToMillisecondDistribution(DateTime.UtcNow.Ticks, m_definedFrameRate).Value; + + return highFrameRate ? + NextSimulatedTimestamp() : + Ticks.AlignToMillisecondDistribution(DateTime.UtcNow.Ticks, m_definedFrameRate).Value; } // When high resolution input timing is requested, we only need to wait for the next signal... m_inputTimer.FrameWaitHandle?.Wait(); + if (highFrameRate) + return NextSimulatedTimestamp(); + // Input timer can be disabled while thread is waiting, so we make sure it is not null // ReSharper disable once ConstantNullCoalescingCondition return m_inputTimer?.LastFrameTime ?? Ticks.AlignToMillisecondDistribution(DateTime.UtcNow.Ticks, m_definedFrameRate).Value; } + private long NextSimulatedTimestamp() + { + if (m_timestampGenerator?.FrameRate != m_definedFrameRate) + m_timestampGenerator = new SimulatedTimestampGenerator(m_definedFrameRate); + + return m_timestampGenerator.Next(); + } + private void m_frameParser_ReceivedChannelFrame(object? sender, EventArgs e) { // We don't stop parsing for exceptions thrown in consumer event handlers @@ -3661,7 +3695,7 @@ private void m_frameParser_ReceivedChannelFrame(object? sender, EventArgs /// Creates a new instance. /// /// The defined frame rate in frames per second. - public ReplayTimer(int definedFrameRate) + /// + /// Maximum time the timer can fall behind its absolute cadence and still catch up by releasing + /// late frames without waiting. Defaults to , i.e., any lateness resets + /// the cadence and no catch-up frames are released. + /// + public ReplayTimer(int definedFrameRate, TimeSpan catchUpWindow = default) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(definedFrameRate); + ArgumentOutOfRangeException.ThrowIfLessThan(catchUpWindow, TimeSpan.Zero); m_periodTicks = (long)Math.Round(Stopwatch.Frequency / (double)definedFrameRate); m_guardBandTicks = (long)Math.Round(Stopwatch.Frequency * SleepGuardBand / 1000.0D); + m_catchUpTicks = (long)Math.Round(Stopwatch.Frequency * catchUpWindow.TotalSeconds); m_nextTick = Stopwatch.GetTimestamp(); DefinedFrameRate = definedFrameRate; + CatchUpWindow = catchUpWindow; } /// @@ -72,14 +81,20 @@ public ReplayTimer(int definedFrameRate) /// public int DefinedFrameRate { get; } + /// + /// Gets the maximum time the timer can fall behind its cadence and still catch up. + /// + public TimeSpan CatchUpWindow { get; } + /// /// Blocks until the next scheduled frame rate interval. /// /// /// The deadline advances by exactly one period from the current deadline (absolute /// cadence) to keep inter-frame intervals consistent. If the deadline has already - /// fallen behind by more than one full period, it resets to "now + period" to - /// prevent a burst of catch-up frames. + /// fallen behind by more than , it resets to "now + period" + /// to prevent a burst of catch-up frames. Within the catch-up window, late frames are + /// released immediately so the long-run frame rate matches the defined frame rate. /// public void WaitNext() { @@ -87,10 +102,10 @@ public void WaitNext() // a steady cadence regardless of per-frame processing jitter long nextTick = m_nextTick + m_periodTicks; - // If the advanced deadline is already in the past, we've fallen - // behind by more than a full period — reset to relative mode to - // avoid a burst of catch-up frames - if (Stopwatch.GetTimestamp() >= nextTick) + // If the advanced deadline is already in the past by more than the + // catch-up window, we've fallen too far behind — reset to relative + // mode to avoid a burst of catch-up frames + if (Stopwatch.GetTimestamp() >= nextTick + m_catchUpTicks) nextTick = Stopwatch.GetTimestamp() + m_periodTicks; m_nextTick = nextTick; diff --git a/src/Gemstone.PhasorProtocols/SimulatedTimestampGenerator.cs b/src/Gemstone.PhasorProtocols/SimulatedTimestampGenerator.cs new file mode 100644 index 0000000000..57e784c8c2 --- /dev/null +++ b/src/Gemstone.PhasorProtocols/SimulatedTimestampGenerator.cs @@ -0,0 +1,210 @@ +//****************************************************************************************************** +// SimulatedTimestampGenerator.cs - Gbtc +// +// Copyright © 2026, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this +// file except in compliance with the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +// Code Modification History: +// ---------------------------------------------------------------------------------------------------- +// 11/05/2026 - J. Ritchie Carroll +// Generated original version of source code. +// +//****************************************************************************************************** + +using System; + +namespace Gemstone.PhasorProtocols; + +/// +/// Generates simulated frame timestamps for paced (e.g., file replay) input by advancing a frame +/// counter across the sub-second distribution of a defined frame rate, instead of reading the +/// wall clock for every frame. +/// +/// +/// +/// Millisecond aligned wall-clock timestamps, i.e., , +/// cannot represent every frame slot when the frame rate exceeds 1,000 frames per second. For example, at +/// 3,000 frames per second only about 2,000 distinct timestamps per second are produced, some slots twice, +/// so consumers aligning to a 3,000-slot grid lose about a third of the frames. Reading the wall clock +/// per frame also misplaces frames when replay pacing stalls and then bursts. +/// +/// +/// This generator anchors to the wall clock on the first frame, then issues each following frame the +/// next slot of the distribution at full tick resolution. Every timestamp lands +/// exactly on the grid used by and +/// , each slot is used once, and consecutive frames are +/// exactly one frame period apart. If the counter drifts from the wall clock by more than +/// , for example after a long stall in replay, the generator re-anchors to the +/// wall clock so timestamps stay near real time. +/// +/// +public sealed class SimulatedTimestampGenerator +{ + #region [ Members ] + + // Constants + + /// + /// Defines the highest frame rate for which millisecond aligned timestamps can represent every frame slot. + /// + public const int MaximumMillisecondFrameRate = 1000; + + /// + /// Defines the default maximum drift between the frame counter and the wall clock before re-anchoring. + /// + public static readonly Ticks DefaultMaximumDrift = Ticks.FromMilliseconds(500.0D); + + // Fields + private long m_secondTicks; // Top of the second, in ticks, for the current slot + private int m_slot; // Current slot index within the second, 0 to FrameRate - 1 + private bool m_anchored; + + #endregion + + #region [ Constructors ] + + /// + /// Creates a new . + /// + /// Defined frame rate, in frames per second. + /// + /// Maximum allowed difference between generated timestamps and the wall clock before the generator + /// re-anchors to the wall clock; defaults to . + /// + public SimulatedTimestampGenerator(int frameRate, Ticks? maximumDrift = null) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(frameRate); + + Ticks drift = maximumDrift ?? DefaultMaximumDrift; + ArgumentOutOfRangeException.ThrowIfNegative(drift.Value, nameof(maximumDrift)); + + FrameRate = frameRate; + MaximumDrift = drift; + } + + #endregion + + #region [ Properties ] + + /// + /// Gets the defined frame rate, in frames per second. + /// + public int FrameRate { get; } + + /// + /// Gets the maximum allowed difference between generated timestamps and the wall clock before re-anchoring. + /// + public Ticks MaximumDrift { get; } + + /// + /// Gets the number of times the generator re-anchored to the wall clock because drift exceeded . + /// + public long Resynchronizations { get; private set; } + + #endregion + + #region [ Methods ] + + /// + /// Gets the timestamp for the next frame, using the current UTC time as the wall-clock reference. + /// + /// Timestamp, in ticks, for the next frame. + public long Next() + { + return Next(DateTime.UtcNow.Ticks); + } + + /// + /// Gets the timestamp for the next frame, using as the wall-clock reference. + /// + /// Current wall-clock time, in ticks. + /// Timestamp, in ticks, for the next frame. + public long Next(long currentTicks) + { + if (!m_anchored) + { + Anchor(currentTicks); + m_anchored = true; + return CurrentTimestamp; + } + + // Advance one frame slot, rolling over to the next second as needed + if (++m_slot >= FrameRate) + { + m_slot = 0; + m_secondTicks += Ticks.PerSecond; + } + + long timestamp = CurrentTimestamp; + + if (Math.Abs(timestamp - currentTicks) <= MaximumDrift.Value) + return timestamp; + + // Counter has drifted too far from the wall clock, e.g., after a long replay stall or a clock change + Anchor(currentTicks); + Resynchronizations++; + + return CurrentTimestamp; + } + + /// + /// Resets the generator so the next frame re-anchors to the wall clock. + /// + public void Reset() + { + m_anchored = false; + } + + // Timestamp of the current slot, on the same grid as Ticks.RoundToSubsecondDistribution + private long CurrentTimestamp => m_secondTicks + m_slot * Ticks.PerSecond / FrameRate; + + // Anchors to the slot at or before the specified time, i.e., floor alignment at tick resolution + private void Anchor(long currentTicks) + { + long ticksBeyondSecond = currentTicks % Ticks.PerSecond; + + if (ticksBeyondSecond < 0L) + ticksBeyondSecond += Ticks.PerSecond; + + m_secondTicks = currentTicks - ticksBeyondSecond; + + // Largest slot whose start, slot * PerSecond / FrameRate (floored), is at or before ticksBeyondSecond + m_slot = (int)(((ticksBeyondSecond + 1L) * FrameRate - 1L) / Ticks.PerSecond); + } + + #endregion + + #region [ Static ] + + // Static Methods + + /// + /// Floor-aligns to the sub-second distribution of . + /// + /// Timestamp to align. + /// Frame rate, in frames per second. + /// Aligned timestamp. + /// + /// Frame rates up to use millisecond alignment, unchanged from + /// prior behavior, see . Higher frame rates align at + /// full tick resolution so that every frame slot remains distinct. + /// + public static Ticks AlignToFrameRate(Ticks timestamp, int frameRate) + { + return frameRate > MaximumMillisecondFrameRate ? + Ticks.AlignToSubsecondDistribution(timestamp, frameRate, 0L) : + Ticks.AlignToMillisecondDistribution(timestamp, frameRate); + } + + #endregion +} diff --git a/src/UnitTests/SimulatedTimestampGeneratorTest.cs b/src/UnitTests/SimulatedTimestampGeneratorTest.cs new file mode 100644 index 0000000000..39c0198e89 --- /dev/null +++ b/src/UnitTests/SimulatedTimestampGeneratorTest.cs @@ -0,0 +1,308 @@ +//****************************************************************************************************** +// SimulatedTimestampGeneratorTest.cs - Gbtc +// +// Copyright © 2026, Grid Protection Alliance. All Rights Reserved. +// +// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See +// the NOTICE file distributed with this work for additional information regarding copyright ownership. +// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may +// not use this file except in compliance with the License. You may obtain a copy of the License at: +// +// http://www.opensource.org/licenses/MIT +// +// Unless agreed to in writing, the subject software distributed under the License is distributed on an +// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the +// License for the specific language governing permissions and limitations. +// +//****************************************************************************************************** +// ReSharper disable InconsistentNaming + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Gemstone.PhasorProtocols.UnitTests; + +/// +/// Unit tests for and the high frame rate +/// catch-up option of . +/// +[TestClass] +public class SimulatedTimestampGeneratorTest +{ + // Arbitrary start time that is not on a second or frame boundary + private static readonly long StartTicks = new DateTime(2026, 11, 5, 12, 0, 0, DateTimeKind.Utc).Ticks + 1_234_567L; + + // Ideal wall-clock time of the i-th frame after start + private static long IdealTime(long index, int frameRate) => StartTicks + index * Ticks.PerSecond / frameRate; + + // Asserts that timestamps hold every slot of every whole second exactly once, evenly spaced + private static void AssertEvenlyDistributed(IReadOnlyList timestamps, int frameRate) + { + long minSpacing = Ticks.PerSecond / frameRate; + long maxSpacing = (Ticks.PerSecond + frameRate - 1) / frameRate; + + Assert.AreEqual(timestamps.Count, timestamps.Distinct().Count(), "Timestamps are not unique"); + + for (int i = 0; i < timestamps.Count; i++) + { + long timestamp = timestamps[i]; + + Assert.AreEqual(timestamp, Ticks.RoundToSubsecondDistribution(timestamp, frameRate).Value, $"Timestamp {i} is not on the {frameRate} fps grid"); + + if (i == 0) + continue; + + long spacing = timestamp - timestamps[i - 1]; + Assert.IsTrue(spacing >= minSpacing && spacing <= maxSpacing, $"Spacing {spacing} at frame {i} is outside [{minSpacing}, {maxSpacing}]"); + } + + // Every whole second fully covered by the sequence holds exactly frameRate timestamps, matching the grid + HashSet grid = [.. Enumerable.Range(0, frameRate).Select(slot => slot * Ticks.PerSecond / frameRate)]; + + IEnumerable> seconds = timestamps + .GroupBy(timestamp => timestamp - timestamp % Ticks.PerSecond) + .Skip(1) // First second is partial + .SkipLast(1); // Last second is partial + + int checkedSeconds = 0; + + foreach (IGrouping second in seconds) + { + HashSet slots = [.. second.Select(timestamp => timestamp - second.Key)]; + Assert.AreEqual(frameRate, slots.Count, $"Second {second.Key} holds {slots.Count} distinct slots"); + Assert.IsTrue(slots.SetEquals(grid), $"Second {second.Key} slots do not match the {frameRate} fps grid"); + checkedSeconds++; + } + + Assert.IsTrue(checkedSeconds > 0, "No whole seconds were checked"); + } + + [TestMethod] + public void MillisecondAlignment_At3000Fps_LosesSlots() + { + // Documents the original defect: with perfect pacing, millisecond alignment cannot represent 3,000 slots per second + const int FrameRate = 3000; + + HashSet timestamps = []; + + for (int i = 0; i < FrameRate; i++) + timestamps.Add(Ticks.AlignToMillisecondDistribution(IdealTime(i, FrameRate), FrameRate).Value); + + Assert.IsTrue(timestamps.Count < FrameRate * 3 / 4, $"Expected millisecond alignment to collapse slots, got {timestamps.Count:N0} distinct"); + } + + [TestMethod] + public void Next_At3000FpsPerfectPacing_Produces3000DistinctEvenlySpacedSlotsPerSecond() + { + const int FrameRate = 3000; + const int Seconds = 5; + + SimulatedTimestampGenerator generator = new(FrameRate); + List timestamps = []; + + for (int i = 0; i < FrameRate * Seconds; i++) + timestamps.Add(generator.Next(IdealTime(i, FrameRate))); + + AssertEvenlyDistributed(timestamps, FrameRate); + Assert.AreEqual(0L, generator.Resynchronizations); + } + + [TestMethod] + public void Next_At3000FpsWithJitterStallsAndBursts_StaysEvenlySpaced() + { + const int FrameRate = 3000; + const int Seconds = 5; + + SimulatedTimestampGenerator generator = new(FrameRate); + Random random = new(12345); + List timestamps = []; + long stallTicks = Ticks.FromMilliseconds(50.0D).Value; + long stallEndTicks = 0L; + + for (int i = 0; i < FrameRate * Seconds; i++) + { + // Mid-way through every second, the replay thread stalls for 50 ms, then delivers the late frames in a burst + if (i % FrameRate == FrameRate / 2) + stallEndTicks = IdealTime(i, FrameRate) + stallTicks; + + // Up to 1 ms of scheduling jitter on every frame + long wallTicks = Math.Max(IdealTime(i, FrameRate), stallEndTicks) + random.Next(0, (int)Ticks.PerMillisecond); + + timestamps.Add(generator.Next(wallTicks)); + } + + AssertEvenlyDistributed(timestamps, FrameRate); + Assert.AreEqual(0L, generator.Resynchronizations); + } + + [DataTestMethod] + [DataRow(30)] + [DataRow(60)] + [DataRow(1000)] + [DataRow(1001)] + [DataRow(2880)] + [DataRow(3000)] + [DataRow(3840)] + [DataRow(7000)] + public void Next_AtVariousFrameRates_ProducesEveryGridSlotOnce(int frameRate) + { + SimulatedTimestampGenerator generator = new(frameRate); + List timestamps = []; + + for (int i = 0; i < frameRate * 3; i++) + timestamps.Add(generator.Next(IdealTime(i, frameRate))); + + AssertEvenlyDistributed(timestamps, frameRate); + } + + [TestMethod] + public void Next_FirstTimestamp_IsFloorOfWallClockSlot() + { + const int FrameRate = 3000; + + for (long offset = 0L; offset < Ticks.PerMillisecond * 2L; offset += 7L) + { + long wallTicks = StartTicks + offset; + long timestamp = new SimulatedTimestampGenerator(FrameRate).Next(wallTicks); + + Assert.AreEqual(Ticks.AlignToSubsecondDistribution(wallTicks, FrameRate, 0L).Value, timestamp, $"Offset {offset}"); + Assert.IsTrue(timestamp <= wallTicks && wallTicks - timestamp < Ticks.PerSecond / FrameRate + 1L, $"Offset {offset}"); + } + } + + [TestMethod] + public void Next_DriftBeyondMaximum_ReanchorsToWallClock() + { + const int FrameRate = 3000; + + SimulatedTimestampGenerator generator = new(FrameRate, Ticks.FromMilliseconds(100.0D)); + List timestamps = []; + + for (int i = 0; i < FrameRate; i++) + timestamps.Add(generator.Next(IdealTime(i, FrameRate))); + + // Replay stalls for two seconds; the counter would lag the wall clock by about two seconds + long resumeTicks = IdealTime(FrameRate, FrameRate) + 2L * Ticks.PerSecond; + long resumed = generator.Next(resumeTicks); + + Assert.AreEqual(1L, generator.Resynchronizations); + Assert.AreEqual(Ticks.AlignToSubsecondDistribution(resumeTicks, FrameRate, 0L).Value, resumed); + Assert.IsTrue(resumed > timestamps[^1]); + + // Pacing continues from the new anchor + timestamps.Clear(); + timestamps.Add(resumed); + + for (int i = 1; i < FrameRate * 3; i++) + timestamps.Add(generator.Next(resumeTicks + i * Ticks.PerSecond / FrameRate)); + + AssertEvenlyDistributed(timestamps, FrameRate); + Assert.AreEqual(1L, generator.Resynchronizations); + } + + [TestMethod] + public void Next_DriftWithinMaximum_DoesNotReanchor() + { + const int FrameRate = 3000; + + SimulatedTimestampGenerator generator = new(FrameRate, Ticks.FromMilliseconds(100.0D)); + long first = generator.Next(StartTicks); + + // A 90 ms stall stays within tolerance, so the next frame takes the next slot + long second = generator.Next(StartTicks + Ticks.FromMilliseconds(90.0D).Value); + + Assert.AreEqual(0L, generator.Resynchronizations); + Assert.AreEqual(Ticks.RoundToSubsecondDistribution(first + Ticks.PerSecond / FrameRate + 1L, FrameRate).Value, second); + } + + [TestMethod] + public void Reset_ReanchorsOnNextFrame() + { + const int FrameRate = 3000; + + SimulatedTimestampGenerator generator = new(FrameRate); + generator.Next(StartTicks); + generator.Next(StartTicks + 3333L); + + generator.Reset(); + + long wallTicks = StartTicks + Ticks.FromMilliseconds(10.0D).Value; + Assert.AreEqual(Ticks.AlignToSubsecondDistribution(wallTicks, FrameRate, 0L).Value, generator.Next(wallTicks)); + Assert.AreEqual(0L, generator.Resynchronizations); + } + + [TestMethod] + public void Constructor_InvalidArguments_Throws() + { + Assert.ThrowsException(() => new SimulatedTimestampGenerator(0)); + Assert.ThrowsException(() => new SimulatedTimestampGenerator(-1)); + Assert.ThrowsException(() => new SimulatedTimestampGenerator(30, new Ticks(-1L))); + } + + [DataTestMethod] + [DataRow(1)] + [DataRow(30)] + [DataRow(60)] + [DataRow(240)] + [DataRow(1000)] + public void AlignToFrameRate_AtOrBelow1000Fps_MatchesMillisecondAlignment(int frameRate) + { + Random random = new(frameRate); + + for (int i = 0; i < 10_000; i++) + { + long ticks = StartTicks + random.NextInt64(0L, Ticks.PerSecond * 2L); + Assert.AreEqual(Ticks.AlignToMillisecondDistribution(ticks, frameRate), SimulatedTimestampGenerator.AlignToFrameRate(ticks, frameRate)); + } + } + + [TestMethod] + public void AlignToFrameRate_At3000Fps_KeepsEverySlot() + { + const int FrameRate = 3000; + + List timestamps = []; + + for (int i = 0; i < FrameRate * 3; i++) + timestamps.Add(SimulatedTimestampGenerator.AlignToFrameRate(IdealTime(i, FrameRate), FrameRate).Value); + + AssertEvenlyDistributed(timestamps, FrameRate); + } + + [TestMethod] + public void ReplayTimer_WithCatchUpWindow_ReleasesLateFramesWithoutWaiting() + { + const int FrameRate = 1000; + const int Frames = 20; + + // Owe about 50 frames, then time how long the next 20 take to release + ReplayTimer catchUpTimer = new(FrameRate, TimeSpan.FromMilliseconds(100.0D)); + Thread.Sleep(50); + + Stopwatch stopwatch = Stopwatch.StartNew(); + + for (int i = 0; i < Frames; i++) + catchUpTimer.WaitNext(); + + double catchUpMilliseconds = stopwatch.Elapsed.TotalMilliseconds; + + // Default timer resets cadence when late, so it paces all 20 frames + ReplayTimer defaultTimer = new(FrameRate); + Thread.Sleep(50); + + stopwatch.Restart(); + + for (int i = 0; i < Frames; i++) + defaultTimer.WaitNext(); + + double defaultMilliseconds = stopwatch.Elapsed.TotalMilliseconds; + + Assert.AreEqual(TimeSpan.Zero, defaultTimer.CatchUpWindow); + Assert.IsTrue(catchUpMilliseconds < 10.0D, $"Catch-up timer took {catchUpMilliseconds:N2} ms for {Frames} owed frames"); + Assert.IsTrue(defaultMilliseconds >= Frames - 2, $"Default timer took {defaultMilliseconds:N2} ms for {Frames} frames"); + } +}