Cotton code
282 lines · 10.3 KB · SwiftRaw
// Audio in: the microphone, or (in Cotton Dev) a recording played into the// same seam as if it were spoken, because a simulator has no voice.//// Every source hands over the same thing: 16 kHz mono Float32, in chunks of// about 100 ms, stamped with where they start in the session. That is what// every sherpa-onnx model reads, and the Apple engine converts it once more// to its own best format. The session keeps the samples in memory only while// it runs, so the second pass can re-read a sentence; nothing is written to// disk, and the samples go when the session ends.@preconcurrency import AVFoundationimport Foundationimport os/// One stretch of audio, 16 kHz mono.public struct VoiceChunk: Sendable {    public let samples: [Float]    /// Where the chunk starts, in milliseconds since the session's audio began.    public let startMs: Int    /// The loudness of the chunk, 0…1, for the control's breathing.    public let level: Double    public init(samples: [Float], startMs: Int) {        self.samples = samples        self.startMs = startMs        level = VoiceChunk.meter(samples)    }    public static let sampleRate: Double = 16_000    public static let format = AVAudioFormat(        commonFormat: .pcmFormatFloat32, sampleRate: sampleRate, channels: 1, interleaved: false)!    public var durationMs: Int { samples.count * 1000 / Int(Self.sampleRate) }    /// The chunk as a buffer in ``format``.    public func buffer() -> AVAudioPCMBuffer? {        guard let buffer = AVAudioPCMBuffer(pcmFormat: Self.format, frameCapacity: AVAudioFrameCount(samples.count)),              let channel = buffer.floatChannelData?[0] else { return nil }        samples.withUnsafeBufferPointer { source in            channel.update(from: source.baseAddress!, count: samples.count)        }        buffer.frameLength = AVAudioFrameCount(samples.count)        return buffer    }    /// RMS as dBFS folded to 0…1 (floor -50 dB): silence reads as silence.    static func meter(_ samples: [Float]) -> Double {        guard !samples.isEmpty else { return 0 }        var sum: Double = 0        for sample in samples { sum += Double(sample) * Double(sample) }        let rms = (sum / Double(samples.count)).squareRoot()        guard rms > 0 else { return 0 }        return min(1, max(0, (20 * log10(rms) + 50) / 50))    }}/// Where audio comes from.public enum VoiceAudioSource: Sendable, Equatable {    case microphone    /// A recording played in real time, as if spoken (Cotton Dev only: the    /// simulator's proof, the accuracy harness).    case recording(URL)}/// The sink a source writes to. Called off the main actor.public typealias VoiceChunkSink = @Sendable (VoiceChunk) -> Void/// A running source.public protocol VoiceAudioInput: AnyObject, Sendable {    func start(_ sink: @escaping VoiceChunkSink, ended: @escaping @Sendable () -> Void) throws    func stop()}/// Converts any PCM buffer to 16 kHz mono floats.final class VoiceResampler: @unchecked Sendable {    private var converter: AVAudioConverter?    private var from: AVAudioFormat?    func samples(_ buffer: AVAudioPCMBuffer) -> [Float] {        let target = VoiceChunk.format        if buffer.format == target, let channel = buffer.floatChannelData?[0] {            return Array(UnsafeBufferPointer(start: channel, count: Int(buffer.frameLength)))        }        if converter == nil || from != buffer.format {            converter = AVAudioConverter(from: buffer.format, to: target)            converter?.primeMethod = .none            from = buffer.format        }        guard let converter else { return [] }        let ratio = target.sampleRate / buffer.format.sampleRate        let capacity = AVAudioFrameCount((Double(buffer.frameLength) * ratio).rounded(.up)) + 32        guard let out = AVAudioPCMBuffer(pcmFormat: target, frameCapacity: capacity) else { return [] }        var given = false        var error: NSError?        let status = converter.convert(to: out, error: &error) { _, state in            if given {                state.pointee = .noDataNow                return nil            }            given = true            state.pointee = .haveData            return buffer        }        guard status != .error, let channel = out.floatChannelData?[0] else { return [] }        return Array(UnsafeBufferPointer(start: channel, count: Int(out.frameLength)))    }}/// Gathers samples into ~100 ms chunks with their start times.final class VoiceChunker: @unchecked Sendable {    private let lock = NSLock()    private var pending: [Float] = []    private var emitted = 0    private let size = Int(VoiceChunk.sampleRate / 10)    func take(_ samples: [Float], _ sink: VoiceChunkSink) {        lock.lock()        pending.append(contentsOf: samples)        var out: [VoiceChunk] = []        while pending.count >= size {            let chunk = Array(pending.prefix(size))            pending.removeFirst(size)            out.append(VoiceChunk(samples: chunk, startMs: emitted * 1000 / Int(VoiceChunk.sampleRate)))            emitted += size        }        lock.unlock()        out.forEach(sink)    }    func flush(_ sink: VoiceChunkSink) {        lock.lock()        let rest = pending        pending = []        let start = emitted * 1000 / Int(VoiceChunk.sampleRate)        emitted += rest.count        lock.unlock()        if !rest.isEmpty { sink(VoiceChunk(samples: rest, startMs: start)) }    }}/// The microphone, through AVAudioEngine's input tap.public final class MicrophoneInput: VoiceAudioInput, @unchecked Sendable {    private let engine = AVAudioEngine()    private let resampler = VoiceResampler()    private let chunker = VoiceChunker()    private var tapped = false    public init() {}    public func start(_ sink: @escaping VoiceChunkSink, ended: @escaping @Sendable () -> Void) throws {        let input = engine.inputNode        let format = input.outputFormat(forBus: 0)        guard format.sampleRate > 0, format.channelCount > 0 else { throw VoiceFailure.noMicrophone }        let resampler = self.resampler        let chunker = self.chunker        input.installTap(onBus: 0, bufferSize: 1600, format: format) { @Sendable buffer, _ in            chunker.take(resampler.samples(buffer), sink)        }        tapped = true        engine.prepare()        try engine.start()    }    public func stop() {        if tapped { engine.inputNode.removeTap(onBus: 0) }        tapped = false        engine.stop()    }}/// A recording played into the session in real time: the simulator's voice.public final class RecordingInput: VoiceAudioInput, @unchecked Sendable {    private let url: URL    private var task: Task<Void, Never>?    public init(url: URL) { self.url = url }    public func start(_ sink: @escaping VoiceChunkSink, ended: @escaping @Sendable () -> Void) throws {        let file = try AVAudioFile(forReading: url)        let url = self.url        task = Task.detached(priority: .userInitiated) {            let resampler = VoiceResampler()            let chunker = VoiceChunker()            let frames: AVAudioFrameCount = AVAudioFrameCount(file.processingFormat.sampleRate / 10)            let clock = ContinuousClock()            let began = clock.now            var played: Double = 0            while !Task.isCancelled {                guard let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: frames),                      (try? file.read(into: buffer, frameCount: frames)) != nil,                      buffer.frameLength > 0                else { break }                chunker.take(resampler.samples(buffer), sink)                played += Double(buffer.frameLength) / file.processingFormat.sampleRate                // Real time: the chunk is due when it would have been spoken.                let due = began.advanced(by: .milliseconds(Int(played * 1000)))                try? await clock.sleep(until: due)            }            chunker.flush(sink)            _ = url            if !Task.isCancelled { ended() }        }    }    public func stop() {        task?.cancel()        task = nil    }}/// Every sample of the session, in memory, so a sentence's audio can be read/// again by the second pass. Dropped whole when the session ends.public final class VoiceTape: @unchecked Sendable {    private let lock = NSLock()    private var samples: [Float] = []    /// The cap: ten minutes. Past it the oldest audio goes (a second pass only    /// ever reads the sentence just ended).    private let cap = Int(VoiceChunk.sampleRate) * 600    private var dropped = 0    public init() {}    public func append(_ chunk: VoiceChunk) {        lock.lock()        defer { lock.unlock() }        samples.append(contentsOf: chunk.samples)        if samples.count > cap {            let over = samples.count - cap            samples.removeFirst(over)            dropped += over        }    }    /// The samples between two session times, clamped to what is held.    public func read(fromMs: Int, toMs: Int) -> [Float] {        lock.lock()        defer { lock.unlock() }        let rate = Int(VoiceChunk.sampleRate)        let lo = max(0, fromMs * rate / 1000 - dropped)        let hi = min(samples.count, toMs * rate / 1000 - dropped)        guard hi > lo else { return [] }        return Array(samples[lo ..< hi])    }    public var durationMs: Int {        lock.lock()        defer { lock.unlock() }        return (samples.count + dropped) * 1000 / Int(VoiceChunk.sampleRate)    }    public func clear() {        lock.lock()        samples = []        samples.reserveCapacity(0)        dropped = 0        lock.unlock()    }}/// Why a session could not run, as the control names it (the words are the/// core's lines, keyed by ``lineKey``).public enum VoiceFailure: Error, Sendable, Equatable {    case denied    case noMicrophone    case onCall    case engineUnavailable(String)    case modelMissing(String)    case notInThisBuild(String)    case core(String)    public var lineKey: String {        switch self {        case .denied: "no_permission"        case .noMicrophone: "no_microphone"        case .onCall: "on_call"        case .engineUnavailable: "unavailable"        case .modelMissing: "model_missing"        case .notInThisBuild: "unavailable"        case .core: "unavailable"        }    }}