Files
Lyrebird/Sources/Lyrebird/Generators/Analysis/BeatTrackHelpers.swift
T
2026-06-21 11:45:58 -07:00

60 lines
1.9 KiB
Swift

// BeatTrackHelpers.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import Foundation
/// Peak ODF value across one audio block. Onsets are impulsive, so the max
/// preserves the peak regardless of where in the block it lands. Returns `0` for
/// an empty row.
@inline(__always)
internal func blockMaxODF(_ row: [Double], count: Int) -> Double {
guard !row.isEmpty else { return 0.0 }
let n: Int = min(count, row.count)
var peak: Double = 0.0
for i: Int in 0..<n {
let v: Double = row[i]
if v > peak { peak = v }
}
return peak
}
/// Fill the 4-row beat-tracker output buffer flat across the block from the
/// core's per-block trigger / tempo state. Returns the row-0 (beat) value for
/// `previousOutputValue`. No heap allocation — the four row values are filled
/// directly (no intermediate array).
@inline(__always)
internal func fillBeatTrackerOutput(
into result: inout [[Double]],
core: BeatTrackerCore,
count: Int
) -> Double {
let beat: Double = core.beatTriggered ? 1.0 : 0.0
let eighth: Double = core.eighthTriggered ? 1.0 : 0.0
let sixteenth: Double = core.sixteenthTriggered ? 1.0 : 0.0
let tempo: Double = core.tempoBPM
fillFlatRow(&result, row: 0, value: beat, count: count)
fillFlatRow(&result, row: 1, value: eighth, count: count)
fillFlatRow(&result, row: 2, value: sixteenth, count: count)
fillFlatRow(&result, row: 3, value: tempo, count: count)
return beat
}
/// Fill one output row with a constant value over `count` samples.
@inline(__always)
private func fillFlatRow(
_ result: inout [[Double]],
row: Int,
value: Double,
count: Int
) {
var v: Double = value
result[row].withUnsafeMutableBufferPointer { buf in
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
vDSP_vfillD(&v, base, 1, vDSP_Length(count))
}
}