Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 38 additions & 4 deletions src/Gemstone.PhasorProtocols/MultiProtocolFrameParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1307,6 +1307,16 @@ private void SharedClient_SendDataException(object? sender, EventArgs<Exception>
/// </summary>
public const int DefaultDefinedFrameRate = 30;

/// <summary>
/// Specifies how far file replay pacing can fall behind and still catch up when the
/// <see cref="DefinedFrameRate"/> exceeds 1,000 frames per second.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public static readonly TimeSpan HighFrameRateReplayCatchUpWindow = TimeSpan.FromMilliseconds(100.0D);

/// <summary>
/// Specifies the default value for the <see cref="MaximumConnectionAttempts"/> property.
/// </summary>
Expand Down Expand Up @@ -1507,6 +1517,7 @@ private void SharedClient_SendDataException(object? sender, EventArgs<Exception>
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;
Expand Down Expand Up @@ -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}");
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -3635,24 +3652,41 @@ private void m_commandChannel_ReceiveDataException(object? sender, EventArgs<Exc
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private long MaintainCapturedFrameReplayTiming()
{
// Above 1,000 frames per second, millisecond aligned wall-clock timestamps cannot represent every frame
// slot, so simulated timestamps come from a frame counter on the full-resolution sub-second distribution
bool highFrameRate = m_definedFrameRate > 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<IChannelFrame, bool> e)
{
// We don't stop parsing for exceptions thrown in consumer event handlers
Expand All @@ -3661,7 +3695,7 @@ private void m_frameParser_ReceivedChannelFrame(object? sender, EventArgs<IChann
IChannelFrame frame = e.Argument1;

if (InjectSimulatedTimestamp && (frame is not IDataFrame || m_transportProtocol != TransportProtocol.File))
frame.Timestamp = Ticks.AlignToMillisecondDistribution(DateTime.UtcNow.Ticks, m_definedFrameRate);
frame.Timestamp = SimulatedTimestampGenerator.AlignToFrameRate(DateTime.UtcNow.Ticks, m_definedFrameRate);

if (ReceivedChannelFrame is not null && e.Argument2)
ReceivedChannelFrame.SafeInvoke(this, e);
Expand Down
29 changes: 22 additions & 7 deletions src/Gemstone.PhasorProtocols/ReplayTimer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,47 +50,62 @@ public sealed class ReplayTimer

private readonly long m_periodTicks; // Query Performance Counter (QPC) ticks per frame
private readonly long m_guardBandTicks; // QPC ticks for the guard-band
private readonly long m_catchUpTicks; // QPC ticks the deadline can lag before cadence is reset
private long m_nextTick; // Next scheduled QPC tick (not equal to DateTime ticks)

/// <summary>
/// Creates a new <see cref="ReplayTimer"/> instance.
/// </summary>
/// <param name="definedFrameRate">The defined frame rate in frames per second.</param>
public ReplayTimer(int definedFrameRate)
/// <param name="catchUpWindow">
/// Maximum time the timer can fall behind its absolute cadence and still catch up by releasing
/// late frames without waiting. Defaults to <see cref="TimeSpan.Zero"/>, i.e., any lateness resets
/// the cadence and no catch-up frames are released.
/// </param>
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;
}

/// <summary>
/// Gets the defined frame rate for this timer.
/// </summary>
public int DefinedFrameRate { get; }

/// <summary>
/// Gets the maximum time the timer can fall behind its cadence and still catch up.
/// </summary>
public TimeSpan CatchUpWindow { get; }

/// <summary>
/// Blocks until the next scheduled frame rate interval.
/// </summary>
/// <remarks>
/// 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 <see cref="CatchUpWindow"/>, 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.
/// </remarks>
public void WaitNext()
{
// Advance deadline absolutely from previous deadline to maintain
// 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;
Expand Down
210 changes: 210 additions & 0 deletions src/Gemstone.PhasorProtocols/SimulatedTimestampGenerator.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// <para>
/// Millisecond aligned wall-clock timestamps, i.e., <see cref="Ticks.AlignToMillisecondDistribution"/>,
/// 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.
/// </para>
/// <para>
/// This generator anchors to the wall clock on the first frame, then issues each following frame the
/// next slot of the <see cref="FrameRate"/> distribution at full tick resolution. Every timestamp lands
/// exactly on the grid used by <see cref="Ticks.RoundToSubsecondDistribution"/> and
/// <see cref="Ticks.AlignToSubsecondDistribution"/>, 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
/// <see cref="MaximumDrift"/>, for example after a long stall in replay, the generator re-anchors to the
/// wall clock so timestamps stay near real time.
/// </para>
/// </remarks>
public sealed class SimulatedTimestampGenerator
{
#region [ Members ]

// Constants

/// <summary>
/// Defines the highest frame rate for which millisecond aligned timestamps can represent every frame slot.
/// </summary>
public const int MaximumMillisecondFrameRate = 1000;

/// <summary>
/// Defines the default maximum drift between the frame counter and the wall clock before re-anchoring.
/// </summary>
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 ]

/// <summary>
/// Creates a new <see cref="SimulatedTimestampGenerator"/>.
/// </summary>
/// <param name="frameRate">Defined frame rate, in frames per second.</param>
/// <param name="maximumDrift">
/// Maximum allowed difference between generated timestamps and the wall clock before the generator
/// re-anchors to the wall clock; defaults to <see cref="DefaultMaximumDrift"/>.
/// </param>
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 ]

/// <summary>
/// Gets the defined frame rate, in frames per second.
/// </summary>
public int FrameRate { get; }

/// <summary>
/// Gets the maximum allowed difference between generated timestamps and the wall clock before re-anchoring.
/// </summary>
public Ticks MaximumDrift { get; }

/// <summary>
/// Gets the number of times the generator re-anchored to the wall clock because drift exceeded <see cref="MaximumDrift"/>.
/// </summary>
public long Resynchronizations { get; private set; }

#endregion

#region [ Methods ]

/// <summary>
/// Gets the timestamp for the next frame, using the current UTC time as the wall-clock reference.
/// </summary>
/// <returns>Timestamp, in ticks, for the next frame.</returns>
public long Next()
{
return Next(DateTime.UtcNow.Ticks);
}

/// <summary>
/// Gets the timestamp for the next frame, using <paramref name="currentTicks"/> as the wall-clock reference.
/// </summary>
/// <param name="currentTicks">Current wall-clock time, in ticks.</param>
/// <returns>Timestamp, in ticks, for the next frame.</returns>
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;
}

/// <summary>
/// Resets the generator so the next frame re-anchors to the wall clock.
/// </summary>
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

/// <summary>
/// Floor-aligns <paramref name="timestamp"/> to the sub-second distribution of <paramref name="frameRate"/>.
/// </summary>
/// <param name="timestamp">Timestamp to align.</param>
/// <param name="frameRate">Frame rate, in frames per second.</param>
/// <returns>Aligned timestamp.</returns>
/// <remarks>
/// Frame rates up to <see cref="MaximumMillisecondFrameRate"/> use millisecond alignment, unchanged from
/// prior behavior, see <see cref="Ticks.AlignToMillisecondDistribution"/>. Higher frame rates align at
/// full tick resolution so that every frame slot remains distinct.
/// </remarks>
public static Ticks AlignToFrameRate(Ticks timestamp, int frameRate)
{
return frameRate > MaximumMillisecondFrameRate ?
Ticks.AlignToSubsecondDistribution(timestamp, frameRate, 0L) :
Ticks.AlignToMillisecondDistribution(timestamp, frameRate);
}

#endregion
}
Loading
Loading