Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions Sources/TranscriptsCore/Audio/AudioCaptureMetrics.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import Foundation

/// Counters only: no samples or transcript text. The capturer supplies its own
/// lock. Capture time is the source clock, never callback arrival time.
public struct AudioCaptureMetrics: Codable, Sendable {
public private(set) var receivedBuffers = 0
public private(set) var writtenBuffers = 0
public private(set) var droppedBuffers = 0
public private(set) var writeFailures = 0
public private(set) var framesWritten: Int64 = 0
public private(set) var writtenSeconds: Double = 0
public private(set) var firstCaptureSeconds: Double?
public private(set) var lastCaptureSeconds: Double?
public private(set) var firstArrivalAt: Date?
public private(set) var lastArrivalAt: Date?
public private(set) var discontinuities = 0
public private(set) var largestGapSeconds: Double = 0
private var expectedNextCaptureSeconds: Double?

public init() {}

public mutating func observe(frames: Int, sampleRate: Double,
captureSeconds: Double?, arrivalAt: Date = Date(),
written: Bool, writeFailed: Bool = false) {
receivedBuffers += 1
if firstArrivalAt == nil { firstArrivalAt = arrivalAt }
lastArrivalAt = arrivalAt
let duration = frames > 0 && sampleRate.isFinite && sampleRate > 0
? Double(frames) / sampleRate : 0
if let time = captureSeconds, time.isFinite {
if firstCaptureSeconds == nil { firstCaptureSeconds = time }
if let expected = expectedNextCaptureSeconds {
let gap = time - expected
if abs(gap) > 0.05 {
discontinuities += 1
largestGapSeconds = max(largestGapSeconds, abs(gap))
}
}
lastCaptureSeconds = time
expectedNextCaptureSeconds = time + duration
}
if written {
writtenBuffers += 1
framesWritten += Int64(max(0, frames))
writtenSeconds += duration
} else {
droppedBuffers += 1
}
if writeFailed { writeFailures += 1 }
}
}
48 changes: 48 additions & 0 deletions Sources/TranscriptsCore/Audio/SupportDiagnostics.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import Foundation

