Skip to content
Open
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
4 changes: 4 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ let package = Package(
.product(name: "Sparkle", package: "Sparkle"),
"WhisperFramework",
"TranscribeCppFramework",
"AmanuObjC",
],
// Sparkle is a framework, and `make app` puts it in
// Contents/Frameworks. SwiftPM builds a bare executable and has no
Expand All @@ -42,6 +43,9 @@ let package = Package(
url: "https://github.com/handy-computer/transcribe.cpp/releases/download/v0.2.0/TranscribeCpp.xcframework.zip",
checksum: "5fffd4557d561ab6e45edd2445978682a513c1cd030c5a330c8519c5b27b64d9"
),
// Objective-C only because Swift cannot catch an NSException; see
// AmanuObjC.h.
.target(name: "AmanuObjC"),
.testTarget(
name: "amanuTests",
dependencies: ["amanu"]
Expand Down
19 changes: 19 additions & 0 deletions Sources/AmanuObjC/AmanuObjC.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#import "AmanuObjC.h"

@implementation AmanuObjCExceptionCatcher
+ (BOOL)catching:(NS_NOESCAPE void (^)(void))block error:(NSError **)error {
@try {
block();
return YES;
} @catch (NSException *exception) {
if (error) {
*error = [NSError errorWithDomain:exception.name
code:0
userInfo:@{
NSLocalizedDescriptionKey: exception.reason ?: exception.name,
}];
}
return NO;
}
}
@end
15 changes: 15 additions & 0 deletions Sources/AmanuObjC/include/AmanuObjC.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

/// AVAudioEngine and AVAudioNode report several misuses (a tap whose format
/// no longer matches the device, a graph that cannot be connected) by raising
/// an Objective-C exception instead of returning an error. Swift cannot catch
/// one: it unwinds every Swift frame above it without running a single catch,
/// defer or assignment, and AppKit swallows it at the run loop. This turns
/// the exception into an ordinary NSError at the call site.
@interface AmanuObjCExceptionCatcher : NSObject
+ (BOOL)catching:(NS_NOESCAPE void (^)(void))block error:(NSError * _Nullable * _Nullable)error;
@end

NS_ASSUME_NONNULL_END
2 changes: 1 addition & 1 deletion Sources/amanu/Amanu.swift
Original file line number Diff line number Diff line change
Expand Up @@ -770,7 +770,7 @@ final class AppController {
// new to say the second time.
notifyUser(
title: localised("amanu — recording failed", "amanu — не удалось начать запись"),
body: "\(error)",
body: (error as? RecordingSession.StartFailure)?.bannerBody ?? "\(error)",
replacing: Self.startFailedBanner)
return false
}
Expand Down
37 changes: 28 additions & 9 deletions Sources/amanu/Audio/MicRecorder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// SDK rather than races here — the state genuinely shared across threads is
// the locked LockedState below.
@preconcurrency import AVFoundation
import AmanuObjC
import Foundation
import os.lock

Expand Down Expand Up @@ -431,11 +432,14 @@ final class MicRecorder: @unchecked Sendable {
// output device or the input side never produces audio. The mixer
// has no sources — nothing is monitored or played — its connection
// exists solely to give the unit a formatted output path.
engine.connect(engine.mainMixerNode, to: engine.outputNode, format: monoFormat)
let engine = self.engine
try Self.guarded {
engine.connect(engine.mainMixerNode, to: engine.outputNode, format: monoFormat)
}
livenessFrames = 0
livenessPeak = 0
livenessSettled = false
installVoiceTap(on: input, format: monoFormat, reusingFile: existing != nil)
try installVoiceTap(on: input, format: monoFormat, reusingFile: existing != nil)
} else {
try installRawTap(on: input, inputFormat: inputFormat, monoFormat: monoFormat)
}
Expand All @@ -457,9 +461,14 @@ final class MicRecorder: @unchecked Sendable {
}
attachedReusingFile = existing != nil

engine.prepare()
do {
try engine.start()
let engine = self.engine
var startError: Error?
try Self.guarded {
engine.prepare()
do { try engine.start() } catch { startError = error }
}
if let startError { throw startError }
} catch {
input.removeTap(onBus: 0)
if existing == nil { file = nil }
Expand Down Expand Up @@ -502,9 +511,9 @@ final class MicRecorder: @unchecked Sendable {
/// path exists to prevent.
private func installVoiceTap(
on input: AVAudioInputNode, format: AVAudioFormat, reusingFile: Bool
) {
) throws {
let checkFrames = Int(format.sampleRate * (reusingFile ? 3 : 1))
input.installTap(onBus: 0, bufferSize: 4096, format: format) { [weak self] buffer, _ in
try Self.guarded { input.installTap(onBus: 0, bufferSize: 4096, format: format) { [weak self] buffer, _ in
guard let self, let writer = self.writer else { return }
if self.firstBufferAt == nil { self.firstBufferAt = Date() }
self.lastBufferAt = Date()
Expand All @@ -527,7 +536,7 @@ final class MicRecorder: @unchecked Sendable {
}

self.writeTracked(buffer, to: writer)
}
} }
}

/// Write one captured buffer, recording its level on the way through and
Expand Down Expand Up @@ -566,7 +575,7 @@ final class MicRecorder: @unchecked Sendable {
}
let sameRate = inputFormat.sampleRate == monoFormat.sampleRate
let ratio = monoFormat.sampleRate / inputFormat.sampleRate
input.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) { [weak self] buffer, _ in
try Self.guarded { input.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) { [weak self] buffer, _ in
guard let self, let writer = self.writer else { return }
if self.firstBufferAt == nil { self.firstBufferAt = Date() }
self.lastBufferAt = Date()
Expand All @@ -588,7 +597,17 @@ final class MicRecorder: @unchecked Sendable {
return
}
self.writeTracked(mono, to: writer)
}
} }
}

