lib/xi/clock.rb in xi-lang-0.1.3 vs lib/xi/clock.rb in xi-lang-0.1.4

- old
+ new

@@ -6,15 +6,19 @@ module Xi class Clock DEFAULT_CPS = 1.0 INTERVAL_SEC = 10 / 1000.0 + attr_reader :init_ts, :latency + def initialize(cps: DEFAULT_CPS) @mutex = Mutex.new @cps = cps @playing = true @streams = [].to_set + @init_ts = Time.now.to_f + @latency = 0.0 @play_thread = Thread.new { thread_routine } end def subscribe(stream) @mutex.synchronize { @streams << stream } @@ -27,25 +31,25 @@ def cps @mutex.synchronize { @cps } end def cps=(new_cps) - @mutex.synchronize { @cps = new_cps } + @mutex.synchronize { @cps = new_cps.to_f } end + def latency=(new_latency) + @latency = new_latency.to_f + end + def playing? @mutex.synchronize { @playing } end def stopped? !playing? end - def now - Time.now.to_f * cps - end - def play @mutex.synchronize { @playing = true } self end alias_method :start, :play @@ -58,16 +62,13 @@ def seconds_per_cycle @mutex.synchronize { 1.0 / @cps } end - def at(cycle_pos) - Time.at(cycle_pos * seconds_per_cycle) - end - def inspect - "#<#{self.class.name}:#{"0x%014x" % object_id} cps=#{cps.inspect} #{playing? ? :playing : :stopped}>" + "#<#{self.class.name}:#{"0x%014x" % object_id} " \ + "cps=#{cps.inspect} #{playing? ? :playing : :stopped}>" end private def thread_routine @@ -76,12 +77,13 @@ sleep INTERVAL_SEC end end def do_tick - cycles = Time.now.to_f * cps return unless playing? - @streams.each { |s| s.notify(cycles) } + now = Time.now.to_f - @init_ts + @latency + cps = self.cps + @streams.each { |s| s.notify(now, cps) } rescue => err error(err) end end end