Skip to content

Commit

Permalink
Beats: add helper to get fractional beats in frame range
Browse files Browse the repository at this point in the history
  • Loading branch information
ronso0 committed Jan 5, 2024
1 parent 0437d5e commit 1a7af25
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/track/beats.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,29 @@ int Beats::numBeatsInRange(audio::FramePos startPosition, audio::FramePos endPos
return i - 2;
};

double Beats::numFractionalBeatsInRange(audio::FramePos startPos, audio::FramePos endPos) const {
double pBeatPercentage;
// get the ratio of first beat / position:
// 1 - ((startPos - beat before range) / first beat length)
if (!getContext(startPos, nullptr, nullptr, nullptr, &pBeatPercentage)) {
return -1;
}
double numBeats = 1 - pBeatPercentage;

// get the last beat ratio:
// (endPos - last beat in range) / last beat length
if (!getContext(endPos, nullptr, nullptr, nullptr, &pBeatPercentage)) {
return -1;
}
numBeats += pBeatPercentage;

// get the beats inside the range
// subtract 1 because we already counted the first beat
numBeats += numBeatsInRange(findNextBeat(startPos), endPos) - 1;

return numBeats;
}

audio::FramePos Beats::findNextBeat(audio::FramePos position) const {
return findNthBeat(position, 1);
}
Expand Down
2 changes: 2 additions & 0 deletions src/track/beats.h
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,8 @@ class Beats : private std::enable_shared_from_this<Beats> {
audio::FramePos snapPosToNearBeat(audio::FramePos position) const;

int numBeatsInRange(audio::FramePos startPosition, audio::FramePos endPosition) const;
double numFractionalBeatsInRange(audio::FramePos startPosition,
audio::FramePos endPosition) const;

/// Find the frame position N beats away from `position`. The number of beats may be
/// negative and does not need to be an integer. In this case the returned position will
Expand Down

0 comments on commit 1a7af25

Please sign in to comment.