Cotton code
200 lines · 8.3 KB · SwiftRaw
// Which microphone the meetings recorder opens.//// The shipping one is the shell's (`SystemMeetingRecorder`). A DEV build// launched by a walk with `WALK_MEETINGS_AUDIO=<path>` opens a file-fed one// instead: the voice plan's proofs run on a simulator with synthetic audio// only (the Mac's `say`, open test sets), and a simulator's microphone is// the Mac's own input, which no walk can speak into. The file-fed capture// writes the SAME container the real one does (linear PCM, 16-bit mono// 24 kHz, in a Core Audio File whose data chunk says -1 until it closes) in// real time, looping the source, so a three-minute walk records three// minutes and a kill mid-recording leaves exactly what a killed phone// leaves. It writes a WAV where the path says `.wav` (the core's file,// its sizes left at their largest until it closes, as the core expects of a// header it rewrites) and a Core Audio File otherwise. Never compiled into a// real build.#if os(iOS)import AVFoundationimport CottonKitimport Foundationenum MeetingsCaptureChoice {    /// The core's file is 16 kHz mono 16-bit PCM (`meetings.record.start`).    static let rate = 16_000.0    @MainActor static func make() -> any MeetingCapture {        #if COTTON_DEV        if let path = ProcessInfo.processInfo.environment["WALK_MEETINGS_AUDIO"], !path.isEmpty {            return FileFedMeetingCapture(source: URL(fileURLWithPath: path), sampleRate: rate)        }        // Comms Dev's seed with its invented voice (`-chat-warm-voice YES`): a recording hears the invented sentence,        // as the simulator has no microphone.        if ChatWarmSeed.asked, ChatWarmSeed.voice,           let invented = Bundle.module.url(forResource: "chat-warm-voice", withExtension: "m4a", subdirectory: "Fixtures") {            return FileFedMeetingCapture(source: invented, sampleRate: rate)        }        #endif        return SystemMeetingRecorder(sampleRate: rate)    }}#if COTTON_DEV/// A capture fed from an audio file at the speed of speech.@MainActorfinal class FileFedMeetingCapture: MeetingCapture {    var onInterruption: ((MeetingCaptureInterruption) -> Void)?    let sampleRate: Double    private let source: URL    private var wave = false    private var samples: [Int16] = []    private var cursor = 0    private var handle: FileHandle?    private var dataStart: UInt64 = 0    private var written: UInt64 = 0    private var pump: Task<Void, Never>?    private var lastLevel = 0.0    init(source: URL, sampleRate: Double = 24_000) {        self.source = source        self.sampleRate = sampleRate    }    func open(at url: URL) throws {        samples = try Self.load(source, rate: sampleRate)        guard !samples.isEmpty else { throw MeetingCaptureFailure.wouldNotStart }        wave = url.pathExtension.lowercased() == "wav"        let header = wave ? Self.waveHeader(rate: sampleRate) : Self.header(rate: sampleRate)        FileManager.default.createFile(atPath: url.path(percentEncoded: false), contents: header)        handle = try FileHandle(forWritingTo: url)        try handle?.seekToEnd()        dataStart = UInt64(header.count)        written = 0        start()    }    func pause() {        pump?.cancel()        pump = nil    }    func resume() throws {        guard handle != nil else { throw MeetingCaptureFailure.wouldNotStart }        start()    }    func close() {        pump?.cancel()        pump = nil        guard let handle else { return }        // Patch the sizes, as AVAudioRecorder's stop does.        if wave {            try? handle.seek(toOffset: 4)            try? handle.write(contentsOf: withUnsafeBytes(of: UInt32(36 + written).littleEndian) { Data($0) })            try? handle.seek(toOffset: 40)            try? handle.write(contentsOf: withUnsafeBytes(of: UInt32(written).littleEndian) { Data($0) })        } else {            let size = Int64(written + 4)            try? handle.seek(toOffset: dataStart - 12)            try? handle.write(contentsOf: withUnsafeBytes(of: size.bigEndian) { Data($0) })        }        try? handle.close()        self.handle = nil    }    func meter() -> Double { lastLevel }    /// Write a tenth of a second every tenth of a second.    private func start() {        guard pump == nil else { return }        pump = Task { [weak self] in            let clock = ContinuousClock()            var next = clock.now            while !Task.isCancelled {                next += .milliseconds(100)                guard let self else { return }                self.write(frames: Int(self.sampleRate / 10))                try? await clock.sleep(until: next)            }        }    }    private func write(frames: Int) {        guard let handle else { return }        var chunk = [Int16]()        chunk.reserveCapacity(frames)        var peak = 0        for _ in 0..<frames {            let sample = samples[cursor]            chunk.append(sample.littleEndian)            peak = max(peak, abs(Int(sample)))            cursor = (cursor + 1) % samples.count        }        let data = chunk.withUnsafeBufferPointer { Data(buffer: $0) }        try? handle.write(contentsOf: data)        written += UInt64(data.count)        lastLevel = min(1, Double(peak) / 16_000)    }    /// `caff`, a `desc` for 16-bit little-endian mono linear PCM at 24 kHz,    /// and a `data` chunk whose size is -1: "still being written".    static func header(rate sampleRate: Double) -> Data {        var data = Data()        func put<T: FixedWidthInteger>(_ value: T) { withUnsafeBytes(of: value.bigEndian) { data.append(contentsOf: $0) } }        data.append(contentsOf: Array("caff".utf8)); put(UInt16(1)); put(UInt16(0))        data.append(contentsOf: Array("desc".utf8)); put(Int64(32))        put(sampleRate.bitPattern)        data.append(contentsOf: Array("lpcm".utf8))        put(UInt32(2))  // kCAFLinearPCMFormatFlagIsLittleEndian; signed integer        put(UInt32(2)); put(UInt32(1)); put(UInt32(1)); put(UInt32(16))        data.append(contentsOf: Array("data".utf8)); put(Int64(-1))        put(UInt32(0))  // edit count        return data    }    /// `RIFF`/`WAVE`, a `fmt ` for 16-bit mono PCM, and a `data` chunk, the    /// sizes at their largest until the file closes.    static func waveHeader(rate: Double) -> Data {        var data = Data()        func put<T: FixedWidthInteger>(_ value: T) { withUnsafeBytes(of: value.littleEndian) { data.append(contentsOf: $0) } }        data.append(contentsOf: Array("RIFF".utf8)); put(UInt32.max)        data.append(contentsOf: Array("WAVE".utf8))        data.append(contentsOf: Array("fmt ".utf8)); put(UInt32(16)); put(UInt16(1)); put(UInt16(1))        put(UInt32(rate)); put(UInt32(rate * 2)); put(UInt16(2)); put(UInt16(16))        data.append(contentsOf: Array("data".utf8)); put(UInt32.max)        return data    }    /// The source, as 16-bit mono samples at `rate`.    static func load(_ url: URL, rate sampleRate: Double) throws -> [Int16] {        let file = try AVAudioFile(forReading: url)        guard            let target = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: sampleRate, channels: 1, interleaved: true),            let converter = AVAudioConverter(from: file.processingFormat, to: target),            let input = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length))        else { throw MeetingCaptureFailure.wouldNotStart }        try file.read(into: input)        let ratio = sampleRate / file.processingFormat.sampleRate        let capacity = AVAudioFrameCount(Double(input.frameLength) * ratio) + 4096        guard let output = AVAudioPCMBuffer(pcmFormat: target, frameCapacity: capacity) else {            throw MeetingCaptureFailure.wouldNotStart        }        var fed = false        var failure: NSError?        converter.convert(to: output, error: &failure) { _, status in            if fed {                status.pointee = .endOfStream                return nil            }            fed = true            status.pointee = .haveData            return input        }        if let failure { throw failure }        guard let channel = output.int16ChannelData?[0] else { throw MeetingCaptureFailure.wouldNotStart }        return Array(UnsafeBufferPointer(start: channel, count: Int(output.frameLength)))    }}#endif#endif