65 lines
2.1 KiB
Python
65 lines
2.1 KiB
Python
"""Tempo-Map conversion between seconds and musical beats.
|
|
|
|
As defined in the concept:
|
|
- Vocals are in seconds
|
|
- Chords and strumming are in beats
|
|
- Conversion ONLY through sec_to_beat() and beat_to_sec().
|
|
"""
|
|
|
|
from bisect import bisect_right
|
|
|
|
from songsplit.schema.tempo import TempoAnchor, TempoDocument
|
|
|
|
|
|
def _get_sorted_anchors(tempo_map: TempoDocument) -> list[TempoAnchor]:
|
|
"""Return anchors sorted by time/beat, raising ValueError if empty."""
|
|
if not tempo_map.anchors:
|
|
raise ValueError("Tempo map has no anchors defined.")
|
|
return sorted(tempo_map.anchors, key=lambda a: a.sec)
|
|
|
|
|
|
def sec_to_beat(sec: float, tempo_map: TempoDocument) -> float:
|
|
"""Convert time in seconds to musical beat (float quarter notes).
|
|
|
|
Constant tempo is assumed between consecutive anchors.
|
|
The last anchor applies until the end of the song.
|
|
Extrapolation is used before the first anchor.
|
|
"""
|
|
anchors = _get_sorted_anchors(tempo_map)
|
|
sec_points = [a.sec for a in anchors]
|
|
|
|
idx = bisect_right(sec_points, sec) - 1
|
|
|
|
if idx < 0:
|
|
# Before the first anchor -> extrapolate using the first anchor's tempo
|
|
anchor = anchors[0]
|
|
delta_sec = sec - anchor.sec
|
|
return anchor.beat + delta_sec * (anchor.bpm / 60.0)
|
|
|
|
anchor = anchors[idx]
|
|
delta_sec = sec - anchor.sec
|
|
return anchor.beat + delta_sec * (anchor.bpm / 60.0)
|
|
|
|
|
|
def beat_to_sec(beat: float, tempo_map: TempoDocument) -> float:
|
|
"""Convert musical beat (float quarter notes) to time in seconds.
|
|
|
|
Constant tempo is assumed between consecutive anchors.
|
|
The last anchor applies until the end of the song.
|
|
Extrapolation is used before the first anchor.
|
|
"""
|
|
anchors = _get_sorted_anchors(tempo_map)
|
|
beat_points = [a.beat for a in anchors]
|
|
|
|
idx = bisect_right(beat_points, beat) - 1
|
|
|
|
if idx < 0:
|
|
# Before the first anchor -> extrapolate using the first anchor's tempo
|
|
anchor = anchors[0]
|
|
delta_beat = beat - anchor.beat
|
|
return anchor.sec + delta_beat * (60.0 / anchor.bpm)
|
|
|
|
anchor = anchors[idx]
|
|
delta_beat = beat - anchor.beat
|
|
return anchor.sec + delta_beat * (60.0 / anchor.bpm)
|