/// Explicitly selected technical fields for sharing. Raw capture sidecars stay
/// local: they contain routes, UIDs and paths useful for private investigation.
public enum SupportDiagnostics {
private static let keys: Set<String> = [
"schemaVersion", "app", "version", "build", "os", "receivedBuffers", "writtenBuffers", "droppedBuffers",
"writeFailures", "framesWritten", "writtenSeconds", "firstCaptureSeconds", "lastCaptureSeconds",
"firstArrivalAt", "lastArrivalAt", "discontinuities", "largestGapSeconds", "clock", "sampleRate", "channels",
"fileSampleRate", "hardwareSampleRate", "voiceProcessingEnabled", "writerStatus", "formatFlags", "bitsPerChannel",
"peak", "latestPeak", "systemCallbackStartOffsetSeconds", "micPlacementSeconds", "systemPlacementSeconds",
"transcriptionSystemOffsetSeconds", "assembledFragments", "isRecovery", "continuing", "inMeeting", "systemAudioEnabled"
]

private static func kind(_ name: String) -> String {
let value = name.lowercased()
if value.contains("iphone") { return "continuity-iphone" }
if value.contains("airpod") || value.contains("bluetooth") { return "bluetooth" }
if value.contains("built-in") || value.contains("macbook") { return "built-in" }
if value.contains("usb") || value.contains("brio") || value.contains("c920") { return "usb" }
return "other"
}

public static func summary(jsonLines: Data) throws -> Data {
let text = String(decoding: jsonLines, as: UTF8.self)
// Keep the beginning (capture setup) and tail (recent changes and stop).
let lines = text.split(separator: "\n")
let selected = lines.count > 100 ? Array(lines.prefix(10)) + Array(lines.suffix(90)) : Array(lines)
let events: [[String: Any]] = selected.compactMap { line in
guard let event = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any],
let name = event["event"] as? String,
let input = event["data"] as? [String: Any] else { return nil }
var safe = input.filter { key, value in
keys.contains(key) && (value is NSNumber || ((value as? String)?.count ?? Int.max) <= 160)
}
if let requested = input["requestedName"] as? String { safe["selectedInputKind"] = kind(requested) }
if let devices = input["devices"] as? [[String: Any]] {
for (idKey, target) in [("actualInputID", "selectedInputKind"), ("defaultOutputID", "defaultOutputKind")] {
if let id = input[idKey] as? NSNumber,
let device = devices.first(where: { ($0["id"] as? NSNumber) == id }),
let deviceName = device["name"] as? String { safe[target] = kind(deviceName) }
}
}
return ["event": String(name.prefix(64)), "data": safe]
}
return try JSONSerialization.data(withJSONObject: events, options: [.prettyPrinted, .sortedKeys])
}
}
43 changes: 41 additions & 2 deletions Sources/TranscriptsMac/AppController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,14 @@ final class AppController: ObservableObject {
let dir = HistoryStore.capturesDir.appendingPathComponent(recordID.uuidString, isDirectory: true)
do {
try rec.start(into: dir)
rec.diagnostics?.event("input-selection", [
"requestedUID": device.uid, "requestedName": device.name,
"overrideUID": self.config.overrideInputUID ?? "none",
"favoriteUIDs": self.config.favoriteInputUIDs,
"callDeviceUIDs": callUIDs, "inMeeting": inMeeting,
"isRecovery": isRecovery, "continuing": continuing,
"systemAudioEnabled": self.config.captureSystemAudio,
])
self.recorder = rec
self.recordingInput = device
self.currentRecordID = recordID
Expand Down Expand Up @@ -551,6 +559,20 @@ final class AppController: ObservableObject {
recording.systemAudioStartOffset =
capturer?.firstSampleAt?.timeIntervalSince(recording.startedAt)
}
rec.diagnostics?.event("capture-stopped", [
"carryForward": carryForward,
"micFile": recording.audioURL.lastPathComponent,
"systemFile": sysURL?.lastPathComponent ?? "none",
"systemCallbackStartOffsetSeconds": recording.systemAudioStartOffset ?? 0,
"startedAt": recording.startedAt.timeIntervalSince1970,
"endedAt": recording.endedAt?.timeIntervalSince1970 ?? 0,
"carriedFragments": self.carriedFragments.map { fragment -> [String: Any] in
["micPath": fragment.micAudioURL.path,
"systemPath": fragment.systemAudioURL?.path ?? "none",
"startedAt": fragment.startedAt.timeIntervalSince1970,
"systemStartOffsetSeconds": fragment.systemAudioStartOffset ?? 0]
},
])

// A deliberate stop while a switch was finalizing saves this
// slice normally instead of letting the queued switch resume it.
Expand Down Expand Up @@ -578,11 +600,20 @@ final class AppController: ObservableObject {

if let sysURL, let micURL = recording.micAudioURL {
let mixed = micURL.deletingLastPathComponent().appendingPathComponent("call-mixed.m4a")
rec.diagnostics?.event("archive-mix", [
"micPath": micURL.path, "systemPath": (recording.systemAudioURL ?? sysURL).path,
"outputPath": mixed.path, "micPlacementSeconds": 0, "systemPlacementSeconds": 0,
"transcriptionSystemOffsetSeconds": recording.systemAudioStartOffset ?? 0,
"assembledFragments": hadFragments,
])
if let mixedURL = await AudioMixer.mix([micURL, recording.systemAudioURL ?? sysURL],
into: mixed, log: { Log.write($0) }) {
recording.audioURL = mixedURL
self.updateRecord(recordID) { $0.audioPath = mixedURL.path }
Log.write("call: mixed your mic + the other participants for transcription")
rec.diagnostics?.event("archive-mix-completed", ["file": mixedURL.lastPathComponent])
} else {
rec.diagnostics?.event("archive-mix-failed")
}
}
// Both sides came back empty: the mic read digital zero and the
Expand Down Expand Up @@ -681,11 +712,15 @@ final class AppController: ObservableObject {
guard config.captureSystemAudio, MeetingDetector.isMeetingAppRunning else { return }
guard explainSystemAudioPermissionIfNeeded() else { return }
let capturer = SystemAudioCapturer()
capturer.diagnostics = recorder?.diagnostics
systemCapturer = capturer
let sysURL = scratchDir.appendingPathComponent("system.caf")
Task { @MainActor in
let ok = await capturer.start(into: sysURL)
if !ok { self.systemCapturer = nil; return }
if !ok {
capturer.diagnostics?.event("system-unavailable")
self.systemCapturer = nil; return
}
if #available(macOS 26, *) { self.attachLiveSystemTranscriber(to: capturer) }
}
}
Expand Down Expand Up @@ -1027,7 +1062,11 @@ final class AppController: ObservableObject {
self.micSilentWhileCallAudible = micQuiet >= Self.deadMicSeconds && farSideLive
// Window titles improve mid-call (join screen → the real
// meeting window) — re-sample every ~15s and upgrade.
if self.tick % 15 == 0 { self.refreshMeetingContext() }
if self.tick % 15 == 0 {
self.refreshMeetingContext()
rec.snapshotDiagnostics()
self.systemCapturer?.snapshotDiagnostics()
}
// Keeps the relaunch marker fresh, so a three-hour session
// stays resumable rather than ageing out of the window.
if self.tick % 30 == 0 { self.relaunch.heartbeat() }
Expand Down
42 changes: 39 additions & 3 deletions Sources/TranscriptsMac/Capture/AudioInputDevices.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ enum AudioInputDevices {
static func all() -> [AudioInputDevice] {
if let staged = staged() { return staged }
return deviceIDs().compactMap { id in
guard inputChannelCount(id) > 0 else { return nil }
guard channelCount(id) > 0 else { return nil }
guard let uid = stringProperty(id, kAudioDevicePropertyDeviceUID),
let name = stringProperty(id, kAudioObjectPropertyName) else { return nil }
guard !uid.hasPrefix(systemAudioTapUIDPrefix) else { return nil }
Expand Down Expand Up @@ -229,6 +229,41 @@ enum AudioInputDevices {

// MARK: - CoreAudio plumbing

/// Include output routes as well as inputs: a Continuity mic listening to
/// Mac speakers and an AirPods call have very different echo paths.
static func diagnosticRoute(actualInputID: AudioDeviceID?, requestedInputID: AudioDeviceID) -> [String: Any] {
var outputAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultOutputDevice,
mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain)
var output = AudioDeviceID(kAudioObjectUnknown)
var size = UInt32(MemoryLayout<AudioDeviceID>.size)
let outputStatus = AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject),
&outputAddress, 0, nil, &size, &output)
var fields: [String: Any] = [
"requestedInputID": requestedInputID,
"devices": deviceIDs().map { id -> [String: Any] in
let uid = stringProperty(id, kAudioDevicePropertyDeviceUID) ?? "unknown"
let name = stringProperty(id, kAudioObjectPropertyName) ?? "unknown"
var device: [String: Any] = [
"id": id,
"uid": uid, "name": name,
"nominalSampleRate": nominalSampleRate(id),
"transportType": transportType(id),
"inputChannels": channelCount(id),
"outputChannels": channelCount(id, scope: kAudioObjectPropertyScopeOutput),
"aggregateSubDeviceUIDs": aggregateSubDeviceUIDs(id),
]
let candidate = AudioInputDevice(uid: uid, name: name, deviceID: id)
if let muted = isInputMuted(candidate) { device["inputMuted"] = muted }
return device
},
]
fields["actualInputID"] = actualInputID
fields["defaultInputID"] = defaultInput()
if outputStatus == noErr { fields["defaultOutputID"] = output }
return fields
}

private static func deviceIDs() -> [AudioDeviceID] {
var addr = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDevices,
Expand All @@ -242,10 +277,11 @@ enum AudioInputDevices {
return ids
}

private static func inputChannelCount(_ device: AudioDeviceID) -> Int {
private static func channelCount(_ device: AudioDeviceID,
scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeInput) -> Int {
var addr = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyStreamConfiguration,
mScope: kAudioObjectPropertyScopeInput,
mScope: scope,
mElement: kAudioObjectPropertyElementMain)
var size: UInt32 = 0
guard AudioObjectGetPropertyDataSize(device, &addr, 0, nil, &size) == noErr, size > 0 else { return 0 }
Expand Down
19 changes: 19 additions & 0 deletions Sources/TranscriptsMac/Capture/CallDetector.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,25 @@ final class CallDetector {

// MARK: - CoreAudio process objects

/// Active audio clients, including renderers outside the meeting app. A
/// monitor/loopback renderer is relevant when a global system tap contains
/// a second copy. Device UIDs can include both inputs and outputs.
static func diagnosticProcesses() -> [[String: Any]] {
processObjects().compactMap { proc in
let input = isRunningInput(proc)
var addr = AudioObjectPropertyAddress(
mSelector: kAudioProcessPropertyIsRunningOutput,
mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain)
var output: UInt32 = 0
var size = UInt32(MemoryLayout<UInt32>.size)
let status = AudioObjectGetPropertyData(proc, &addr, 0, nil, &size, &output)
guard input || (status == noErr && output != 0) else { return nil }
return ["processObjectID": proc, "bundleID": bundleID(proc) ?? "unknown",
"runningInput": input, "runningOutput": output != 0,
"deviceUIDs": processDevices(proc).compactMap { deviceUID($0) }]
}
}

private static func processObjects() -> [AudioObjectID] {
var addr = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyProcessObjectList,
Expand Down
76 changes: 76 additions & 0 deletions Sources/TranscriptsMac/Capture/CaptureDiagnostics.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import Foundation
import TranscriptsCore
import TranscriptsEngine

/// Append-only, per-capture evidence. Survives a crash and follows the capture's
/// existing retention policy. No audio, window titles, or transcript text.
/// Encoding and disk IO never run on the audio callback.
final class CaptureDiagnostics: @unchecked Sendable {
private let queue = DispatchQueue(label: "ltd.hatcher.transcripts.capture-diagnostics", qos: .utility)
private let url: URL
private var failed = false

init(directory: URL) {
url = directory.appendingPathComponent("capture-diagnostics.jsonl")
event("capture-open", [
"schemaVersion": 1,
"captureID": directory.lastPathComponent,
"app": Bundle.main.bundleIdentifier ?? "unknown",
"version": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown",
"build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown",
"os": ProcessInfo.processInfo.operatingSystemVersionString,
"processID": ProcessInfo.processInfo.processIdentifier,
])
}

func event(_ name: String, _ fields: [String: Any] = [:]) {
// Freeze mutable caller-owned dictionaries before crossing queues.
let envelope: [String: Any] = ["event": name, "at": Date().timeIntervalSince1970, "data": fields]
guard JSONSerialization.isValidJSONObject(envelope),
var data = try? JSONSerialization.data(withJSONObject: envelope, options: [.sortedKeys]) else { return }
data.append(0x0a)
let line = data
queue.async { [self] in
do {
if !FileManager.default.fileExists(atPath: url.path) {
guard FileManager.default.createFile(atPath: url.path, contents: nil) else {
throw CocoaError(.fileWriteUnknown)
}
}
let handle = try FileHandle(forWritingTo: url)
defer { try? handle.close() }
try handle.seekToEnd()
try handle.write(contentsOf: line)
} catch {
if !failed { Log.write("capture diagnostics: could not write \(url.path): \(error)"); failed = true }
}
}
}

func metrics(_ name: String, _ metrics: AudioCaptureMetrics, extra: [String: Any] = [:]) {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
guard let data = try? encoder.encode(metrics),
var fields = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return }
fields.merge(extra) { _, new in new }
event(name, fields)
}

/// For the hardware self-check before it removes its scratch directory.
/// Never call from an audio callback.
func flush() -> URL {
queue.sync {}
return url
}

/// Timer/main-thread snapshots, and explicit start/stop snapshots. Query the
/// actual AudioUnit device as selection can fail or reset on reconfiguration.
func route(_ name: String, actualInputID: UInt32?, requestedInputID: UInt32) {
var fields = AudioInputDevices.diagnosticRoute(actualInputID: actualInputID,
requestedInputID: requestedInputID)
fields["meetingDeviceUIDs"] = CallDetector.meetingAppDeviceUIDs()
fields["meetingApp"] = CallDetector.meetingAppUsingInput() ?? "none"
fields["activeAudioProcesses"] = CallDetector.diagnosticProcesses()
event(name, fields)
}
}
Loading