perf(globe,media,ptt): optimize globe renderer, image pipeline, and live PTT audio (#1896)

This commit is contained in:
jack authored and GitHub committed 2026-11-26 12:35:58 -10:00
1 parent 13b599fad7
commit b7c75eb581
17 files changed
+763 -284

No files matched your search

+30 -2
View File
@@ -20,8 +20,32 @@ enum ImageDownsampler {
typealias PlatformImage = NSImage
#endif
private static let cache: NSCache<NSString, PlatformImage> = {
let cache = NSCache<NSString, PlatformImage>()
cache.countLimit = 48
cache.totalCostLimit = 32 * 1024 * 1024
return cache
}()
private static func cacheKey(for url: URL, maxPixelSize: Int) -> NSString {
"\(url.path)#\(maxPixelSize)" as NSString
}
static func cachedImage(for url: URL, maxPixelSize: Int) -> PlatformImage? {
guard maxPixelSize > 0 else { return nil }
return cache.object(forKey: cacheKey(for: url, maxPixelSize: maxPixelSize))
}
static func resetForPanic() {
cache.removeAllObjects()
}
static func loadDownsampledImage(from url: URL, maxPixelSize: Int) -> PlatformImage? {
guard maxPixelSize > 0 else { return nil }
let key = cacheKey(for: url, maxPixelSize: maxPixelSize)
if let cached = cache.object(forKey: key) {
return cached
}
let sourceOptions: CFDictionary = [
kCGImageSourceShouldCache: false
] as CFDictionary
@@ -43,10 +67,14 @@ enum ImageDownsampler {
return nil
}
let image: PlatformImage
#if os(iOS)
return UIImage(cgImage: cgImage)
image = UIImage(cgImage: cgImage)
#else
return NSImage(cgImage: cgImage, size: NSSize(width: cgImage.width, height: cgImage.height))
image = NSImage(cgImage: cgImage, size: NSSize(width: cgImage.width, height: cgImage.height))
#endif
let cost = max(1, cgImage.width * cgImage.height * 4)
cache.setObject(image, forKey: key, cost: cost)
return image
}
}
+57 -67
View File
@@ -17,17 +17,38 @@ enum ImageUtils {
private static let targetImageBytes: Int = 45_000
private static let maxSourceImageBytes: Int = 10 * 1024 * 1024
private static let timestampFormatterLock = NSLock()
private static let timestampFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyyMMdd_HHmmss"
return formatter
}()
static func processImage(at url: URL, maxDimension: CGFloat = 448, outputDirectory: URL? = nil) throws -> URL {
try validateImageSource(at: url)
let data = try Data(contentsOf: url)
#if os(iOS)
guard let image = UIImage(data: data) else { throw ImageUtilsError.invalidImage }
return try processImage(image, maxDimension: maxDimension, outputDirectory: outputDirectory)
#else
guard let image = NSImage(data: data) else { throw ImageUtilsError.invalidImage }
return try processImage(image, maxDimension: maxDimension, outputDirectory: outputDirectory)
#endif
return try autoreleasepool {
let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let source = CGImageSourceCreateWithURL(url as CFURL, sourceOptions),
ImageContainerValidator.validateDimensions(of: source) == nil else {
throw ImageUtilsError.invalidImage
}
// Downsample directly through ImageIO so sending a 12-48 MP photo never
// decodes the full-resolution bitmap into memory.
let maxPixelSize = max(1, Int(ceil(maxDimension)))
let thumbnailOptions: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: false,
kCGImageSourceThumbnailMaxPixelSize: maxPixelSize
]
guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbnailOptions as CFDictionary) else {
throw ImageUtilsError.invalidImage
}
return try encodeAndWriteJPEG(from: cgImage, outputDirectory: outputDirectory)
}
}
static func validateImageSource(at url: URL) throws {
@@ -57,25 +78,7 @@ enum ImageUtils {
throw ImageUtilsError.encodingFailed
}
// Use CGImageDestination to encode without metadata (same as macOS)
var quality = compressionQuality
guard var jpegData = encodeJPEG(from: cgImage, quality: quality) else {
throw ImageUtilsError.encodingFailed
}
// Compress to target size
while jpegData.count > targetImageBytes && quality > 0.3 {
quality -= 0.1
autoreleasepool {
if let next = encodeJPEG(from: cgImage, quality: quality) {
jpegData = next
}
}
}
let outputURL = try makeOutputURL(outputDirectory: outputDirectory)
try jpegData.write(to: outputURL, options: .atomic)
return outputURL
return try encodeAndWriteJPEG(from: cgImage, outputDirectory: outputDirectory)
}
}
@@ -93,27 +96,6 @@ enum ImageUtils {
UIGraphicsEndImageContext()
return rendered ?? image
}
// Shared EXIF-stripping JPEG encoder for both iOS and macOS
private static func encodeJPEG(from cgImage: CGImage, quality: CGFloat) -> Data? {
guard let data = CFDataCreateMutable(nil, 0) else {
return nil
}
guard let destination = CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil) else {
return nil
}
// Security: Strip ALL metadata (EXIF, GPS, TIFF, IPTC, XMP)
// By only specifying compression quality and no metadata keys,
// we ensure a clean JPEG with no privacy-leaking information
let options: [CFString: Any] = [
kCGImageDestinationLossyCompressionQuality: quality
]
CGImageDestinationAddImage(destination, cgImage, options as CFDictionary)
guard CGImageDestinationFinalize(destination) else {
return nil
}
return data as Data
}
#else
static func processImage(_ image: NSImage, maxDimension: CGFloat = 448, outputDirectory: URL? = nil) throws -> URL {
return try autoreleasepool {
@@ -139,21 +121,7 @@ enum ImageUtils {
guard let cgImage = context.makeImage() else {
throw ImageUtilsError.encodingFailed
}
var quality = compressionQuality
guard var jpegData = encodeJPEG(from: cgImage, quality: quality) else {
throw ImageUtilsError.encodingFailed
}
while jpegData.count > targetImageBytes && quality > 0.3 {
quality -= 0.1
autoreleasepool {
if let next = encodeJPEG(from: cgImage, quality: quality) {
jpegData = next
}
}
}
let outputURL = try makeOutputURL(outputDirectory: outputDirectory)
try jpegData.write(to: outputURL, options: .atomic)
return outputURL
return try encodeAndWriteJPEG(from: cgImage, outputDirectory: outputDirectory)
}
}
@@ -172,6 +140,28 @@ enum ImageUtils {
scaledImage.unlockFocus()
return scaledImage
}
#endif
private static func encodeAndWriteJPEG(from cgImage: CGImage, outputDirectory: URL?) throws -> URL {
var quality = compressionQuality
guard var jpegData = encodeJPEG(from: cgImage, quality: quality) else {
throw ImageUtilsError.encodingFailed
}
// Compress to target size
while jpegData.count > targetImageBytes && quality > 0.3 {
quality -= 0.1
autoreleasepool {
if let next = encodeJPEG(from: cgImage, quality: quality) {
jpegData = next
}
}
}
let outputURL = try makeOutputURL(outputDirectory: outputDirectory)
try jpegData.write(to: outputURL, options: .atomic)
return outputURL
}
// Shared EXIF-stripping JPEG encoder for both iOS and macOS
private static func encodeJPEG(from cgImage: CGImage, quality: CGFloat) -> Data? {
@@ -193,12 +183,12 @@ enum ImageUtils {
}
return data as Data
}
#endif
private static func makeOutputURL(outputDirectory: URL? = nil) throws -> URL {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd_HHmmss"
let fileName = "img_\(formatter.string(from: Date()))_\(UUID().uuidString).jpg"
let timestamp = timestampFormatterLock.withLock {
timestampFormatter.string(from: Date())
}
let fileName = "img_\(timestamp)_\(UUID().uuidString).jpg"
let directory: URL
if let outputDirectory {
+35 -23
View File
@@ -15,7 +15,9 @@ import Foundation
/// Not thread-safe — confine to one queue.
final class PTTFrameEncoder {
private let converter: AVAudioConverter
private let outputBuffer: AVAudioCompressedBuffer
private var pendingInput: [AVAudioPCMBuffer] = []
private var pendingIndex = 0
init?() {
guard let pcm = PTTAudioFormat.pcmFormat,
@@ -24,6 +26,11 @@ final class PTTFrameEncoder {
else { return nil }
converter.bitRate = PTTAudioFormat.bitRate
self.converter = converter
self.outputBuffer = AVAudioCompressedBuffer(
format: converter.outputFormat,
packetCapacity: 8,
maximumPacketSize: max(converter.maximumOutputPacketSize, 1)
)
}
/// Feeds PCM (16 kHz mono float) and returns every complete AAC frame the
@@ -36,18 +43,20 @@ final class PTTFrameEncoder {
private func drainConverter() -> [Data] {
var frames: [Data] = []
while true {
let output = AVAudioCompressedBuffer(
format: converter.outputFormat,
packetCapacity: 8,
maximumPacketSize: max(converter.maximumOutputPacketSize, 1)
)
outputBuffer.packetCount = 0
outputBuffer.byteLength = 0
var error: NSError?
let status = converter.convert(to: output, error: &error) { [weak self] _, outStatus in
guard let self, let next = self.pendingInput.first else {
let status = converter.convert(to: outputBuffer, error: &error) { [weak self] _, outStatus in
guard let self, self.pendingIndex < self.pendingInput.count else {
outStatus.pointee = .noDataNow
return nil
}
self.pendingInput.removeFirst()
let next = self.pendingInput[self.pendingIndex]
self.pendingIndex += 1
if self.pendingIndex == self.pendingInput.count {
self.pendingInput.removeAll(keepingCapacity: true)
self.pendingIndex = 0
}
outStatus.pointee = .haveData
return next
}
@@ -55,33 +64,33 @@ final class PTTFrameEncoder {
SecureLogger.error("PTT encode failed: \(error?.localizedDescription ?? "unknown")", category: .session)
return frames
}
frames.append(contentsOf: Self.extractPackets(from: output))
Self.appendPackets(from: outputBuffer, to: &frames)
// .haveData means the output buffer filled and more may be ready;
// anything else means the converter wants more input.
if status != .haveData { return frames }
}
}
private static func extractPackets(from buffer: AVAudioCompressedBuffer) -> [Data] {
guard buffer.packetCount > 0, let descriptions = buffer.packetDescriptions else { return [] }
var frames: [Data] = []
frames.reserveCapacity(Int(buffer.packetCount))
private static func appendPackets(from buffer: AVAudioCompressedBuffer, to frames: inout [Data]) {
guard buffer.packetCount > 0, let descriptions = buffer.packetDescriptions else { return }
frames.reserveCapacity(frames.count + Int(buffer.packetCount))
for index in 0..<Int(buffer.packetCount) {
let description = descriptions[index]
guard description.mDataByteSize > 0 else { continue }
let start = buffer.data.advanced(by: Int(description.mStartOffset))
frames.append(Data(bytes: start, count: Int(description.mDataByteSize)))
}
return frames
}
}
/// Streaming AAC-LC -> PCM decoder for live voice. Stateful; one instance per
/// inbound burst. Not thread-safe — confine to one queue/actor.
final class PTTFrameDecoder {
private static let maxFrameBytes = 8 * 1024
private let converter: AVAudioConverter
private let pcmFormat: AVAudioFormat
private let aacFormat: AVAudioFormat
private let inputBuffer: AVAudioCompressedBuffer
init?() {
guard let pcm = PTTAudioFormat.pcmFormat,
@@ -90,22 +99,25 @@ final class PTTFrameDecoder {
else { return nil }
self.converter = converter
self.pcmFormat = pcm
self.aacFormat = aac
self.inputBuffer = AVAudioCompressedBuffer(
format: aac,
packetCapacity: 1,
maximumPacketSize: Self.maxFrameBytes
)
}
/// Decodes one raw AAC frame to PCM. Returns nil for malformed input or
/// while the decoder is still priming (the first frame of a stream).
func decode(_ frame: Data) -> AVAudioPCMBuffer? {
guard !frame.isEmpty, frame.count <= 8 * 1024 else { return nil }
guard !frame.isEmpty, frame.count <= Self.maxFrameBytes else { return nil }
let input = AVAudioCompressedBuffer(format: aacFormat, packetCapacity: 1, maximumPacketSize: frame.count)
frame.withUnsafeBytes { raw in
guard let base = raw.baseAddress else { return }
input.data.copyMemory(from: base, byteCount: frame.count)
inputBuffer.data.copyMemory(from: base, byteCount: frame.count)
}
input.byteLength = UInt32(frame.count)
input.packetCount = 1
input.packetDescriptions?.pointee = AudioStreamPacketDescription(
inputBuffer.byteLength = UInt32(frame.count)
inputBuffer.packetCount = 1
inputBuffer.packetDescriptions?.pointee = AudioStreamPacketDescription(
mStartOffset: 0,
mVariableFramesInPacket: 0,
mDataByteSize: UInt32(frame.count)
@@ -125,7 +137,7 @@ final class PTTFrameDecoder {
}
consumed = true
outStatus.pointee = .haveData
return input
return self.inputBuffer
}
guard status != .error else {
SecureLogger.debug("PTT decode failed: \(error?.localizedDescription ?? "unknown")", category: .session)
+75 -25
View File
@@ -9,6 +9,7 @@
@preconcurrency import AVFoundation
import BitLogger
import Foundation
import os
/// The engine operations behind live-burst playback, abstracted so the
/// player's lifecycle (jitter start, category-escalation restart, stop) is
@@ -127,26 +128,59 @@ private final class PTTPlaybackCompletionState: @unchecked Sendable {
case retired
}
private let lock = NSLock()
private let lock: UnsafeMutablePointer<os_unfair_lock>
private var state: State = .scheduled
init() {
lock = UnsafeMutablePointer<os_unfair_lock>.allocate(capacity: 1)
lock.initialize(to: os_unfair_lock())
}
deinit {
lock.deinitialize(count: 1)
lock.deallocate()
}
/// Returns true exactly once when playback completion wins the race with
/// an engine rebuild or stop.
func complete() -> Bool {
lock.withLock {
guard case .scheduled = state else { return false }
state = .completed
return true
}
os_unfair_lock_lock(lock)
defer { os_unfair_lock_unlock(lock) }
guard case .scheduled = state else { return false }
state = .completed
return true
}
/// Returns true exactly once when a rebuild or stop claims this
/// still-pending schedule. Later callbacks from that engine are stale.
func retireIfPending() -> Bool {
lock.withLock {
guard case .scheduled = state else { return false }
state = .retired
return true
os_unfair_lock_lock(lock)
defer { os_unfair_lock_unlock(lock) }
guard case .scheduled = state else { return false }
state = .retired
return true
}
}
/// Confines stateful AAC decoding to a private serial queue off `@MainActor`.
private final class PTTDecodeWorker: @unchecked Sendable {
private let queue = DispatchQueue(label: "chat.bitchat.ptt.decode", qos: .userInitiated)
private let decoder: PTTFrameDecoder
init(decoder: PTTFrameDecoder) {
self.decoder = decoder
}
func decode(_ frames: [Data], completion: @escaping @Sendable ([AVAudioPCMBuffer]) -> Void) {
queue.async { [decoder] in
var decoded: [AVAudioPCMBuffer] = []
decoded.reserveCapacity(frames.count)
for frame in frames {
if let pcm = decoder.decode(frame) {
decoded.append(pcm)
}
}
completion(decoded)
}
}
}
@@ -173,7 +207,7 @@ final class PTTBurstPlayer {
private let makeEngine: @MainActor () -> PTTPlaybackEngine
private var engine: PTTPlaybackEngine
private let decoder: PTTFrameDecoder
private let decodeWorker: PTTDecodeWorker
private let coordinator: AudioSessionCoordinator
/// Injectable so tests don't fight over the app-wide exclusive-playback
/// slot (a parallel test's `play()` would stop this player mid-test).
@@ -181,6 +215,9 @@ final class PTTBurstPlayer {
private var queuedBuffers: [AVAudioPCMBuffer] = []
private var queuedDuration: TimeInterval = 0
/// Number of frame batches currently decoding on `decodeWorker`. Keeps
/// `finishAfterDrain()` from treating an in-flight decode as already drained.
private var pendingDecodeCount = 0
private struct ScheduledBuffer {
let id: UInt64
let buffer: AVAudioPCMBuffer
@@ -223,7 +260,7 @@ final class PTTBurstPlayer {
makeEngine: (@MainActor () -> PTTPlaybackEngine)? = nil
) {
guard let format = PTTAudioFormat.pcmFormat, let decoder = PTTFrameDecoder() else { return nil }
self.decoder = decoder
self.decodeWorker = PTTDecodeWorker(decoder: decoder)
self.coordinator = coordinator ?? .shared
self.exclusivity = exclusivity ?? .shared
let factory = makeEngine ?? { SystemPTTPlaybackEngine(format: format) }
@@ -251,20 +288,28 @@ final class PTTBurstPlayer {
deadlineTask?.cancel()
}
/// Decodes and queues frames (in burst order). Starts playback when the
/// jitter buffer fills.
/// Decodes frames off-main (in burst order) and schedules/queues them on
/// `@MainActor`. Starts playback when the jitter buffer fills.
func enqueue(_ frames: [Data]) {
guard !stopped else { return }
for frame in frames {
guard let pcm = decoder.decode(frame) else { continue }
if engineStarted {
schedule(pcm)
} else {
queuedBuffers.append(pcm)
queuedDuration += Double(pcm.frameLength) / PTTAudioFormat.sampleRate
guard !stopped, !frames.isEmpty else { return }
pendingDecodeCount += 1
decodeWorker.decode(frames) { [weak self] decoded in
Task { @MainActor [weak self] in
guard let self else { return }
self.pendingDecodeCount = max(0, self.pendingDecodeCount - 1)
guard !self.stopped else { return }
for pcm in decoded {
if self.engineStarted {
self.schedule(pcm)
} else {
self.queuedBuffers.append(pcm)
self.queuedDuration += Double(pcm.frameLength) / PTTAudioFormat.sampleRate
}
}
self.startIfReady(force: self.finished)
self.stopIfDrained()
}
}
startIfReady(force: false)
}
/// The burst ended: stop once everything scheduled has played out.
@@ -283,6 +328,7 @@ final class PTTBurstPlayer {
func stop() {
guard !stopped else { return }
stopped = true
pendingDecodeCount = 0
deadlineTask?.cancel()
removeConfigObserver()
queuedBuffers = []
@@ -477,7 +523,11 @@ final class PTTBurstPlayer {
guard completionState.complete() else { return }
Task { @MainActor [weak self] in
guard let self, self.engineGeneration == generation else { return }
self.scheduledBuffers.removeAll { $0.id == id }
if self.scheduledBuffers.first?.id == id {
self.scheduledBuffers.removeFirst()
} else {
self.scheduledBuffers.removeAll { $0.id == id }
}
self.stopIfDrained()
}
}
@@ -492,7 +542,7 @@ final class PTTBurstPlayer {
}
private func stopIfDrained() {
guard finished, scheduledBuffers.isEmpty else { return }
guard finished, pendingDecodeCount == 0, scheduledBuffers.isEmpty else { return }
// Started: everything scheduled has played out. Never started with
// nothing queued or in flight (e.g. no decodable frames): nothing
// will ever play. Otherwise the engine start is still pending (the
+24 -1
View File
@@ -189,7 +189,8 @@ final class PTTCaptureEngine: @unchecked Sendable {
}
engine.inputNode.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) { [weak self] buffer, _ in
self?.queue.async { self?.process(buffer, generation: generation) }
guard let copied = Self.copyPCMBuffer(buffer) else { return }
self?.queue.async { self?.process(copied, generation: generation) }
}
// Route/category changes reconfigure the engine underneath the tap;
// stop and finalize cleanly — the .m4a captured so far still sends.
@@ -323,4 +324,26 @@ final class PTTCaptureEngine: @unchecked Sendable {
}
fileURL = nil
}
/// Copies PCM samples from CoreAudio's tap buffer into an owned buffer before
/// handing off asynchronously so CoreAudio cannot recycle storage mid-encode.
private static func copyPCMBuffer(_ buffer: AVAudioPCMBuffer) -> AVAudioPCMBuffer? {
let frameLength = buffer.frameLength
guard frameLength > 0,
let copy = AVAudioPCMBuffer(pcmFormat: buffer.format, frameCapacity: frameLength)
else { return nil }
copy.frameLength = frameLength
let srcList = UnsafeMutableAudioBufferListPointer(buffer.mutableAudioBufferList)
let dstList = UnsafeMutableAudioBufferListPointer(copy.mutableAudioBufferList)
guard srcList.count == dstList.count else { return nil }
for index in 0..<srcList.count {
let byteCount = Int(srcList[index].mDataByteSize)
guard byteCount > 0,
let srcData = srcList[index].mData,
let dstData = dstList[index].mData else { continue }
memcpy(dstData, srcData, byteCount)
dstList[index].mDataByteSize = srcList[index].mDataByteSize
}
return copy
}
}
+101 -30
View File
@@ -89,6 +89,39 @@ final class ChatLiveVoiceCoordinator {
let burstID: Data
}
/// Serializes ADTS file writes off `@MainActor` while keeping `finalize`/`cancel`
/// able to flush and close deterministically before promoting or deleting the file.
private final class LiveCaptureFileWriter: @unchecked Sendable {
private let queue: DispatchQueue
private var handle: FileHandle?
init(handle: FileHandle, queue: DispatchQueue) {
self.handle = handle
self.queue = queue
}
func write(_ data: Data) {
guard !data.isEmpty else { return }
queue.async { [self] in
guard let handle else { return }
do {
try handle.write(contentsOf: data)
} catch {
SecureLogger.error("PTT: incoming burst write failed: \(error)", category: .session)
try? handle.close()
self.handle = nil
}
}
}
func closeSynchronously() {
queue.sync {
try? handle?.close()
handle = nil
}
}
}
private final class Assembly {
let burstID: Data
let peerID: PeerID
@@ -98,7 +131,7 @@ final class ChatLiveVoiceCoordinator {
var messageID: String { message.id }
var messageTimestamp: Date { message.timestamp }
let fileURL: URL
var fileHandle: FileHandle?
var fileWriter: LiveCaptureFileWriter?
/// Data packets buffered ahead of `nextSeq` (seq -> frames).
var buffered: [UInt16: [Data]] = [:]
/// Next data-packet seq to deliver (seq 0 is START).
@@ -111,21 +144,33 @@ final class ChatLiveVoiceCoordinator {
/// `ChatLiveVoiceCoordinator.gapSkipSeconds` the gap is skipped.
var gapSince: Date?
var player: PTTBurstPlayer?
var idleTimeout: Task<Void, Never>?
var idleTimer: DispatchSourceTimer?
var gapRedrain: Task<Void, Never>?
var key: AssemblyKey { AssemblyKey(peerID: peerID, scope: scope, burstID: burstID) }
init(burstID: Data, peerID: PeerID, scope: VoiceBurstScope, nickname: String, message: BitchatMessage, fileURL: URL, fileHandle: FileHandle) {
init(
burstID: Data,
peerID: PeerID,
scope: VoiceBurstScope,
nickname: String,
message: BitchatMessage,
fileURL: URL,
fileWriter: LiveCaptureFileWriter
) {
self.burstID = burstID
self.peerID = peerID
self.scope = scope
self.nickname = nickname
self.message = message
self.fileURL = fileURL
self.fileHandle = fileHandle
self.fileWriter = fileWriter
self.firstPacketAt = Date()
}
deinit {
idleTimer?.cancel()
}
}
private struct FinishedBurst {
@@ -143,6 +188,8 @@ final class ChatLiveVoiceCoordinator {
private unowned let context: any ChatLiveVoiceContext
private let fileStore: BLEIncomingFileStore
private let asyncQuotaEnforcement: Bool
private let ioQueue = DispatchQueue(label: "chat.bitchat.ptt.live-io", qos: .utility)
/// Captures live in the store's directories, so file operations go
/// through the store's (injectable) file manager.
private var fileManager: FileManager { fileStore.fileManager }
@@ -159,14 +206,18 @@ final class ChatLiveVoiceCoordinator {
/// application-support directory: they pass `false` so parallel test
/// runs never sweep each other's in-flight capture files.
/// `asyncStartupSweep` moves the disk sweep off the main actor for cold launch.
/// `asyncQuotaEnforcement` offloads the incoming-media directory scan onto
/// `ioQueue` in production while keeping synchronous unit tests deterministic.
init(
context: any ChatLiveVoiceContext,
fileStore: BLEIncomingFileStore = BLEIncomingFileStore(),
sweepsOnInit: Bool = true,
asyncStartupSweep: Bool = false
asyncStartupSweep: Bool = false,
asyncQuotaEnforcement: Bool = false
) {
self.context = context
self.fileStore = fileStore
self.asyncQuotaEnforcement = asyncQuotaEnforcement
// Orphaned partial captures from a previous session (live-only bursts
// whose finalized note never arrived) are dead weight the quota can
// never reclaim (eviction skips voice_live_* by design) — sweep them
@@ -218,8 +269,9 @@ final class ChatLiveVoiceCoordinator {
// START from another peer opens its own assembly instead of
// capturing this one's frames.
let key = AssemblyKey(peerID: peerID, scope: scope, burstID: packet.burstID)
let payloadByteCount = payload.count
if let assembly = assemblies[key] {
apply(packet, to: assembly)
apply(packet, payloadByteCount: payloadByteCount, to: assembly)
return
}
@@ -234,7 +286,7 @@ final class ChatLiveVoiceCoordinator {
guard let assembly = makeAssembly(burstID: packet.burstID, peerID: peerID, scope: scope, nickname: nickname, timestamp: timestamp) else { return }
assemblies[key] = assembly
updatePublicTalkerIndicator()
apply(packet, to: assembly)
apply(packet, payloadByteCount: payloadByteCount, to: assembly)
case .end, .canceled:
// Control packet for a burst we never saw — nothing to do.
break
@@ -365,7 +417,14 @@ final class ChatLiveVoiceCoordinator {
// finalized transfers; reserve the burst's worst case up front.
// Eviction skips voice_live_* names, so partials still streaming in
// are safe no matter which caller triggers enforcement.
fileStore.enforceQuota(reservingBytes: TransportConfig.pttMaxBurstBytes)
if asyncQuotaEnforcement {
let store = fileStore
ioQueue.async {
store.enforceQuota(reservingBytes: TransportConfig.pttMaxBurstBytes)
}
} else {
fileStore.enforceQuota(reservingBytes: TransportConfig.pttMaxBurstBytes)
}
fileManager.createFile(
atPath: fileURL.path,
contents: nil,
@@ -396,7 +455,7 @@ final class ChatLiveVoiceCoordinator {
nickname: nickname,
message: message,
fileURL: fileURL,
fileHandle: handle
fileWriter: LiveCaptureFileWriter(handle: handle, queue: ioQueue)
)
// DM bubbles ride the full inbound pipeline (store append, unread,
@@ -431,8 +490,8 @@ final class ChatLiveVoiceCoordinator {
context.setActivePublicVoiceTalker(talker)
}
private func apply(_ packet: VoiceBurstPacket, to assembly: Assembly) {
assembly.receivedBytes += packet.encode().count
private func apply(_ packet: VoiceBurstPacket, payloadByteCount: Int, to assembly: Assembly) {
assembly.receivedBytes += payloadByteCount
let elapsed = Date().timeIntervalSince(assembly.firstPacketAt)
// Flood guards: a real burst arrives at ~2 KB/s.
guard assembly.receivedBytes <= TransportConfig.pttInboundMaxBytesPerSecond * Int(elapsed + 2),
@@ -496,13 +555,14 @@ final class ChatLiveVoiceCoordinator {
}
private func deliver(_ frames: [Data], to assembly: Assembly) {
for frame in frames {
do {
try assembly.fileHandle?.write(contentsOf: ADTSFramer.frame(frame))
} catch {
SecureLogger.error("PTT: incoming burst write failed: \(error)", category: .session)
assembly.fileHandle = nil
if let writer = assembly.fileWriter, !frames.isEmpty {
let totalBytes = frames.reduce(0) { $0 + $1.count + 7 }
var batch = Data()
batch.reserveCapacity(totalBytes)
for frame in frames {
batch.append(ADTSFramer.frame(frame))
}
writer.write(batch)
}
assembly.deliveredFrames += frames.count
assembly.player?.enqueue(frames)
@@ -519,7 +579,8 @@ final class ChatLiveVoiceCoordinator {
}
private func finalize(_ assembly: Assembly) {
assembly.idleTimeout?.cancel()
assembly.idleTimer?.cancel()
assembly.idleTimer = nil
assembly.gapRedrain?.cancel()
// Deliver whatever is decodable past any remaining holes.
while !assembly.buffered.isEmpty, let smallest = assembly.buffered.keys.min() {
@@ -529,8 +590,8 @@ final class ChatLiveVoiceCoordinator {
assembly.nextSeq &+= 1
}
}
try? assembly.fileHandle?.close()
assembly.fileHandle = nil
assembly.fileWriter?.closeSynchronously()
assembly.fileWriter = nil
assemblies.removeValue(forKey: assembly.key)
updatePublicTalkerIndicator()
@@ -634,11 +695,12 @@ final class ChatLiveVoiceCoordinator {
}
private func cancelAssembly(_ assembly: Assembly) {
assembly.idleTimeout?.cancel()
assembly.idleTimer?.cancel()
assembly.idleTimer = nil
assembly.gapRedrain?.cancel()
assembly.player?.stop()
try? assembly.fileHandle?.close()
assembly.fileHandle = nil
assembly.fileWriter?.closeSynchronously()
assembly.fileWriter = nil
assemblies.removeValue(forKey: assembly.key)
updatePublicTalkerIndicator()
removeBubble(of: assembly)
@@ -650,14 +712,23 @@ final class ChatLiveVoiceCoordinator {
// MARK: - Timers
private func rescheduleIdleTimeout(for assembly: Assembly) {
assembly.idleTimeout?.cancel()
let key = assembly.key
assembly.idleTimeout = Task { @MainActor [weak self] in
try? await Task.sleep(nanoseconds: UInt64(TransportConfig.pttBurstEndTimeoutSeconds * 1_000_000_000))
guard !Task.isCancelled, let self, let assembly = self.assemblies[key] else { return }
// Talker went silent/out of range without an END.
self.finalize(assembly)
let deadline = DispatchTime.now() + TransportConfig.pttBurstEndTimeoutSeconds
if let timer = assembly.idleTimer {
timer.schedule(deadline: deadline)
return
}
let key = assembly.key
let timer = DispatchSource.makeTimerSource(queue: .main)
timer.schedule(deadline: deadline)
timer.setEventHandler { [weak self] in
MainActor.assumeIsolated {
guard let self, let assembly = self.assemblies[key] else { return }
// Talker went silent/out of range without an END.
self.finalize(assembly)
}
}
assembly.idleTimer = timer
timer.resume()
}
private func scheduleGapRedrain(for assembly: Assembly) {
@@ -697,15 +697,6 @@ final class ChatMediaTransferCoordinator {
let targetPeer = context.selectedPrivateChatPeer
let generation = imagePreparationBarrier.currentGeneration
do {
try ImageUtils.validateImageSource(at: sourceURL)
} catch {
SecureLogger.error("Image send preparation failed: \(error)", category: .session)
context.addSystemMessage("Failed to prepare image for sending.")
return
}
let prepareImagePacket = self.prepareImagePacket
let barrier = imagePreparationBarrier
Task.detached(priority: .userInitiated) { [weak self, barrier] in
@@ -714,7 +705,8 @@ final class ChatMediaTransferCoordinator {
try barrier.performIfCurrent(
generation: generation,
operation: {
try prepareImagePacket(sourceURL)
try ImageUtils.validateImageSource(at: sourceURL)
return try prepareImagePacket(sourceURL)
}
)
}
+3 -1
View File
@@ -215,7 +215,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
lazy var liveVoiceCoordinator = ChatLiveVoiceCoordinator(
context: self,
sweepsOnInit: !TestEnvironment.isRunningTests,
asyncStartupSweep: true
asyncStartupSweep: true,
asyncQuotaEnforcement: !TestEnvironment.isRunningTests
)
lazy var verificationCoordinator = ChatVerificationCoordinator(context: self)
lazy var groupCoordinator = ChatGroupCoordinator(context: self)
@@ -1708,6 +1709,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
LocationNotesPool.shared.resetForPanic()
LocationNotesDependencies.clearCachedIdentitiesForPanic()
WaveformCache.shared.resetForPanic()
ImageDownsampler.resetForPanic()
// Drop private group keys and rosters (keychain + disk)
groupStore.wipe()
+50 -11
View File
@@ -147,6 +147,25 @@ enum GlobeGeometry {
/// Sutherland–Hodgman clip of a polygon to the rect.
static func clipPolygon(_ pts: [CGPoint], to rect: ClipRect) -> [CGPoint] {
guard let first = pts.first else { return pts }
let left = CGFloat(rect.left), right = CGFloat(rect.right)
let top = CGFloat(rect.top), bottom = CGFloat(rect.bottom)
// Fast bounding-box pre-check avoids 4 edge passes and allocations when
// a polygon is fully inside or fully outside the expanded clip rect.
var minX = first.x, maxX = first.x
var minY = first.y, maxY = first.y
for p in pts.dropFirst() {
if p.x < minX { minX = p.x } else if p.x > maxX { maxX = p.x }
if p.y < minY { minY = p.y } else if p.y > maxY { maxY = p.y }
}
if maxX < left || minX > right || maxY < top || minY > bottom {
return []
}
if minX >= left && maxX <= right && minY >= top && maxY <= bottom {
return pts
}
func clipEdge(
_ input: [CGPoint],
inside: (CGPoint) -> Bool,
@@ -167,8 +186,6 @@ enum GlobeGeometry {
}
return result
}
let left = CGFloat(rect.left), right = CGFloat(rect.right)
let top = CGFloat(rect.top), bottom = CGFloat(rect.bottom)
var out = pts
out = clipEdge(out, inside: { $0.x >= left }) { a, b in
CGPoint(x: left, y: a.y + (left - a.x) / (b.x - a.x) * (b.y - a.y))
@@ -214,6 +231,31 @@ enum GlobeGeometry {
)
}
/// Precomputed disc probe point and its geographic coordinates for one frame's camera,
/// avoiding redundant `GlobeMath.unproject` calls for every back-crossing land ring.
struct UnprojectedSample {
let nx: Double
let ny: Double
let lat: Double
let lon: Double
}
private static let inversionProbeCoords: [(Double, Double)] = [
(0, 0), (-0.5, 0), (0.5, 0), (0, -0.5), (0, 0.5),
(-0.35, -0.35), (0.35, -0.35), (-0.35, 0.35), (0.35, 0.35)
]
/// Unprojects the 9 fixed disc probes once per frame for `projectedFillNeedsInversion`.
static func unprojectInversionSamples(centerLat: Double, centerLon: Double) -> [UnprojectedSample] {
var out: [UnprojectedSample] = []
out.reserveCapacity(inversionProbeCoords.count)
for (nx, ny) in inversionProbeCoords {
guard let location = GlobeMath.unproject(x: nx, y: ny, centerLat: centerLat, centerLon: centerLon) else { continue }
out.append(UnprojectedSample(nx: nx, ny: ny, lat: location.lat, lon: location.lon))
}
return out
}
/// Orthographic projection can choose the wrong side of the horizon closure for very
/// large rings. A single center-point check is ambiguous for a large polygon and
/// caused an occasional whole-disc fill, so compare several visible points with the
@@ -225,18 +267,15 @@ enum GlobeGeometry {
cy: Double,
r: Double,
centerLat: Double,
centerLon: Double
centerLon: Double,
samples: [UnprojectedSample]? = nil
) -> Bool {
let samples: [(Double, Double)] = [
(0, 0), (-0.5, 0), (0.5, 0), (0, -0.5), (0, 0.5),
(-0.35, -0.35), (0.35, -0.35), (-0.35, 0.35), (0.35, 0.35)
]
let resolvedSamples = samples ?? unprojectInversionSamples(centerLat: centerLat, centerLon: centerLon)
var normalErrors = 0
var invertedErrors = 0
for (nx, ny) in samples {
guard let location = GlobeMath.unproject(x: nx, y: ny, centerLat: centerLat, centerLon: centerLon) else { continue }
let geographicInside = ringContains(ring, lat: location.lat, lon: location.lon)
let projectedInside = polygonContains(polygon, x: cx + nx * r, y: cy + ny * r)
for sample in resolvedSamples {
let geographicInside = ringContains(ring, lat: sample.lat, lon: sample.lon)
let projectedInside = polygonContains(polygon, x: cx + sample.nx * r, y: cy + sample.ny * r)
if projectedInside != geographicInside { normalErrors += 1 }
if !projectedInside != geographicInside { invertedErrors += 1 }
}
+85 -26
View File
@@ -150,20 +150,76 @@ struct GlobeMotionGovernor {
}
}
/// High-frequency camera state observed only by `GlobeView`, isolating 120 FPS drags,
/// flings, and zooms from `GeohashPickerView`'s chrome overlays.
@MainActor
final class GlobeCameraState: ObservableObject {
fileprivate(set) var centerLat: Double
fileprivate(set) var centerLon: Double
fileprivate(set) var zoom: Double
fileprivate(set) var isInteracting = false
fileprivate(set) var isAnimating = false
/// Detail level for moving frames; `.full` whenever the globe is at rest.
fileprivate(set) var motionDetail: GlobeMotionDetail = .full
init(centerLat: Double, centerLon: Double, zoom: Double) {
self.centerLat = centerLat
self.centerLon = centerLon
self.zoom = zoom
}
fileprivate func update(lat: Double, lon: Double, zoom newZoom: Double? = nil) {
let nextZoom = newZoom ?? zoom
guard centerLat != lat || centerLon != lon || zoom != nextZoom else { return }
objectWillChange.send()
centerLat = lat
centerLon = lon
zoom = nextZoom
}
fileprivate func setZoom(_ newZoom: Double) {
guard zoom != newZoom else { return }
objectWillChange.send()
zoom = newZoom
}
fileprivate func setInteracting(_ value: Bool) {
guard isInteracting != value else { return }
objectWillChange.send()
isInteracting = value
}
fileprivate func setAnimating(_ value: Bool) {
guard isAnimating != value else { return }
objectWillChange.send()
isAnimating = value
}
fileprivate func setMotionDetail(_ value: GlobeMotionDetail) {
guard motionDetail != value else { return }
objectWillChange.send()
motionDetail = value
}
}
/// Hoisted state for the interactive 3D globe: view center, zoom, geohash precision
/// and the current selection. All mutation funnels through this class so rendering,
/// gestures and buttons stay in sync.
@MainActor
final class GlobeState: ObservableObject {
@Published private(set) var centerLat: Double
@Published private(set) var centerLon: Double
@Published private(set) var zoom: Double
/// Observed by `GlobeView` for per-frame rendering without invalidating outer chrome.
let camera: GlobeCameraState
@Published private(set) var precision: Int
@Published private(set) var selectedGeohash = ""
@Published private(set) var isInteracting = false
@Published private(set) var isAnimating = false
var centerLat: Double { camera.centerLat }
var centerLon: Double { camera.centerLon }
var zoom: Double { camera.zoom }
var isInteracting: Bool { camera.isInteracting }
var isAnimating: Bool { camera.isAnimating }
/// Detail level for moving frames; `.full` whenever the globe is at rest.
@Published private(set) var motionDetail: GlobeMotionDetail = .full
var motionDetail: GlobeMotionDetail { camera.motionDetail }
private(set) var baseRadius: Double = 0
private(set) var screenMin: Double = 0
@@ -211,9 +267,9 @@ final class GlobeState: ObservableObject {
/// target once the viewport is laid out.
init(targetLat: Double, targetLon: Double, initialPrecision: Int, startZoomedOut: Bool) {
let precision = min(max(initialPrecision, 1), GlobeMath.maxPrecision)
centerLat = startZoomedOut ? targetLat * 0.4 : targetLat
centerLon = startZoomedOut ? GlobeMath.normalizeLon(targetLon - 70) : targetLon
zoom = GlobeMath.minZoom
let initialLat = startZoomedOut ? targetLat * 0.4 : targetLat
let initialLon = startZoomedOut ? GlobeMath.normalizeLon(targetLon - 70) : targetLon
self.camera = GlobeCameraState(centerLat: initialLat, centerLon: initialLon, zoom: GlobeMath.minZoom)
self.precision = precision
if startZoomedOut {
introTarget = (targetLat, targetLon, precision)
@@ -241,10 +297,10 @@ final class GlobeState: ObservableObject {
// Cinematic intro: spin and zoom from the far view into the target location.
animateTo(lat: target.lat, lon: target.lon, zoom: targetZoom, precision: target.precision, duration: 1.4)
} else {
centerLat = target.lat
centerLon = target.lon
zoom = targetZoom
precision = target.precision
camera.update(lat: target.lat, lon: target.lon, zoom: targetZoom)
if precision != target.precision {
precision = target.precision
}
}
}
syncSelection()
@@ -254,7 +310,7 @@ final class GlobeState: ObservableObject {
func beginInteraction() {
// Mark the touch first so catching a fling continues the same motion session.
isInteracting = true
camera.setInteracting(true)
motionStateChanged()
cancelAnimations()
}
@@ -263,7 +319,7 @@ final class GlobeState: ObservableObject {
/// within the same motion session.
func endInteraction(flingVelocityX vx: Double = 0, flingVelocityY vy: Double = 0) {
fling(vx: vx, vy: vy)
isInteracting = false
camera.setInteracting(false)
motionStateChanged()
}
@@ -272,17 +328,18 @@ final class GlobeState: ObservableObject {
let r = globeRadius
guard r > 0 else { return }
let degPerPoint = 180 / (Double.pi * r)
centerLon = GlobeMath.normalizeLon(centerLon - dx * degPerPoint)
let nextLon = GlobeMath.normalizeLon(centerLon - dx * degPerPoint)
// A view already past the drag limit (a polar target) may move toward the
// equator but not further out, and never snaps back to the limit.
centerLat = clampedLat(centerLat + dy * degPerPoint, reaching: centerLat)
let nextLat = clampedLat(centerLat + dy * degPerPoint, reaching: centerLat)
camera.update(lat: nextLat, lon: nextLon)
syncSelection()
}
/// Continuous zoom from pinch gestures; precision follows automatically.
func zoomBy(_ factor: Double) {
guard factor != 1, factor.isFinite, factor > 0 else { return }
zoom = min(max(zoom * factor, GlobeMath.minZoom), GlobeMath.maxZoom)
camera.setZoom(min(max(zoom * factor, GlobeMath.minZoom), GlobeMath.maxZoom))
syncPrecisionFromZoom()
syncSelection()
}
@@ -334,7 +391,7 @@ final class GlobeState: ObservableObject {
func cancelAnimations() {
motion = nil
if isAnimating {
isAnimating = false
camera.setAnimating(false)
motionStateChanged()
}
}
@@ -342,7 +399,7 @@ final class GlobeState: ObservableObject {
private func start(_ newMotion: Motion) {
motion = newMotion
if !isAnimating {
isAnimating = true
camera.setAnimating(true)
motionStateChanged()
}
clock.start()
@@ -350,7 +407,7 @@ final class GlobeState: ObservableObject {
private func finishMotion() {
motion = nil
isAnimating = false
camera.setAnimating(false)
motionStateChanged()
}
@@ -405,12 +462,14 @@ final class GlobeState: ObservableObject {
private func applyTween(_ tween: Tween, t: Double) {
// The target itself is always reachable: a polar cell's center can lie past
// the drag limit, and clamping it would end the animation on another cell.
centerLat = clampedLat(tween.startLat + (tween.endLat - tween.startLat) * t, reaching: tween.endLat)
centerLon = GlobeMath.normalizeLon(tween.startLon + tween.dLon * t)
let nextLat = clampedLat(tween.startLat + (tween.endLat - tween.startLat) * t, reaching: tween.endLat)
let nextLon = GlobeMath.normalizeLon(tween.startLon + tween.dLon * t)
// Exponential interpolation feels natural for zoom.
zoom = tween.startZoom * pow(tween.endZoom / tween.startZoom, t)
let nextZoom = tween.startZoom * pow(tween.endZoom / tween.startZoom, t)
camera.update(lat: nextLat, lon: nextLon, zoom: nextZoom)
if let target = tween.targetPrecision {
precision = min(max(target, 1), GlobeMath.maxPrecision)
let clamped = min(max(target, 1), GlobeMath.maxPrecision)
if precision != clamped { precision = clamped }
} else {
syncPrecisionFromZoom()
}
@@ -432,7 +491,7 @@ final class GlobeState: ObservableObject {
}
private func publishMotionDetail() {
if motionDetail != governor.detail { motionDetail = governor.detail }
camera.setMotionDetail(governor.detail)
}
/// Clamps to the drag limit, widened (up to that pole) on `reach`'s side only.
+182 -88
View File
@@ -34,6 +34,7 @@ struct GlobeColors: Equatable {
/// crosshair at the screen center.
struct GlobeView: View {
@ObservedObject var state: GlobeState
@ObservedObject private var camera: GlobeCameraState
let colors: GlobeColors
let world: GlobeWorldData
@@ -45,6 +46,13 @@ struct GlobeView: View {
@State private var selectionFeedback = UISelectionFeedbackGenerator()
#endif
init(state: GlobeState, colors: GlobeColors, world: GlobeWorldData) {
self.state = state
self._camera = ObservedObject(wrappedValue: state.camera)
self.colors = colors
self.world = world
}
var body: some View {
GeometryReader { proxy in
ZStack {
@@ -53,10 +61,10 @@ struct GlobeView: View {
.equatable()
let renderer = GlobeRenderer(
centerLat: state.centerLat,
centerLon: state.centerLon,
centerLat: camera.centerLat,
centerLon: camera.centerLon,
radius: state.globeRadius,
zoom: state.zoom,
zoom: camera.zoom,
selectedGeohash: state.selectedGeohash,
detail: state.frameDetail,
colors: colors,
@@ -70,7 +78,7 @@ struct GlobeView: View {
GlobeTouchLayer(state: state)
// Isolated so its pulse does not redraw the globe geometry.
// Isolated so its GPU opacity pulse never redraws the globe geometry.
GlobeCrosshair(color: colors.accent, isInMotion: state.isInMotion)
.allowsHitTesting(false)
}
@@ -158,33 +166,36 @@ private struct GlobeCrosshair: View {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@Environment(\.scenePhase) private var scenePhase
@State private var isLowPowerMode = ProcessInfo.processInfo.isLowPowerModeEnabled
@State private var pulseDimmed = false
private var isPaused: Bool {
isInMotion || reduceMotion || scenePhase != .active || isLowPowerMode
}
var body: some View {
TimelineView(.animation(minimumInterval: 1.0 / 20.0, paused: isPaused)) { timeline in
Canvas { context, size in
let alpha = isPaused ? 0.9 : Self.pulse(at: timeline.date)
let shading = GraphicsContext.Shading.color(color.opacity(alpha))
let cx = size.width / 2
let cy = size.height / 2
let gap: CGFloat = 5
let len: CGFloat = 9
var path = Path()
path.move(to: CGPoint(x: cx - gap - len, y: cy))
path.addLine(to: CGPoint(x: cx - gap, y: cy))
path.move(to: CGPoint(x: cx + gap, y: cy))
path.addLine(to: CGPoint(x: cx + gap + len, y: cy))
path.move(to: CGPoint(x: cx, y: cy - gap - len))
path.addLine(to: CGPoint(x: cx, y: cy - gap))
path.move(to: CGPoint(x: cx, y: cy + gap))
path.addLine(to: CGPoint(x: cx, y: cy + gap + len))
context.stroke(path, with: shading, lineWidth: 1.6)
context.fill(Path(ellipseIn: CGRect(x: cx - 1.8, y: cy - 1.8, width: 3.6, height: 3.6)), with: shading)
}
// Static vector geometry + Core Animation opacity pulse runs entirely on the
// compositor with zero CPU/SwiftUI redraw ticks while idle.
Canvas { context, size in
let shading = GraphicsContext.Shading.color(color)
let cx = size.width / 2
let cy = size.height / 2
let gap: CGFloat = 5
let len: CGFloat = 9
var path = Path()
path.move(to: CGPoint(x: cx - gap - len, y: cy))
path.addLine(to: CGPoint(x: cx - gap, y: cy))
path.move(to: CGPoint(x: cx + gap, y: cy))
path.addLine(to: CGPoint(x: cx + gap + len, y: cy))
path.move(to: CGPoint(x: cx, y: cy - gap - len))
path.addLine(to: CGPoint(x: cx, y: cy - gap))
path.move(to: CGPoint(x: cx, y: cy + gap))
path.addLine(to: CGPoint(x: cx, y: cy + gap + len))
context.stroke(path, with: shading, lineWidth: 1.6)
context.fill(Path(ellipseIn: CGRect(x: cx - 1.8, y: cy - 1.8, width: 3.6, height: 3.6)), with: shading)
}
.opacity(isPaused ? 0.9 : (pulseDimmed ? 0.45 : 1.0))
.onAppear { syncPulseAnimation() }
.onChange(of: isPaused) { _ in syncPulseAnimation() }
.onReceive(
NotificationCenter.default.publisher(for: .NSProcessInfoPowerStateDidChange)
.receive(on: RunLoop.main)
@@ -193,12 +204,17 @@ private struct GlobeCrosshair: View {
}
}
/// 0.45 → 1 → 0.45 over 2.2s, eased like the Android picker's reversing tween.
private static func pulse(at date: Date) -> Double {
let period = 1.1
let phase = date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: period * 2) / period
let t = phase <= 1 ? phase : 2 - phase
return 0.45 + 0.55 * GlobeEasing.fastOutSlowIn(t)
private func syncPulseAnimation() {
if isPaused {
withAnimation(.linear(duration: 0.12)) {
pulseDimmed = false
}
} else {
pulseDimmed = false
withAnimation(.easeInOut(duration: 1.1).repeatForever(autoreverses: true)) {
pulseDimmed = true
}
}
}
}
@@ -220,6 +236,25 @@ private struct GlobeRenderer {
private typealias DiscPoint = GlobeGeometry.DiscPoint
/// Precomputed trigonometric terms for graticule parallels and meridians at each
/// motion detail step (4°, 8°, 10°), avoiding ~1,600 sin/cos calls per frame.
private static let graticuleCurvesByStep: [Int: [[GlobeMath.Terms]]] = [
4: buildGraticuleCurves(step: 4),
8: buildGraticuleCurves(step: 8),
10: buildGraticuleCurves(step: 10)
]
private static func buildGraticuleCurves(step: Double) -> [[GlobeMath.Terms]] {
var curves: [[GlobeMath.Terms]] = []
for lat in stride(from: -75.0, through: 75.0, by: 15) {
curves.append(stride(from: -180.0, through: 180.0, by: step).map { GlobeMath.Terms(lat: lat, lon: $0) })
}
for lon in stride(from: -180.0, to: 180.0, by: 15) {
curves.append(stride(from: -90.0, through: 90.0, by: step).map { GlobeMath.Terms(lat: $0, lon: lon) })
}
return curves
}
func draw(in context: inout GraphicsContext, size: CGSize) {
guard radius > 0, size.width > 0, size.height > 0 else { return }
let cx = Double(size.width) / 2
@@ -227,6 +262,7 @@ private struct GlobeRenderer {
let r = radius
let center = CGPoint(x: cx, y: cy)
let projector = GlobeMath.PreparedProjector(centerLat: centerLat, centerLon: centerLon)
let inversionSamples = GlobeGeometry.unprojectInversionSamples(centerLat: centerLat, centerLon: centerLon)
let clip = GlobeGeometry.ClipRect(size: size)
let screenRect = CGRect(origin: .zero, size: size)
// Once the disc covers the screen, the sphere-wide gradients are constant across
@@ -270,13 +306,27 @@ private struct GlobeRenderer {
context.fill(Path(screenRect), with: .color(colors.oceanCenter))
}
drawGraticule(in: &context, cx: cx, cy: cy, r: r, clip: clip)
drawGraticule(in: &context, projector: projector, cx: cx, cy: cy, r: r, clip: clip)
// Fill every landmass first. Coastlines are drawn in a separate final pass so a
// large continent fill can never cover an island outline drawn earlier.
// Fill every landmass first. Non-inverted rings are batched into one CG path
// fill; coastlines are drawn in a separate final pass so a large continent fill
// can never cover an island outline drawn earlier.
var landFill = Path()
var coastlines = Path()
for ring in world.land {
drawLand(ring, in: &context, projector: projector, cx: cx, cy: cy, r: r, clip: clip, coastlines: &coastlines)
drawLand(
ring,
in: &context,
projector: projector,
inversionSamples: inversionSamples,
cx: cx, cy: cy, r: r,
clip: clip,
landFill: &landFill,
coastlines: &coastlines
)
}
if !landFill.isEmpty {
context.fill(landFill, with: .color(colors.land))
}
context.stroke(coastlines, with: .color(colors.coastline), lineWidth: 1.4 * pixel)
@@ -355,13 +405,20 @@ private struct GlobeRenderer {
}
}
private func drawGraticule(in context: inout GraphicsContext, cx: Double, cy: Double, r: Double, clip: GlobeGeometry.ClipRect) {
let step = detail.graticuleStepDegrees
private func drawGraticule(
in context: inout GraphicsContext,
projector: GlobeMath.PreparedProjector,
cx: Double, cy: Double, r: Double,
clip: GlobeGeometry.ClipRect
) {
let stepKey = Int(detail.graticuleStepDegrees.rounded())
let curves = Self.graticuleCurvesByStep[stepKey] ?? Self.buildGraticuleCurves(step: detail.graticuleStepDegrees)
var path = Path()
func trace(_ points: [(lat: Double, lon: Double)]) {
for curve in curves {
var prev: GlobeMath.Projection?
for point in points {
if let p = GlobeMath.project(lat: point.lat, lon: point.lon, centerLat: centerLat, centerLon: centerLon), p.cosC > 0.02 {
for terms in curve {
let p = projector.project(terms)
if p.cosC > 0.02 {
if let pp = prev, let segment = GlobeGeometry.clipSegment(
CGPoint(x: cx + pp.x * r, y: cy + pp.y * r),
CGPoint(x: cx + p.x * r, y: cy + p.y * r),
@@ -376,14 +433,6 @@ private struct GlobeRenderer {
}
}
}
// Latitude lines
for lat in stride(from: -75.0, through: 75.0, by: 15) {
trace(stride(from: -180.0, through: 180.0, by: step).map { (lat, $0) })
}
// Longitude lines
for lon in stride(from: -180.0, to: 180.0, by: 15) {
trace(stride(from: -90.0, through: 90.0, by: step).map { ($0, lon) })
}
context.stroke(path, with: .color(colors.graticule), lineWidth: pixel)
}
@@ -391,8 +440,10 @@ private struct GlobeRenderer {
_ ring: GlobeRing,
in context: inout GraphicsContext,
projector: GlobeMath.PreparedProjector,
inversionSamples: [GlobeGeometry.UnprojectedSample],
cx: Double, cy: Double, r: Double,
clip: GlobeGeometry.ClipRect,
landFill: inout Path,
coastlines: inout Path
) {
let pointStride = ring.count >= 64 ? detail.landPointStride : 1
@@ -411,31 +462,26 @@ private struct GlobeRenderer {
guard anyFront else { return }
appendRuns(GlobeGeometry.frontRuns(pts), to: &coastlines, cx: cx, cy: cy, r: r, clip: clip)
let polygon = GlobeGeometry.fillPolygon(pts, cx: cx, cy: cy, r: r)
let invert = anyBack && GlobeGeometry.projectedFillNeedsInversion(
polygon: polygon, ring: ring, cx: cx, cy: cy, r: r, centerLat: centerLat, centerLon: centerLon
)
fill(pts, polygon: polygon, color: colors.land, in: &context, cx: cx, cy: cy, r: r, clip: clip, invert: invert)
}
private func fill(
_ pts: [DiscPoint],
polygon: [CGPoint]? = nil,
color: Color,
in context: inout GraphicsContext,
cx: Double, cy: Double, r: Double,
clip: GlobeGeometry.ClipRect,
invert: Bool = false
) {
guard pts.contains(where: \.front) else { return }
let poly = polygon ?? GlobeGeometry.fillPolygon(pts, cx: cx, cy: cy, r: r)
guard poly.count >= 3 else { return }
let clipped = GlobeGeometry.clipPolygon(poly, to: clip)
let polygon = GlobeGeometry.fillPolygon(pts, cx: cx, cy: cy, r: r)
guard polygon.count >= 3 else { return }
let invert = anyBack && GlobeGeometry.projectedFillNeedsInversion(
polygon: polygon,
ring: ring,
cx: cx,
cy: cy,
r: r,
centerLat: centerLat,
centerLon: centerLon,
samples: inversionSamples
)
let clipped = GlobeGeometry.clipPolygon(polygon, to: clip)
guard clipped.count >= 3 else { return }
var path = Path()
if invert {
// Even-odd filling with the globe disc flips the one ring whose horizon
// closure the projection put on the wrong side.
var path = Path()
let clipBounds = CGRect(x: clip.left, y: clip.top, width: clip.right - clip.left, height: clip.bottom - clip.top)
let discRect = CGRect(x: cx - r, y: cy - r, width: r * 2, height: r * 2)
if discRect.contains(clipBounds) {
@@ -443,10 +489,31 @@ private struct GlobeRenderer {
} else {
path.addEllipse(in: discRect)
}
path.addLines(clipped)
path.closeSubpath()
context.fill(path, with: .color(colors.land), style: FillStyle(eoFill: true))
} else {
landFill.addLines(clipped)
landFill.closeSubpath()
}
}
private func fill(
_ pts: [DiscPoint],
color: Color,
in context: inout GraphicsContext,
cx: Double, cy: Double, r: Double,
clip: GlobeGeometry.ClipRect
) {
guard pts.contains(where: \.front) else { return }
let poly = GlobeGeometry.fillPolygon(pts, cx: cx, cy: cy, r: r)
guard poly.count >= 3 else { return }
let clipped = GlobeGeometry.clipPolygon(poly, to: clip)
guard clipped.count >= 3 else { return }
var path = Path()
path.addLines(clipped)
path.closeSubpath()
context.fill(path, with: .color(color), style: FillStyle(eoFill: invert))
context.fill(path, with: .color(color))
}
private func drawCities(
@@ -467,7 +534,19 @@ private struct GlobeRenderer {
}
let width = Double(size.width)
let height = Double(size.height)
for city in world.cities where city.rank <= maxRank {
// Batch city dots into 4 quantized opacity bands per color so dozens of visible
// cities become at most 8 fill calls instead of one CG fill per dot.
let alphaBands: [Double] = [0.35, 0.58, 0.80, 1.0]
var capitalPaths = Array(repeating: Path(), count: alphaBands.count)
var cityPaths = Array(repeating: Path(), count: alphaBands.count)
var labels: [(name: String, point: CGPoint, alpha: Double)] = []
let canShowLabels = detail.showCityLabels && zoom >= 2.5
// `world.cities` is sorted by `rank` ascending, so we can stop as soon as we
// pass `maxRank`.
for city in world.cities {
if city.rank > maxRank { break }
let p = projector.project(city.terms)
guard p.cosC >= 0.03 else { continue }
let sx = cx + p.x * r
@@ -477,24 +556,39 @@ private struct GlobeRenderer {
let alpha = min(max(p.cosC, 0.25), 1)
let important = city.capital || city.megacity
let dotRadius = important ? 2.6 : 1.8
let dotColor = city.capital ? colors.accent.opacity(alpha) : colors.label.opacity(alpha * 0.85)
context.fill(
Path(ellipseIn: CGRect(x: sx - dotRadius, y: sy - dotRadius, width: dotRadius * 2, height: dotRadius * 2)),
with: .color(dotColor)
)
if detail.showCityLabels && (zoom >= 6 || (important && zoom >= 2.5)) {
drawLabel(
city.name,
at: CGPoint(x: sx + dotRadius + 3, y: sy),
anchor: .leading,
size: 10,
weight: .medium,
color: colors.label.opacity(200 / 255 * alpha),
halo: colors.labelHalo.opacity(140 / 255 * alpha),
in: &context
)
let dotRect = CGRect(x: sx - dotRadius, y: sy - dotRadius, width: dotRadius * 2, height: dotRadius * 2)
let band = min(alphaBands.count - 1, Int(((alpha - 0.25) / 0.75) * Double(alphaBands.count)))
if city.capital {
capitalPaths[band].addEllipse(in: dotRect)
} else {
cityPaths[band].addEllipse(in: dotRect)
}
if canShowLabels && (zoom >= 6 || important) {
labels.append((city.name, CGPoint(x: sx + dotRadius + 3, y: sy), alpha))
}
}
for band in alphaBands.indices {
if !cityPaths[band].isEmpty {
context.fill(cityPaths[band], with: .color(colors.label.opacity(alphaBands[band] * 0.85)))
}
if !capitalPaths[band].isEmpty {
context.fill(capitalPaths[band], with: .color(colors.accent.opacity(alphaBands[band])))
}
}
for label in labels {
drawLabel(
label.name,
at: label.point,
anchor: .leading,
size: 10,
weight: .medium,
color: colors.label.opacity(200 / 255 * label.alpha),
halo: colors.labelHalo.opacity(140 / 255 * label.alpha),
in: &context
)
}
}
@@ -557,7 +651,7 @@ private struct GlobeRenderer {
}
/// Text with a thin halo in the background color so labels stay legible over land,
/// grid lines and the limb shading.
/// grid lines and the limb shading. Uses 4 cardinal halo offsets (5 draws total vs 9).
private func drawLabel(
_ string: String,
at point: CGPoint,
@@ -573,7 +667,7 @@ private struct GlobeRenderer {
)
resolved.shading = .color(halo)
let w = size * 0.09
for (dx, dy) in [(-w, 0), (w, 0), (0, -w), (0, w), (-w, -w), (w, -w), (-w, w), (w, w)] {
for (dx, dy) in [(-w, 0), (w, 0), (0, -w), (0, w)] {
context.draw(resolved, at: CGPoint(x: point.x + dx, y: point.y + dy), anchor: anchor)
}
resolved.shading = .color(color)
+8
View File
@@ -55,6 +55,14 @@ struct GlobeWorldData: Sendable {
self.land = land
self.borders = borders
self.cities = cities
.enumerated()
.sorted { lhs, rhs in
if lhs.element.rank != rhs.element.rank {
return lhs.element.rank < rhs.element.rank
}
return lhs.offset < rhs.offset
}
.map(\.element)
}
private init(bundle: Bundle) {
@@ -77,6 +77,13 @@ struct ImagePreviewView: View {
private func loadImage() {
let imageURL = url
if let cached = ImageDownsampler.cachedImage(
for: imageURL,
maxPixelSize: ImageDownsampler.fullScreenMaxPixelSize
) {
self.platformImage = cached
return
}
DispatchQueue.global(qos: .userInitiated).async {
guard let image = ImageDownsampler.loadDownsampledImage(
from: imageURL,
@@ -247,6 +247,12 @@ struct BlockRevealImageView: View {
loadGeneration &+= 1
let generation = loadGeneration
let imageURL = url
if let cached = ImageDownsampler.cachedImage(for: imageURL, maxPixelSize: maxPixelSize) {
self.platformImage = cached
self.loadedMaxPixelSize = maxPixelSize
self.aspectRatio = cached.size.height > 0 ? cached.size.width / cached.size.height : 1
return
}
DispatchQueue.global(qos: .userInitiated).async {
let image = ImageDownsampler.loadDownsampledImage(
from: imageURL,
@@ -85,4 +85,39 @@ struct ImageUtilsTests {
#expect(FileManager.default.fileExists(atPath: firstURL.path))
#expect(FileManager.default.fileExists(atPath: secondURL.path))
}
@Test
func processImageAtURL_downsamplesAndWritesJpeg() throws {
let sourceImage = makePlatformImage(size: CGSize(width: 800, height: 600))
let sourceDir = makeTemporaryDirectoryURL("image-src-\(UUID().uuidString)")
let outputDir = makeTemporaryDirectoryURL("image-dst-\(UUID().uuidString)")
defer {
try? FileManager.default.removeItem(at: sourceDir)
try? FileManager.default.removeItem(at: outputDir)
}
let sourceURL = try ImageUtils.processImage(sourceImage, maxDimension: 800, outputDirectory: sourceDir)
let downsampledURL = try ImageUtils.processImage(at: sourceURL, maxDimension: 200, outputDirectory: outputDir)
let data = try Data(contentsOf: downsampledURL)
#expect(data.starts(with: Data([0xFF, 0xD8])))
let loaded = try #require(ImageDownsampler.loadDownsampledImage(from: downsampledURL, maxPixelSize: 1024))
#expect(max(loaded.size.width, loaded.size.height) <= 200.5)
}
@Test
func imageDownsampler_cachesAndClearsOnPanicReset() throws {
let image = makePlatformImage(size: CGSize(width: 128, height: 128))
let dir = makeTemporaryDirectoryURL("image-cache-\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: dir) }
let fileURL = try ImageUtils.processImage(image, maxDimension: 128, outputDirectory: dir)
#expect(ImageDownsampler.cachedImage(for: fileURL, maxPixelSize: 64) == nil)
let decoded = try #require(ImageDownsampler.loadDownsampledImage(from: fileURL, maxPixelSize: 64))
let cached = try #require(ImageDownsampler.cachedImage(for: fileURL, maxPixelSize: 64))
#expect(decoded === cached)
ImageDownsampler.resetForPanic()
#expect(ImageDownsampler.cachedImage(for: fileURL, maxPixelSize: 64) == nil)
}
}
+39
View File
@@ -1,3 +1,4 @@
import Combine
import CoreGraphics
import Foundation
import Testing
@@ -482,4 +483,42 @@ struct GeohashPickerTargetTests {
#expect(GeohashCoverage.string(forPrecision: 5, locale: Locale(identifier: "de_DE")) == "~4.9 km")
#expect(GeohashCoverage.string(forPrecision: 2, locale: Locale(identifier: "en_US")) == "~777 mi")
}
@Test func worldDataSortsCitiesStablyByRankAscending() {
let cities = [
GlobeCity(name: "Low", lat: 0, lon: 0, rank: 4, capital: false, megacity: false),
GlobeCity(name: "TopA", lat: 1, lon: 1, rank: 1, capital: true, megacity: false),
GlobeCity(name: "Mid", lat: 2, lon: 2, rank: 3, capital: false, megacity: true),
GlobeCity(name: "TopB", lat: 3, lon: 3, rank: 1, capital: false, megacity: true)
]
let world = GlobeWorldData(land: [], borders: [], cities: cities)
#expect(world.cities.map(\.name) == ["TopA", "TopB", "Mid", "Low"])
}
@Test func clipPolygonFastAcceptsInsideAndRejectsOutside() {
let rect = GlobeGeometry.ClipRect(left: 0, top: 0, right: 100, bottom: 100)
let inside = [CGPoint(x: 10, y: 10), CGPoint(x: 90, y: 10), CGPoint(x: 50, y: 90)]
#expect(GlobeGeometry.clipPolygon(inside, to: rect) == inside)
let outside = [CGPoint(x: 200, y: 200), CGPoint(x: 250, y: 200), CGPoint(x: 220, y: 250)]
#expect(GlobeGeometry.clipPolygon(outside, to: rect).isEmpty)
}
@Test func cameraDragWithinCellDoesNotInvalidateChromeObservable() {
let state = GlobeState(targetLat: 48.2, targetLon: 16.37, initialPrecision: 2, startZoomedOut: false)
state.setViewport(baseRadius: 200, screenMin: 400, animateIntro: false)
var chromeInvalidations = 0
var cameraInvalidations = 0
let chromeSub = state.objectWillChange.sink { chromeInvalidations += 1 }
let cameraSub = state.camera.objectWillChange.sink { cameraInvalidations += 1 }
defer {
chromeSub.cancel()
cameraSub.cancel()
}
// Tiny rotation stays within the same precision-2 geohash cell.
state.rotateBy(dx: 0.5, dy: 0.5)
#expect(cameraInvalidations == 1)
#expect(chromeInvalidations == 0)
}
}
+24
View File
@@ -83,6 +83,30 @@ struct PTTAudioTests {
#expect(energy > 1)
}
@Test func encoderAndDecoderReuseScratchBuffersAcrossChunks() throws {
let encoder = try #require(PTTFrameEncoder())
let decoder = try #require(PTTFrameDecoder())
let format = try #require(PTTAudioFormat.pcmFormat)
let chunkFrames = AVAudioFrameCount(0.2 * PTTAudioFormat.sampleRate)
var totalDecodedSamples = 0
for chunk in 0..<4 {
let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: chunkFrames))
buffer.frameLength = chunkFrames
let channel = try #require(buffer.floatChannelData?[0])
let baseIndex = chunk * Int(chunkFrames)
for i in 0..<Int(chunkFrames) {
channel[i] = sinf(2 * .pi * 440 * Float(baseIndex + i) / Float(PTTAudioFormat.sampleRate)) * 0.5
}
for frame in encoder.encode(buffer) {
if let pcm = decoder.decode(frame) {
totalDecodedSamples += Int(pcm.frameLength)
}
}
}
#expect(totalDecodedSamples >= 8 * Int(PTTAudioFormat.samplesPerFrame))
}
// MARK: - Helpers
private func encodeSineFrames(seconds: Double) throws -> [Data] {