From fa9240d7048a0ecebf5c0de3f064736ac31f4416 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:47:30 +0100 Subject: [PATCH] Add live video media layer (VideoToolbox/AVFoundation) H.264 Constrained Baseline encoder (center-crop/scale into pooled NV12, in-band SPS/PPS on keyframes, live bitrate and forced keyframes), paced decoder with a 350 ms jitter buffer and keyframe resync, passthrough MP4 writer that tolerates mesh loss (held frames, silence-filled audio gaps), segment joiner that holds dropouts as a freeze, clip transcoder that fits a byte budget, poster loader, and camera/synthetic frame sources. --- bitchat/Features/video/LiveVideoAVCC.swift | 269 ++++++++++ .../video/LiveVideoCameraSource.swift | 459 ++++++++++++++++ .../Features/video/LiveVideoFrameSource.swift | 300 +++++++++++ .../Features/video/LiveVideoH264Decoder.swift | 288 ++++++++++ .../Features/video/LiveVideoH264Encoder.swift | 288 ++++++++++ .../Features/video/LiveVideoMp4Segments.swift | 329 ++++++++++++ .../Features/video/LiveVideoMp4Writer.swift | 351 ++++++++++++ .../Features/video/VideoPosterLoader.swift | 62 +++ bitchat/Features/video/VideoTranscoder.swift | 301 +++++++++++ .../Features/Video/LiveVideoMediaTests.swift | 500 ++++++++++++++++++ 10 files changed, 3147 insertions(+) create mode 100644 bitchat/Features/video/LiveVideoAVCC.swift create mode 100644 bitchat/Features/video/LiveVideoCameraSource.swift create mode 100644 bitchat/Features/video/LiveVideoFrameSource.swift create mode 100644 bitchat/Features/video/LiveVideoH264Decoder.swift create mode 100644 bitchat/Features/video/LiveVideoH264Encoder.swift create mode 100644 bitchat/Features/video/LiveVideoMp4Segments.swift create mode 100644 bitchat/Features/video/LiveVideoMp4Writer.swift create mode 100644 bitchat/Features/video/VideoPosterLoader.swift create mode 100644 bitchat/Features/video/VideoTranscoder.swift create mode 100644 bitchatTests/Features/Video/LiveVideoMediaTests.swift diff --git a/bitchat/Features/video/LiveVideoAVCC.swift b/bitchat/Features/video/LiveVideoAVCC.swift new file mode 100644 index 00000000..cc417f18 --- /dev/null +++ b/bitchat/Features/video/LiveVideoAVCC.swift @@ -0,0 +1,269 @@ +// +// LiveVideoAVCC.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import CoreMedia +import Foundation + +/// Annex B <-> AVCC plumbing shared by the VideoToolbox/AVFoundation media +/// layer. The wire carries Annex B (4-byte start codes, SPS+PPS in-band on +/// every IDR) while CoreMedia wants length-prefixed NAL units plus a format +/// description built from the parameter sets. +enum LiveVideoAVCC { + static let typeSlice: UInt8 = 1 + static let typeIDR: UInt8 = 5 + static let typeSEI: UInt8 = 6 + static let typeSPS: UInt8 = 7 + static let typePPS: UInt8 = 8 + static let typeAUD: UInt8 = 9 + static let typeFiller: UInt8 = 12 + + /// Length-prefix size used for every AVCC sample this layer builds. + static let lengthSize = 4 + static let startCode = Data([0, 0, 0, 1]) + + static func nalType(_ nal: Data) -> UInt8 { + guard let first = nal.first else { return 0 } + return first & 0x1F + } + + /// Splits an Annex B access unit (3- or 4-byte start codes) into NAL units + /// without their start codes. Returns an empty array when the buffer does + /// not start with a start code. + static func nalUnits(inAnnexB data: Data) -> [Data] { + let bytes = [UInt8](data) + let count = bytes.count + var starts: [(codeStart: Int, payloadStart: Int)] = [] + var index = 0 + while index + 2 < count { + if bytes[index] == 0, bytes[index + 1] == 0 { + if bytes[index + 2] == 1 { + let codeStart = index > 0 && bytes[index - 1] == 0 ? index - 1 : index + starts.append((codeStart, index + 3)) + index += 3 + continue + } + if bytes[index + 2] == 0 { + index += 1 + continue + } + } + index += 1 + } + guard let first = starts.first, bytes[0.. start.payloadStart, bytes[end - 1] == 0 { end -= 1 } + guard end > start.payloadStart else { continue } + units.append(Data(bytes[start.payloadStart.. Data { + var out = Data(capacity: nalUnits.reduce(0) { $0 + $1.count + 4 }) + for nal in nalUnits { + out.append(startCode) + out.append(nal) + } + return out + } + + /// Joins NAL units into an AVCC sample with 4-byte big-endian lengths. + static func avccSample(from nalUnits: [Data]) -> Data { + var out = Data(capacity: nalUnits.reduce(0) { $0 + $1.count + 4 }) + for nal in nalUnits { + let length = UInt32(nal.count) + out.append(UInt8(truncatingIfNeeded: length >> 24)) + out.append(UInt8(truncatingIfNeeded: length >> 16)) + out.append(UInt8(truncatingIfNeeded: length >> 8)) + out.append(UInt8(truncatingIfNeeded: length)) + out.append(nal) + } + return out + } + + /// Splits a length-prefixed AVCC buffer back into NAL units. Stops at the + /// first malformed length instead of reading past the buffer. + static func nalUnits(inAVCC data: Data, lengthSize: Int) -> [Data] { + guard (1...4).contains(lengthSize) else { return [] } + var units: [Data] = [] + data.withUnsafeBytes { raw in + guard let base = raw.bindMemory(to: UInt8.self).baseAddress else { return } + var offset = 0 + while offset + lengthSize <= raw.count { + var length = 0 + for byte in 0.. 0, offset + length <= raw.count else { break } + units.append(Data(bytes: base + offset, count: length)) + offset += length + } + } + return units + } + + /// First SPS and PPS of an Annex B access unit, if both are present. + static func parameterSets(in nalUnits: [Data]) -> (sps: Data, pps: Data)? { + guard let sps = nalUnits.first(where: { nalType($0) == typeSPS }), + let pps = nalUnits.first(where: { nalType($0) == typePPS }) + else { return nil } + return (sps, pps) + } + + static func formatDescription(sps: Data, pps: Data) -> CMVideoFormatDescription? { + var description: CMVideoFormatDescription? + let status = sps.withUnsafeBytes { spsRaw -> OSStatus in + pps.withUnsafeBytes { ppsRaw -> OSStatus in + guard let spsBase = spsRaw.bindMemory(to: UInt8.self).baseAddress, + let ppsBase = ppsRaw.bindMemory(to: UInt8.self).baseAddress + else { return -1 } + let pointers: [UnsafePointer] = [spsBase, ppsBase] + let sizes = [sps.count, pps.count] + return CMVideoFormatDescriptionCreateFromH264ParameterSets( + allocator: kCFAllocatorDefault, + parameterSetCount: 2, + parameterSetPointers: pointers, + parameterSetSizes: sizes, + nalUnitHeaderLength: Int32(lengthSize), + formatDescriptionOut: &description + ) + } + } + return status == noErr ? description : nil + } + + /// Every H.264 parameter set (SPS first, then PPS) of a format description, + /// plus its NAL length-prefix size. + static func parameterSets(of description: CMFormatDescription) -> (sets: [Data], lengthSize: Int)? { + var count = 0 + var headerLength: Int32 = 0 + let status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( + description, + parameterSetIndex: 0, + parameterSetPointerOut: nil, + parameterSetSizeOut: nil, + parameterSetCountOut: &count, + nalUnitHeaderLengthOut: &headerLength + ) + guard status == noErr, count > 0 else { return nil } + var sets: [Data] = [] + for index in 0..? + var size = 0 + guard CMVideoFormatDescriptionGetH264ParameterSetAtIndex( + description, + parameterSetIndex: index, + parameterSetPointerOut: &pointer, + parameterSetSizeOut: &size, + parameterSetCountOut: nil, + nalUnitHeaderLengthOut: nil + ) == noErr, let pointer else { return nil } + sets.append(Data(bytes: pointer, count: size)) + } + return (sets, Int(headerLength)) + } + + /// Wraps an AVCC sample in a ready CMSampleBuffer. A nil duration leaves it + /// invalid (the consumer derives it from the next timestamp). + static func sampleBuffer( + avcc: Data, + format: CMFormatDescription, + pts: CMTime, + duration: CMTime = .invalid, + keyframe: Bool + ) -> CMSampleBuffer? { + guard !avcc.isEmpty, let block = blockBuffer(copying: avcc) else { return nil } + var timing = CMSampleTimingInfo(duration: duration, presentationTimeStamp: pts, decodeTimeStamp: .invalid) + var sampleSize = avcc.count + var sample: CMSampleBuffer? + let status = CMSampleBufferCreateReady( + allocator: kCFAllocatorDefault, + dataBuffer: block, + formatDescription: format, + sampleCount: 1, + sampleTimingEntryCount: 1, + sampleTimingArray: &timing, + sampleSizeEntryCount: 1, + sampleSizeArray: &sampleSize, + sampleBufferOut: &sample + ) + guard status == noErr, let sample else { return nil } + markSync(sample, keyframe: keyframe) + return sample + } + + static func markSync(_ sample: CMSampleBuffer, keyframe: Bool) { + guard let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: true), + CFArrayGetCount(attachments) > 0 + else { return } + let dictionary = unsafeBitCast(CFArrayGetValueAtIndex(attachments, 0), to: CFMutableDictionary.self) + let notSync = keyframe ? kCFBooleanFalse : kCFBooleanTrue + let dependsOnOthers = keyframe ? kCFBooleanFalse : kCFBooleanTrue + CFDictionarySetValue( + dictionary, + Unmanaged.passUnretained(kCMSampleAttachmentKey_NotSync).toOpaque(), + Unmanaged.passUnretained(notSync!).toOpaque() + ) + CFDictionarySetValue( + dictionary, + Unmanaged.passUnretained(kCMSampleAttachmentKey_DependsOnOthers).toOpaque(), + Unmanaged.passUnretained(dependsOnOthers!).toOpaque() + ) + } + + /// True unless the sample carries `NotSync = true`. + static func isSync(_ sample: CMSampleBuffer) -> Bool { + guard let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: false), + CFArrayGetCount(attachments) > 0 + else { return true } + let dictionary = unsafeBitCast(CFArrayGetValueAtIndex(attachments, 0), to: CFDictionary.self) + guard let value = CFDictionaryGetValue(dictionary, Unmanaged.passUnretained(kCMSampleAttachmentKey_NotSync).toOpaque()) else { + return true + } + return !CFBooleanGetValue(unsafeBitCast(value, to: CFBoolean.self)) + } + + /// Copies `data` into a CMBlockBuffer that owns its memory. + static func blockBuffer(copying data: Data) -> CMBlockBuffer? { + var block: CMBlockBuffer? + guard CMBlockBufferCreateWithMemoryBlock( + allocator: kCFAllocatorDefault, + memoryBlock: nil, + blockLength: data.count, + blockAllocator: kCFAllocatorDefault, + customBlockSource: nil, + offsetToData: 0, + dataLength: data.count, + flags: kCMBlockBufferAssureMemoryNowFlag, + blockBufferOut: &block + ) == noErr, let block else { return nil } + let status = data.withUnsafeBytes { raw -> OSStatus in + guard let base = raw.baseAddress else { return -1 } + return CMBlockBufferReplaceDataBytes(with: base, blockBuffer: block, offsetIntoDestination: 0, dataLength: data.count) + } + return status == noErr ? block : nil + } + + /// Contiguous bytes of a sample buffer's data. + static func data(of sample: CMSampleBuffer) -> Data? { + guard let block = CMSampleBufferGetDataBuffer(sample) else { return nil } + let length = CMBlockBufferGetDataLength(block) + guard length > 0 else { return nil } + var data = Data(count: length) + let status = data.withUnsafeMutableBytes { raw -> OSStatus in + guard let base = raw.baseAddress else { return -1 } + return CMBlockBufferCopyDataBytes(block, atOffset: 0, dataLength: length, destination: base) + } + return status == noErr ? data : nil + } +} diff --git a/bitchat/Features/video/LiveVideoCameraSource.swift b/bitchat/Features/video/LiveVideoCameraSource.swift new file mode 100644 index 00000000..9480b249 --- /dev/null +++ b/bitchat/Features/video/LiveVideoCameraSource.swift @@ -0,0 +1,459 @@ +// +// LiveVideoCameraSource.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import AVFoundation +import BitLogger +import CoreMedia +import CoreVideo +import Foundation + +/// Camera (+ optional microphone) capture for a live video sender. +/// +/// Video: an `AVCaptureSession` delivering upright (portrait on iOS) pixel +/// buffers at up to 30 fps; the encoder crops/scales them, so any preset +/// works. `session` is exposed so a preview layer can attach to it. +/// Audio: an `AVAudioEngine` tap resampled and encoded with the live-voice +/// pieces (`PTTInputResampler` + `PTTFrameEncoder`), holding a capture token +/// from `AudioSessionCoordinator` exactly like `PTTCaptureEngine`. Losing the +/// audio session (call, Siri, route loss) stops audio only; video continues. +/// +/// `@unchecked Sendable`: capture configuration is confined to +/// `sessionQueue`, frame state to `videoQueue`, encoder state to +/// `audioQueue`, engine/lifecycle state to the main actor; the clock and mute +/// flag are lock-protected. +final class LiveVideoCameraSource: NSObject, LiveVideoFrameSource, @unchecked Sendable { + enum CameraError: Error { + case permissionDenied + case cameraUnavailable + case configurationFailed + case microphoneUnavailable + } + + enum Position { + case front + case back + } + + private static let maxFps: Int32 = 30 + + /// Attach an `AVCaptureVideoPreviewLayer` to this session for the + /// sender's own preview. + let session = AVCaptureSession() + let audioEnabled: Bool + + var onPixelBuffer: ((CVPixelBuffer, Int64) -> Void)? + var onAudioFrames: (([Data], Int64) -> Void)? + + var isMuted: Bool { + get { stateLock.withLock { muted } } + set { stateLock.withLock { muted = newValue } } + } + + /// Camera currently in use (or about to be, before `start()`). + var position: Position { + stateLock.withLock { currentPosition } + } + + private let sessionQueue = DispatchQueue(label: "chat.bitchat.video.camera.session", qos: .userInitiated) + private let videoQueue = DispatchQueue(label: "chat.bitchat.video.camera.frames", qos: .userInitiated) + private let audioQueue = DispatchQueue(label: "chat.bitchat.video.camera.audio", qos: .userInitiated) + private let videoOutput = AVCaptureVideoDataOutput() + private let coordinator: AudioSessionCoordinator + private let sessionLease: PTTCaptureSessionLease + private let captureGeneration = PTTCaptureGeneration() + + // Lock-protected. + private let stateLock = NSLock() + private var muted = false + private var currentPosition: Position + /// Host-clock seconds at `start()`; timestamps are relative to it. + private var clockOriginSeconds: Double = 0 + + // sessionQueue-confined. + private var videoInput: AVCaptureDeviceInput? + private var outputAdded = false + + // videoQueue-confined. + private var lastFramePtsUs: Int64 = .min + + // audioQueue-confined. + private var resampler: PTTInputResampler? + private var encoder: PTTFrameEncoder? + private var firstAudioPtsUs: Int64? + private var aacFramesEmitted: Int64 = 0 + + // Main-actor-confined. + @MainActor private var engine: AVAudioEngine? + @MainActor private var engineStarted = false + @MainActor private var configChangeObserver: NSObjectProtocol? + + init(position: Position = .front, audioEnabled: Bool = true, coordinator: AudioSessionCoordinator = .shared) { + self.currentPosition = position + self.audioEnabled = audioEnabled + self.coordinator = coordinator + self.sessionLease = PTTCaptureSessionLease(coordinator: coordinator) + super.init() + } + + deinit { + sessionLease.release() + } + + // MARK: - Permissions + + static func requestCameraAccess() async -> Bool { + await requestAccess(for: .video) + } + + static func requestMicrophoneAccess() async -> Bool { + await requestAccess(for: .audio) + } + + private static func requestAccess(for mediaType: AVMediaType) async -> Bool { + switch AVCaptureDevice.authorizationStatus(for: mediaType) { + case .authorized: + return true + case .notDetermined: + return await AVCaptureDevice.requestAccess(for: mediaType) + default: + return false + } + } + + // MARK: - Lifecycle + + /// Starts the camera, then (if enabled and permitted) the microphone. + /// Throws when the camera cannot run; a microphone failure only logs, and + /// the stream continues without audio. + @MainActor + func start() async throws { + guard await Self.requestCameraAccess() else { throw CameraError.permissionDenied } + stateLock.withLock { clockOriginSeconds = Self.hostSeconds() } + videoQueue.sync { lastFramePtsUs = .min } + let position = self.position + try await onSessionQueue { try self.configureAndRun(position: position) } + + guard audioEnabled else { return } + guard await Self.requestMicrophoneAccess() else { + SecureLogger.info("Live video: microphone permission denied; streaming without audio", category: .session) + return + } + do { + try await startAudio() + } catch { + SecureLogger.error("Live video: microphone unavailable, streaming without audio: \(error)", category: .session) + } + } + + @MainActor + func stop() { + stopAudio() + sessionQueue.async { [self] in + if session.isRunning { session.stopRunning() } + } + } + + /// Switches between the front and back camera while running (or picks + /// the camera the next `start()` uses). + func setPosition(_ position: Position) async throws { + stateLock.withLock { currentPosition = position } + try await onSessionQueue { + guard self.outputAdded else { return } + self.session.beginConfiguration() + do { + try self.installInput(position: position) + self.configureConnection() + } catch { + self.session.commitConfiguration() + throw error + } + self.session.commitConfiguration() + // Frame rate settings belong to the device: reapply on the new one. + self.capFrameRate() + } + } + + func switchCamera() async throws { + try await setPosition(position == .front ? .back : .front) + } + + // MARK: - Session queue + + private func onSessionQueue(_ body: @escaping () throws -> Void) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + sessionQueue.async { + do { + try body() + continuation.resume() + } catch { + continuation.resume(throwing: error) + } + } + } + } + + private func configureAndRun(position: Position) throws { + session.beginConfiguration() + do { + // 640×480 covers the largest preset (480×640 portrait) without + // paying for full-resolution capture. + if session.canSetSessionPreset(.vga640x480) { + session.sessionPreset = .vga640x480 + } else if session.canSetSessionPreset(.medium) { + session.sessionPreset = .medium + } + try installInput(position: position) + if !outputAdded { + let nv12 = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange + if videoOutput.availableVideoPixelFormatTypes.contains(nv12) { + videoOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: nv12] + } + videoOutput.alwaysDiscardsLateVideoFrames = true + videoOutput.setSampleBufferDelegate(self, queue: videoQueue) + guard session.canAddOutput(videoOutput) else { throw CameraError.configurationFailed } + session.addOutput(videoOutput) + outputAdded = true + } + configureConnection() + } catch { + session.commitConfiguration() + throw error + } + session.commitConfiguration() + capFrameRate() + if !session.isRunning { session.startRunning() } + guard session.isRunning else { throw CameraError.configurationFailed } + SecureLogger.info("Live video: camera running", category: .session) + } + + private func installInput(position: Position) throws { + guard let device = Self.device(for: position) else { throw CameraError.cameraUnavailable } + if let videoInput, videoInput.device.uniqueID == device.uniqueID { return } + let input = try AVCaptureDeviceInput(device: device) + if let videoInput { session.removeInput(videoInput) } + guard session.canAddInput(input) else { + if let videoInput, session.canAddInput(videoInput) { session.addInput(videoInput) } + throw CameraError.configurationFailed + } + session.addInput(input) + videoInput = input + } + + /// Portrait, upright frames on iOS (the encoder's targets are 3:4 + /// portrait). macOS cameras stay landscape; the encoder center-crops. + private func configureConnection() { + guard let connection = videoOutput.connection(with: .video) else { return } + #if os(iOS) + if #available(iOS 17.0, *) { + if connection.isVideoRotationAngleSupported(90) { + connection.videoRotationAngle = 90 + } + } else if connection.isVideoOrientationSupported { + connection.videoOrientation = .portrait + } + #endif + // Viewers see the scene as it is (readable text); only the local + // preview layer mirrors the front camera. + if connection.isVideoMirroringSupported { + connection.automaticallyAdjustsVideoMirroring = false + connection.isVideoMirrored = false + } + } + + private func capFrameRate() { + guard let device = videoInput?.device else { return } + let target = CMTime(value: 1, timescale: Self.maxFps) + let supported = device.activeFormat.videoSupportedFrameRateRanges.contains { + $0.minFrameDuration <= target && target <= $0.maxFrameDuration + } + guard supported else { return } + do { + try device.lockForConfiguration() + device.activeVideoMinFrameDuration = target + device.unlockForConfiguration() + } catch { + SecureLogger.debug("Live video: could not cap camera frame rate: \(error)", category: .session) + } + } + + private static func device(for position: Position) -> AVCaptureDevice? { + let wanted: AVCaptureDevice.Position = position == .front ? .front : .back + return AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: wanted) + ?? AVCaptureDevice.default(for: .video) + } + + private static func hostSeconds() -> Double { + CMClockGetTime(CMClockGetHostTimeClock()).seconds + } + + private func relativeUs(hostSeconds: Double) -> Int64 { + let origin = stateLock.withLock { clockOriginSeconds } + return Int64((hostSeconds - origin) * 1_000_000) + } + + // MARK: - Audio (main actor lifecycle, audioQueue processing) + + @MainActor + private func startAudio() async throws { + let generation = captureGeneration.begin() + let token = try await coordinator.acquire(.capture) { [weak self] in + self?.handleAudioInterruption(for: generation) + } + // stop() ran while the session was activating: starting the engine + // now would leave a hot mic after release. + guard captureGeneration.isCurrent(generation) else { + coordinator.release(token) + throw CancellationError() + } + sessionLease.install(token) + do { + try beginAudioCapture(generation: generation) + } catch { + sessionLease.release() + throw error + } + } + + @MainActor + private func beginAudioCapture(generation: UInt) throws { + // Fresh engine per capture so its input unit binds to the session + // that is active now (see PTTCaptureEngine.engine). + let engine = AVAudioEngine() + self.engine = engine + let inputFormat = engine.inputNode.outputFormat(forBus: 0) + guard inputFormat.sampleRate > 0, inputFormat.channelCount > 0, + let resampler = PTTInputResampler(inputFormat: inputFormat), + let encoder = PTTFrameEncoder() + else { throw CameraError.microphoneUnavailable } + + audioQueue.sync { + self.resampler = resampler + self.encoder = encoder + self.firstAudioPtsUs = nil + self.aacFramesEmitted = 0 + } + engine.inputNode.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) { [weak self] buffer, time in + let hostSeconds = time.isHostTimeValid ? AVAudioTime.seconds(forHostTime: time.hostTime) : nil + self?.audioQueue.async { self?.processAudio(buffer, hostSeconds: hostSeconds, generation: generation) } + } + configChangeObserver = NotificationCenter.default.addObserver( + forName: .AVAudioEngineConfigurationChange, + object: engine, + queue: .main + ) { [weak self] _ in + Task { @MainActor [weak self] in + self?.handleAudioInterruption(for: generation) + } + } + engine.prepare() + do { + try engine.start() + } catch { + removeConfigObserver() + engine.inputNode.removeTap(onBus: 0) + audioQueue.sync { self.resetAudioState() } + throw error + } + engineStarted = true + SecureLogger.info("Live video: microphone running (\(Int(inputFormat.sampleRate)) Hz, \(inputFormat.channelCount) ch)", category: .session) + } + + /// Interruption, route loss or engine reconfiguration: audio ends for this + /// stream; video keeps going. + @MainActor + private func handleAudioInterruption(for generation: UInt) { + guard captureGeneration.invalidate(ifCurrent: generation) else { return } + stopEngineIfStarted() + audioQueue.sync { resetAudioState() } + sessionLease.release() + SecureLogger.info("Live video: audio interrupted; continuing video only", category: .session) + } + + @MainActor + private func stopAudio() { + captureGeneration.invalidate() + stopEngineIfStarted() + audioQueue.sync { resetAudioState() } + sessionLease.release() + } + + /// Never touches `inputNode` of an engine that did not start (that would + /// instantiate its input unit; see PTTCaptureEngine). + @MainActor + private func stopEngineIfStarted() { + removeConfigObserver() + guard engineStarted, let engine else { + self.engine = nil + return + } + engineStarted = false + engine.inputNode.removeTap(onBus: 0) + engine.stop() + self.engine = nil + } + + @MainActor + private func removeConfigObserver() { + if let observer = configChangeObserver { + NotificationCenter.default.removeObserver(observer) + configChangeObserver = nil + } + } + + private func resetAudioState() { + resampler = nil + encoder = nil + firstAudioPtsUs = nil + aacFramesEmitted = 0 + } + + private func processAudio(_ buffer: AVAudioPCMBuffer, hostSeconds: Double?, generation: UInt) { + guard captureGeneration.isCurrent(generation), + let encoder, + let resampled = resampler?.resample(buffer) + else { return } + if firstAudioPtsUs == nil { + firstAudioPtsUs = max(0, hostSeconds.map { relativeUs(hostSeconds: $0) } ?? 0) + } + if isMuted, let channels = resampled.floatChannelData { + for channel in 0..= 0 else { return } + // Software cap in case the device ignored the frame duration request + // (20% tolerance for capture jitter). + let minIntervalUs = Int64(1_000_000 / Self.maxFps) * 8 / 10 + if lastFramePtsUs != .min, ptsUs - lastFramePtsUs < minIntervalUs { return } + lastFramePtsUs = ptsUs + onPixelBuffer?(pixelBuffer, ptsUs) + } +} diff --git a/bitchat/Features/video/LiveVideoFrameSource.swift b/bitchat/Features/video/LiveVideoFrameSource.swift new file mode 100644 index 00000000..daf41b0c --- /dev/null +++ b/bitchat/Features/video/LiveVideoFrameSource.swift @@ -0,0 +1,300 @@ +// +// LiveVideoFrameSource.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import AVFoundation +import BitLogger +import CoreVideo +import Foundation + +/// Where a live video sender gets its pictures and (optional) audio: the +/// camera + microphone, or a synthetic test card + tone. +/// +/// Timestamps are microseconds on one clock that starts at 0 when `start()` +/// begins, shared by video and audio so the sender can interleave them. +/// `onAudioFrames` delivers consecutive raw AAC-LC frames (16 kHz mono, no +/// ADTS); its timestamp is the first frame's, each following frame is +/// `PTTAudioFormat.frameDuration` later. Callbacks run on the source's +/// serial queues; set them before `start()`. +protocol LiveVideoFrameSource: AnyObject { + var onPixelBuffer: ((CVPixelBuffer, Int64) -> Void)? { get set } + var onAudioFrames: (([Data], Int64) -> Void)? { get set } + /// Muted audio keeps flowing as encoded silence, so viewers' audio clock + /// and the recording's timeline stay continuous. + var isMuted: Bool { get set } + @MainActor func start() async throws + @MainActor func stop() +} + +/// Deterministic moving test card (color bars, a bouncing box, a frame +/// counter in digits and binary) plus a 440 Hz tone, for the simulator (which +/// has no camera) and automated tests, so nothing ever captures a real room. +/// +/// `@unchecked Sendable`: generator state is confined to `queue`; `isMuted` +/// is lock-protected. +final class LiveVideoSyntheticSource: LiveVideoFrameSource, @unchecked Sendable { + let width: Int + let height: Int + let fps: Int + let audioEnabled: Bool + let toneHz: Double + + var onPixelBuffer: ((CVPixelBuffer, Int64) -> Void)? + var onAudioFrames: (([Data], Int64) -> Void)? + + var isMuted: Bool { + get { muteLock.withLock { muted } } + set { muteLock.withLock { muted = newValue } } + } + + private let queue = DispatchQueue(label: "chat.bitchat.video.synthetic", qos: .userInitiated) + private let muteLock = NSLock() + private var muted = false + + // Queue-confined state. + private var videoTimer: DispatchSourceTimer? + private var audioTimer: DispatchSourceTimer? + private var startUptimeNs: UInt64 = 0 + private var frameIndex = 0 + private var audioEncoder: PTTFrameEncoder? + private var samplesGenerated: Int64 = 0 + private var aacFramesEmitted: Int64 = 0 + private var pool: CVPixelBufferPool? + private lazy var background: [UInt32] = makeBackground() + + init(width: Int = 480, height: Int = 640, fps: Int = 15, audioEnabled: Bool = true, toneHz: Double = 440) { + self.width = max(16, width & ~1) + self.height = max(16, height & ~1) + self.fps = min(max(fps, 1), 60) + self.audioEnabled = audioEnabled + self.toneHz = toneHz + } + + deinit { + videoTimer?.cancel() + audioTimer?.cancel() + } + + func start() async throws { + queue.sync { + guard videoTimer == nil else { return } + startUptimeNs = DispatchTime.now().uptimeNanoseconds + frameIndex = 0 + samplesGenerated = 0 + aacFramesEmitted = 0 + audioEncoder = audioEnabled ? PTTFrameEncoder() : nil + if audioEnabled, audioEncoder == nil { + SecureLogger.error("Live video: synthetic tone encoder unavailable", category: .session) + } + + let video = DispatchSource.makeTimerSource(queue: queue) + video.schedule(deadline: .now(), repeating: .nanoseconds(1_000_000_000 / fps), leeway: .milliseconds(2)) + video.setEventHandler { [weak self] in self?.emitVideoFrame() } + videoTimer = video + video.resume() + + if audioEncoder != nil { + // Generated by elapsed sample count, so timer jitter never + // stretches or squeezes the tone's timeline. + let audio = DispatchSource.makeTimerSource(queue: queue) + audio.schedule(deadline: .now(), repeating: .milliseconds(32), leeway: .milliseconds(4)) + audio.setEventHandler { [weak self] in self?.emitAudio() } + audioTimer = audio + audio.resume() + } + } + } + + func stop() { + queue.sync { + videoTimer?.cancel() + audioTimer?.cancel() + videoTimer = nil + audioTimer = nil + audioEncoder = nil + } + } + + // MARK: - Generators (also used directly by tests) + + /// Renders test-card frame `index` as a BGRA pixel buffer. + func makeFrame(index: Int) -> CVPixelBuffer? { + if pool == nil { + let attributes: [CFString: Any] = [ + kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_32BGRA, + kCVPixelBufferWidthKey: width, + kCVPixelBufferHeightKey: height, + kCVPixelBufferIOSurfacePropertiesKey: [String: Any]() + ] + CVPixelBufferPoolCreate(kCFAllocatorDefault, nil, attributes as CFDictionary, &pool) + } + var created: CVPixelBuffer? + if let pool { + CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool, &created) + } + guard let buffer = created else { return nil } + + CVPixelBufferLockBaseAddress(buffer, []) + defer { CVPixelBufferUnlockBaseAddress(buffer, []) } + guard let base = CVPixelBufferGetBaseAddress(buffer) else { return nil } + let rowPixels = CVPixelBufferGetBytesPerRow(buffer) / 4 + let pixels = base.bindMemory(to: UInt32.self, capacity: rowPixels * height) + + background.withUnsafeBufferPointer { source in + guard let sourceBase = source.baseAddress else { return } + for row in 0..> bit) & 1 == 1 + fill(pixels, rowPixels, x: bit * cell, y: 0, w: cell, h: max(4, height / 64), color: on ? Self.white : Self.black) + } + + // Decimal frame counter, bottom-left, on a dark plate. + let digits = Array(String(index)) + let scale = max(2, width / 60) + let plateHeight = 7 * scale + fill(pixels, rowPixels, x: 0, y: height - plateHeight, w: (digits.count * 4 + 1) * scale, h: plateHeight, color: Self.black) + for (position, character) in digits.enumerated() { + guard let glyph = Self.glyphs[character] else { continue } + for (row, bits) in glyph.enumerated() { + for column in 0..<3 where bits & (0b100 >> column) != 0 { + fill( + pixels, rowPixels, + x: (position * 4 + 1 + column) * scale, + y: height - plateHeight + (row + 1) * scale, + w: scale, h: scale, + color: Self.white + ) + } + } + } + return buffer + } + + /// `frameCount` samples of the tone (or silence) at 16 kHz mono, phase- + /// continuous from sample `startSample`. + func makeToneBuffer(startSample: Int64, frameCount: AVAudioFrameCount, silent: Bool = false) -> AVAudioPCMBuffer? { + guard let format = PTTAudioFormat.pcmFormat, + let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount), + let channel = buffer.floatChannelData?[0] + else { return nil } + buffer.frameLength = frameCount + let step = 2 * Double.pi * toneHz / PTTAudioFormat.sampleRate + for index in 0.. UInt32 { + // Little-endian 32BGRA: B in the low byte, A in the high byte. + blue | (green << 8) | (red << 16) | (0xFF << 24) + } + + private static func bounce(_ value: Int, range: Int) -> Int { + guard range > 0 else { return 0 } + let period = range * 2 + let phase = value % period + return phase <= range ? phase : period - phase + } + + /// Color bars over the top two thirds, a grey ramp below. + private func makeBackground() -> [UInt32] { + var pixels = [UInt32](repeating: 0, count: width * height) + let barsHeight = height * 2 / 3 + for row in 0.., _ rowPixels: Int, x: Int, y: Int, w: Int, h: Int, color: UInt32) { + let x0 = max(0, x) + let y0 = max(0, y) + let x1 = min(width, x + w) + let y1 = min(height, y + h) + guard x1 > x0, y1 > y0 else { return } + for row in y0.. +// + +import BitLogger +import CoreGraphics +import CoreMedia +import CoreVideo +import Foundation +import VideoToolbox + +/// Decodes released live video units (Annex B access units) to CGImages and +/// paces them by presentation time behind a small jitter buffer, so bursty +/// mesh delivery still plays smoothly — the VideoToolbox counterpart of +/// Android's `LiveVideoDecoder`. +/// +/// - The format description is (re)built from the in-band SPS/PPS of a +/// keyframe; until the first keyframe after (re)configuration, a resync, or +/// a decoder error, delta frames are dropped instead of decoded to garbage. +/// - Frames are shown `jitterMs` behind their pts. A frame more than 1.5 s +/// late (or 3 s early) rebases the clock instead of being shown off-time. +/// +/// Threading: `submit` may be called from one serial caller queue; the other +/// methods from anywhere. Decoding and pacing run on a private serial worker +/// queue (pacing sleeps there, so the backlog stays compressed and bounded); +/// `onFrame` is delivered on the main queue. +/// `@unchecked Sendable`: shared flags are lock-protected; decoder state is +/// confined to `worker`. +final class LiveVideoH264Decoder: @unchecked Sendable { + private static let queueCapacity = 96 + private static let rebaseLateMs: Int64 = 1_500 + private static let rebaseEarlyMs: Int64 = 3_000 + + private let onFrame: (CGImage) -> Void + private let jitterMs: Int64 + private let worker = DispatchQueue(label: "chat.bitchat.video.decoder", qos: .userInitiated) + /// Signaled by `stop()` to cut a pacing wait short. + private let wake = DispatchSemaphore(value: 0) + + // Lock-protected state shared between callers and the worker. + private let lock = NSLock() + private var pending = 0 + /// Bumped by a flush; queued units from an older generation are skipped. + private var generation: UInt = 0 + private var needKeyframeFlag = false + private var stopped = false + private var finishing = false + private var width = 0 + private var height = 0 + private var decodedCount = 0 + + // Worker-confined state. + private var session: VTDecompressionSession? + private var format: CMVideoFormatDescription? + private var formatParameters: (sps: Data, pps: Data)? + private var configuredSize = (width: 0, height: 0) + private var needKeyframe = true + private var baseMs: Int64? + + var framesDecoded: Int { + lock.withLock { decodedCount } + } + + init(onFrame: @escaping (CGImage) -> Void, jitterMs: Int64 = 350) { + self.onFrame = onFrame + self.jitterMs = jitterMs + } + + deinit { + if let session { VTDecompressionSessionInvalidate(session) } + } + + /// Sets the stream's picture size (from START). A size change waits for + /// the next keyframe before decoding again. + func configure(width: Int, height: Int) { + lock.withLock { + guard width != self.width || height != self.height else { return } + self.width = width + self.height = height + needKeyframeFlag = true + } + } + + func submit(annexB: Data, ptsMs: Int64, keyframe: Bool) { + let ticket: UInt? = lock.withLock { + guard !stopped, !finishing else { return nil } + if pending >= Self.queueCapacity { + // Falling behind: drop the backlog and resume at a keyframe. + generation &+= 1 + pending = 0 + needKeyframeFlag = true + guard keyframe else { return nil } + } + pending += 1 + return generation + } + guard let ticket else { return } + worker.async { [self] in + let current: Bool = lock.withLock { + guard ticket == generation else { return false } + pending = max(0, pending - 1) + return !stopped + } + guard current else { return } + process(annexB: annexB, ptsMs: ptsMs, keyframe: keyframe) + } + } + + /// After units were withheld (app in background), restart cleanly at the + /// next keyframe. + func resyncAtKeyframe() { + lock.withLock { + generation &+= 1 + pending = 0 + needKeyframeFlag = true + } + } + + /// Lets every already-submitted unit decode and present, then releases the + /// decoder. Later submits are ignored. + func finishAfterDrain() { + lock.withLock { finishing = true } + worker.async { [self] in + releaseSession() + } + } + + /// Stops immediately: pending units are discarded and no further frames + /// are delivered. + func stop() { + let wasStopped = lock.withLock { + let was = stopped + stopped = true + generation &+= 1 + pending = 0 + return was + } + guard !wasStopped else { return } + wake.signal() + worker.async { [self] in + releaseSession() + } + } + + // MARK: - Worker queue + + private func process(annexB: Data, ptsMs: Int64, keyframe: Bool) { + let (size, resync) = lock.withLock { () -> ((width: Int, height: Int), Bool) in + let resync = needKeyframeFlag + needKeyframeFlag = false + return ((width, height), resync) + } + if resync { needKeyframe = true } + if needKeyframe && !keyframe { return } + + let units = LiveVideoAVCC.nalUnits(inAnnexB: annexB) + guard !units.isEmpty else { return } + + if keyframe { + if let sets = LiveVideoAVCC.parameterSets(in: units) { + let changed = formatParameters.map { $0.sps != sets.sps || $0.pps != sets.pps } ?? true + if session == nil || changed || size != configuredSize { + guard rebuildSession(sps: sets.sps, pps: sets.pps) else { return } + configuredSize = size + } + } + guard session != nil else { return } + needKeyframe = false + } + guard let session, let format else { return } + + let slices = units.filter { + let type = LiveVideoAVCC.nalType($0) + return type != LiveVideoAVCC.typeSPS && type != LiveVideoAVCC.typePPS + && type != LiveVideoAVCC.typeAUD && type != LiveVideoAVCC.typeFiller + } + guard !slices.isEmpty, + let sample = LiveVideoAVCC.sampleBuffer( + avcc: LiveVideoAVCC.avccSample(from: slices), + format: format, + pts: CMTime(value: ptsMs, timescale: 1_000), + keyframe: keyframe + ) + else { return } + + // Synchronous decode (no async flag): the handler runs before return. + var decoded: CGImage? + var decodeError: OSStatus = noErr + let status = VTDecompressionSessionDecodeFrame( + session, + sampleBuffer: sample, + flags: [], + infoFlagsOut: nil + ) { status, _, imageBuffer, _, _ in + guard status == noErr, let imageBuffer else { + decodeError = status + return + } + var image: CGImage? + VTCreateCGImageFromCVPixelBuffer(imageBuffer, options: nil, imageOut: &image) + decoded = image + } + if status != noErr || decodeError != noErr { + let code = status != noErr ? status : decodeError + SecureLogger.debug("Live video: decode error \(code); waiting for next keyframe", category: .session) + // Also covers kVTInvalidSessionErr after an iOS background + // transition: the session is rebuilt at the next keyframe. + releaseSession() + needKeyframe = true + return + } + guard let decoded else { return } + present(decoded, ptsMs: ptsMs) + } + + private func present(_ image: CGImage, ptsMs: Int64) { + let now = Self.nowMs() + var base = baseMs ?? (now - ptsMs + jitterMs) + var due = base + ptsMs + if due < now - Self.rebaseLateMs || due > now + Self.rebaseEarlyMs { + base = now - ptsMs + jitterMs + due = base + ptsMs + } + baseMs = base + let wait = min(due - now, Self.rebaseEarlyMs) + if wait > 0 { + // Woken early only by stop(). + _ = wake.wait(timeout: .now() + .milliseconds(Int(wait))) + } + let deliver: Bool = lock.withLock { + guard !stopped else { return false } + decodedCount += 1 + return true + } + guard deliver else { return } + DispatchQueue.main.async { [self] in + guard !lock.withLock({ stopped }) else { return } + onFrame(image) + } + } + + private func rebuildSession(sps: Data, pps: Data) -> Bool { + releaseSession() + guard let description = LiveVideoAVCC.formatDescription(sps: sps, pps: pps) else { + SecureLogger.debug("Live video: invalid SPS/PPS", category: .session) + return false + } + let attributes: [CFString: Any] = [ + kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_32BGRA, + kCVPixelBufferIOSurfacePropertiesKey: [String: Any]() + ] + var created: VTDecompressionSession? + let status = VTDecompressionSessionCreate( + allocator: kCFAllocatorDefault, + formatDescription: description, + decoderSpecification: nil, + imageBufferAttributes: attributes as CFDictionary, + outputCallback: nil, + decompressionSessionOut: &created + ) + guard status == noErr, let created else { + SecureLogger.error("Live video: decoder creation failed (\(status))", category: .session) + return false + } + VTSessionSetProperty(created, key: kVTDecompressionPropertyKey_RealTime, value: kCFBooleanTrue) + session = created + format = description + formatParameters = (sps, pps) + return true + } + + private func releaseSession() { + if let session { + VTDecompressionSessionInvalidate(session) + } + session = nil + format = nil + formatParameters = nil + } + + private static func nowMs() -> Int64 { + Int64(DispatchTime.now().uptimeNanoseconds / 1_000_000) + } +} diff --git a/bitchat/Features/video/LiveVideoH264Encoder.swift b/bitchat/Features/video/LiveVideoH264Encoder.swift new file mode 100644 index 00000000..0ce8d223 --- /dev/null +++ b/bitchat/Features/video/LiveVideoH264Encoder.swift @@ -0,0 +1,288 @@ +// +// LiveVideoH264Encoder.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import BitLogger +import CoreMedia +import CoreVideo +import Foundation +import VideoToolbox + +/// One encoded H.264 access unit, ready for the wire: Annex B with 4-byte +/// start codes, and on keyframes prefixed with SPS + PPS so any keyframe can +/// start a decoder (viewers join mid-stream). +struct LiveVideoEncodedFrame { + let annexB: Data + let ptsUs: Int64 + let keyframe: Bool +} + +/// Real-time H.264 Constrained Baseline encoder for live video, the +/// VideoToolbox counterpart of Android's `H264Encoder`. +/// +/// Any input picture (camera NV12, synthetic BGRA, any size) is center-cropped +/// and scaled to `width`×`height` NV12 through a pixel transfer session into a +/// pooled buffer before encoding, so callers never resize themselves. +/// +/// Threading: `encode`/`setBitrate`/`requestKeyframe`/`finish`/`invalidate` +/// may be called from any thread (session state is lock-protected); `onFrame` +/// is always called on the encoder's private serial queue, in output order. +/// `@unchecked Sendable`: mutable state is guarded by `lock` or confined to +/// `callbackQueue`. +final class LiveVideoH264Encoder: @unchecked Sendable { + enum EncoderError: Error { + case invalidDimensions + case sessionCreationFailed(OSStatus) + case pixelTransferUnavailable(OSStatus) + } + + let width: Int + let height: Int + let fps: Int + + /// Called on the encoder's serial queue with each encoded access unit. + var onFrame: ((LiveVideoEncodedFrame) -> Void)? + + private let callbackQueue = DispatchQueue(label: "chat.bitchat.video.encoder", qos: .userInitiated) + private let lock = NSLock() + + // Lock-protected state. + private var session: VTCompressionSession? + private var transfer: VTPixelTransferSession? + private var pool: CVPixelBufferPool? + private var forceKeyframe = false + private var lastPtsUs: Int64 = .min + private(set) var currentBitrate: Int + + init(width: Int, height: Int, fps: Int, bitrate: Int, keyframeIntervalSeconds: Int) throws { + guard width >= 16, height >= 16, width % 2 == 0, height % 2 == 0, fps > 0 else { + throw EncoderError.invalidDimensions + } + self.width = width + self.height = height + self.fps = fps + self.currentBitrate = bitrate + + var created: VTCompressionSession? + let status = VTCompressionSessionCreate( + allocator: kCFAllocatorDefault, + width: Int32(width), + height: Int32(height), + codecType: kCMVideoCodecType_H264, + encoderSpecification: nil, + imageBufferAttributes: Self.pixelBufferAttributes(width: width, height: height) as CFDictionary, + compressedDataAllocator: nil, + outputCallback: nil, + refcon: nil, + compressionSessionOut: &created + ) + guard status == noErr, let session = created else { + throw EncoderError.sessionCreationFailed(status) + } + + Self.set(session, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue) + // Constrained Baseline is what every Android decoder accepts; older + // OS encoders that lack the constant fall back to plain Baseline. + if VTSessionSetProperty(session, key: kVTCompressionPropertyKey_ProfileLevel, value: kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel) != noErr { + Self.set(session, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_Baseline_AutoLevel) + } + Self.set(session, kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse) + Self.set(session, kVTCompressionPropertyKey_MaxKeyFrameInterval, NSNumber(value: max(1, fps * keyframeIntervalSeconds))) + Self.set(session, kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, NSNumber(value: max(1, keyframeIntervalSeconds))) + Self.set(session, kVTCompressionPropertyKey_ExpectedFrameRate, NSNumber(value: fps)) + Self.applyBitrate(bitrate, to: session) + VTCompressionSessionPrepareToEncodeFrames(session) + + var transferSession: VTPixelTransferSession? + let transferStatus = VTPixelTransferSessionCreate(allocator: kCFAllocatorDefault, pixelTransferSessionOut: &transferSession) + guard transferStatus == noErr, let transferSession else { + VTCompressionSessionInvalidate(session) + throw EncoderError.pixelTransferUnavailable(transferStatus) + } + // Trim = preserve aspect ratio and crop to fill: a center crop. + Self.set(transferSession, kVTPixelTransferPropertyKey_ScalingMode, kVTScalingMode_Trim) + + var createdPool: CVPixelBufferPool? + CVPixelBufferPoolCreate( + kCFAllocatorDefault, + [kCVPixelBufferPoolMinimumBufferCountKey: 3] as CFDictionary, + Self.pixelBufferAttributes(width: width, height: height) as CFDictionary, + &createdPool + ) + + self.session = session + self.transfer = transferSession + self.pool = createdPool + } + + deinit { + invalidate() + } + + /// Encodes one picture. `ptsUs` must increase; frames at or before the + /// previous timestamp are dropped (VideoToolbox rejects them anyway). + func encode(_ pixelBuffer: CVPixelBuffer, ptsUs: Int64) { + lock.lock() + defer { lock.unlock() } + guard let session, ptsUs > lastPtsUs else { return } + guard let input = prepare(pixelBuffer) else { return } + lastPtsUs = ptsUs + + var properties: CFDictionary? + if forceKeyframe { + forceKeyframe = false + properties = [kVTEncodeFrameOptionKey_ForceKeyFrame: kCFBooleanTrue] as CFDictionary + } + let status = VTCompressionSessionEncodeFrame( + session, + imageBuffer: input, + presentationTimeStamp: CMTime(value: ptsUs, timescale: 1_000_000), + duration: CMTime(value: 1, timescale: CMTimeScale(fps)), + frameProperties: properties, + infoFlagsOut: nil + ) { [weak self] status, flags, sample in + self?.handleOutput(status: status, flags: flags, sample: sample) + } + if status != noErr { + SecureLogger.error("Live video: encode failed (\(status))", category: .session) + } + } + + /// Changes the target bitrate of the running session (congestion control). + func setBitrate(_ bitrate: Int) { + lock.lock() + defer { lock.unlock() } + guard bitrate > 0, bitrate != currentBitrate, let session else { return } + currentBitrate = bitrate + Self.applyBitrate(bitrate, to: session) + } + + /// The next encoded picture will be an IDR. + func requestKeyframe() { + lock.lock() + forceKeyframe = true + lock.unlock() + } + + /// Flushes every pending frame and waits until `onFrame` has seen them all. + func finish() { + lock.lock() + if let session { + VTCompressionSessionCompleteFrames(session, untilPresentationTimeStamp: .invalid) + } + lock.unlock() + // Output handlers hop to callbackQueue; draining it delivers the tail. + callbackQueue.sync {} + } + + /// Tears the session down; pending output is discarded. Idempotent. + func invalidate() { + lock.lock() + let session = self.session + let transfer = self.transfer + self.session = nil + self.transfer = nil + self.pool = nil + lock.unlock() + if let session { VTCompressionSessionInvalidate(session) } + if let transfer { VTPixelTransferSessionInvalidate(transfer) } + } + + // MARK: - Private + + /// Returns `pixelBuffer` itself when it already matches the encoder, else + /// a pooled NV12 copy center-cropped/scaled to width×height. + private func prepare(_ pixelBuffer: CVPixelBuffer) -> CVPixelBuffer? { + let format = CVPixelBufferGetPixelFormatType(pixelBuffer) + if CVPixelBufferGetWidth(pixelBuffer) == width, + CVPixelBufferGetHeight(pixelBuffer) == height, + format == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange || format == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange { + return pixelBuffer + } + guard let transfer else { return nil } + var output: CVPixelBuffer? + if let pool { + CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool, &output) + } + if output == nil { + CVPixelBufferCreate( + kCFAllocatorDefault, + width, + height, + kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, + Self.pixelBufferAttributes(width: width, height: height) as CFDictionary, + &output + ) + } + guard let output else { return nil } + let status = VTPixelTransferSessionTransferImage(transfer, from: pixelBuffer, to: output) + guard status == noErr else { + SecureLogger.error("Live video: pixel transfer failed (\(status))", category: .session) + return nil + } + return output + } + + /// Runs on a VideoToolbox thread; converts synchronously (the sample's + /// memory belongs to the encoder) and hands the frame to the serial queue. + private func handleOutput(status: OSStatus, flags: VTEncodeInfoFlags, sample: CMSampleBuffer?) { + guard status == noErr, !flags.contains(.frameDropped), let sample else { + if status != noErr { + SecureLogger.error("Live video: encoder output error (\(status))", category: .session) + } + return + } + guard let frame = Self.annexBFrame(from: sample) else { return } + callbackQueue.async { [weak self] in + self?.onFrame?(frame) + } + } + + static func annexBFrame(from sample: CMSampleBuffer) -> LiveVideoEncodedFrame? { + guard CMSampleBufferDataIsReady(sample), + let format = CMSampleBufferGetFormatDescription(sample), + let data = LiveVideoAVCC.data(of: sample), + let parameters = LiveVideoAVCC.parameterSets(of: format) + else { return nil } + let keyframe = LiveVideoAVCC.isSync(sample) + var units = LiveVideoAVCC.nalUnits(inAVCC: data, lengthSize: parameters.lengthSize) + .filter { LiveVideoAVCC.nalType($0) != LiveVideoAVCC.typeFiller } + guard !units.isEmpty else { return nil } + if keyframe { + // In-band SPS/PPS let a viewer start at any keyframe. + units.removeAll { [LiveVideoAVCC.typeSPS, LiveVideoAVCC.typePPS].contains(LiveVideoAVCC.nalType($0)) } + units.insert(contentsOf: parameters.sets, at: 0) + } + let pts = CMSampleBufferGetPresentationTimeStamp(sample) + let ptsUs = pts.isValid ? CMTimeConvertScale(pts, timescale: 1_000_000, method: .roundHalfAwayFromZero).value : 0 + return LiveVideoEncodedFrame(annexB: LiveVideoAVCC.annexB(from: units), ptsUs: ptsUs, keyframe: keyframe) + } + + private static func applyBitrate(_ bitrate: Int, to session: VTCompressionSession) { + set(session, kVTCompressionPropertyKey_AverageBitRate, NSNumber(value: bitrate)) + // Cap each one-second window at 1.5x the average: the mesh link has no + // spare capacity for the bursts unconstrained VBR produces. + let bytesPerSecond = max(1, bitrate * 3 / 2 / 8) + set(session, kVTCompressionPropertyKey_DataRateLimits, [NSNumber(value: bytesPerSecond), NSNumber(value: 1)] as CFArray) + } + + private static func set(_ session: VTSession, _ key: CFString, _ value: CFTypeRef?) { + let status = VTSessionSetProperty(session, key: key, value: value) + if status != noErr { + SecureLogger.debug("Live video: VideoToolbox rejected \(key) (\(status))", category: .session) + } + } + + private static func pixelBufferAttributes(width: Int, height: Int) -> [CFString: Any] { + [ + kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, + kCVPixelBufferWidthKey: width, + kCVPixelBufferHeightKey: height, + kCVPixelBufferIOSurfacePropertiesKey: [String: Any]() + ] + } +} diff --git a/bitchat/Features/video/LiveVideoMp4Segments.swift b/bitchat/Features/video/LiveVideoMp4Segments.swift new file mode 100644 index 00000000..f13f873b --- /dev/null +++ b/bitchat/Features/video/LiveVideoMp4Segments.swift @@ -0,0 +1,329 @@ +// +// LiveVideoMp4Segments.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import AVFoundation +import BitLogger +import CoreMedia +import Foundation + +/// Joins recordings of one live stream that a viewer captured across +/// dropouts — the counterpart of Android's `Mp4Segments`. +/// +/// Every segment comes from the same sender encoder, so samples are copied +/// without re-encoding (AVAssetReader passthrough -> AVAssetWriter +/// passthrough). Each segment is placed at its offset on the sender's clock +/// (its first video pts), and the last video sample before a dropout is given +/// a duration that reaches the next segment, so the dropout plays back as a +/// held frame. Audio is bridged with encoded silence for the same span. +/// +/// Why a sample remux instead of `AVMutableComposition` + passthrough export: +/// a composition can only express the gap as an empty edit (a black/blank +/// stretch in most players) or a scaled edit (an edit list with a non-unit +/// rate, which passthrough export and Android's extractors handle poorly). +/// Extending the last sample's duration encodes the freeze in plain sample +/// timing that every player honors, with no edit lists at all. +enum LiveVideoMp4Segments { + private struct Sample { + let buffer: CMSampleBuffer + let isVideo: Bool + /// First pts of the buffer, on the joined timeline once placed. + let ptsUs: Int64 + /// End of the buffer's last sample (pts + duration), same timeline. + let endUs: Int64 + /// Offset added to the buffer's own timestamps when it is written. + var shiftUs: Int64 = 0 + } + + /// `segments` pairs each file with its first video timestamp on the + /// sender's clock (microseconds). Returns false when nothing usable was + /// read or the output could not be written. + static func join(_ segments: [(url: URL, firstVideoPtsUs: Int64)], to output: URL) async -> Bool { + guard !segments.isEmpty else { return false } + var loaded: [(asset: AVURLAsset, tracks: SegmentTracks, firstPtsUs: Int64)] = [] + for (url, firstPtsUs) in segments { + let asset = AVURLAsset(url: url) + guard let tracks = await loadTracks(asset) else { + SecureLogger.debug("Live video: skipping unreadable segment", category: .session) + continue + } + loaded.append((asset, tracks, firstPtsUs)) + } + guard !loaded.isEmpty else { return false } + let baseUs = segments[0].firstVideoPtsUs + // Reading and writing block on the media pipeline (and poll writer + // readiness), so they run on a dispatch queue, not the async pool. + let segmentsToJoin = loaded + return await withCheckedContinuation { continuation in + DispatchQueue.global(qos: .utility).async { + continuation.resume(returning: joinSynchronously(segmentsToJoin, baseUs: baseUs, to: output)) + } + } + } + + private struct SegmentTracks { + let video: AVAssetTrack + let videoFormat: CMFormatDescription? + let audio: AVAssetTrack? + let audioFormat: CMFormatDescription? + } + + private static func loadTracks(_ asset: AVURLAsset) async -> SegmentTracks? { + guard let video = try? await asset.loadTracks(withMediaType: .video).first else { return nil } + let audio = try? await asset.loadTracks(withMediaType: .audio).first + let videoFormat = try? await video.load(.formatDescriptions).first + var audioFormat: CMFormatDescription? + if let audio { + audioFormat = try? await audio.load(.formatDescriptions).first + } + return SegmentTracks(video: video, videoFormat: videoFormat, audio: audio, audioFormat: audioFormat) + } + + private static func joinSynchronously( + _ segments: [(asset: AVURLAsset, tracks: SegmentTracks, firstPtsUs: Int64)], + baseUs: Int64, + to output: URL + ) -> Bool { + var videoFormat: CMFormatDescription? + var audioFormat: CMFormatDescription? + var samples: [Sample] = [] + var lastEndUs: Int64 = -1 + + for (asset, tracks, firstPtsUs) in segments { + guard let segment = readSegment(asset, tracks: tracks), !segment.isEmpty else { + SecureLogger.debug("Live video: skipping unreadable segment", category: .session) + continue + } + if videoFormat == nil { videoFormat = tracks.videoFormat } + if audioFormat == nil { audioFormat = tracks.audioFormat } + // Rebase the segment to its own start, place it on the sender's + // clock, and never let it overlap the previous one. + let segmentStart = segment.map(\.ptsUs).min() ?? 0 + let offsetUs = max(firstPtsUs - baseUs, lastEndUs + 1) + let shiftUs = offsetUs - segmentStart + var segmentEnd = offsetUs + for sample in segment { + samples.append(Sample( + buffer: sample.buffer, + isVideo: sample.isVideo, + ptsUs: sample.ptsUs + shiftUs, + endUs: sample.endUs + shiftUs, + shiftUs: shiftUs + )) + // Video sample durations are re-derived when writing, so only + // a video sample's start bounds the segment; audio counts in full. + segmentEnd = max(segmentEnd, sample.isVideo ? sample.ptsUs + shiftUs : sample.endUs + shiftUs) + } + lastEndUs = segmentEnd + } + guard let videoFormat, samples.contains(where: \.isVideo) else { return false } + samples.sort { $0.ptsUs < $1.ptsUs } + return write(samples, videoFormat: videoFormat, audioFormat: audioFormat, to: output) + } + + /// Reads every compressed sample of the segment. Each track gets its own + /// reader, so draining video first can never stall on unread audio. + private static func readSegment(_ asset: AVURLAsset, tracks: SegmentTracks) -> [Sample]? { + guard let video = readTrack(asset, track: tracks.video, isVideo: true) else { return nil } + let audio = tracks.audio.flatMap { readTrack(asset, track: $0, isVideo: false) } ?? [] + return video + audio + } + + private static func readTrack(_ asset: AVURLAsset, track: AVAssetTrack, isVideo: Bool) -> [Sample]? { + guard let reader = try? AVAssetReader(asset: asset) else { return nil } + // Passthrough (nil settings): compressed samples, attachments intact. + let output = AVAssetReaderTrackOutput(track: track, outputSettings: nil) + output.alwaysCopiesSampleData = false + guard reader.canAdd(output) else { return nil } + reader.add(output) + guard reader.startReading() else { return nil } + + var samples: [Sample] = [] + while let buffer = output.copyNextSampleBuffer() { + // Passthrough readers also emit zero-sample marker buffers. + guard CMSampleBufferGetNumSamples(buffer) > 0 else { continue } + let pts = CMSampleBufferGetPresentationTimeStamp(buffer) + guard pts.isNumeric else { continue } + let duration = CMSampleBufferGetDuration(buffer) + let ptsUs = microseconds(pts) + let endUs = duration.isNumeric ? ptsUs + microseconds(duration) : ptsUs + samples.append(Sample(buffer: buffer, isVideo: isVideo, ptsUs: ptsUs, endUs: endUs)) + } + guard reader.status != .failed else { return nil } + return samples + } + + private static func microseconds(_ time: CMTime) -> Int64 { + CMTimeConvertScale(time, timescale: 1_000_000, method: .roundHalfAwayFromZero).value + } + + private static func write( + _ samples: [Sample], + videoFormat: CMFormatDescription, + audioFormat: CMFormatDescription?, + to output: URL + ) -> Bool { + try? FileManager.default.removeItem(at: output) + guard let writer = try? AVAssetWriter(outputURL: output, fileType: .mp4) else { return false } + // Samples arrive already sorted by time, so the writer's own + // interleaving gate only gets in the way: across a dropout one track + // has nothing to offer for seconds, and a non-real-time input would + // stall waiting for it. Real-time inputs skip that gate. + let videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: nil, sourceFormatHint: videoFormat) + videoInput.expectsMediaDataInRealTime = true + writer.add(videoInput) + var audioInput: AVAssetWriterInput? + if let audioFormat { + let input = AVAssetWriterInput(mediaType: .audio, outputSettings: nil, sourceFormatHint: audioFormat) + input.expectsMediaDataInRealTime = true + if writer.canAdd(input) { + writer.add(input) + audioInput = input + } + } + guard writer.startWriting() else { return false } + let firstUs = samples[0].ptsUs + writer.startSession(atSourceTime: CMTime(value: firstUs, timescale: 1_000_000)) + + let videoSamples = samples.filter(\.isVideo) + var nextVideoPts: [Int: Int64] = [:] + for index in videoSamples.indices.dropLast() { + nextVideoPts[index] = videoSamples[index + 1].ptsUs + } + var videoIndex = 0 + var lastVideoDuration: Int64 = 66_666 + var lastPts: [Bool: Int64] = [true: .min, false: .min] + var endUs = firstUs + var wroteVideo = false + var nextAudioUs: Int64? + // Silence filler only fits the live format (AAC-LC 16 kHz mono). + let silence = audioFormat.flatMap { isLiveAudioFormat($0) ? LiveVideoMp4Writer.silentAACFrame : nil } + + for sample in samples { + guard sample.ptsUs > lastPts[sample.isVideo, default: .min] else { + if sample.isVideo { videoIndex += 1 } + continue + } + let input: AVAssetWriterInput + // Shift every entry by the segment offset: passthrough audio + // buffers carry several AAC packets, each with its own timing. + var timings = timingEntries(of: sample.buffer).map { entry -> CMSampleTimingInfo in + var shifted = entry + shifted.presentationTimeStamp = shift(entry.presentationTimeStamp, byUs: sample.shiftUs) + shifted.decodeTimeStamp = shift(entry.decodeTimeStamp, byUs: sample.shiftUs) + return shifted + } + guard !timings.isEmpty else { continue } + if sample.isVideo { + input = videoInput + // Held frame: a video sample lasts until the next one, which + // spans any dropout between segments. + if let next = nextVideoPts[videoIndex], next > sample.ptsUs { + lastVideoDuration = next - sample.ptsUs + } + if timings.count == 1 { + timings[0].duration = CMTime(value: lastVideoDuration, timescale: 1_000_000) + } + videoIndex += 1 + } else { + guard let audioInput else { continue } + input = audioInput + // The writer packs audio back to back, so a dropout between + // segments must be held with silence or the later segment's + // audio would play early against its picture. + if let expectedStart = nextAudioUs, let silence, let audioFormat { + let frameUs = LiveVideoMp4Writer.audioFrameDurationUs + var expected = expectedStart + var inserted = 0 + while sample.ptsUs - expected >= frameUs / 2, inserted < maxSilenceFrames { + guard let filler = LiveVideoMp4Writer.audioSample(silence, ptsUs: expected, format: audioFormat), + waitUntilReady(audioInput, writer: writer), + audioInput.append(filler) + else { break } + expected += frameUs + inserted += 1 + } + } + } + var retimed: CMSampleBuffer? + guard CMSampleBufferCreateCopyWithNewTiming( + allocator: kCFAllocatorDefault, + sampleBuffer: sample.buffer, + sampleTimingEntryCount: timings.count, + sampleTimingArray: &timings, + sampleBufferOut: &retimed + ) == noErr, let retimed else { continue } + guard waitUntilReady(input, writer: writer), input.append(retimed) else { + if writer.status == .failed { break } + continue + } + lastPts[sample.isVideo] = sample.ptsUs + if sample.isVideo { wroteVideo = true } + let end = CMTimeAdd(CMSampleBufferGetPresentationTimeStamp(retimed), CMSampleBufferGetDuration(retimed)) + if end.isNumeric { + let bufferEndUs = microseconds(end) + endUs = max(endUs, bufferEndUs) + if !sample.isVideo { nextAudioUs = bufferEndUs } + } + } + + guard wroteVideo, writer.status == .writing else { + SecureLogger.error("Live video: segment join failed: \(writer.error?.localizedDescription ?? "no video")", category: .session) + writer.cancelWriting() + try? FileManager.default.removeItem(at: output) + return false + } + videoInput.markAsFinished() + audioInput?.markAsFinished() + writer.endSession(atSourceTime: CMTime(value: endUs, timescale: 1_000_000)) + let done = DispatchSemaphore(value: 0) + writer.finishWriting { done.signal() } + done.wait() + guard writer.status == .completed else { + try? FileManager.default.removeItem(at: output) + return false + } + return true + } + + /// Longest dropout bridged with silence (~2 min, beyond the 90 s at which + /// a silent stream closes). + private static let maxSilenceFrames = 2_000 + + private static func isLiveAudioFormat(_ format: CMFormatDescription) -> Bool { + guard let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(format)?.pointee else { return false } + return asbd.mFormatID == kAudioFormatMPEG4AAC + && asbd.mSampleRate == PTTAudioFormat.sampleRate + && asbd.mChannelsPerFrame == PTTAudioFormat.channelCount + } + + private static func timingEntries(of buffer: CMSampleBuffer) -> [CMSampleTimingInfo] { + var count = 0 + guard CMSampleBufferGetSampleTimingInfoArray(buffer, entryCount: 0, arrayToFill: nil, entriesNeededOut: &count) == noErr, + count > 0 + else { return [] } + var entries = [CMSampleTimingInfo](repeating: CMSampleTimingInfo(), count: count) + guard CMSampleBufferGetSampleTimingInfoArray(buffer, entryCount: count, arrayToFill: &entries, entriesNeededOut: &count) == noErr else { + return [] + } + return entries + } + + private static func shift(_ time: CMTime, byUs shiftUs: Int64) -> CMTime { + guard time.isNumeric else { return time } + return CMTimeAdd(time, CMTime(value: shiftUs, timescale: 1_000_000)) + } + + private static func waitUntilReady(_ input: AVAssetWriterInput, writer: AVAssetWriter) -> Bool { + let deadline = Date().addingTimeInterval(1) + while !input.isReadyForMoreMediaData { + guard writer.status == .writing, Date() < deadline else { return false } + Thread.sleep(forTimeInterval: 0.002) + } + return true + } +} diff --git a/bitchat/Features/video/LiveVideoMp4Writer.swift b/bitchat/Features/video/LiveVideoMp4Writer.swift new file mode 100644 index 00000000..9b05850d --- /dev/null +++ b/bitchat/Features/video/LiveVideoMp4Writer.swift @@ -0,0 +1,351 @@ +// +// LiveVideoMp4Writer.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import AVFoundation +import BitLogger +import CoreMedia +import Foundation + +/// Muxes already-encoded live video (Annex B H.264) and raw AAC-LC frames +/// into an MP4 without re-encoding — the AVAssetWriter counterpart of +/// Android's `Mp4Writer`. The sender records its own stream with it, and +/// viewers rebuild a stream from the units they received, so it tolerates +/// what a lossy mesh produces: +/// +/// - nothing is written until a keyframe carrying SPS/PPS arrives (that +/// keyframe creates the track format and starts the session at its pts); +/// earlier video and audio are dropped; +/// - samples at or before their track's previous timestamp are dropped; +/// - gaps are fine: each video sample lasts until the next one, so missing +/// frames play back as a held picture; missing audio is filled with +/// encoded silence (AVAssetWriter would otherwise close audio gaps and +/// drift the sound ahead of the picture). +/// +/// Threading: call from one serial queue (methods are also lock-protected, +/// so a stray call from elsewhere cannot corrupt state). +final class LiveVideoMp4Writer { + /// How long a real-time append may wait for the writer before dropping. + private static let readyTimeout: TimeInterval = 0.25 + /// Duration given to the final video sample, which has no successor. + private static let fallbackFrameDurationUs: Int64 = 66_666 + + let url: URL + private let hasAudio: Bool + private let lock = NSLock() + + private var writer: AVAssetWriter? + private var videoInput: AVAssetWriterInput? + private var audioInput: AVAssetWriterInput? + private var videoFormat: CMVideoFormatDescription? + private var videoParameters: (sps: Data, pps: Data)? + private var audioFormat: CMAudioFormatDescription? + private var failed = false + private var finished = false + + /// One-sample lookahead: a video sample's duration is the distance to the + /// next one, so it is appended when its successor arrives. + private var pendingVideo: (avcc: Data, ptsUs: Int64, keyframe: Bool)? + private var lastVideoPtsUs: Int64 = .min + private var lastAudioPtsUs: Int64 = .min + private var lastVideoDurationUs: Int64 = fallbackFrameDurationUs + private var startPtsUs: Int64 = 0 + private var endPtsUs: Int64 = 0 + + private(set) var videoSamples = 0 + private(set) var audioSamples = 0 + + init(url: URL, hasAudio: Bool) { + self.url = url + self.hasAudio = hasAudio + } + + func writeVideo(annexB: Data, ptsUs: Int64, keyframe: Bool) { + lock.lock() + defer { lock.unlock() } + guard !failed, !finished, ptsUs > lastVideoPtsUs else { return } + let units = LiveVideoAVCC.nalUnits(inAnnexB: annexB) + guard !units.isEmpty else { return } + + if writer == nil { + // MP4 needs the first video sample to be a sync sample and the + // track format up front: wait for a self-contained keyframe. + guard keyframe, let sets = LiveVideoAVCC.parameterSets(in: units) else { return } + guard start(sps: sets.sps, pps: sets.pps, ptsUs: ptsUs) else { return } + } + + // Parameter sets live in the track format. Keep them in-band only if + // the encoder changed them mid-stream, so the sample stays decodable. + let inBandSetsMatch = LiveVideoAVCC.parameterSets(in: units).map { + $0.sps == videoParameters?.sps && $0.pps == videoParameters?.pps + } ?? true + let kept = units.filter { nal in + switch LiveVideoAVCC.nalType(nal) { + case LiveVideoAVCC.typeAUD, LiveVideoAVCC.typeFiller: + return false + case LiveVideoAVCC.typeSPS, LiveVideoAVCC.typePPS: + return !inBandSetsMatch + default: + return true + } + } + guard !kept.isEmpty else { return } + + if let previous = pendingVideo { + let duration = ptsUs - previous.ptsUs + appendVideo(previous, durationUs: duration) + lastVideoDurationUs = duration + } + pendingVideo = (LiveVideoAVCC.avccSample(from: kept), ptsUs, keyframe) + lastVideoPtsUs = ptsUs + } + + /// Raw AAC-LC 16 kHz mono access unit (no ADTS), 1024 samples long. + func writeAudio(aac: Data, ptsUs: Int64) { + lock.lock() + defer { lock.unlock() } + guard hasAudio, !failed, !finished, !aac.isEmpty, + let writer, writer.status == .writing, + let audioInput, let audioFormat, + ptsUs >= startPtsUs, ptsUs > lastAudioPtsUs + else { return } + + // AVAssetWriter packs passthrough audio back to back and ignores + // timestamp gaps, so units lost on the mesh would pull all later + // audio early against the picture. Hold the timeline with silence. + let frameUs = Self.audioFrameDurationUs + if lastAudioPtsUs != .min, let silence = Self.silentAACFrame { + var expected = lastAudioPtsUs + frameUs + var inserted = 0 + while ptsUs - expected >= frameUs / 2, inserted < Self.maxSilenceFrames { + guard let filler = Self.audioSample(silence, ptsUs: expected, format: audioFormat), + append(filler, to: audioInput) + else { break } + expected += frameUs + inserted += 1 + } + } + + guard let sample = Self.audioSample(aac, ptsUs: ptsUs, format: audioFormat), + append(sample, to: audioInput) + else { return } + lastAudioPtsUs = ptsUs + audioSamples += 1 + endPtsUs = max(endPtsUs, ptsUs + frameUs) + } + + /// Finalizes the file synchronously. Returns false (and deletes the file) + /// when no video was written or the writer failed. + @discardableResult + func finish() -> Bool { + lock.lock() + defer { lock.unlock() } + guard !finished else { return false } + finished = true + guard let writer else { return false } + + if let last = pendingVideo { + appendVideo(last, durationUs: lastVideoDurationUs) + pendingVideo = nil + } + guard !failed, writer.status == .writing, videoSamples > 0 else { + writer.cancelWriting() + try? FileManager.default.removeItem(at: url) + return false + } + videoInput?.markAsFinished() + audioInput?.markAsFinished() + writer.endSession(atSourceTime: CMTime(value: max(endPtsUs, startPtsUs + 1), timescale: 1_000_000)) + + let done = DispatchSemaphore(value: 0) + writer.finishWriting { done.signal() } + done.wait() + guard writer.status == .completed else { + SecureLogger.error("Live video: MP4 finalize failed: \(writer.error?.localizedDescription ?? "unknown")", category: .session) + try? FileManager.default.removeItem(at: url) + return false + } + return true + } + + // MARK: - Private + + static var audioFrameDurationUs: Int64 { + Int64(PTTAudioFormat.samplesPerFrame) * 1_000_000 / Int64(PTTAudioFormat.sampleRate) + } + + /// Longest audio gap bridged with silence (~2 min); longer dropouts end + /// the recording segment anyway. + private static let maxSilenceFrames = 2_000 + + /// One steady-state AAC-LC frame of digital silence (a few bytes), + /// encoded once with the live-voice encoder. + static let silentAACFrame: Data? = { + guard let encoder = PTTFrameEncoder(), let format = PTTAudioFormat.pcmFormat else { return nil } + var frames: [Data] = [] + // Run past the encoder's priming so the frame is a plain silent one. + for _ in 0..<4 { + guard let pcm = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: PTTAudioFormat.samplesPerFrame) else { return nil } + pcm.frameLength = PTTAudioFormat.samplesPerFrame + if let channel = pcm.floatChannelData?[0] { + channel.update(repeating: 0, count: Int(pcm.frameLength)) + } + frames.append(contentsOf: encoder.encode(pcm)) + } + return frames.last + }() + + /// Wraps one raw AAC frame in a ready sample buffer. + static func audioSample(_ aac: Data, ptsUs: Int64, format: CMAudioFormatDescription) -> CMSampleBuffer? { + guard let block = LiveVideoAVCC.blockBuffer(copying: aac) else { return nil } + var packet = AudioStreamPacketDescription(mStartOffset: 0, mVariableFramesInPacket: 0, mDataByteSize: UInt32(aac.count)) + var sample: CMSampleBuffer? + let status = CMAudioSampleBufferCreateReadyWithPacketDescriptions( + allocator: kCFAllocatorDefault, + dataBuffer: block, + formatDescription: format, + sampleCount: 1, + presentationTimeStamp: CMTime(value: ptsUs, timescale: 1_000_000), + packetDescriptions: &packet, + sampleBufferOut: &sample + ) + return status == noErr ? sample : nil + } + + private func start(sps: Data, pps: Data, ptsUs: Int64) -> Bool { + guard let format = LiveVideoAVCC.formatDescription(sps: sps, pps: pps) else { + SecureLogger.debug("Live video: MP4 writer got invalid SPS/PPS", category: .session) + return false + } + do { + try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try? FileManager.default.removeItem(at: url) + let writer = try AVAssetWriter(outputURL: url, fileType: .mp4) + let video = AVAssetWriterInput(mediaType: .video, outputSettings: nil, sourceFormatHint: format) + video.expectsMediaDataInRealTime = true + guard writer.canAdd(video) else { throw LiveVideoMp4WriterError.inputRejected } + writer.add(video) + + if hasAudio, let audioFormat = Self.makeAudioFormat() { + let audio = AVAssetWriterInput(mediaType: .audio, outputSettings: nil, sourceFormatHint: audioFormat) + audio.expectsMediaDataInRealTime = true + if writer.canAdd(audio) { + writer.add(audio) + self.audioInput = audio + self.audioFormat = audioFormat + } + } + guard writer.startWriting() else { + throw writer.error ?? LiveVideoMp4WriterError.inputRejected + } + writer.startSession(atSourceTime: CMTime(value: ptsUs, timescale: 1_000_000)) + self.writer = writer + self.videoInput = video + self.videoFormat = format + self.videoParameters = (sps, pps) + self.startPtsUs = ptsUs + self.endPtsUs = ptsUs + return true + } catch { + SecureLogger.error("Live video: MP4 writer unavailable: \(error)", category: .session) + failed = true + return false + } + } + + private func appendVideo(_ sample: (avcc: Data, ptsUs: Int64, keyframe: Bool), durationUs: Int64) { + guard let videoInput, let videoFormat, + let buffer = LiveVideoAVCC.sampleBuffer( + avcc: sample.avcc, + format: videoFormat, + pts: CMTime(value: sample.ptsUs, timescale: 1_000_000), + duration: CMTime(value: max(1, durationUs), timescale: 1_000_000), + keyframe: sample.keyframe + ) + else { return } + guard append(buffer, to: videoInput) else { return } + videoSamples += 1 + endPtsUs = max(endPtsUs, sample.ptsUs + max(1, durationUs)) + } + + private func append(_ sample: CMSampleBuffer, to input: AVAssetWriterInput) -> Bool { + guard let writer, writer.status == .writing else { + markFailedIfNeeded() + return false + } + let deadline = Date().addingTimeInterval(Self.readyTimeout) + while !input.isReadyForMoreMediaData { + guard writer.status == .writing, Date() < deadline else { + SecureLogger.debug("Live video: MP4 writer busy; dropping sample", category: .session) + markFailedIfNeeded() + return false + } + Thread.sleep(forTimeInterval: 0.002) + } + guard input.append(sample) else { + markFailedIfNeeded() + return false + } + return true + } + + private func markFailedIfNeeded() { + guard let writer, writer.status == .failed, !failed else { return } + failed = true + SecureLogger.error("Live video: MP4 writer failed: \(writer.error?.localizedDescription ?? "unknown")", category: .session) + } + + /// CoreAudio's AAC magic cookie is an MPEG-4 ES_Descriptor wrapping the + /// AudioSpecificConfig; with the bare 2-byte config AVAssetWriter writes + /// an `esds` that AVFoundation then refuses to load as a track. The + /// encoder that `PTTFrameEncoder` uses produces exactly the right cookie + /// for this format, so take it from there (raw config as last resort). + private static let aacMagicCookie: Data = { + if let pcm = PTTAudioFormat.pcmFormat, + let aac = PTTAudioFormat.aacFormat, + let converter = AVAudioConverter(from: pcm, to: aac), + let cookie = converter.magicCookie, + !cookie.isEmpty { + return cookie + } + // Object type 2 (LC), frequency index 8 (16 kHz), channel config 1. + return Data([0x14, 0x08]) + }() + + /// AAC-LC, 16 kHz, mono, 1024 frames per packet. + static func makeAudioFormat() -> CMAudioFormatDescription? { + var description = AudioStreamBasicDescription( + mSampleRate: PTTAudioFormat.sampleRate, + mFormatID: kAudioFormatMPEG4AAC, + mFormatFlags: 0, + mBytesPerPacket: 0, + mFramesPerPacket: PTTAudioFormat.samplesPerFrame, + mBytesPerFrame: 0, + mChannelsPerFrame: PTTAudioFormat.channelCount, + mBitsPerChannel: 0, + mReserved: 0 + ) + var format: CMAudioFormatDescription? + let status = aacMagicCookie.withUnsafeBytes { cookie in + CMAudioFormatDescriptionCreate( + allocator: kCFAllocatorDefault, + asbd: &description, + layoutSize: 0, + layout: nil, + magicCookieSize: cookie.count, + magicCookie: cookie.baseAddress, + extensions: nil, + formatDescriptionOut: &format + ) + } + return status == noErr ? format : nil + } +} + +enum LiveVideoMp4WriterError: Error { + case inputRejected +} diff --git a/bitchat/Features/video/VideoPosterLoader.swift b/bitchat/Features/video/VideoPosterLoader.swift new file mode 100644 index 00000000..14e79f6f --- /dev/null +++ b/bitchat/Features/video/VideoPosterLoader.swift @@ -0,0 +1,62 @@ +// +// VideoPosterLoader.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import AVFoundation +import CoreGraphics +import Foundation + +/// Poster frame + duration for video bubbles, with a small in-memory cache so +/// scrolling a chat does not re-decode every clip. +enum VideoPosterLoader { + private final class Entry { + let poster: CGImage? + let durationSeconds: Double + + init(poster: CGImage?, durationSeconds: Double) { + self.poster = poster + self.durationSeconds = durationSeconds + } + } + + /// Long edge of the generated poster, in pixels (bubbles are small). + private static let maxPosterEdge: CGFloat = 480 + + private static let cache: NSCache = { + let cache = NSCache() + cache.countLimit = 64 + return cache + }() + + static func load(url: URL) async -> (poster: CGImage?, durationSeconds: Double) { + if let cached = cache.object(forKey: url as NSURL) { + return (cached.poster, cached.durationSeconds) + } + let asset = AVURLAsset(url: url) + let duration = (try? await asset.load(.duration)).map { $0.isNumeric ? $0.seconds : 0 } ?? 0 + + let generator = AVAssetImageGenerator(asset: asset) + generator.appliesPreferredTrackTransform = true + generator.maximumSize = CGSize(width: maxPosterEdge, height: maxPosterEdge) + // Any nearby frame will do; exact seeking would decode from the + // previous keyframe for nothing. + generator.requestedTimeToleranceBefore = .positiveInfinity + generator.requestedTimeToleranceAfter = CMTime(seconds: 1, preferredTimescale: 600) + let poster = try? await generator.image(at: .zero).image + + // Only cache what was readable, so a file still being written gets a + // fresh attempt next time. + if poster != nil || duration > 0 { + cache.setObject(Entry(poster: poster, durationSeconds: duration), forKey: url as NSURL) + } + return (poster, duration) + } + + static func evict(url: URL) { + cache.removeObject(forKey: url as NSURL) + } +} diff --git a/bitchat/Features/video/VideoTranscoder.swift b/bitchat/Features/video/VideoTranscoder.swift new file mode 100644 index 00000000..e9251e2e --- /dev/null +++ b/bitchat/Features/video/VideoTranscoder.swift @@ -0,0 +1,301 @@ +// +// VideoTranscoder.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import AVFoundation +import BitLogger +import CoreMedia +import Foundation + +/// Re-encodes a recorded clip or gallery video into a small H.264/AAC MP4 +/// that fits one mesh file transfer — the counterpart of Android's +/// `VideoTranscoder`. +/// +/// The bitrate comes from the duration and byte budget; resolution and frame +/// rate follow the bitrate; the upright aspect ratio is kept in 16-pixel +/// blocks (long edge at most 320). Sources longer than 60 s are trimmed. +/// Audio is dropped when the budget cannot afford intelligible speech next to +/// the picture. If the first result is still too big, one retry runs at a +/// bitrate scaled down by the overshoot. +enum VideoTranscoder { + enum TranscodeError: Error, Equatable { + case noVideoTrack + case readerFailed(String) + case writerFailed(String) + /// Even the retry exceeded the budget. + case doesNotFit(bytes: Int, maxBytes: Int) + } + + static let maxSourceDuration: Double = 60 + private static let audioBitrate = 12_000 + private static let audioMinimumTotalBitrate = 30_000 + private static let containerHeadroom = 0.92 + private static let maxAttempts = 2 + private static let maxLongEdge = 320 + + struct Plan: Equatable { + let width: Int + let height: Int + let fps: Int + let videoBitrate: Int + let withAudio: Bool + } + + @discardableResult + static func transcode(source: URL, output: URL, maxBytes: Int = 100 * 1024) async throws -> URL { + let asset = AVURLAsset(url: source) + guard let videoTrack = try await asset.loadTracks(withMediaType: .video).first else { + throw TranscodeError.noVideoTrack + } + let audioTrack = try? await asset.loadTracks(withMediaType: .audio).first + let (naturalSize, transform) = try await videoTrack.load(.naturalSize, .preferredTransform) + let assetDuration = try await asset.load(.duration) + let sourceDuration = assetDuration.seconds + let duration = min(max(sourceDuration.isFinite ? sourceDuration : maxSourceDuration, 0.5), maxSourceDuration) + let upright = CGRect(origin: .zero, size: naturalSize).applying(transform).size + let uprightSize = CGSize(width: abs(upright.width), height: abs(upright.height)) + + var totalBits = Double(maxBytes) * 8 * containerHeadroom + var lastSize = 0 + for attempt in 1...maxAttempts { + let plan = plan(totalBits: totalBits, duration: duration, uprightSize: uprightSize, hasAudio: audioTrack != nil) + let job = Job( + asset: asset, + videoTrack: videoTrack, + audioTrack: plan.withAudio ? audioTrack : nil, + naturalSize: naturalSize, + transform: transform, + assetDuration: assetDuration, + duration: duration, + plan: plan, + output: output + ) + try await job.run() + let size = (try? FileManager.default.attributesOfItem(atPath: output.path)[.size] as? Int) ?? Int.max + SecureLogger.info("Video transcode attempt \(attempt): \(plan.width)x\(plan.height)@\(plan.fps) \(plan.videoBitrate) bps -> \(size) B", category: .session) + if size <= maxBytes { return output } + lastSize = size + totalBits *= Double(maxBytes) / Double(size) * 0.9 + } + try? FileManager.default.removeItem(at: output) + throw TranscodeError.doesNotFit(bytes: lastSize, maxBytes: maxBytes) + } + + static func plan(totalBits: Double, duration: Double, uprightSize: CGSize, hasAudio: Bool) -> Plan { + let totalBps = Int(totalBits / max(duration, 0.5)) + let withAudio = hasAudio && totalBps >= audioMinimumTotalBitrate + let videoBps = min(max(totalBps - (withAudio ? audioBitrate : 0), 6_000), 600_000) + let longSide = videoBps >= 60_000 ? maxLongEdge : 192 + let fps: Int + switch videoBps { + case 120_000...: fps = 24 + case 40_000...: fps = 15 + case 18_000...: fps = 10 + default: fps = 6 + } + let aspect = uprightSize.width / max(uprightSize.height, 1) + let width: Int + let height: Int + if aspect >= 1 { + width = longSide + height = roundTo16(Double(longSide) / aspect) + } else { + width = roundTo16(Double(longSide) * aspect) + height = longSide + } + return Plan(width: width, height: height, fps: fps, videoBitrate: videoBps, withAudio: withAudio) + } + + private static func roundTo16(_ value: Double) -> Int { + max(64, Int((value / 16).rounded()) * 16) + } + + // MARK: - One encode pass + + /// AVAssetReader (upright, scaled, frame-rate-limited through a video + /// composition) -> AVAssetWriter (H.264 Baseline + optional AAC). + private struct Job { + let asset: AVURLAsset + let videoTrack: AVAssetTrack + let audioTrack: AVAssetTrack? + let naturalSize: CGSize + let transform: CGAffineTransform + let assetDuration: CMTime + let duration: Double + let plan: Plan + let output: URL + + func run() async throws { + try? FileManager.default.removeItem(at: output) + let reader: AVAssetReader + let writer: AVAssetWriter + do { + reader = try AVAssetReader(asset: asset) + writer = try AVAssetWriter(outputURL: output, fileType: .mp4) + } catch { + throw TranscodeError.readerFailed(error.localizedDescription) + } + reader.timeRange = CMTimeRange(start: .zero, duration: CMTime(seconds: duration, preferredTimescale: 600)) + + let videoOutput = AVAssetReaderVideoCompositionOutput( + videoTracks: [videoTrack], + videoSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA] + ) + videoOutput.videoComposition = makeComposition() + videoOutput.alwaysCopiesSampleData = false + guard reader.canAdd(videoOutput) else { throw TranscodeError.readerFailed("video output rejected") } + reader.add(videoOutput) + + let videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoSettings()) + videoInput.expectsMediaDataInRealTime = false + guard writer.canAdd(videoInput) else { throw TranscodeError.writerFailed("video input rejected") } + writer.add(videoInput) + + var audioOutput: AVAssetReaderTrackOutput? + var audioInput: AVAssetWriterInput? + if let audioTrack { + let output = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: [ + AVFormatIDKey: kAudioFormatLinearPCM, + AVSampleRateKey: PTTAudioFormat.sampleRate, + AVNumberOfChannelsKey: 1, + AVLinearPCMBitDepthKey: 16, + AVLinearPCMIsFloatKey: false, + AVLinearPCMIsBigEndianKey: false, + AVLinearPCMIsNonInterleaved: false + ]) + output.alwaysCopiesSampleData = false + let settings = audioSettings(writer: writer) + if reader.canAdd(output), let settings { + let input = AVAssetWriterInput(mediaType: .audio, outputSettings: settings) + input.expectsMediaDataInRealTime = false + if writer.canAdd(input) { + reader.add(output) + writer.add(input) + audioOutput = output + audioInput = input + } + } + } + + guard reader.startReading() else { + throw TranscodeError.readerFailed(reader.error?.localizedDescription ?? "startReading") + } + guard writer.startWriting() else { + reader.cancelReading() + throw TranscodeError.writerFailed(writer.error?.localizedDescription ?? "startWriting") + } + writer.startSession(atSourceTime: .zero) + + let endTime = CMTime(seconds: duration, preferredTimescale: 600) + await withCheckedContinuation { (continuation: CheckedContinuation) in + let group = DispatchGroup() + pump(output: videoOutput, into: videoInput, label: "video", endTime: endTime, group: group) + if let audioOutput, let audioInput { + pump(output: audioOutput, into: audioInput, label: "audio", endTime: endTime, group: group) + } + group.notify(queue: .global(qos: .utility)) { continuation.resume() } + } + + if reader.status == .failed { + writer.cancelWriting() + throw TranscodeError.readerFailed(reader.error?.localizedDescription ?? "read") + } + await writer.finishWriting() + guard writer.status == .completed else { + throw TranscodeError.writerFailed(writer.error?.localizedDescription ?? "finish") + } + } + + /// Upright frames at the planned size and frame rate: the composition + /// applies `preferredTransform`, then scales to fill and center-crops. + private func makeComposition() -> AVMutableVideoComposition { + let target = CGSize(width: plan.width, height: plan.height) + let rotated = CGRect(origin: .zero, size: naturalSize).applying(transform) + let upright = CGSize(width: abs(rotated.width), height: abs(rotated.height)) + let scale = max(target.width / max(upright.width, 1), target.height / max(upright.height, 1)) + let placement = transform + .concatenating(CGAffineTransform(translationX: -rotated.minX, y: -rotated.minY)) + .concatenating(CGAffineTransform(scaleX: scale, y: scale)) + .concatenating(CGAffineTransform( + translationX: (target.width - upright.width * scale) / 2, + y: (target.height - upright.height * scale) / 2 + )) + + let layer = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack) + layer.setTransform(placement, at: .zero) + let instruction = AVMutableVideoCompositionInstruction() + // Must span the whole source timeline, not just the trimmed part. + instruction.timeRange = CMTimeRange(start: .zero, duration: assetDuration) + instruction.layerInstructions = [layer] + + let composition = AVMutableVideoComposition() + composition.renderSize = target + composition.frameDuration = CMTime(value: 1, timescale: CMTimeScale(plan.fps)) + composition.instructions = [instruction] + return composition + } + + private func videoSettings() -> [String: Any] { + [ + AVVideoCodecKey: AVVideoCodecType.h264, + AVVideoWidthKey: plan.width, + AVVideoHeightKey: plan.height, + AVVideoCompressionPropertiesKey: [ + AVVideoAverageBitRateKey: plan.videoBitrate, + AVVideoProfileLevelKey: AVVideoProfileLevelH264BaselineAutoLevel, + AVVideoMaxKeyFrameIntervalKey: plan.fps * 3, + AVVideoAllowFrameReorderingKey: false, + AVVideoExpectedSourceFrameRateKey: plan.fps + ] + ] + } + + /// AAC-LC mono 16 kHz at ~12 kbps, or the PTT bitrate if the encoder + /// refuses one that low. + private func audioSettings(writer: AVAssetWriter) -> [String: Any]? { + for bitrate in [VideoTranscoder.audioBitrate, PTTAudioFormat.bitRate] { + let settings: [String: Any] = [ + AVFormatIDKey: kAudioFormatMPEG4AAC, + AVSampleRateKey: PTTAudioFormat.sampleRate, + AVNumberOfChannelsKey: 1, + AVEncoderBitRateKey: bitrate + ] + if writer.canApply(outputSettings: settings, forMediaType: .audio) { return settings } + } + return nil + } + + /// Copies samples until the reader runs dry (or past the trim point), + /// driven by the input's own readiness callback; leaves `group` once + /// the track is done. + private func pump( + output: AVAssetReaderOutput, + into input: AVAssetWriterInput, + label: String, + endTime: CMTime, + group: DispatchGroup + ) { + group.enter() + let queue = DispatchQueue(label: "chat.bitchat.video.transcode.\(label)") + var finished = false + input.requestMediaDataWhenReady(on: queue) { + guard !finished else { return } + while input.isReadyForMoreMediaData { + guard let sample = output.copyNextSampleBuffer(), + CMSampleBufferGetPresentationTimeStamp(sample) < endTime, + input.append(sample) + else { + finished = true + input.markAsFinished() + group.leave() + return + } + } + } + } + } +} diff --git a/bitchatTests/Features/Video/LiveVideoMediaTests.swift b/bitchatTests/Features/Video/LiveVideoMediaTests.swift new file mode 100644 index 00000000..b6a06714 --- /dev/null +++ b/bitchatTests/Features/Video/LiveVideoMediaTests.swift @@ -0,0 +1,500 @@ +// +// LiveVideoMediaTests.swift +// bitchatTests +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import AVFoundation +import CoreGraphics +import Foundation +import Testing +@testable import bitchat + +/// Synthetic media helpers: everything is generated from the test card and +/// tone, so no test touches a camera or microphone. +private enum VideoTestMedia { + static func tempURL(_ name: String = UUID().uuidString, ext: String = "mp4") -> URL { + FileManager.default.temporaryDirectory + .appendingPathComponent("bitchat-video-tests", isDirectory: true) + .appendingPathComponent("\(name).\(ext)") + } + + /// Encodes `frameCount` test-card frames at `fps` and returns the encoder + /// output in order. + static func encode( + width: Int = 144, + height: Int = 192, + fps: Int = 12, + bitrate: Int = 120_000, + frameCount: Int, + firstPtsUs: Int64 = 0, + keyframeAt: Set = [], + sourceWidth: Int = 480, + sourceHeight: Int = 640 + ) throws -> [LiveVideoEncodedFrame] { + let encoder = try LiveVideoH264Encoder(width: width, height: height, fps: fps, bitrate: bitrate, keyframeIntervalSeconds: 2) + let source = LiveVideoSyntheticSource(width: sourceWidth, height: sourceHeight, fps: fps, audioEnabled: false) + let collected = Collected() + encoder.onFrame = { collected.append($0) } + for index in 0.. [Data] { + let source = LiveVideoSyntheticSource(audioEnabled: true) + guard let encoder = PTTFrameEncoder() else { return [] } + let chunks = Int(seconds * PTTAudioFormat.sampleRate) / Int(PTTAudioFormat.samplesPerFrame) + var frames: [Data] = [] + for chunk in 0.. = 0..<0, + to url: URL + ) -> Bool { + let writer = LiveVideoMp4Writer(url: url, hasAudio: !audio.isEmpty) + // Interleave by timestamp the way a live sender would. + var audioIndex = 0 + let frameUs = LiveVideoMp4Writer.audioFrameDurationUs + func writeAudio(through ptsUs: Int64) { + while audioIndex < audio.count, audioStartUs + Int64(audioIndex) * frameUs <= ptsUs { + if !lost.contains(audioIndex) { + writer.writeAudio(aac: audio[audioIndex], ptsUs: audioStartUs + Int64(audioIndex) * frameUs) + } + audioIndex += 1 + } + } + for frame in frames { + writer.writeVideo(annexB: frame.annexB, ptsUs: frame.ptsUs, keyframe: frame.keyframe) + writeAudio(through: frame.ptsUs) + } + writeAudio(through: .max) + return writer.finish() + } + + static func nalTypes(_ annexB: Data) -> [UInt8] { + LiveVideoAVCC.nalUnits(inAnnexB: annexB).map(LiveVideoAVCC.nalType) + } + + static func fileSize(_ url: URL) -> Int { + (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int) ?? 0 + } +} + +private final class Collected: @unchecked Sendable { + private let lock = NSLock() + private var storage: [Value] = [] + + func append(_ value: Value) { + lock.withLock { storage.append(value) } + } + + var values: [Value] { + lock.withLock { storage } + } +} + +struct LiveVideoAVCCTests { + @Test func splitsThreeAndFourByteStartCodes() { + let annexB = Data([0, 0, 0, 1, 0x67, 0xAA, 0, 0, 1, 0x68, 0xBB, 0, 0, 0, 1, 0x65, 0x01, 0x00]) + let units = LiveVideoAVCC.nalUnits(inAnnexB: annexB) + #expect(units == [Data([0x67, 0xAA]), Data([0x68, 0xBB]), Data([0x65, 0x01])]) + #expect(LiveVideoAVCC.nalUnits(inAnnexB: Data([0x65, 0x01])).isEmpty) + } + + @Test func avccRoundTrip() { + let units = [Data([0x65, 1, 2, 3]), Data([0x06, 9])] + let avcc = LiveVideoAVCC.avccSample(from: units) + #expect(avcc.prefix(4) == Data([0, 0, 0, 4])) + #expect(LiveVideoAVCC.nalUnits(inAVCC: avcc, lengthSize: 4) == units) + // A truncated length must not read past the buffer. + #expect(LiveVideoAVCC.nalUnits(inAVCC: avcc.prefix(6), lengthSize: 4).isEmpty) + } +} + +struct LiveVideoH264EncoderTests { + @Test func keyframesCarryParameterSetsAndDeltasDoNot() throws { + let frames = try VideoTestMedia.encode(frameCount: 30) + #expect(frames.count >= 28) + let first = try #require(frames.first) + #expect(first.keyframe) + #expect(first.annexB.prefix(4) == LiveVideoAVCC.startCode) + let keyTypes = VideoTestMedia.nalTypes(first.annexB) + #expect(Array(keyTypes.prefix(2)) == [LiveVideoAVCC.typeSPS, LiveVideoAVCC.typePPS]) + #expect(keyTypes.contains(LiveVideoAVCC.typeIDR)) + + for frame in frames.dropFirst() where !frame.keyframe { + let types = VideoTestMedia.nalTypes(frame.annexB) + #expect(!types.contains(LiveVideoAVCC.typeSPS)) + #expect(!types.contains(LiveVideoAVCC.typeFiller)) + #expect(types.contains(LiveVideoAVCC.typeSlice)) + } + // Monotonic, microsecond pts straight from the input. + #expect(zip(frames, frames.dropFirst()).allSatisfy { $0.ptsUs < $1.ptsUs }) + } + + @Test func requestKeyframeForcesIDR() throws { + let fps = 12 + let frames = try VideoTestMedia.encode(fps: fps, frameCount: 20, keyframeAt: [10]) + let forced = try #require(frames.first { $0.ptsUs == 10 * 1_000_000 / Int64(fps) }) + #expect(forced.keyframe) + #expect(VideoTestMedia.nalTypes(forced.annexB).first == LiveVideoAVCC.typeSPS) + } + + @Test func rejectsOddDimensions() { + #expect(throws: LiveVideoH264Encoder.EncoderError.self) { + try LiveVideoH264Encoder(width: 145, height: 192, fps: 8, bitrate: 18_000, keyframeIntervalSeconds: 2) + } + } +} + +struct LiveVideoMp4WriterTests { + @Test func encodedFramesMuxIntoPlayableMp4() async throws { + let frames = try VideoTestMedia.encode(fps: 12, frameCount: 48) + let url = VideoTestMedia.tempURL() + defer { try? FileManager.default.removeItem(at: url) } + #expect(VideoTestMedia.writeMp4(frames, to: url)) + + let asset = AVURLAsset(url: url) + let tracks = try await asset.loadTracks(withMediaType: .video) + #expect(tracks.count == 1) + let duration = try await asset.load(.duration).seconds + #expect(duration > 3.5 && duration < 4.5) + let size = try await tracks[0].load(.naturalSize) + #expect(size == CGSize(width: 144, height: 192)) + #expect(try await asset.loadTracks(withMediaType: .audio).isEmpty) + } + + @Test func aacFramesProduceDecodableAudioTrack() async throws { + let frames = try VideoTestMedia.encode(fps: 12, frameCount: 36) + let audio = VideoTestMedia.toneFrames(seconds: 3) + #expect(audio.count > 40) + let url = VideoTestMedia.tempURL() + defer { try? FileManager.default.removeItem(at: url) } + // ~0.6 s of audio lost on the mesh mid-stream: the writer must hold + // the timeline with silence, not pull later audio early. + #expect(VideoTestMedia.writeMp4(frames, audio: audio, droppingAudio: 15..<25, to: url)) + + let asset = AVURLAsset(url: url) + let audioTrack = try #require(try await asset.loadTracks(withMediaType: .audio).first) + let audioDuration = try await audioTrack.load(.timeRange).duration.seconds + #expect(audioDuration > 2.5 && audioDuration < 3.5) + + // The magic cookie must be good enough to decode. + let reader = try AVAssetReader(asset: asset) + let output = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM]) + reader.add(output) + #expect(reader.startReading()) + var pcmFrames = 0 + while let sample = output.copyNextSampleBuffer() { + pcmFrames += CMSampleBufferGetNumSamples(sample) + } + #expect(reader.status == .completed) + #expect(pcmFrames > Int(PTTAudioFormat.sampleRate * 2)) + } + + @Test func waitsForKeyframeAndHoldsAcrossGaps() async throws { + let frames = try VideoTestMedia.encode(fps: 10, frameCount: 40) + let url = VideoTestMedia.tempURL() + defer { try? FileManager.default.removeItem(at: url) } + let writer = LiveVideoMp4Writer(url: url, hasAudio: true) + // Audio before the first keyframe and a leading delta are dropped. + writer.writeAudio(aac: Data([0x21, 0x10]), ptsUs: 0) + writer.writeVideo(annexB: frames[1].annexB, ptsUs: frames[1].ptsUs, keyframe: false) + // Frames 10..<25 lost on the mesh; the delta after the gap is kept. + for (index, frame) in frames.enumerated() where !(10..<25).contains(index) { + writer.writeVideo(annexB: frame.annexB, ptsUs: frame.ptsUs, keyframe: frame.keyframe) + } + // Duplicate and out-of-order timestamps are ignored. + writer.writeVideo(annexB: frames[30].annexB, ptsUs: frames[30].ptsUs, keyframe: false) + // 25 kept; the newest is still waiting for its successor (duration). + #expect(writer.videoSamples == 24) + #expect(writer.finish()) + + let asset = AVURLAsset(url: url) + let duration = try await asset.load(.duration).seconds + #expect(duration > 3.5 && duration < 4.5) + let track = try #require(try await asset.loadTracks(withMediaType: .video).first) + let reader = try AVAssetReader(asset: asset) + let output = AVAssetReaderTrackOutput(track: track, outputSettings: nil) + reader.add(output) + reader.startReading() + var samples = 0 + var firstIsSync = false + // Passthrough readers also emit zero-sample marker buffers; skip them. + while let sample = output.copyNextSampleBuffer() { + guard CMSampleBufferGetNumSamples(sample) > 0 else { continue } + if samples == 0 { firstIsSync = LiveVideoAVCC.isSync(sample) } + samples += 1 + } + #expect(samples == 25) + #expect(firstIsSync) + } + + @Test func finishWithoutVideoFails() { + let url = VideoTestMedia.tempURL() + let writer = LiveVideoMp4Writer(url: url, hasAudio: true) + writer.writeAudio(aac: Data([0x21, 0x10]), ptsUs: 0) + #expect(!writer.finish()) + #expect(!FileManager.default.fileExists(atPath: url.path)) + } +} + +struct LiveVideoH264DecoderTests { + @MainActor + @Test func roundTripProducesImagesOfConfiguredSize() async throws { + let frames = try VideoTestMedia.encode(width: 240, height: 320, fps: 12, frameCount: 24) + var images: [CGImage] = [] + let decoder = LiveVideoH264Decoder(onFrame: { images.append($0) }, jitterMs: 50) + decoder.configure(width: 240, height: 320) + for frame in frames { + decoder.submit(annexB: frame.annexB, ptsMs: frame.ptsUs / 1_000, keyframe: frame.keyframe) + } + decoder.finishAfterDrain() + let deadline = Date().addingTimeInterval(10) + while images.count < frames.count, Date() < deadline { + try await Task.sleep(nanoseconds: 20_000_000) + } + decoder.stop() + #expect(images.count == frames.count) + #expect(decoder.framesDecoded == frames.count) + #expect(images.allSatisfy { $0.width == 240 && $0.height == 320 }) + } + + @MainActor + @Test func dropsDeltasUntilKeyframe() async throws { + let frames = try VideoTestMedia.encode(fps: 12, frameCount: 12) + var images = 0 + let decoder = LiveVideoH264Decoder(onFrame: { _ in images += 1 }, jitterMs: 0) + decoder.configure(width: 144, height: 192) + // Joined mid-stream: no keyframe yet, nothing must be shown. + for frame in frames.dropFirst() where !frame.keyframe { + decoder.submit(annexB: frame.annexB, ptsMs: frame.ptsUs / 1_000, keyframe: false) + } + try await Task.sleep(nanoseconds: 300_000_000) + #expect(images == 0) + #expect(decoder.framesDecoded == 0) + + // A keyframe starts decoding. + decoder.submit(annexB: frames[0].annexB, ptsMs: 2_000, keyframe: true) + let deadline = Date().addingTimeInterval(3) + while decoder.framesDecoded < 1, Date() < deadline { + try await Task.sleep(nanoseconds: 20_000_000) + } + #expect(decoder.framesDecoded == 1) + + // After a resync, deltas are withheld until the next keyframe. + decoder.resyncAtKeyframe() + decoder.submit(annexB: frames[1].annexB, ptsMs: 2_083, keyframe: false) + try await Task.sleep(nanoseconds: 300_000_000) + #expect(decoder.framesDecoded == 1) + decoder.submit(annexB: frames[0].annexB, ptsMs: 2_166, keyframe: true) + let second = Date().addingTimeInterval(3) + while decoder.framesDecoded < 2, Date() < second { + try await Task.sleep(nanoseconds: 20_000_000) + } + decoder.stop() + #expect(decoder.framesDecoded == 2) + } +} + +struct LiveVideoMp4SegmentsTests { + @Test func joinHoldsDropoutAsFreeze() async throws { + let fps = 12 + let first = try VideoTestMedia.encode(fps: fps, frameCount: 24) + // Second segment resumes 5 s into the stream at a fresh keyframe. + let second = try VideoTestMedia.encode(fps: fps, frameCount: 24, firstPtsUs: 5_000_000) + let audio = VideoTestMedia.toneFrames(seconds: 2) + let firstURL = VideoTestMedia.tempURL() + let secondURL = VideoTestMedia.tempURL() + let joinedURL = VideoTestMedia.tempURL() + defer { + for url in [firstURL, secondURL, joinedURL] { try? FileManager.default.removeItem(at: url) } + } + #expect(VideoTestMedia.writeMp4(first, audio: audio, to: firstURL)) + #expect(VideoTestMedia.writeMp4(second, audio: audio, audioStartUs: 5_000_000, to: secondURL)) + + let joined = await LiveVideoMp4Segments.join( + [(url: firstURL, firstVideoPtsUs: 0), (url: secondURL, firstVideoPtsUs: 5_000_000)], + to: joinedURL + ) + #expect(joined) + let asset = AVURLAsset(url: joinedURL) + let duration = try await asset.load(.duration).seconds + #expect(duration > 6.5 && duration < 7.5) + let video = try #require(try await asset.loadTracks(withMediaType: .video).first) + // Audio keeps its place across the dropout (silence fills the gap): + // it must run to the end of the second segment, not stop near 4 s. + let audioTrack = try #require(try await asset.loadTracks(withMediaType: .audio).first) + let audioRange = try await audioTrack.load(.timeRange) + #expect(audioRange.end.seconds > 6.5) + + // 48 samples, and the one before the dropout spans it (a freeze). + let reader = try AVAssetReader(asset: asset) + let output = AVAssetReaderTrackOutput(track: video, outputSettings: nil) + reader.add(output) + reader.startReading() + var durations: [Double] = [] + while let sample = output.copyNextSampleBuffer() { + guard CMSampleBufferGetNumSamples(sample) > 0 else { continue } + durations.append(CMSampleBufferGetDuration(sample).seconds) + } + #expect(durations.count == 48) + #expect(durations.max() ?? 0 > 2.5) + } + + @Test func joinWithNoReadableSegmentsFails() async { + let missing = VideoTestMedia.tempURL() + let output = VideoTestMedia.tempURL() + #expect(!(await LiveVideoMp4Segments.join([(url: missing, firstVideoPtsUs: 0)], to: output))) + #expect(!(await LiveVideoMp4Segments.join([], to: output))) + } +} + +struct VideoTranscoderTests { + @Test func planFollowsBudgetAndAspect() { + // 100 KiB over 10 s ≈ 75 kbps: audio kept, 320 long edge, 15 fps. + let portrait = VideoTranscoder.plan(totalBits: 100 * 1024 * 8 * 0.92, duration: 10, uprightSize: CGSize(width: 1080, height: 1920), hasAudio: true) + #expect(portrait.withAudio) + #expect(portrait.height == 320) + #expect(portrait.width % 16 == 0 && portrait.width == 176) + #expect(portrait.fps == 15) + // 60 s leaves ~12.5 kbps: no audio, small picture. + let long = VideoTranscoder.plan(totalBits: 100 * 1024 * 8 * 0.92, duration: 60, uprightSize: CGSize(width: 1920, height: 1080), hasAudio: true) + #expect(!long.withAudio) + #expect(long.width == 192 && long.height % 16 == 0) + #expect(long.fps == 6) + } + + @Test func transcodedClipFitsBudget() async throws { + // 3 s of 480×640 @ 24 fps with frequent keyframes and a tone. The + // test card compresses very well, so the budget is set below the + // source size (~50 KiB) to force a real shrink. + let frames = try VideoTestMedia.encode( + width: 480, height: 640, fps: 24, bitrate: 900_000, frameCount: 72, + keyframeAt: Set(stride(from: 6, to: 72, by: 6)) + ) + let audio = VideoTestMedia.toneFrames(seconds: 3) + let sourceURL = VideoTestMedia.tempURL() + let outputURL = VideoTestMedia.tempURL() + defer { + try? FileManager.default.removeItem(at: sourceURL) + try? FileManager.default.removeItem(at: outputURL) + } + #expect(VideoTestMedia.writeMp4(frames, audio: audio, to: sourceURL)) + let maxBytes = 48 * 1024 + let sourceSize = VideoTestMedia.fileSize(sourceURL) + #expect(sourceSize > maxBytes) + + let result = try await VideoTranscoder.transcode(source: sourceURL, output: outputURL, maxBytes: maxBytes) + let size = VideoTestMedia.fileSize(result) + #expect(size > 0 && size <= maxBytes) + + let asset = AVURLAsset(url: result) + let video = try #require(try await asset.loadTracks(withMediaType: .video).first) + let naturalSize = try await video.load(.naturalSize) + #expect(max(naturalSize.width, naturalSize.height) <= 320) + #expect(Int(naturalSize.width) % 16 == 0 && Int(naturalSize.height) % 16 == 0) + #expect(naturalSize.height > naturalSize.width) + let duration = try await asset.load(.duration).seconds + #expect(duration > 2.5 && duration < 3.5) + #expect(try await asset.loadTracks(withMediaType: .audio).count == 1) + } + + @Test func impossibleBudgetThrowsTypedError() async throws { + let frames = try VideoTestMedia.encode(fps: 12, frameCount: 24) + let sourceURL = VideoTestMedia.tempURL() + let outputURL = VideoTestMedia.tempURL() + defer { try? FileManager.default.removeItem(at: sourceURL) } + #expect(VideoTestMedia.writeMp4(frames, to: sourceURL)) + await #expect(throws: VideoTranscoder.TranscodeError.self) { + try await VideoTranscoder.transcode(source: sourceURL, output: outputURL, maxBytes: 600) + } + #expect(!FileManager.default.fileExists(atPath: outputURL.path)) + } +} + +struct VideoPosterLoaderTests { + @Test func loadsPosterAndDuration() async throws { + let frames = try VideoTestMedia.encode(fps: 12, frameCount: 24) + let url = VideoTestMedia.tempURL() + defer { + VideoPosterLoader.evict(url: url) + try? FileManager.default.removeItem(at: url) + } + #expect(VideoTestMedia.writeMp4(frames, to: url)) + let result = await VideoPosterLoader.load(url: url) + let poster = try #require(result.poster) + #expect(poster.width == 144 && poster.height == 192) + #expect(result.durationSeconds > 1.5 && result.durationSeconds < 2.5) + // Cached: a second call returns the same image object. + let again = await VideoPosterLoader.load(url: url) + #expect(again.poster === poster) + } +} + +struct LiveVideoSyntheticSourceTests { + @MainActor + @Test func deliversFramesAndToneOnOneClock() async throws { + let source = LiveVideoSyntheticSource(width: 144, height: 192, fps: 20, audioEnabled: true) + let videoPts = Collected() + let widths = Collected() + let audio = Collected<(count: Int, ptsUs: Int64)>() + source.onPixelBuffer = { buffer, ptsUs in + widths.append(CVPixelBufferGetWidth(buffer)) + videoPts.append(ptsUs) + } + source.onAudioFrames = { frames, ptsUs in audio.append((frames.count, ptsUs)) } + try await source.start() + try await Task.sleep(nanoseconds: 700_000_000) + source.isMuted = true + try await Task.sleep(nanoseconds: 300_000_000) + source.stop() + + let pts = videoPts.values + #expect(pts.count >= 10) + #expect(widths.values.allSatisfy { $0 == 144 }) + #expect(zip(pts, pts.dropFirst()).allSatisfy { $0 < $1 }) + let batches = audio.values + #expect(batches.reduce(0) { $0 + $1.count } >= 8) + // Audio timestamps advance exactly one AAC frame (64 ms) per frame. + for (previous, next) in zip(batches, batches.dropFirst()) { + #expect(next.ptsUs == previous.ptsUs + Int64(previous.count) * 64_000) + } + } + + @Test func testCardMovesBetweenFrames() throws { + let source = LiveVideoSyntheticSource(width: 144, height: 192, fps: 8, audioEnabled: false) + let a = try #require(source.makeFrame(index: 0)) + let b = try #require(source.makeFrame(index: 5)) + #expect(CVPixelBufferGetPixelFormatType(a) == kCVPixelFormatType_32BGRA) + CVPixelBufferLockBaseAddress(a, .readOnly) + CVPixelBufferLockBaseAddress(b, .readOnly) + defer { + CVPixelBufferUnlockBaseAddress(a, .readOnly) + CVPixelBufferUnlockBaseAddress(b, .readOnly) + } + let length = CVPixelBufferGetBytesPerRow(a) * CVPixelBufferGetHeight(a) + let same = memcmp(CVPixelBufferGetBaseAddress(a), CVPixelBufferGetBaseAddress(b), length) == 0 + #expect(!same) + } +}