Class: HeadMusic::Time::SmpteConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/head_music/time/smpte_converter.rb

Overview

Converts between clock time (elapsed nanoseconds) and SMPTE timecode (hours:minutes:seconds:frames) at a fixed framerate. This is independent of tempo and meter: only the framerate and the timecode at clock time 0 determine the mapping.

Constant Summary collapse

NANOSECONDS_PER_SECOND =

Nanoseconds in one second.

1_000_000_000.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(framerate:, starting_smpte_timecode:) ⇒ SmpteConverter

Returns a new instance of SmpteConverter.



15
16
17
18
# File 'lib/head_music/time/smpte_converter.rb', line 15

def initialize(framerate:, starting_smpte_timecode:)
  @framerate = framerate
  @starting_smpte_timecode = starting_smpte_timecode
end

Instance Attribute Details

#framerateObject (readonly)

Returns the value of attribute framerate.



13
14
15
# File 'lib/head_music/time/smpte_converter.rb', line 13

def framerate
  @framerate
end

#starting_smpte_timecodeObject (readonly)

Returns the value of attribute starting_smpte_timecode.



13
14
15
# File 'lib/head_music/time/smpte_converter.rb', line 13

def starting_smpte_timecode
  @starting_smpte_timecode
end

Instance Method Details

#clock_to_smpte(clock_position) ⇒ SmpteTimecode

Returns the corresponding SMPTE timecode.

Parameters:

Returns:



22
23
24
25
26
# File 'lib/head_music/time/smpte_converter.rb', line 22

def clock_to_smpte(clock_position)
  elapsed_seconds = clock_position.nanoseconds / NANOSECONDS_PER_SECOND
  total_frames = (elapsed_seconds * framerate).round + starting_smpte_timecode.to_total_frames
  frames_to_timecode(total_frames)
end

#frames_to_timecode(total_frames) ⇒ Object (private)

Decompose total frames into a normalized HH:MM:SS:FF timecode.



39
40
41
42
43
44
45
46
47
48
# File 'lib/head_music/time/smpte_converter.rb', line 39

def frames_to_timecode(total_frames)
  frames_per_minute = framerate * 60
  frames_per_hour = frames_per_minute * 60

  hours, remaining = total_frames.divmod(frames_per_hour)
  minutes, remaining = remaining.divmod(frames_per_minute)
  seconds, frames = remaining.divmod(framerate)

  SmpteTimecode.new(hours, minutes, seconds, frames, framerate: framerate).normalize!
end

#smpte_to_clock(smpte_timecode) ⇒ ClockPosition

Returns the corresponding clock time.

Parameters:

  • smpte_timecode (SmpteTimecode)

    the SMPTE timecode to convert

Returns:



30
31
32
33
34
# File 'lib/head_music/time/smpte_converter.rb', line 30

def smpte_to_clock(smpte_timecode)
  elapsed_frames = smpte_timecode.to_total_frames - starting_smpte_timecode.to_total_frames
  elapsed_seconds = elapsed_frames / framerate.to_f
  ClockPosition.new((elapsed_seconds * NANOSECONDS_PER_SECOND).round)
end