#!/usr/bin/env swift//// What a KILLED recording leaves behind, per container and per format — the// measurement behind the recorder's capture settings.//// swift apps/cotton/scripts/measure-capture-containers.swift [directory]//// It needs no microphone and no permission: the audio is synthesised, written// with `AVAudioFile` (the same writer `AVAudioRecorder` is built on), and the// "kill" is the bytes COPIED mid-write with the writer still open, which is what// a force-quit leaves on the disk.//// It answers four questions, and the numbers it prints are the ones in// Cotton note "The phone and Mac app — how a screen is built" ("The recorder CAPTURES linear PCM into// `.caf`")://// 1. can a killed file be READ, and what length does it claim;// 2. can it be EXPORTED to the `.m4a` a meeting is delivered in;// 3. what each format costs per minute, and what the export costs in time;// 4. what the CAF chunk headers actually say, which is the mechanism: `data`// at -1 is enough for fixed-size PCM packets and not for AAC, whose frame// count lives in a `pakt` chunk written only at `stop()`.//// Re-run it before changing the capture format. It is the only honest way to// answer "will this survive being killed", and both walks that asked the// question got it wrong by reasoning instead.import AVFoundationimportFoundationlet root = URL( fileURLWithPath: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : NSTemporaryDirectory() + "cotton-capture-measure")try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)print("measuring in \(root.path)\n")// ── Synthetic audio, speech-shaped ──────────────────────────────────────────func tone(_ format: AVAudioFormat, seconds: Double, from offset: Double) -> AVAudioPCMBuffer {let frames = AVAudioFrameCount(format.sampleRate * seconds)let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frames)! buffer.frameLength = frameslet channel = buffer.floatChannelData![0]for index in0..<Int(frames) {let at = offset + Double(index) / format.sampleRatelet fundamental = 120 + 40 * sin(2 * .pi * 0.3 * at)var value = sin(2 * .pi * fundamental * at) * 0.3 value += sin(2 * .pi * fundamental * 2.4 * at) * 0.15// The pauses matter: a continuous tone compresses like nothing real. channel[index] = Float(value * (sin(2 * .pi * 0.25 * at) > -0.4 ? 1 : 0.05)) }return buffer}// ── The cases ───────────────────────────────────────────────────────────────structCase {let name: Stringlet slug: Stringlet ext: Stringlet rate: Doublelet settings: [String: Any]}func pcm(_ rate: Double) -> [String: Any] { [ AVFormatIDKey: Int(kAudioFormatLinearPCM), AVSampleRateKey: rate, AVNumberOfChannelsKey: 1, AVLinearPCMBitDepthKey: 16, AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsNonInterleaved: false, ]}let aac: [String: Any] = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 44_100.0, AVNumberOfChannelsKey: 1, AVEncoderBitRateKey: 64_000,]let cases: [Case] = [Case(name: "PCM 16-bit mono 24 kHz in caf", slug: "pcm-24k-caf", ext: "caf", rate: 24_000, settings: pcm(24_000)),Case(name: "PCM 16-bit mono 44.1 kHz in caf", slug: "pcm-44k-caf", ext: "caf", rate: 44_100, settings: pcm(44_100)),Case(name: "AAC 64 kbps mono 44.1 kHz in caf", slug: "aac-caf", ext: "caf", rate: 44_100, settings: aac),Case(name: "AAC 64 kbps mono 44.1 kHz in m4a", slug: "aac-m4a", ext: "m4a", rate: 44_100, settings: aac),]// ── Reading the bytes back ──────────────────────────────────────────────────func size(_ url: URL) -> Int { ((try? FileManager.default.attributesOfItem(atPath: url.path))?[.size] as? Int) ?? -1}func playerSays(_ url: URL) -> String {guardlet player = try? AVAudioPlayer(contentsOf: url) else { return"no player at all" }returnString(format: "%.3f s", player.duration)}func fileSays(_ url: URL) -> String {guardlet file = try? AVAudioFile(forReading: url) else { return"will not open" }returnString(format: "%.3f s (%lld frames)", Double(file.length) / file.fileFormat.sampleRate, file.length)}/// The CAF chunk table — the mechanism, in the bytes themselves.func chunks(_ url: URL) -> String {guardlet bytes = try? Data(contentsOf: url), bytes.count > 8, bytes.prefix(4) == Data("caff".utf8)else { return"not a CAF" }var at = 8var said: [String] = []while at + 12 <= bytes.count {let name = String(decoding: bytes[at..<(at + 4)], as: UTF8.self)let length = bytes[(at + 4)..<(at + 12)].reduce(Int64(0)) { ($0 << 8) | Int64($1) } said.append("\(name) \(length)")if length < 0 { break } at += 12 + Int(length) }return said.joined(separator: " · ")}func exported(_ url: URL, to destination: URL) async -> String {try? FileManager.default.removeItem(at: destination)guardlet session = AVAssetExportSession( asset: AVURLAsset(url: url), presetName: AVAssetExportPresetAppleM4A)else { return"no session" }let began = Date()do {tryawait session.export(to: destination, as: .m4a)returnString( format: "ok in %.2f s — %@, %d bytes", Date().timeIntervalSince(began), playerSays(destination), size(destination)) } catch {let failure = error as NSErrorlet under = (failure.userInfo[NSUnderlyingErrorKey] as? NSError).map {" / \($0.domain) \($0.code)" }return"FAILED — \(failure.domain) \(failure.code)\(under ?? "")" }}/// Write `seconds` of audio, copying the file at the halfway mark. The writer is/// released when this returns, which is what closes and finalises the file.func write(_ item: Case, seconds: Double, live: URL, killed: URL?) throws {let format = AVAudioFormat(standardFormatWithSampleRate: item.rate, channels: 1)!let writer = try AVAudioFile(forWriting: live, settings: item.settings)let chunk = 0.25var written = 0.0var copied = killed == nilwhile written < seconds {try writer.write(from: tone(format, seconds: chunk, from: written)) written += chunkif !copied, written >= seconds / 2, let killed {tryFileManager.default.copyItem(at: live, to: killed) copied = true } }}// ── 1 and 2: killed and closed, read and exported ───────────────────────────let seconds = 13.0print("── \(Int(seconds)) s written, the copy taken at half way with the writer still open\n")for item in cases {let live = root.appendingPathComponent("closed-\(item.slug).\(item.ext)")let killed = root.appendingPathComponent("killed-\(item.slug).\(item.ext)")try? FileManager.default.removeItem(at: live)try? FileManager.default.removeItem(at: killed)try write(item, seconds: seconds, live: live, killed: killed) print(item.name) print(" killed : \(size(killed)) bytes · AVAudioFile \(fileSays(killed)) · AVAudioPlayer \(playerSays(killed))") print(" chunks: \(chunks(killed))") print(" closed : \(size(live)) bytes · AVAudioFile \(fileSays(live)) · AVAudioPlayer \(playerSays(live))") print(" chunks: \(chunks(live))") print(" per minute: \(String(format: "%.2f", Double(size(live)) / seconds * 60 / 1_048_576)) MiB") print(" export(killed) → m4a : \(await exported(killed, to: root.appendingPathComponent("export-killed-\(item.slug).m4a")))") print(" export(closed) → m4a : \(await exported(live, to: root.appendingPathComponent("export-closed-\(item.slug).m4a")))") print("")}// ── 3: what a long recording costs, and what the export costs ───────────────let minutes = 10.0let long = root.appendingPathComponent("long-pcm-24k.caf")try? FileManager.default.removeItem(at: long)try write(cases[0], seconds: minutes * 60, live: long, killed: nil)print("── \(Int(minutes)) min of \(cases[0].name)")print(" \(size(long)) bytes (\(String(format: "%.2f", Double(size(long)) / 1_048_576)) MiB)")print(" export → m4a : \(await exported(long, to: root.appendingPathComponent("long-export.m4a")))\n")// ── 4: the shipping API's own file, without a microphone ────────────────────let opened = root.appendingPathComponent("recorder-pcm.caf")try? FileManager.default.removeItem(at: opened)let recorder = try AVAudioRecorder(url: opened, settings: pcm(24_000))recorder.isMeteringEnabled = trueprint("── AVAudioRecorder with the shipping settings (no record(), so no microphone)")print(" prepareToRecord: \(recorder.prepareToRecord()) · metering \(recorder.isMeteringEnabled)")print(" the file it opened: \(size(opened)) bytes · chunks: \(chunks(opened))")