/// Run an AVFAudio call that reports failure by raising an Objective-C
/// exception, and turn the exception into a thrown error. Without this
/// a raise in `start` unwinds through `RecordingSession.start` and the
/// auto-record timer without running a catch: the system tap that had
/// already started is never stopped, the session is never assigned, and
/// the timer that called it never fires again (2026-11-16, 0.6.5).
static func guarded(_ body: () -> Void) throws {
try AmanuObjCExceptionCatcher.catching(body)
}

/// Feed `buffer` through `converter` exactly once, for the rate-mismatched
Expand Down
19 changes: 19 additions & 0 deletions Sources/amanu/RecordingSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,25 @@ final class RecordingSession {
case .microphone(let error): return "microphone: \(error)"
}
}

/// What the banner says: that the call is not being recorded and what to
/// try. The system's own error text is for the log, not for the person.
var bannerBody: String {
switch self {
case .microphone:
return localised(
"The microphone wouldn't start, so this call is not being recorded. "
+ "If it keeps happening, quit and reopen amanu.",
"Микрофон не запустился, звонок не записывается. "
+ "Если повторяется — закройте и снова откройте amanu.")
case .systemAudio:
return localised(
"System audio wouldn't start, so this call is not being recorded. "
+ "Check the permission in amanu Setup.",
"Системный звук не запустился, звонок не записывается. "
+ "Проверьте разрешение в настройках amanu.")
}
}
}

/// What started this session. Manual recordings are never stopped or
Expand Down
73 changes: 73 additions & 0 deletions Tests/amanuTests/MicExceptionGuardTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import AVFoundation
import Foundation
import Testing

@testable import amanu

