Repository Public
1// SP Lecture Studio — LectureCapture2// File: Packages/LectureCapture/Sources/SegmentedAudioWriter.swift3// Description: Writes captured audio as bounded, finalized CAF segments (16-bit PCM) with exact timeline accounting and SHA-256 checksums.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import AVFoundation9import LectureCore10import LectureStorage1112/// Audio is never kept in one fragile file: every `segmentDuration` seconds the current file is closed (finalized,13/// checksummed, reported) and a new one is opened, without dropping a sample. A crash can only affect the open segment.14public final class SegmentedAudioWriter {15 public let package: ProjectPackage16 public let session: RecordingSession17 public let segmentDuration: Double18 /// Called when a segment file is created (not yet finalized).19 public var onOpen: ((MediaSegment) -> Void)?20 /// Called when a segment is closed and safe on disk.21 public var onFinalize: ((MediaSegment) -> Void)?2223 private var file: AVAudioFile?24 private var current: MediaSegment?25 private var framesInSegment: Int64 = 026 private var nextIndex: Int27 /// Timeline position of the next sample to be written.28 public private(set) var position: MediaTime29 public private(set) var segments: [MediaSegment] = []30 public private(set) var lastError: String?3132 public init(package: ProjectPackage, session: RecordingSession, startIndex: Int = 1, segmentDuration: Double = 30) {33 self.package = package; self.session = session; self.segmentDuration = segmentDuration34 nextIndex = startIndex; position = session.timelineStart35 }3637 /// Appends a mono Float32 buffer. Returns the timeline time of its first sample, or nil if it could not be written.38 @discardableResult39 public func append(_ buffer: AVAudioPCMBuffer) -> MediaTime? {40 let rate = buffer.format.sampleRate41 guard buffer.frameLength > 0, rate > 0 else { return nil }42 if let cur = current, cur.sampleRate != rate { closeCurrent() } // route change: new format → new segment43 if file == nil { guard open(rate: rate) else { return nil } }44 guard let file, var cur = current else { return nil }45 let start = cur.start + MediaTime(frames: framesInSegment, sampleRate: rate)46 do { try file.write(from: buffer) } catch { lastError = error.localizedDescription; return nil }47 framesInSegment += Int64(buffer.frameLength)48 cur.frames = framesInSegment; cur.duration = MediaTime(frames: framesInSegment, sampleRate: rate)49 current = cur50 position = cur.start + cur.duration51 if Double(framesInSegment) >= segmentDuration * rate { closeCurrent() }52 return start53 }5455 private func open(rate: Double) -> Bool {56 let name = ProjectLayout.segmentFileName(kind: .audio, session: session, index: nextIndex)57 let relative = ProjectLayout.mediaDirectory + "/" + name58 let url = package.url(relative)59 let settings: [String: Any] = [AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: rate, AVNumberOfChannelsKey: 1,60 AVLinearPCMBitDepthKey: 16, AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false]61 do {62 try FileManager.default.createDirectory(at: package.mediaURL, withIntermediateDirectories: true)63 file = try AVAudioFile(forWriting: url, settings: settings, commonFormat: .pcmFormatFloat32, interleaved: false)64 } catch { lastError = error.localizedDescription; return false }65 #if os(iOS)66 try? FileManager.default.setAttributes([.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: url.path)67 #endif68 let seg = MediaSegment(kind: .audio, path: relative, index: nextIndex, start: position, duration: .zero, sampleRate: rate, channels: 1, frames: 0, finalized: false)69 current = seg; framesInSegment = 0; nextIndex += 170 onOpen?(seg)71 return true72 }7374 /// Closes the open segment (if any) so that everything captured so far is finalized on disk.75 public func closeCurrent() {76 guard var seg = current else { return }77 file?.close() // writes the final CAF header now (not whenever the object is released)78 file = nil79 current = nil80 let url = package.url(seg.path)81 if framesInSegment == 0 { try? FileManager.default.removeItem(at: url); nextIndex -= 1; return }82 if let h = try? FileHandle(forWritingTo: url) { try? h.synchronize(); try? h.close() }83 seg.finalized = true84 seg.sha256 = try? Hashing.sha256(of: url)85 segments.append(seg)86 framesInSegment = 087 onFinalize?(seg)88 }8990 /// The segment being written, with its current length (for manifest checkpoints).91 public var openSegment: MediaSegment? { current }9293 public func finish() -> [MediaSegment] { closeCurrent(); return segments }94}95