Cotton code
28 lines · 1.2 KB · SwiftRaw
// The catalogue's levelling over one stream of samples, before a model that// does not level its own input (its row's `level_input`): while the loudest// sample so far stays under `belowPeak`, every sample is raised so that peak// reads `toPeak`, by at most `maxGain`. A voice loud enough is left as it is.// The measurements behind the catalogue levelled quiet recordings the same way.import CottonKitpublic final class VoiceLeveller {    private let levelling: VoiceLevelling    private var peak: Float = 0    public init(_ levelling: VoiceLevelling) {        self.levelling = levelling    }    /// One leveller for the models a stream reaches; none when each levels itself.    public static func over(_ entries: [VoiceModelEntry?]) -> VoiceLeveller? {        entries.lazy.compactMap { $0?.level }.first.map(VoiceLeveller.init)    }    public func level(_ samples: [Float]) -> [Float] {        for sample in samples where abs(sample) > peak { peak = abs(sample) }        guard peak > 0, peak < levelling.belowPeak else { return samples }        let gain = min(levelling.toPeak / peak, levelling.maxGain)        return samples.map { max(-1, min(1, $0 * gain)) }    }}