FixedIntervalClock.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * NatCorder
  3. * Copyright (c) 2020 Yusuf Olokoba.
  4. */
  5. namespace NatSuite.Recorders.Clocks {
  6. using System.Runtime.CompilerServices;
  7. /// <summary>
  8. /// Clock that produces timestamps spaced at a fixed interval.
  9. /// This clock is useful for enforcing a fixed framerate in a recording.
  10. /// </summary>
  11. public sealed class FixedIntervalClock : IClock {
  12. /// <summary>
  13. /// Interval between consecutive timestamps generated by the clock in seconds.
  14. /// </summary>
  15. public double interval { get; set; }
  16. /// <summary>
  17. /// Current timestamp in nanoseconds.
  18. /// The very first value reported by this property will always be zero.
  19. /// </summary>
  20. public long timestamp {
  21. [MethodImpl(MethodImplOptions.Synchronized)]
  22. get => (long)((autoTick ? ticks++ : ticks) * interval * 1e+9);
  23. }
  24. /// <summary>
  25. /// Create a fixed interval clock for a given framerate.
  26. /// </summary>
  27. /// <param name="framerate">Desired framerate for clock's timestamps.</param>
  28. /// <param name="autoTick">Optional. If true, the clock will tick when its `Timestamp` is accessed.</param>
  29. public FixedIntervalClock (int framerate, bool autoTick = true) : this(1.0 / framerate, autoTick) { }
  30. /// <summary>
  31. /// Create a fixed interval clock with a given timestamp interval.
  32. /// </summary>
  33. /// <param name="interval">Interval between consecutive timestamps in seconds.</param>
  34. /// <param name="autoTick">Optional. If true, the clock will tick when its `Timestamp` is accessed.</param>
  35. public FixedIntervalClock (double interval, bool autoTick = true) {
  36. this.interval = interval;
  37. this.ticks = 0;
  38. this.autoTick = autoTick;
  39. }
  40. /// <summary>
  41. /// Advance the clock by its time interval.
  42. /// </summary>
  43. [MethodImpl(MethodImplOptions.Synchronized)]
  44. public void Tick () => ticks++;
  45. private readonly bool autoTick;
  46. private int ticks;
  47. }
  48. }