SPB Git

Repository Public

TrackBuffer.swift 4.8 KB 92 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXDJEngine/TrackBuffer.swift3// Description: A fully decoded track held in memory as planar 32-bit float, so the render thread never touches the disk.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AVFoundation8import Foundation910public enum TrackLoadError: Error, Equatable, LocalizedError {11    case unreadable(String)12    case empty13    case tooLong(seconds: Double)14    case cancelled1516    public var errorDescription: String? {17        switch self {18        case let .unreadable(reason): "The audio file could not be read: \(reason)"19        case .empty: "The audio file contains no audio."20        case let .tooLong(seconds): "The track is \(Int(seconds / 60)) minutes long; ORIX DJ decodes tracks into memory and accepts up to \(Int(TrackBuffer.maxSeconds / 60)) minutes."21        case .cancelled: "Loading was cancelled."22        }23    }24}2526/// Immutable decoded audio. Created off the audio thread; the render thread only reads it.27public final class TrackBuffer: @unchecked Sendable {28    public static let maxSeconds = 150.0 * 602930    public let left: UnsafeMutablePointer<Float>31    public let right: UnsafeMutablePointer<Float>32    public let frameCount: Int33    public let sampleRate: Double34    public let sourceChannels: Int3536    public var duration: Double { Double(frameCount) / sampleRate }37    public var byteSize: Int { frameCount * 2 * MemoryLayout<Float>.size }3839    /// Takes ownership of two planar arrays of equal length.40    public init(left l: [Float], right r: [Float], sampleRate: Double, sourceChannels: Int = 2) {41        precondition(l.count == r.count)42        frameCount = l.count; self.sampleRate = sampleRate; self.sourceChannels = sourceChannels43        left = .allocate(capacity: max(1, l.count)); right = .allocate(capacity: max(1, r.count))44        l.withUnsafeBufferPointer { if let b = $0.baseAddress { left.update(from: b, count: l.count) } }45        r.withUnsafeBufferPointer { if let b = $0.baseAddress { right.update(from: b, count: r.count) } }46    }4748    private init(frames: Int, sampleRate: Double, sourceChannels: Int) {49        frameCount = frames; self.sampleRate = sampleRate; self.sourceChannels = sourceChannels50        left = .allocate(capacity: max(1, frames)); right = .allocate(capacity: max(1, frames))51        left.initialize(repeating: 0, count: max(1, frames)); right.initialize(repeating: 0, count: max(1, frames))52    }5354    deinit { left.deallocate(); right.deallocate() }5556    public var leftBuffer: UnsafeBufferPointer<Float> { UnsafeBufferPointer(start: left, count: frameCount) }57    public var rightBuffer: UnsafeBufferPointer<Float> { UnsafeBufferPointer(start: right, count: frameCount) }5859    /// Decodes a file completely. Blocking; call from a background queue.60    public static func load(url: URL, progress: ((Double) -> Void)? = nil, isCancelled: (() -> Bool)? = nil) throws -> TrackBuffer {61        let file: AVAudioFile62        do { file = try AVAudioFile(forReading: url) } catch { throw TrackLoadError.unreadable(error.localizedDescription) }63        let format = file.processingFormat64        let total = Int(file.length)65        guard total > 0, format.channelCount > 0 else { throw TrackLoadError.empty }66        let seconds = Double(total) / format.sampleRate67        guard seconds <= maxSeconds else { throw TrackLoadError.tooLong(seconds: seconds) }68        guard format.commonFormat == .pcmFormatFloat32, !format.isInterleaved else { throw TrackLoadError.unreadable("unexpected processing format") }69        let out = TrackBuffer(frames: total, sampleRate: format.sampleRate, sourceChannels: Int(format.channelCount))70        let chunk: AVAudioFrameCount = 131_07271        guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: chunk) else { throw TrackLoadError.unreadable("no buffer") }72        var written = 073        while written < total {74            if isCancelled?() == true { throw TrackLoadError.cancelled }75            do { try file.read(into: buffer, frameCount: min(chunk, AVAudioFrameCount(total - written))) } catch {76                // Some compressed files report a length slightly above what decodes; keep what was read.77                if written > 0 { break }78                throw TrackLoadError.unreadable(error.localizedDescription)79            }80            let n = Int(buffer.frameLength)81            if n == 0 { break }82            guard let data = buffer.floatChannelData else { throw TrackLoadError.unreadable("no channel data") }83            (out.left + written).update(from: data[0], count: n)84            (out.right + written).update(from: format.channelCount > 1 ? data[1] : data[0], count: n)85            written += n86            progress?(Double(written) / Double(total))87        }88        guard written > 0 else { throw TrackLoadError.empty }89        return out90    }91}92
Files main
Menu

Theme