Mulberry/App/Audio/Decoder.swift
astar76 8e6f8a86a4 Mulberry for iOS: initial SwiftUI port of the Android app
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 19:30:49 -05:00

117 lines
4.3 KiB
Swift

import AVFoundation
/// A PCM source in the engine's format (stereo, non-interleaved Float32 at `Decoder.rate`).
protocol AudioSource: AnyObject {
/// Total frames in engine-rate frames (0 when unknown, e.g. streams).
var frames: AVAudioFramePosition { get }
/// Reads up to `buffer.frameCapacity` frames; returns false at end of stream.
func read(into buffer: AVAudioPCMBuffer) -> Bool
func seek(to frame: AVAudioFramePosition)
}
enum Decoder {
static let rate: Double = 48000
static let format = AVAudioFormat(standardFormatWithSampleRate: rate, channels: 2)!
/// Opens a song (respecting cue start/end) with the best available decoder.
static func open(_ song: Song) -> AudioSource? {
let url = song.url
var src: AudioSource?
if let f = try? AVAudioFile(forReading: url) {
src = NativeSource(file: f)
} else if let ff = FFSource.open(url) {
src = ff
}
guard let s = src else { return nil }
if song.cueIndex > 0 {
return Segment(s, start: AVAudioFramePosition(song.start * rate),
end: song.end > song.start ? AVAudioFramePosition(song.end * rate) : s.frames)
}
return s
}
static func probeDuration(_ url: URL) -> Double {
guard let s = FFSource.open(url), s.frames > 0 else { return 0 }
return Double(s.frames) / rate
}
}
/// AVAudioFile (MP3, AAC, ALAC, FLAC, WAV, AIFF, CAF/Opus) resampled to the engine format.
final class NativeSource: AudioSource {
private let file: AVAudioFile
private let conv: AVAudioConverter?
private let inBuf: AVAudioPCMBuffer
private let ratio: Double
private var eof = false
init?(file: AVAudioFile) {
self.file = file
let inFmt = file.processingFormat
ratio = Decoder.rate / inFmt.sampleRate
conv = inFmt == Decoder.format ? nil : AVAudioConverter(from: inFmt, to: Decoder.format)
if conv == nil && inFmt != Decoder.format { return nil }
guard let b = AVAudioPCMBuffer(pcmFormat: inFmt, frameCapacity: 8192) else { return nil }
inBuf = b
if inFmt.channelCount == 1 { conv?.channelMap = [0, 0] }
}
var frames: AVAudioFramePosition { AVAudioFramePosition(Double(file.length) * ratio) }
func seek(to frame: AVAudioFramePosition) {
file.framePosition = max(0, min(file.length, AVAudioFramePosition(Double(frame) / ratio)))
conv?.reset()
eof = false
}
func read(into buffer: AVAudioPCMBuffer) -> Bool {
buffer.frameLength = 0
guard let conv else {
do { try file.read(into: buffer) } catch { return false }
return buffer.frameLength > 0
}
var error: NSError?
let status = conv.convert(to: buffer, error: &error) { [self] _, outStatus in
if eof { outStatus.pointee = .endOfStream; return nil }
do {
try file.read(into: inBuf, frameCount: inBuf.frameCapacity)
} catch {
eof = true; outStatus.pointee = .endOfStream; return nil
}
if inBuf.frameLength == 0 { eof = true; outStatus.pointee = .endOfStream; return nil }
outStatus.pointee = .haveData
return inBuf
}
return status != .error && buffer.frameLength > 0
}
}
/// A slice of another source (cue-sheet tracks).
final class Segment: AudioSource {
private let base: AudioSource
private let start: AVAudioFramePosition
private let end: AVAudioFramePosition
private var pos: AVAudioFramePosition
init(_ base: AudioSource, start: AVAudioFramePosition, end: AVAudioFramePosition) {
self.base = base
self.start = start
self.end = max(start, end)
pos = start
base.seek(to: start)
}
var frames: AVAudioFramePosition { end - start }
func seek(to frame: AVAudioFramePosition) {
pos = start + max(0, min(frames, frame))
base.seek(to: pos)
}
func read(into buffer: AVAudioPCMBuffer) -> Bool {
guard pos < end, base.read(into: buffer) else { return false }
let left = end - pos
if AVAudioFramePosition(buffer.frameLength) > left { buffer.frameLength = AVAudioFrameCount(left) }
pos += AVAudioFramePosition(buffer.frameLength)
return buffer.frameLength > 0
}
}