/// AVFAudio reports misuse by raising an Objective-C exception, which Swift
/// cannot catch: it unwinds the stack and, on the main run loop, kills the
/// timer that fires auto-record. `MicRecorder.guarded` must turn it into a throw.
struct MicExceptionGuardTests {
@Test("An Objective-C exception becomes a thrown error that keeps its reason")
func exceptionBecomesError() {
do {
try MicRecorder.guarded {
NSException(name: .genericException, reason: "tap busy", userInfo: nil).raise()
}
Issue.record("the exception was not turned into an error")
} catch {
#expect(error.localizedDescription.contains("tap busy"))
}
}

@Test("A body that does not raise runs untouched")
func plainBodyRuns() throws {
var ran = false
try MicRecorder.guarded { ran = true }
#expect(ran)
}

// The two below raise the real AVFAudio exceptions, so they need an input
// device; without one they are cancelled (shown as skipped) rather than passed.
// The engine is returned with its node: the node does not keep it alive.
private static func inputNode() throws -> (engine: AVAudioEngine, input: AVAudioInputNode) {
let engine = AVAudioEngine()
let input = engine.inputNode
if input.outputFormat(forBus: 0).sampleRate <= 0 {
try Test.cancel("no audio input device on this machine")
}
return (engine, input)
}

@Test("A second installTap on the same bus becomes a thrown error")
func doubleTapThrows() throws {
let (engine, input) = try Self.inputNode()
defer { withExtendedLifetime(engine) {} }
let format = input.outputFormat(forBus: 0)
input.installTap(onBus: 0, bufferSize: 4096, format: format) { _, _ in }
defer { input.removeTap(onBus: 0) }

#expect(throws: (any Error).self) {
try MicRecorder.guarded {
input.installTap(onBus: 0, bufferSize: 4096, format: format) { _, _ in }
}
}
}

@Test("A tap format that does not match the input becomes a thrown error")
func badFormatThrows() throws {
let (engine, input) = try Self.inputNode()
defer { withExtendedLifetime(engine) {} }
let hardware = input.outputFormat(forBus: 0)
let wrong = try #require(
AVAudioFormat(
standardFormatWithSampleRate: hardware.sampleRate == 16_000 ? 44_100 : 16_000,
channels: 1))
#expect(throws: (any Error).self) {
try MicRecorder.guarded {
input.installTap(onBus: 0, bufferSize: 4096, format: wrong) { _, _ in }
}
}
input.removeTap(onBus: 0)
}
}
27 changes: 27 additions & 0 deletions Tests/amanuTests/RecordingSessionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import Testing
/// calls a stall.
final class FakeMicRecorder: MicTrackRecorder {
var startError: Error?
/// Runs inside `start`, before it succeeds, for a test that needs the
/// real way a recorder fails (an Objective-C exception behind `guarded`).
var duringStart: (() throws -> Void)?
var writesFile = true
private(set) var started = false
private(set) var stopped = false
Expand All @@ -24,6 +27,7 @@ final class FakeMicRecorder: MicTrackRecorder {

func start(writingTo url: URL, callApps: [String]) throws {
if let startError { throw startError }
try duringStart?()
started = true
if writesFile { try Data(repeating: 1, count: 64).write(to: url) }
}
Expand Down Expand Up @@ -104,6 +108,29 @@ struct RecordingSessionTests {
"A folder with no meta.json is invisible to every list and would never be tidied.")
}

@Test("An Objective-C exception inside the mic start ends as a clean start failure")
func micExceptionAfterSystemStart() throws {
let root = try makeRoot()
defer { try? FileManager.default.removeItem(at: root) }
let mic = FakeMicRecorder(), system = FakeSystemRecorder()
// What AVFAudio does on a second installTap or a format mismatch.
mic.duringStart = {
try MicRecorder.guarded {
NSException(name: .genericException, reason: "tap busy", userInfo: nil).raise()
}
}
let session = try RecordingSession(root: root, mic: mic, system: system)

#expect {
try session.start(systemAudioScope: "all")
} throws: { error in
guard case RecordingSession.StartFailure.microphone = error else { return false }
return true
}
#expect(system.started && system.stopped, "The tap that had started must be stopped.")
#expect(!exists(session.dir), "Nothing is left behind for a session that never ran.")
}

@Test("A tap that refuses to start leaves no folder behind")
func systemFailureLeavesNoFolder() throws {
let root = try makeRoot()
Expand Down
19 changes: 19 additions & 0 deletions Tests/amanuTests/StartFailureBannerTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Foundation
import Testing

@testable import amanu

struct StartFailureBannerTests {
@Test("The banner says the call is not being recorded, without the system's error text")
func bannerNamesTheConsequence() {
struct Reason: LocalizedError { var errorDescription: String? { "tap busy" } }
for failure in [
RecordingSession.StartFailure.microphone(Reason()),
RecordingSession.StartFailure.systemAudio(Reason()),
] {
let text = failure.bannerBody
#expect(!text.contains("tap busy"), "the raw reason stays in the log")
#expect(text.contains("not being recorded") || text.contains("не записывается"))
}
}
}