diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..eb70981 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + build-and-test: + name: Build and test + runs-on: xcode-27 + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Show toolchain + run: | + xcodebuild -version + swift --version + - name: Lint Swift + run: | + brew install swiftlint + swiftlint lint --strict + - name: Build and test Swift package + run: | + swift build + swift test + - name: Build macOS demo + run: xcodebuild -project Aural.xcodeproj -scheme Aural -destination 'platform=macOS' CODE_SIGNING_ALLOWED=NO build + - name: Build iOS Simulator demo + run: xcodebuild -project Aural.xcodeproj -scheme Aural -destination 'generic/platform=iOS Simulator' CODE_SIGNING_ALLOWED=NO build diff --git a/Agents.md b/Agents.md index 62ae5b1..c1323b9 100644 --- a/Agents.md +++ b/Agents.md @@ -147,6 +147,6 @@ Before opening a PR (or completing an automated change): - Minimal transcription example lives in `Aural/TranscriptionView.swift`. - Advanced transcription UI lives in `Aural/AdvancedTranscriptionView.swift`. - Error cases and localized descriptions are centralized in `Sources/AuralKit/SpeechSessionError.swift`. -- CI uses Codemagic (`codemagic.yaml`); green builds are required before merging. +- CI uses GitHub Actions (`.github/workflows/ci.yml`). The Build and test job must pass before merging. Happy transcribing! diff --git a/Aural/CustomVocabularyDemoView.swift b/Aural/CustomVocabularyDemoView.swift index 71a7eba..3d42f1a 100644 --- a/Aural/CustomVocabularyDemoView.swift +++ b/Aural/CustomVocabularyDemoView.swift @@ -30,12 +30,13 @@ struct CustomVocabularyDemoView: View { TranscriptionControlsView( status: viewModel.status, error: viewModel.errorMessage, - showStopButton: showStopButton, buttonColor: buttonColor, buttonIcon: buttonIcon, statusMessage: statusMessage, onPrimaryAction: handlePrimaryAction, - onStopAction: handleStopAction + onFinishAction: { model.finishTranscription() }, + onCancelAction: { model.cancelTranscription() }, + isPreparing: model.isCompiling ) .padding(.horizontal) } @@ -256,15 +257,6 @@ private extension CustomVocabularyDemoView { } } - var showStopButton: Bool { - switch model.status { - case .idle, .stopping: - return false - case .preparing, .transcribing, .paused: - return true - } - } - var statusMessage: String { switch model.status { case .idle: @@ -274,9 +266,9 @@ private extension CustomVocabularyDemoView { case .transcribing: return "Listening..." case .paused: - return "Paused — tap to resume or stop" + return "Paused" case .stopping: - return "Stopping..." + return "Ending session..." } } @@ -285,7 +277,7 @@ private extension CustomVocabularyDemoView { case .idle: model.startTranscription() case .preparing: - model.stopTranscription() + model.cancelTranscription() case .transcribing: model.pauseTranscription() case .paused: @@ -295,7 +287,4 @@ private extension CustomVocabularyDemoView { } } - func handleStopAction() { - model.stopTranscription() - } } diff --git a/Aural/CustomVocabularyDemoViewModel.swift b/Aural/CustomVocabularyDemoViewModel.swift index 05e9ba2..ed54c5c 100644 --- a/Aural/CustomVocabularyDemoViewModel.swift +++ b/Aural/CustomVocabularyDemoViewModel.swift @@ -57,10 +57,9 @@ final class CustomVocabularyDemoViewModel { // MARK: - Intent Handlers func startTranscription() { - guard status != .transcribing, status != .preparing else { return } + guard status == .idle, transcriptionTask == nil else { return } resetTranscriptionState() - cancelExistingTasks() transcriptionTask = Task { @MainActor in do { @@ -68,7 +67,8 @@ final class CustomVocabularyDemoViewModel { monitorDownloadProgress() try await processTranscriptionStream(stream) } catch is CancellationError { - // expected when stopped + partialText = "" + currentTimeRange = "" } catch { errorMessage = error.localizedDescription isCompiling = false @@ -78,17 +78,15 @@ final class CustomVocabularyDemoViewModel { } } - func stopTranscription() { - progressTask?.cancel() - progressTask = nil - resetProgressObservation(clearFraction: true) - transcriptionTask?.cancel() - transcriptionTask = nil + func finishTranscription() { + Task { await session.finishTranscribing() } + } - Task { @MainActor in - await session.stopTranscribing() - partialText = "" - currentTimeRange = "" + func cancelTranscription() { + if session.status == .idle { + transcriptionTask?.cancel() + } else { + Task { await session.cancelTranscribing() } } } @@ -111,7 +109,7 @@ final class CustomVocabularyDemoViewModel { func handleToggleChange(_ isEnabled: Bool) { isCustomVocabularyEnabled = isEnabled if !isEnabled, status == .transcribing || status == .preparing { - stopTranscription() + cancelTranscription() } } @@ -124,7 +122,7 @@ final class CustomVocabularyDemoViewModel { } func teardown() { - stopTranscription() + cancelTranscription() statusTask?.cancel() statusTask = nil } @@ -153,10 +151,6 @@ final class CustomVocabularyDemoViewModel { isCompiling || status == .preparing || status == .transcribing } - var isStopDisabled: Bool { - status == .idle || status == .stopping - } - // MARK: - Private helpers private func bindStatusStream() { @@ -287,11 +281,6 @@ extension CustomVocabularyDemoViewModel { compilationDuration = nil } - private func cancelExistingTasks() { - transcriptionTask?.cancel() - progressTask?.cancel() - } - private func prepareTranscriptionStream() async throws -> AsyncThrowingStream { let startTime = Date() diff --git a/Aural/Info.plist b/Aural/Info.plist index 0881dfd..d7cb7ca 100644 --- a/Aural/Info.plist +++ b/Aural/Info.plist @@ -17,7 +17,7 @@ CFBundlePackageType APPL CFBundleShortVersionString - 2.1.1 + 3.0.0 CFBundleVersion 1 LSMinimumSystemVersion diff --git a/Aural/SettingsView.swift b/Aural/SettingsView.swift index f63b92b..56d0ea5 100644 --- a/Aural/SettingsView.swift +++ b/Aural/SettingsView.swift @@ -63,7 +63,7 @@ struct SettingsView: View { Text("AuralKit Demo") .font(.caption) .foregroundStyle(.secondary) - Text("Version 2.1.1") + Text("Version 3.0.0") .font(.caption2) .foregroundStyle(.secondary) } diff --git a/Aural/TranscriptionManager.swift b/Aural/TranscriptionManager.swift index ed48a85..d269138 100644 --- a/Aural/TranscriptionManager.swift +++ b/Aural/TranscriptionManager.swift @@ -14,7 +14,7 @@ class TranscriptionManager { var selectedPreset: DemoTranscriberPreset = .manual { didSet { if oldValue != selectedPreset, status != .idle { - stopTranscription() + finishTranscription() } } } @@ -66,7 +66,8 @@ class TranscriptionManager { currentTimeRange = "" isSpeechDetected = true - let session = SpeechSession(locale: selectedLocale, preset: selectedPreset.preset) + let sessionLocale = selectedLocale + let session = SpeechSession(locale: sessionLocale, preset: selectedPreset.preset) speechSession = session observeStatus(from: session) observeAudioInput(from: session) @@ -77,12 +78,12 @@ class TranscriptionManager { for try await result in session.startTranscribing() { self.handleTranscriptionResult(result) } - self.finishSession() + self.finishSession(locale: sessionLocale) } catch is CancellationError { self.cleanupSession() } catch { self.error = error.localizedDescription - self.finishSession() + self.finishSession(locale: sessionLocale) } } } @@ -122,12 +123,14 @@ class TranscriptionManager { return String(format: "%d:%02d.%02d", minutes, remainingSeconds, milliseconds) } - func stopTranscription() { - guard status != .idle, status != .stopping else { return } - Task { @MainActor in - await self.speechSession?.stopTranscribing() - } - stopAuxiliaryTasks() + func finishTranscription() { + guard let speechSession else { return } + Task { await speechSession.finishTranscribing() } + } + + func cancelTranscription() { + guard let speechSession else { return } + Task { await speechSession.cancelTranscribing() } } func pauseTranscription() { @@ -154,7 +157,7 @@ class TranscriptionManager { case .idle: startTranscription() case .preparing: - stopTranscription() + cancelTranscription() case .transcribing: pauseTranscription() case .paused: @@ -182,15 +185,22 @@ class TranscriptionManager { transcriptionHistory.removeAll { $0.id == record.id } } - private func finishSession() { - if !currentTranscript.isEmpty { + private func finishSession(locale: Locale) { + let transcript = String(finalizedText.characters) + if !transcript.isEmpty { + let ranges = finalizedText.runs.compactMap(\.audioTimeRange) + let timeRange = if let first = ranges.first, let last = ranges.last { + "\(formatTime(first.start)) - \(formatTime(last.end))" + } else { + "" + } let record = TranscriptionRecord( id: UUID(), - text: currentTranscript, - locale: selectedLocale, + text: transcript, + locale: locale, timestamp: Date(), alternatives: [], - timeRange: currentTimeRange + timeRange: timeRange ) transcriptionHistory.insert(record, at: 0) } diff --git a/Aural/TranscriptionView.swift b/Aural/TranscriptionView.swift index 07d3431..e8dc9f5 100644 --- a/Aural/TranscriptionView.swift +++ b/Aural/TranscriptionView.swift @@ -36,12 +36,12 @@ struct TranscriptionView: View { TranscriptionControlsView( status: manager.status, error: manager.error, - showStopButton: showStopButton, buttonColor: buttonColor, buttonIcon: buttonIcon, statusMessage: statusMessage, onPrimaryAction: { manager.primaryAction() }, - onStopAction: { manager.stopTranscription() }, + onFinishAction: { manager.finishTranscription() }, + onCancelAction: { manager.cancelTranscription() }, animationScale: animationScale ) .padding(.horizontal) @@ -166,15 +166,6 @@ struct TranscriptionView: View { } } - private var showStopButton: Bool { - switch manager.status { - case .idle, .stopping: - return false - case .preparing, .transcribing, .paused: - return true - } - } - private var statusMessage: String { switch manager.status { case .idle: @@ -184,9 +175,9 @@ struct TranscriptionView: View { case .transcribing: return "Listening..." case .paused: - return "Paused — tap to resume or stop" + return "Paused" case .stopping: - return "Stopping..." + return "Ending session..." } } } diff --git a/Aural/TranscriptionViewComponents.swift b/Aural/TranscriptionViewComponents.swift index 46b7d8d..8c30bbf 100644 --- a/Aural/TranscriptionViewComponents.swift +++ b/Aural/TranscriptionViewComponents.swift @@ -120,12 +120,13 @@ struct TranscriptionTextView: View { struct TranscriptionControlsView: View { let status: SpeechSession.Status let error: String? - let showStopButton: Bool let buttonColor: Color let buttonIcon: String let statusMessage: String let onPrimaryAction: () -> Void - let onStopAction: () -> Void + let onFinishAction: () -> Void + let onCancelAction: () -> Void + var isPreparing = false var animationScale: CGFloat = 1.0 var body: some View { @@ -153,12 +154,17 @@ struct TranscriptionControlsView: View { } .buttonStyle(.glass) .buttonBorderShape(.circle) - .disabled(error != nil || status == .stopping) + .disabled(error != nil || status == .stopping || isPreparing) - if showStopButton { - Button("Stop", action: onStopAction) - .buttonStyle(.borderedProminent) - .tint(.gray) + if status != .idle || isPreparing { + HStack { + if status == .transcribing || status == .paused { + Button("Finish", action: onFinishAction) + .buttonStyle(.borderedProminent) + } + Button("Cancel", action: onCancelAction) + .buttonStyle(.bordered) + } } Text(statusMessage) diff --git a/README.md b/README.md index bb56b1a..b0a642a 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![Swift Package Manager](https://img.shields.io/badge/SPM-compatible-brightgreen.svg)](https://swift.org/package-manager) [![GitHub release](https://img.shields.io/github/release/rryam/AuralKit.svg)](https://github.com/rryam/AuralKit/releases) -[![Codemagic build status](https://api.codemagic.io/apps/6858c0b3eab03a007ef8b1f6/auralkit/status_badge.svg)](https://codemagic.io/app/6858c0b3eab03a007ef8b1f6/auralkit/latest_build) +[![CI](https://github.com/rryam/AuralKit/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/rryam/AuralKit/actions/workflows/ci.yml) AuralKit is a simple, lightweight Swift wrapper for speech-to-text transcription using iOS 26's `SpeechTranscriber` and `SpeechAnalyzer` APIs while handling microphone capture, buffer conversion, model downloads, and cancellation on your behalf. @@ -21,6 +21,7 @@ AuralKit is a simple, lightweight Swift wrapper for speech-to-text transcription - Async streams for lifecycle status, audio inputs, and transcription results - Device capability helper to inspect available transcribers and locales - Xcode 27-ready file transcription path that can use Speech's native analyzer file input when built with Swift 6.4+ +- Transcription from a selected audio track in a local movie or other media file on iOS and macOS 27+ - Xcode 27-ready live capture and analyzer preheating configuration with Xcode 26 fallbacks - ScreenCaptureKit-backed transcription for selected content audio on iOS 27+ and macOS 26+ - SwiftUI-friendly API that mirrors Apple's sample project design @@ -35,6 +36,7 @@ AuralKit is a simple, lightweight Swift wrapper for speech-to-text transcription - [Usage](#usage) - [Simple Transcription](#simple-transcription) - [Partial Results](#partial-results) + - [Media File Audio](#media-file-audio) - [Screen Capture Audio](#screen-capture-audio) - [Session Observability](#session-observability) - [Monitoring Model Downloads](#monitoring-model-downloads) @@ -58,6 +60,8 @@ This project would not have been possible without Apple's excellent sample code. ## Quick Start +The examples below use the AuralKit 3.0 API. + ```swift import AuralKit @@ -80,9 +84,9 @@ let streamTask = Task { } } -// Later, when you want to stop capturing audio +// Later, when you want to finish capturing audio Task { - await session.stopTranscribing() + await session.finishTranscribing() await streamTask.value } ``` @@ -96,11 +100,11 @@ Add AuralKit to your project through Xcode: 2. Enter: `https://github.com/rryam/AuralKit` 3. Click Add Package -Or add it to your `Package.swift`: +Select 3.0.0 in Xcode or add the following dependency to your `Package.swift`: ```swift dependencies: [ - .package(url: "https://github.com/rryam/AuralKit", from: "2.1.1") + .package(url: "https://github.com/rryam/AuralKit", from: "3.0.0") ] ``` @@ -140,13 +144,24 @@ let streamTask = Task { } } -// Stop when needed +// Finish capture and wait for the final results Task { - await session.stopTranscribing() + await session.finishTranscribing() await streamTask.value } ``` +### Migrating from AuralKit 2.x + +Replace `stopTranscribing()` with `finishTranscribing()` when saving a live transcript. Keep +reading the result stream until it ends and use `isFinal` to decide what to save. Finish waits +for an active file transcription to reach the end of the file. If setup is still in progress, +Finish closes the stream without starting capture. + +Use `cancelTranscribing()` to abandon a run. The stream ends with `CancellationError`, including +when using the one-shot file API. The stream may still contain results already yielded before +cancellation. Clear any displayed partial text and handle cancellation separately from errors. + ## Demo App Check out the included **Aural** demo app to see AuralKit in action! The demo showcases: @@ -276,6 +291,28 @@ struct ContentView: View { The `TranscriptionManager` in the demo app adds language selection, history tracking, and export. +### Media File Audio + +With Swift 6.4 and iOS or macOS 27+, pass a local media file to `streamTranscription(fromMediaFile:audioTrackID:options:)`. The default is the first audio track. Use `AVURLAsset` to find a particular audio track, then pass its `trackID`. + +```swift +import AVFoundation +import AuralKit + +let asset = AVURLAsset(url: movieURL) +let tracks = try await asset.loadTracks(withMediaType: .audio) + +if let commentary = tracks.dropFirst().first { + let session = SpeechSession() + let results = session.streamTranscription(fromMediaFile: movieURL, audioTrackID: commentary.trackID) + for try await result in results where result.isFinal { + print(result.text) + } +} +``` + +Use the default `.automatic` input provider. The file must be in an allowed directory and contain its audio. `FileTranscriptionOptions.maxDuration` applies to the selected track’s duration on the media timeline. The app needs `NSSpeechRecognitionUsageDescription` for the Speech permission prompt. + ### Screen Capture Audio On OS versions where ScreenCaptureKit can stream selected content audio, AuralKit can transcribe audio chosen with the system picker: @@ -305,6 +342,8 @@ let stream = session.startTranscribingScreenCapture( Screen capture transcription still returns normal `SpeechTranscriber.Result` values. AuralKit handles the ScreenCaptureKit stream, converts audio `CMSampleBuffer`s into analyzer-compatible buffers, and feeds the existing SpeechAnalyzer pipeline. +On OS 27 and later, set `SpeechSession.logging = .debug` to see the native stream's `SCStream.isCapturing` state after capture starts, stops, or updates its content filter. The property reports screen capture activity. Audio delivery can be checked independently by looking at transcription results. + ### Error Handling AuralKit surfaces detailed `SpeechSessionError` values so you can present actionable messaging: @@ -451,8 +490,11 @@ public final class SpeechSession { /// Start transcribing - returns stream of SpeechTranscriber.Result public func startTranscribing() -> AsyncThrowingStream - /// Stop transcribing - public func stopTranscribing() async + /// End live capture and drain final results + public func finishTranscribing() async + + /// Abort transcription with CancellationError + public func cancelTranscribing() async } ``` diff --git a/Sources/AuralKit/MicrophoneAudioIngress.swift b/Sources/AuralKit/MicrophoneAudioIngress.swift new file mode 100644 index 0000000..4945466 --- /dev/null +++ b/Sources/AuralKit/MicrophoneAudioIngress.swift @@ -0,0 +1,47 @@ +import AVFoundation +import Foundation +import Speech + +/// One installed tap owns its converter and delivery continuation. Closing joins +/// admitted callbacks before the session finishes analyzer input or releases leases. +@available(iOS 26.0, macOS 26.0, *) +final class MicrophoneAudioIngress: @unchecked Sendable { + private let queue = DispatchQueue(label: "com.auralkit.microphone.input", qos: .userInitiated) + private let converter = BufferConverter() + private let format: AVAudioFormat + private let onError: @Sendable (Error) -> Void + private var deliver: (@Sendable (AVAudioPCMBuffer) -> Void)? + + init( + format: AVAudioFormat, + deliver: @escaping @Sendable (AVAudioPCMBuffer) -> Void, + onError: @escaping @Sendable (Error) -> Void + ) { + self.format = format + self.deliver = deliver + self.onError = onError + } + + func receive(_ buffer: AVAudioPCMBuffer, ownsBuffer: Bool = false) { + queue.sync { + guard let deliver else { return } + do { + let converted = try converter.convertBuffer(buffer, to: format) + if converted === buffer, !ownsBuffer { + guard let copy = buffer.copy() as? AVAudioPCMBuffer else { + throw SpeechSessionError.conversionBufferCreationFailed + } + deliver(copy) + } else { + deliver(converted) + } + } catch { + onError(error) + } + } + } + + func close() { + queue.sync { deliver = nil } + } +} diff --git a/Sources/AuralKit/ModelManager.swift b/Sources/AuralKit/ModelManager.swift index e56f576..23e12d5 100644 --- a/Sources/AuralKit/ModelManager.swift +++ b/Sources/AuralKit/ModelManager.swift @@ -13,17 +13,23 @@ actor ModelManager { private let reservations: SpeechAssetReservations private let assetDownloader: (@Sendable ([any SpeechModule]) async throws -> Void)? + private let installationRequest: @Sendable ([any SpeechModule]) async throws -> AssetInstallationRequest? private var leases: Set = [] + private var generation = 0 private var preparations = 0 private var preparationWaiters: [CheckedContinuation] = [] private(set) var cleanupTask: Task? init( reservations: SpeechAssetReservations = .shared, - assetDownloader: (@Sendable ([any SpeechModule]) async throws -> Void)? = nil + assetDownloader: (@Sendable ([any SpeechModule]) async throws -> Void)? = nil, + installationRequest: @escaping @Sendable ([any SpeechModule]) async throws -> AssetInstallationRequest? = { + try await AssetInventory.assetInstallationRequest(supporting: $0) + } ) { self.reservations = reservations self.assetDownloader = assetDownloader + self.installationRequest = installationRequest } /// Ensure the speech model for the given locale is available @@ -48,8 +54,8 @@ actor ModelManager { return } - try await prepareAssets(for: [module]) { manager in - try await manager.downloadAssetsIfNeeded(for: [module]) + try await prepareAssets(for: [module]) { manager, generation in + try await manager.downloadAssetsIfNeeded(for: [module], generation: generation) } } @@ -59,19 +65,19 @@ actor ModelManager { supportedLocales: @escaping @Sendable () async -> [Locale], installedLocales: @escaping @Sendable () async -> [Locale] ) async throws { - try await prepareAssets(for: [module], validate: { manager in + try await prepareAssets(for: [module]) { manager, generation in guard await manager.localeMatches(provider: supportedLocales, locale: locale) else { throw SpeechSessionError.unsupportedLocale(locale) } - }, install: { manager in if await manager.localeMatches(provider: installedLocales, locale: locale) { manager.logger.notice("Locale \(locale.identifier(.bcp47)) already installed") + try manager.requireCurrent(generation) manager.currentDownloadProgress = nil } else { manager.logger.info("Ensuring model download for locale \(locale.identifier(.bcp47))") - try await manager.downloadAssetsIfNeeded(for: [module]) + try await manager.downloadAssetsIfNeeded(for: [module], generation: generation) } - }) + } } private func localeMatches( @@ -85,27 +91,28 @@ actor ModelManager { func ensureAssets(for modules: [any SpeechModule]) async throws { guard !modules.isEmpty else { return } - try await prepareAssets(for: modules) { manager in - try await manager.downloadAssetsIfNeeded(for: modules) + try await prepareAssets(for: modules) { manager, generation in + try await manager.downloadAssetsIfNeeded(for: modules, generation: generation) } } - private func downloadAssetsIfNeeded(for modules: [any SpeechModule]) async throws { - try requirePreparation() + private func downloadAssetsIfNeeded(for modules: [any SpeechModule], generation: Int) async throws { + try requireCurrent(generation) if let assetDownloader { try await assetDownloader(modules) return } - if let downloader = try await AssetInventory.assetInstallationRequest(supporting: modules) { - try requirePreparation() + let request = try await reservations.withInventoryAccess { + try await self.requestInstallation(for: modules, generation: generation) + } + if let downloader = request { + try requireCurrent(generation) currentDownloadProgress = downloader.progress logger.info("Starting asset download for \(modules.count) module(s)") do { try await downloader.downloadAndInstall() - currentDownloadProgress = nil - logger.notice("Asset download completed successfully") } catch { - currentDownloadProgress = nil + if self.generation == generation { currentDownloadProgress = nil } logger.error("Asset download failed: \(error.localizedDescription, privacy: .public)") // Check for network connectivity errors @@ -117,28 +124,38 @@ actor ModelManager { throw SpeechSessionError.modelDownloadFailed(nsError) } + try requireCurrent(generation) + currentDownloadProgress = nil + logger.notice("Asset download completed successfully") } else { + try requireCurrent(generation) currentDownloadProgress = nil logger.debug("No asset download required for modules") } } - /// Close preparation admission and join it before returning locale leases. - /// A late native acquisition/download must not outlive its manager cleanup. + private func requestInstallation( + for modules: [any SpeechModule], generation: Int + ) async throws -> AssetInstallationRequest? { + try requireCurrent(generation) + return try await installationRequest(modules) + } + + /// Close admission and join preparation before returning locale leases. + /// Reader may release its input workspace only after this boundary completes. func releaseLocales() async { if let cleanupTask { await cleanupTask.value return } + generation &+= 1 let cleanup = Task { if self.preparations != 0 { await withCheckedContinuation { self.preparationWaiters.append($0) } } let pending = self.leases self.leases.removeAll() - for lease in pending { - await self.reservations.release(lease) - } + for lease in pending { await self.reservations.release(lease) } self.currentDownloadProgress = nil self.cleanupTask = nil self.logger.debug("Released \(pending.count) session locale lease(s)") @@ -149,18 +166,18 @@ actor ModelManager { private func prepareAssets( for modules: [any SpeechModule], - validate: @Sendable (isolated ModelManager) async throws -> Void = { _ in }, - install: @Sendable (isolated ModelManager) async throws -> Void + install: @Sendable (isolated ModelManager, Int) async throws -> Void ) async throws { - try requirePreparation() + let generation = self.generation + try requireCurrent(generation) preparations += 1 defer { preparationFinished() } + // Preserve first-install behavior: downloading may create native reservations. + // Those reservations remain borrowed; only explicit acquisitions are owned here. + try await install(self, generation) + try requireCurrent(generation) var acquired: [SpeechAssetReservations.Lease] = [] do { - try await validate(self) - try requirePreparation() - // These are module-defined asset locales, not guessed equivalents - // of the user's preferred transcription language. let locales = modules.compactMap { $0 as? any LocaleDependentSpeechModule } .flatMap { $0.selectedLocales } var requested = Set() @@ -172,24 +189,15 @@ actor ModelManager { } catch { throw SpeechSessionError.modelReservationFailed(locale, error) } - try requirePreparation() + try requireCurrent(generation) } - try await install(self) - try requirePreparation() leases.formUnion(acquired) } catch { - for lease in acquired { - await reservations.release(lease) - } + for lease in acquired { await reservations.release(lease) } throw error } } - private func requirePreparation() throws { - try Task.checkCancellation() - guard cleanupTask == nil else { throw CancellationError() } - } - private func preparationFinished() { preparations -= 1 guard preparations == 0 else { return } @@ -197,4 +205,9 @@ actor ModelManager { preparationWaiters.removeAll() for waiter in waiters { waiter.resume() } } + + private func requireCurrent(_ generation: Int) throws { + try Task.checkCancellation() + guard self.generation == generation, cleanupTask == nil else { throw CancellationError() } + } } diff --git a/Sources/AuralKit/ScreenCaptureAudioProcessor.swift b/Sources/AuralKit/ScreenCaptureAudioProcessor.swift new file mode 100644 index 0000000..a4aff49 --- /dev/null +++ b/Sources/AuralKit/ScreenCaptureAudioProcessor.swift @@ -0,0 +1,193 @@ +import AVFoundation +import CoreMedia +import Foundation +import Speech + +/// Serializes audio conversion and admits callbacks only from the currently running stream. +@available(iOS 26.0, macOS 26.0, *) +final class ScreenCaptureAudioProcessor: @unchecked Sendable { + let queue = DispatchQueue(label: "com.auralkit.screencapture.audio", qos: .userInitiated) + private let conversion: any ScreenCaptureAudioConversion + private let input: AsyncStream.Continuation + private let onError: @Sendable (Error) -> Void + // Accessed only on queue, including during start and stop. + private var activeStream: ObjectIdentifier? + + init( + targetFormat: AVAudioFormat, + useNativeConversion: Bool, + input: AsyncStream.Continuation, + onError: @escaping @Sendable (Error) -> Void + ) { +#if compiler(>=6.4) + if #available(iOS 27.0, macOS 27.0, *), useNativeConversion { + conversion = NativeScreenCaptureAudioConversion(targetFormat: targetFormat) + } else { + conversion = LegacyScreenCaptureAudioConversion(targetFormat: targetFormat) + } +#else + conversion = LegacyScreenCaptureAudioConversion(targetFormat: targetFormat) +#endif + self.input = input + self.onError = onError + } + + func start(_ stream: ObjectIdentifier) { + queue.sync { activeStream = stream } + } + + func drain(_ stream: ObjectIdentifier) -> Error? { + queue.sync { + guard activeStream == stream else { return nil } + activeStream = nil + do { + try yield(conversion.flush()) + return nil + } catch { + return error + } + } + } + + func discard(_ stream: ObjectIdentifier? = nil) { + queue.sync { + guard stream == nil || activeStream == stream else { return } + activeStream = nil + conversion.discard() + } + } + + func receive(_ sample: CMSampleBuffer, from stream: ObjectIdentifier) { + dispatchPrecondition(condition: .onQueue(queue)) + guard activeStream == stream, sample.isValid, sample.numSamples > 0, + sample.dataReadiness == .ready, + let description = sample.formatDescription?.audioStreamBasicDescription, + description.mFormatID == kAudioFormatLinearPCM else { return } + var sourceDescription = description + guard let format = AVAudioFormat(streamDescription: &sourceDescription) else { return } + do { + try yield(conversion.convert(sample, format: format)) + } catch { + activeStream = nil + conversion.discard() + onError(error) + } + } + + private func yield(_ inputs: [AnalyzerInput]) { + for buffer in inputs { input.yield(buffer) } + } +} + +@available(iOS 26.0, macOS 26.0, *) +private protocol ScreenCaptureAudioConversion { + func convert(_ sample: CMSampleBuffer, format: AVAudioFormat) throws -> [AnalyzerInput] + func flush() throws -> [AnalyzerInput] + func discard() +} + +private func copyPCMBuffer(_ sample: CMSampleBuffer, format: AVAudioFormat) throws -> AVAudioPCMBuffer { + let frameCount = AVAudioFrameCount(sample.numSamples) + guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount) else { + throw SpeechSessionError.conversionBufferCreationFailed + } + buffer.frameLength = frameCount + do { + try sample.copyPCMData(fromRange: 0.. [AnalyzerInput] { + let source = try copyPCMBuffer(sample, format: format) + let converted = try converter.convertBuffer(source, to: targetFormat) + return [AnalyzerInput(buffer: converted)] + } + + func flush() -> [AnalyzerInput] { [] } + func discard() {} +} + +#if compiler(>=6.4) +@available(iOS 27.0, macOS 27.0, *) +private final class NativeScreenCaptureAudioConversion: ScreenCaptureAudioConversion { + private let targetFormat: AVAudioFormat + private var converter: AnalyzerInputConverter? + private var converterSourceFormat: AVAudioFormat? + private var nextFrame: AVAudioFramePosition = 0 + + init(targetFormat: AVAudioFormat) { + self.targetFormat = targetFormat + } + + func convert(_ sample: CMSampleBuffer, format: AVAudioFormat) throws -> [AnalyzerInput] { + var inputs: [AnalyzerInput] = [] + if format == targetFormat, sample.dataBuffer != nil { + inputs = try flush() + // Keep the existing contiguous transcript clock across pauses and source changes. + // Copy the timing metadata while retaining the original audio data. + let rate = CMTimeScale(targetFormat.sampleRate) + let timing = CMSampleTimingInfo( + duration: CMTime(value: 1, timescale: rate), + presentationTimeStamp: CMTime(value: nextFrame, timescale: rate), + decodeTimeStamp: .invalid + ) + let frameCount = AVAudioFramePosition(sample.numSamples) + // The copied sample buffer and its retained data remain read-only after handoff. + nonisolated(unsafe) let retimed = try CMSampleBuffer(copying: sample, withNewTiming: [timing]) + let input = AnalyzerInput(buffer: CMReadySampleBuffer(unsafeWithDataBuffer: retimed)) + nextFrame += frameCount + inputs.append(input) + return inputs + } + + let source = try copyPCMBuffer(sample, format: format) + if converterSourceFormat != format { + inputs = try flush() + } + let time: AVAudioTime? + let activeConverter: AnalyzerInputConverter + if let converter { + activeConverter = converter + time = nil + } else { + activeConverter = AnalyzerInputConverter(analyzerFormat: targetFormat) + converter = activeConverter + converterSourceFormat = format + time = AVAudioTime(sampleTime: nextFrame, atRate: targetFormat.sampleRate) + } + let converted = try activeConverter.convert(source, at: time) + advanceClock(with: converted) + inputs += converted + return inputs + } + + func flush() throws -> [AnalyzerInput] { + guard let converter else { return [] } + discard() + let remaining = try converter.flush() + advanceClock(with: remaining) + return remaining + } + + func discard() { + converter = nil + converterSourceFormat = nil + } + + private func advanceClock(with inputs: [AnalyzerInput]) { + for input in inputs { + nextFrame += input.bufferDuration.convertScale( + CMTimeScale(targetFormat.sampleRate), method: .roundHalfAwayFromZero + ).value + } + } +} +#endif diff --git a/Sources/AuralKit/ScreenCapturePipelineHooks.swift b/Sources/AuralKit/ScreenCapturePipelineHooks.swift index 14692fb..8878bc6 100644 --- a/Sources/AuralKit/ScreenCapturePipelineHooks.swift +++ b/Sources/AuralKit/ScreenCapturePipelineHooks.swift @@ -15,6 +15,6 @@ struct ScreenCapturePipelineHooks { let authorize: @MainActor () async throws -> Void let prepareAnalysis: @MainActor () async throws -> ScreenCapturePreparedAnalysis let makeProvider: @MainActor ( - AVAudioFormat, AsyncStream.Continuation, @escaping @Sendable (Error) -> Void + AVAudioFormat, AsyncStream.Continuation, @escaping @Sendable (Error?) -> Task ) -> any ScreenCaptureInput } diff --git a/Sources/AuralKit/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index 1b5af8c..5fa4f9f 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -1,6 +1,5 @@ import Foundation -/// The narrow boundary around actual capture calls, shared by SCStream and controlled fixtures. @available(iOS 26.0, macOS 26.0, *) @MainActor protocol ScreenCaptureStream: AnyObject { @@ -8,26 +7,35 @@ protocol ScreenCaptureStream: AnyObject { func stopCapture() async throws } -/// Carries admission through async returns. The public caller checks ownership at -/// the instant it publishes status or propagates a failure into session teardown. -@available(iOS 26.0, macOS 26.0, *) -@MainActor -struct ScreenCaptureResumeOutcome { - let isCurrent: @MainActor () -> Bool - let error: Error? +// A failure after the native stream has already stopped must not leave it marked running. +struct ScreenCaptureDrainFailure: Error { + let underlyingError: Error } /// Serializes capture side effects across suspension. Admission changes intent immediately; -/// only internal operations are joined, never a public caller that may await run retirement. +/// only internal operations are joined, never a public caller that may await session cleanup. @available(iOS 26.0, macOS 26.0, *) @MainActor final class ScreenCaptureTransitions { + private struct TerminalFailure { + let control: UUID + let error: Error + let operation: Task? + } + enum DesiredState { case running, paused, stopped } private(set) var desiredState = DesiredState.running private(set) var stream: (any ScreenCaptureStream)? private(set) var isRunning = false private var revision = UUID() + private var streamRevision: UUID? + private var terminatedStream: ObjectIdentifier? + private var controlRevision = UUID() private var tail: Task? + private var terminalFailure: TerminalFailure? + private var drainFailure: ScreenCaptureDrainFailure? + private var explicitStopPending = false + private var explicitStopFailure: Error? // Synchronous admission returns the owned handle before any capture call can suspend. func replace(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) -> Task { @@ -40,6 +48,9 @@ final class ScreenCaptureTransitions { try await self.stopCurrent() guard self.desiredState != .stopped, self.revision == admitted else { return } self.stream = try makeStream() + self.drainFailure = nil + self.streamRevision = admitted + self.terminatedStream = nil try await self.startCurrent(revision: admitted) } catch { // A stale picker operation must not report failure against its successor. @@ -49,39 +60,104 @@ final class ScreenCaptureTransitions { } } + func update( + _ expectedStream: any ScreenCaptureStream, + operation: @escaping @MainActor () async throws -> Void + ) -> Task { + let admitted = revision + return enqueue { + guard self.desiredState != .stopped, self.revision == admitted, + self.stream === expectedStream else { return } + do { + try await operation() + } catch { + guard self.desiredState != .stopped, self.revision == admitted else { return } + throw error + } + } + } + + func isCurrent(_ expectedStream: any ScreenCaptureStream) -> Bool { + desiredState != .stopped && stream === expectedStream && streamRevision == revision + } + + func didStop(_ expectedStream: any ScreenCaptureStream, error: Error?) -> Bool { + guard stream === expectedStream else { return false } + terminatedStream = ObjectIdentifier(expectedStream) + isRunning = false + if explicitStopPending, streamRevision == revision, let error { + explicitStopFailure = explicitStopFailure ?? error + } + guard isCurrent(expectedStream) else { return false } + if let error { terminalFailure = TerminalFailure(control: controlRevision, error: error, operation: tail) } + controlRevision = UUID() + desiredState = .stopped + return true + } + func pause() -> Task { guard desiredState != .stopped else { return enqueue {} } + let control = UUID() + controlRevision = control desiredState = .paused - return enqueue { try await self.stopCurrent() } + return enqueue { + do { + try await self.stopCurrent() + } catch { + if self.controlRevision == control, !(error is ScreenCaptureDrainFailure) { + self.desiredState = .running + } + throw error + } + } } - func resume() -> Task { + func resume( + onCompletion: @escaping @MainActor (Result) -> Void + ) -> Task { + let control = UUID() + controlRevision = control desiredState = desiredState == .stopped ? .stopped : .running let admitted = revision - let previous = tail - let operation = Task { @MainActor in - _ = try? await previous?.value - let error: Error? - do { - try await self.startCurrent(revision: admitted) - error = nil - } catch let failure { - error = failure + let operation = enqueue { try await self.startCurrent(revision: admitted) } + // This observer is never the operation tail: following a replacement cannot join itself. + return Task { @MainActor in + var selection = admitted + var pending = operation + while true { + let result = await pending.result + if let terminal = self.terminalFailure, terminal.control == control { + _ = await terminal.operation?.result + return terminal.error + } + guard self.desiredState == .running, self.controlRevision == control else { return nil } + if self.revision != selection, let successor = self.tail { + selection = self.revision + pending = successor + continue + } + onCompletion(result) + return nil } - return ScreenCaptureResumeOutcome( - isCurrent: { self.desiredState == .running && self.revision == admitted }, - error: error - ) } - tail = Task { _ = await operation.value } - return operation } func stop() -> Task { + controlRevision = UUID() desiredState = .stopped + explicitStopPending = true return enqueue { - try await self.stopCurrent() - self.stream = nil + defer { + self.stream = nil + self.explicitStopPending = false + self.explicitStopFailure = nil + } + do { + try await self.stopCurrent() + } catch { + throw self.explicitStopFailure ?? error + } + if let error = self.explicitStopFailure ?? self.drainFailure { throw error } } } @@ -98,13 +174,23 @@ final class ScreenCaptureTransitions { private func stopCurrent() async throws { guard isRunning, let stream else { return } - try await stream.stopCapture() + do { + try await stream.stopCapture() + } catch let error as ScreenCaptureDrainFailure { + isRunning = false + drainFailure = error + throw error + } catch { + guard terminatedStream == ObjectIdentifier(stream) else { throw error } + } isRunning = false } private func startCurrent(revision admitted: UUID) async throws { guard desiredState == .running, revision == admitted, !isRunning, let stream else { return } try await stream.startCapture() + drainFailure = nil + guard terminatedStream != ObjectIdentifier(stream) else { return } // Nothing else can perform capture calls until this operation exits. Intent can // still change during start; compensate before allowing a queued operation to run. isRunning = true diff --git a/Sources/AuralKit/SpeechAssetReservations.swift b/Sources/AuralKit/SpeechAssetReservations.swift index fac5e0d..a66b3ac 100644 --- a/Sources/AuralKit/SpeechAssetReservations.swift +++ b/Sources/AuralKit/SpeechAssetReservations.swift @@ -1,9 +1,10 @@ import Foundation import Speech -/// The single owner of AuralKit's app-wide locale reservation mutations. -/// Native inventory calls are serialized across suspension points, not merely -/// isolated to an actor. Existing reservations are borrowed, never reclaimed. +/// Coordinates reservation mutations made through AuralKit's shared instance. +/// Its native inventory calls are serialized across suspension points, not merely +/// isolated to an actor. Unrelated AssetInventory clients are outside this queue. +/// Existing reservations are borrowed, never reclaimed. @available(iOS 26.0, macOS 26.0, *) actor SpeechAssetReservations { struct Inventory: Sendable { @@ -48,7 +49,7 @@ actor SpeechAssetReservations { private var aliases: [String: Alias] = [:] private var holdings: [UUID: Holding] = [:] private var tail: Task? - private var queuedOperations = 0 + private(set) var queuedOperations = 0 init(inventory: Inventory = .live) { self.inventory = inventory @@ -56,17 +57,7 @@ actor SpeechAssetReservations { func acquire(_ locale: Locale) async throws -> Lease { try Task.checkCancellation() - let previous = tail - queuedOperations += 1 - let operation = Task { - await previous?.value - return try await self.acquireSerially(locale) - } - tail = Task { - _ = await operation.result - self.operationFinished() - } - let lease = try await operation.value + let lease = try await enqueue { try await self.acquireSerially(locale) }.value do { try Task.checkCancellation() return lease @@ -79,17 +70,40 @@ actor SpeechAssetReservations { } func release(_ lease: Lease) async { + _ = await enqueue { await self.releaseSerially(lease) }.result + } + + /// Installation requests also reserve locales; their creation shares this queue. + /// The subsequent download must run outside it. + func withInventoryAccess( + _ operation: @escaping @Sendable () async throws -> Value + ) async throws -> Value { + try Task.checkCancellation() + let task = enqueue { + try Task.checkCancellation() + return try await operation() + } + return try await withTaskCancellationHandler { + try await task.value + } onCancel: { + task.cancel() + } + } + + private func enqueue( + _ operation: @escaping @Sendable () async throws -> Value + ) -> Task { let previous = tail queuedOperations += 1 - let operation = Task { + let task = Task { await previous?.value - await self.releaseSerially(lease) + return try await operation() } tail = Task { - await operation.value + _ = await task.result self.operationFinished() } - await operation.value + return task } private func operationFinished() { @@ -110,6 +124,10 @@ actor SpeechAssetReservations { } let before = Self.index(await inventory.locales()) + if before[alias] != nil { + // Preserve an exact external reservation without mutating it. + return admit(alias: alias, protecting: []) + } let created = try await inventory.reserve(locale) let after = Self.index(await inventory.locales()) let protectedKeys: Set @@ -117,7 +135,7 @@ actor SpeechAssetReservations { let added = Set(after.keys).subtracting(before.keys) // The API returns a Bool, not the canonical asset locale. Only one // unambiguous new native identity establishes ownership. Preserve - // unknown reservations if another app client changed inventory. + // unknown reservations if another inventory client changed it. guard added.count == 1, let key = added.first, let actual = after[key] else { throw ReservationError.ambiguousInventoryChange } diff --git a/Sources/AuralKit/SpeechSession+Audio.swift b/Sources/AuralKit/SpeechSession+Audio.swift index c5bc9af..3c9950f 100644 --- a/Sources/AuralKit/SpeechSession+Audio.swift +++ b/Sources/AuralKit/SpeechSession+Audio.swift @@ -29,22 +29,7 @@ extension SpeechSession { throw SpeechSessionError.invalidAudioDataType } - audioEngine.inputNode.removeTap(onBus: 0) - - let inputFormat = audioEngine.inputNode.outputFormat(forBus: 0) - - if Self.shouldLog(.debug) { - Self.logger.debug( - "Installing audio tap with buffer size \(Self.microphoneTapBufferSize, privacy: .public) frames" - ) - } - - audioEngine.inputNode.installTap( - onBus: 0, - bufferSize: Self.microphoneTapBufferSize, - format: inputFormat, - block: makeAudioTapHandler() - ) + try installMicrophoneTap() audioEngine.prepare() try audioEngine.start() @@ -54,11 +39,39 @@ extension SpeechSession { } } + private func installMicrophoneTap() throws { + let inputNode = audioEngine.inputNode + inputNode.removeTap(onBus: 0) + let inputFormat = inputNode.outputFormat(forBus: 0) +#if swift(>=6.4) + if #available(iOS 27.0, macOS 27.0, *) { + guard inputFormat.sampleRate > 0, inputFormat.channelCount > 0 else { + throw SpeechSessionError.invalidAudioDataType + } + let bufferSize = AVAudioFrameCount((inputFormat.sampleRate / 10).rounded(.up)) + let processBuffer = try makeAudioTapHandler(ownsTapBuffer: true) + try inputNode.installAudioTap(onBus: 0, bufferSize: bufferSize, format: inputFormat) { buffer, _ in + guard buffer.frameLength > 0 else { return } + processBuffer(AVAudioPCMBuffer(copying: buffer)) + } + return + } +#endif + let processBuffer = try makeAudioTapHandler() + inputNode.installTap(onBus: 0, bufferSize: Self.microphoneTapBufferSize, format: inputFormat) { buffer, _ in + processBuffer(buffer) + } + } + func stopAudioStreaming() { - guard isAudioStreaming else { return } + guard isAudioStreaming else { + closeMicrophoneInput() + return + } #if swift(>=6.4) if #available(iOS 27.0, macOS 27.0, *), stopPreparedNativeCaptureStreaming() { + closeMicrophoneInput() return } #endif @@ -67,6 +80,8 @@ extension SpeechSession { Self.logger.debug("Stopping audio streaming") } audioEngine.stop() + closeMicrophoneInput() + audioEngine.inputNode.removeTap(onBus: 0) isAudioStreaming = false } @@ -117,22 +132,31 @@ extension SpeechSession { #endif } - private func makeAudioTapHandler() -> AVAudioNodeTapBlock { - let run = liveTranscription - return { [weak self, weak run] buffer, _ in - guard let bufferCopy = buffer.copy() as? AVAudioPCMBuffer else { - if Self.shouldLog(.error) { - Self.logger.error("Failed to copy audio buffer for processing.") + private func makeAudioTapHandler( + ownsTapBuffer: Bool = false + ) throws -> @Sendable (AVAudioPCMBuffer) -> Void { + guard let inputBuilder, let analyzerFormat else { throw SpeechSessionError.invalidAudioDataType } + guard let run = liveTranscription, !run.retired, !run.finishing else { throw CancellationError() } + run.microphoneInput?.close() + let ingress = MicrophoneAudioIngress( + format: analyzerFormat, + deliver: { inputBuilder.yield(AnalyzerInput(buffer: $0)) }, + onError: { error in + let description = error.localizedDescription + Task { @MainActor in + if Self.shouldLog(.error) { + Self.logger.error("Audio processing error: \(description, privacy: .public)") + } } - return } - let sendableBuffer = SendablePCMBuffer(buffer: bufferCopy) + ) + run.microphoneInput = ingress + return { buffer in ingress.receive(buffer, ownsBuffer: ownsTapBuffer) } + } - Task { @MainActor [weak self, weak run] in - guard let self, let run else { return } - self.enqueueLiveAudioBuffer(sendableBuffer, run: run) - } - } + private func closeMicrophoneInput() { + liveTranscription?.microphoneInput?.close() + liveTranscription?.microphoneInput = nil } #if os(iOS) @@ -194,7 +218,8 @@ extension SpeechSession { } private func handleInterruptionEnded(options: AVAudioSession.InterruptionOptions) async { - guard shouldResumeAfterInterruption, let run = liveTranscription, !run.retired else { return } + guard shouldResumeAfterInterruption, status == .paused, + let run = liveTranscription, !run.retired, !run.finishing else { return } shouldResumeAfterInterruption = false guard options.contains(.shouldResume) else { diff --git a/Sources/AuralKit/SpeechSession+CaptureControl.swift b/Sources/AuralKit/SpeechSession+CaptureControl.swift new file mode 100644 index 0000000..ab28bd2 --- /dev/null +++ b/Sources/AuralKit/SpeechSession+CaptureControl.swift @@ -0,0 +1,89 @@ +import Foundation + +@available(iOS 26.0, macOS 26.0, *) +@MainActor +extension SpeechSession { + /// Stop capture and join every admitted setup, input and result task. + /// + /// Safe to call even if `startTranscribing()` has not been invoked or the stream has already + /// completed; the method simply waits for cleanup and returns. + /// For live transcription, waits for setup, admitted audio processing and result + /// delivery to exit. For file transcription, also waits for setup, file ingestion and result + /// delivery to exit before returning. The caller may then release its audio + /// file lease or remove its request-owned workspace. + public func stopTranscribing() async { + if let run = liveTranscription { + await retireLiveTranscription(run, error: nil)?.value + return + } + if let run = fileTranscription { + await retireFileTranscription(run, error: nil)?.value + return + } + // Every accepted transcription owns a run before setup can suspend. + // An idle stop must not start unowned cleanup that can overlap a new run. + } + + /// Drain accepted audio and deliver final results before returning. + /// Preparing streams are closed without starting capture. + public func finishTranscribing() async { + if let run = liveTranscription { + await finishLiveTranscription(run) + } else if let run = fileTranscription { + if status == .preparing { + await retireFileTranscription(run, error: nil)?.value + } else { + await run.setupTask?.value + await run.ingestionTask?.value + await run.recognizerTask?.value + await run.terminalTask?.value + } + } + } + + /// Abandon the run and join its teardown. The stream ends with cancellation. + public func cancelTranscribing() async { + if let run = liveTranscription { + run.cancellationRequested = true + await retireLiveTranscription(run, error: CancellationError())?.value + } else if let run = fileTranscription { + run.cancellationRequested = true + await retireFileTranscription(run, error: CancellationError())?.value + } + } + + /// Pause capture without tearing down the analyzer pipeline. + /// + /// Safe to call only when the session is actively transcribing live audio (microphone or + /// screen capture). Calls during file transcription or in any other state are ignored. + public func pauseTranscribing() async { + guard status == .transcribing, isPausableStreamingMode, + let run = liveTranscription, !run.retired else { return } + if streamingMode == .screenCapture { + return await pauseScreenCaptureStreamingIfNeeded(run: run) + } + stopAudioStreaming() + guard liveTranscription === run, !run.retired else { return } + setStatus(.paused) + } + + /// Resume a paused capture session. + /// - Throws: `SpeechSessionError` if audio streaming cannot restart. + public func resumeTranscribing() async throws { + guard status == .paused, isPausableStreamingMode, + let run = liveTranscription else { return } + do { + try requireCurrentLiveTranscription(run) + if streamingMode == .screenCapture { + try await resumeScreenCaptureStreamingIfNeeded(run: run) + return + } else { + try startAudioStreaming() + } + setStatus(.transcribing) + } catch { + await retireLiveTranscription(run, error: error)?.value + throw error + } + } +} diff --git a/Sources/AuralKit/SpeechSession+CustomVocabulary.swift b/Sources/AuralKit/SpeechSession+CustomVocabulary.swift index 33fae33..4a98798 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabulary.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabulary.swift @@ -149,6 +149,23 @@ struct CustomVocabularyCompilation: Sendable { let configuration: SFSpeechLanguageModel.Configuration let cacheKey: String let outputDirectory: URL + let artifacts: CustomVocabularyArtifacts +} + +/// Retained by the configuration and every in-flight native consumer. +@available(iOS 26.0, macOS 26.0, *) +final class CustomVocabularyArtifacts: Sendable { + let directory: URL + + init(directory: URL) { self.directory = directory } + + deinit { + do { + try FileManager.default.removeItem(at: directory) + } catch { + logCustomVocabularyError("Failed to retire vocabulary directory.", path: directory.path, error: error) + } + } } @available(iOS 26.0, macOS 26.0, *) @@ -168,50 +185,46 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send let assetURL: URL } - private let fileManager: FileManager - // Replaces only the Apple export/prepare work; allocation and cleanup always - // run through the production filesystem path. - private let prepareModel: (@Sendable ( + typealias PrepareModel = @Sendable ( SpeechSession.CustomVocabulary, URL, SFSpeechLanguageModel.Configuration - ) async throws -> Void)? + ) async throws -> Void + + private let fileManager: FileManager + private let prepareModel: PrepareModel init( fileManager: FileManager = .default, - prepareModel: (@Sendable ( - SpeechSession.CustomVocabulary, URL, SFSpeechLanguageModel.Configuration - ) async throws -> Void)? = nil + prepareModel: @escaping PrepareModel = { descriptor, assetURL, configuration in + try await descriptor.makeModelData().export(to: assetURL) + try Task.checkCancellation() + try await SFSpeechLanguageModel.prepareCustomLanguageModel(for: assetURL, configuration: configuration) + } ) { self.fileManager = fileManager self.prepareModel = prepareModel } func compile(descriptor: SpeechSession.CustomVocabulary) async throws -> CustomVocabularyCompilation { + try Task.checkCancellation() let cacheKey = try descriptor.stableCacheKey() let paths = try preparePaths(for: cacheKey) - var transferred = false - defer { - if !transferred { removeOutputDirectory(paths.outputDirectory) } - } + let artifacts = CustomVocabularyArtifacts(directory: paths.outputDirectory) + defer { withExtendedLifetime(artifacts) {} } let configuration = makeConfiguration(for: descriptor, paths: paths) try Task.checkCancellation() try await exportModelData(descriptor, with: paths, configuration: configuration) try Task.checkCancellation() - transferred = true return CustomVocabularyCompilation( configuration: configuration, cacheKey: cacheKey, - outputDirectory: paths.outputDirectory + outputDirectory: paths.outputDirectory, + artifacts: artifacts ) } private func preparePaths(for cacheKey: String) throws -> CompilationPaths { - let baseDirectories = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask) - guard let baseDirectory = baseDirectories.first else { - throw SpeechSessionError.customVocabularyPreparationFailed - } - - let outputDirectory = baseDirectory + let outputDirectory = fileManager.temporaryDirectory .appendingPathComponent("com.auralkit.vocabulary", isDirectory: true) .appendingPathComponent("\(cacheKey)-\(UUID().uuidString)", isDirectory: true) @@ -271,17 +284,12 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send } do { - if let prepareModel { - try await prepareModel(descriptor, paths.assetURL, configuration) - } else { - let modelData = descriptor.makeModelData() - try await modelData.export(to: paths.assetURL) - try await SFSpeechLanguageModel.prepareCustomLanguageModel( - for: paths.assetURL, - configuration: configuration - ) - } + // The session already runs the compiler in a detached task and joins it. + try await prepareModel(descriptor, paths.assetURL, configuration) + } catch is CancellationError { + throw CancellationError() } catch { + try Task.checkCancellation() throw SpeechSessionError.customVocabularyCompilationFailed(error) } } diff --git a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift index 308d61d..e6f098b 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift @@ -8,6 +8,8 @@ import OSLog extension SpeechSession { /// Configure the session's custom vocabulary, compiling assets as needed. + /// Purged temporary artifacts are rebuilt. Cancellation joins compilation + /// before rejecting its result; native consumers retain their own artifacts. /// /// - Parameter vocabulary: The vocabulary descriptor to activate, or `nil` to clear the current /// configuration. @@ -55,54 +57,44 @@ extension SpeechSession { } if cacheKey == customVocabularyCacheKey, - customVocabularyConfiguration != nil { + customVocabularyFilesExist { customVocabularyDescriptor = vocabulary return } - // Offload compilation to background task to avoid blocking main actor UI - // Capture compiler before detached task to avoid cross-actor access + let compilation = try await compileCustomVocabulary(vocabulary) + try requireVocabularyAdmission(liveRun) + guard customVocabularyRequestID == requestID else { throw CancellationError() } + applyCustomVocabularyCompilation(compilation, descriptor: vocabulary) + } + + var customVocabularyFilesExist: Bool { + guard let configuration = customVocabularyConfiguration else { return false } + let paths = [configuration.languageModel, configuration.vocabulary].compactMap { $0 } + return paths.allSatisfy { FileManager.default.isReadableFile(atPath: $0.path) } + } + + func compileCustomVocabulary(_ vocabulary: CustomVocabulary) async throws -> CustomVocabularyCompilation { let compiler = customVocabularyCompiler - let compilation = try await Task.detached(priority: .userInitiated) { + let task = Task.detached(priority: .userInitiated) { try await compiler.compile(descriptor: vocabulary) - }.value - - // A successful compiler result transfers a private directory to this - // request. Rejected results must be retired too, after compilation joins. - do { - try requireVocabularyAdmission(liveRun) - guard customVocabularyRequestID == requestID else { throw CancellationError() } - } catch { - if compilation.outputDirectory != customVocabularyOutputDirectory { - do { - try FileManager.default.removeItem(at: compilation.outputDirectory) - } catch { - logCustomVocabularyError( - "Failed to delete retired vocabulary directory.", - path: compilation.outputDirectory.path, error: error - ) - } - } - throw error } - - if let previousDirectory = customVocabularyOutputDirectory, - previousDirectory != compilation.outputDirectory { - do { - try FileManager.default.removeItem(at: previousDirectory) - } catch { - logCustomVocabularyError( - "Failed to delete previous vocabulary directory.", - path: previousDirectory.path, - error: error - ) - } + let result = await withTaskCancellationHandler { + await task.result + } onCancel: { + task.cancel() } + // The result's artifact owner is released only after compilation joins. + try Task.checkCancellation() + return try result.get() + } - customVocabularyDescriptor = vocabulary + func applyCustomVocabularyCompilation(_ compilation: CustomVocabularyCompilation, descriptor: CustomVocabulary) { + customVocabularyDescriptor = descriptor customVocabularyConfiguration = compilation.configuration customVocabularyCacheKey = compilation.cacheKey customVocabularyOutputDirectory = compilation.outputDirectory + customVocabularyArtifacts = compilation.artifacts } /// Start a dictation-backed transcription stream that leverages the currently configured custom vocabulary. @@ -114,7 +106,10 @@ extension SpeechSession { contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil ) -> AsyncThrowingStream { do { - let (stream, newContinuation, run) = try admitDictationTranscription() + let admission = try admitDictationTranscription() + let stream = admission.stream + let newContinuation = admission.continuation + let run = admission.run run.setupTask = Task { @MainActor [weak self] in guard let self else { return } await self.startDictationPipeline( @@ -129,11 +124,13 @@ extension SpeechSession { } } - private func admitDictationTranscription() throws -> ( - AsyncThrowingStream, - AsyncThrowingStream.Continuation, - LiveTranscriptionRun - ) { + private struct DictationAdmission { + let stream: AsyncThrowingStream + let continuation: AsyncThrowingStream.Continuation + let run: LiveTranscriptionRun + } + + private func admitDictationTranscription() throws -> DictationAdmission { guard continuation == nil, recognizerTask == nil, fileTranscription == nil, liveTranscription == nil, streamingMode == .inactive else { throw SpeechSessionError.recognitionStreamSetupFailed @@ -149,7 +146,7 @@ extension SpeechSession { } setStatus(.preparing) continuation = .dictation(newContinuation) - return (stream, newContinuation, run) + return DictationAdmission(stream: stream, continuation: newContinuation, run: run) } /// Compile and activate the provided custom vocabulary, then begin dictation-backed transcription. @@ -164,7 +161,10 @@ extension SpeechSession { contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil ) async throws -> AsyncThrowingStream { try requireVocabularyAdmission(nil) - let (stream, newContinuation, run) = try admitDictationTranscription() + let admission = try admitDictationTranscription() + let stream = admission.stream + let newContinuation = admission.continuation + let run = admission.run let preparation = Task { @MainActor in try await self.configureCustomVocabulary(customVocabulary, liveRun: run) try self.requireCurrentLiveTranscription(run) @@ -201,18 +201,8 @@ extension SpeechSession { func clearCustomVocabularyArtifacts(removeDescriptor: Bool) { customVocabularyRequestID = nil - if let directory = customVocabularyOutputDirectory { - // Best-effort cleanup of vocabulary directory - do { - try FileManager.default.removeItem(at: directory) - } catch { - logCustomVocabularyError( - "Failed to delete vocabulary directory during cleanup.", - path: directory.path, - error: error - ) - } - } + // Active native consumers retain their own owner until teardown joins. + customVocabularyArtifacts = nil customVocabularyConfiguration = nil customVocabularyCacheKey = nil diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 7f96076..5600364 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -68,38 +68,12 @@ public extension SpeechSession { options: FileTranscriptionOptions = .init(), progressHandler: (@Sendable (Double) -> Void)? = nil ) -> AsyncThrowingStream { - let (stream, newContinuation) = AsyncThrowingStream.makeStream() - - guard continuation == nil, recognizerTask == nil, - fileTranscription == nil, liveTranscription == nil, streamingMode == .inactive else { - newContinuation.finish(throwing: SpeechSessionError.recognitionStreamSetupFailed) - return stream - } - - let run = FileTranscriptionRun() - fileTranscription = run - newContinuation.onTermination = { [weak self, weak run] _ in - Task { @MainActor [weak self, weak run] in - guard let self, let run else { return } - self.retireFileTranscription(run, error: nil) - } - } - - setStatus(.preparing) - continuation = .speech(newContinuation) - - run.setupTask = Task { @MainActor [weak self] in - guard let self else { return } - await self.startFilePipeline( - run: run, - with: newContinuation, - audioFileURL: audioFile, - options: options, - progressHandler: progressHandler + startFileTranscription { session, continuation, run in + await session.startFilePipeline( + run: run, with: continuation, audioFileURL: audioFile, + options: options, progressHandler: progressHandler ) } - - return stream } /// Convenience wrapper that collects final results from file transcription. @@ -130,6 +104,7 @@ public extension SpeechSession { } let finalResults = try await stream.reduce(into: [SpeechTranscriber.Result](), accumulator) + try Task.checkCancellation() return finalResults } } @@ -186,47 +161,6 @@ private extension SpeechSession { } } - func ingestFileInput( - _ run: FileTranscriptionRun, - validation: (file: AVAudioFile, totalFrames: AVAudioFramePosition), - progressHandler: (@Sendable (Double) -> Void)?, - ingest: (@Sendable () async throws -> Bool)? - ) async { - do { - try requireCurrentFileTranscription(run) - let completed: Bool - if let ingest { - completed = try await ingest() - } else { - completed = try await feedAudioFile(validation, progressHandler: progressHandler) - } - try requireCurrentFileTranscription(run) - guard completed else { - // Cancellation was checked above. An input that ended - // before its declared length is an incomplete read; - // don't leave analysis open or report partial success. - throw SpeechSessionError.audioFileReadFailed(CocoaError( - .fileReadUnknown, - userInfo: [ - NSLocalizedDescriptionKey: "Audio input ended before all declared frames were read." - ] - )) - } - progressHandler?(1.0) - if !run.usesNativeFileAnalyzer { - try await finalizeFileInput(run) - } - } catch is CancellationError { - // A finalizer may fail with CancellationError even when - // public stop did not initiate cancellation. - if fileTranscription === run, !run.retired { - retireFileTranscription(run, error: CancellationError()) - } - } catch { - retireFileTranscription(run, error: error) - } - } - func validateAudioFile( at url: URL, options: FileTranscriptionOptions @@ -261,6 +195,10 @@ private extension SpeechSession { return (audioFile, totalFrames) } +} + +@available(iOS 26.0, macOS 26.0, *) +extension SpeechSession { func sanitizeAudioFileURL( _ url: URL, allowedDirectories: [URL] @@ -293,7 +231,8 @@ private extension SpeechSession { func setUpFilePipeline( run: FileTranscriptionRun, with streamContinuation: AsyncThrowingStream.Continuation, - contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? + contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]?, + mode: StreamingMode = .filePlayback ) async throws { if Self.shouldLog(.notice) { Self.logger.notice("Starting file transcription pipeline") @@ -310,85 +249,46 @@ private extension SpeechSession { run: run, results: transcriber.results, streamContinuation: streamContinuation ) - streamingMode = .filePlayback + streamingMode = mode setStatus(.transcribing) if Self.shouldLog(.info) { Self.logger.info("File transcription pipeline active (mode: file playback)") } } - nonisolated func feedAudioFile( - _ payload: (file: AVAudioFile, totalFrames: AVAudioFramePosition), - progressHandler: (@Sendable (Double) -> Void)? - ) async throws -> Bool { -#if swift(>=6.4) - if #available(iOS 27.0, macOS 27.0, *), - progressHandler == nil, - await shouldUseNativeAssetInputProvider { - return try await feedAudioFileWithNativeAnalyzer(payload.file, progressHandler: progressHandler) - } -#endif - var processedFrames: AVAudioFramePosition = 0 - let frameCapacity: AVAudioFrameCount = 4096 - let file = payload.file - let totalFrames = payload.totalFrames - let format = file.processingFormat - - guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) else { - throw SpeechSessionError.conversionBufferCreationFailed - } - - while processedFrames < totalFrames { - if Task.isCancelled { break } - - let framesToRead = AudioFileReadSize.next( - remaining: totalFrames - processedFrames, capacity: frameCapacity - ) - - buffer.frameLength = framesToRead - - do { - try file.read(into: buffer, frameCount: framesToRead) - } catch { - throw SpeechSessionError.audioFileReadFailed(error) - } - - if buffer.frameLength == 0 { - break - } - - guard let bufferCopy = buffer.copy() as? AVAudioPCMBuffer else { - throw SpeechSessionError.conversionBufferCreationFailed - } - - let sendableBuffer = SendablePCMBuffer(buffer: bufferCopy) - - try await self.processAudioBuffer(sendableBuffer) +} - processedFrames += AVAudioFramePosition(buffer.frameLength) +@available(iOS 26.0, macOS 26.0, *) +extension SpeechSession { + typealias FileResultContinuation = AsyncThrowingStream.Continuation - if let progressHandler, totalFrames > 0 { - let progress = min(1.0, max(0.0, Double(processedFrames) / Double(totalFrames))) - await MainActor.run { - progressHandler(progress) - } - } + func startFileTranscription( + mode: StreamingMode = .filePlayback, + _ setup: @escaping @MainActor (SpeechSession, FileResultContinuation, FileTranscriptionRun) async -> Void + ) -> AsyncThrowingStream { + let (stream, newContinuation) = AsyncThrowingStream.makeStream() + guard continuation == nil, recognizerTask == nil, + fileTranscription == nil, liveTranscription == nil, streamingMode == .inactive else { + newContinuation.finish(throwing: SpeechSessionError.recognitionStreamSetupFailed) + return stream } - - await MainActor.run { - self.inputBuilder?.finish() + let run = FileTranscriptionRun() + fileTranscription = run + newContinuation.onTermination = { [weak self, weak run] termination in + guard case .cancelled = termination else { return } + Task { @MainActor [weak self, weak run] in + guard let self, let run else { return } + self.retireFileTranscription(run, error: CancellationError()) + } } - - return !Task.isCancelled && processedFrames >= totalFrames - } - - func shouldUseNativeFileAnalyzer(progressHandler: (@Sendable (Double) -> Void)?) -> Bool { -#if swift(>=6.4) - if #available(iOS 27.0, macOS 27.0, *) { - return inputProviderPreference == .automatic && progressHandler == nil + if mode == .mediaPlayback { streamingMode = mode } + setStatus(.preparing) + continuation = .speech(newContinuation) + run.setupTask = Task { @MainActor [weak self] in + guard let self else { return } + await setup(self, newContinuation, run) } -#endif - return false + return stream } } diff --git a/Sources/AuralKit/SpeechSession+FileInput.swift b/Sources/AuralKit/SpeechSession+FileInput.swift new file mode 100644 index 0000000..80a7162 --- /dev/null +++ b/Sources/AuralKit/SpeechSession+FileInput.swift @@ -0,0 +1,132 @@ +import Foundation +import AVFoundation +import Speech + +@available(iOS 26.0, macOS 26.0, *) +extension SpeechSession { + func ingestFileInput( + _ run: FileTranscriptionRun, + validation: (file: AVAudioFile, totalFrames: AVAudioFramePosition), + progressHandler: (@Sendable (Double) -> Void)?, + ingest: (@Sendable () async throws -> Bool)? + ) async { + do { + try requireCurrentFileTranscription(run) + let completed: Bool + if let ingest { + completed = try await ingest() + } else { + completed = try await feedAudioFile(validation, run: run, progressHandler: progressHandler) + } + try requireCurrentFileTranscription(run) + guard completed else { + // Cancellation was checked above. An input that ended + // before its declared length is an incomplete read; + // don't leave analysis open or report partial success. + throw Self.incompleteAudioFileReadError() + } + if let progressHandler { reportFileProgress(1.0, handler: progressHandler, run: run) } + if !run.usesNativeFileAnalyzer { + try await finalizeFileInput(run) + } + try requireCurrentFileTranscription(run) + completeFileIngestion(run) + } catch is CancellationError { + // A finalizer may fail with CancellationError even when + // public stop did not initiate cancellation. + if fileTranscription === run, !run.retired { + retireFileTranscription(run, error: CancellationError()) + } + } catch { + retireFileTranscription(run, error: error) + } + } + + nonisolated func feedAudioFile( + _ payload: (file: AVAudioFile, totalFrames: AVAudioFramePosition), + run: FileTranscriptionRun, + progressHandler: (@Sendable (Double) -> Void)? + ) async throws -> Bool { +#if swift(>=6.4) + if #available(iOS 27.0, macOS 27.0, *), + progressHandler == nil, + await shouldUseNativeAssetInputProvider { + return try await feedAudioFileWithNativeAnalyzer(payload.file, progressHandler: progressHandler) + } +#endif + var processedFrames: AVAudioFramePosition = 0 + let frameCapacity: AVAudioFrameCount = 4096 + let file = payload.file + let totalFrames = payload.totalFrames + let format = file.processingFormat + + guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) else { + throw SpeechSessionError.conversionBufferCreationFailed + } + + while processedFrames < totalFrames { + if Task.isCancelled { break } + + let framesToRead = AudioFileReadSize.next( + remaining: totalFrames - processedFrames, capacity: frameCapacity + ) + + buffer.frameLength = framesToRead + + do { + try file.read(into: buffer, frameCount: framesToRead) + } catch { + throw SpeechSessionError.audioFileReadFailed(error) + } + + if buffer.frameLength == 0 { + throw Self.incompleteAudioFileReadError() + } + + guard let bufferCopy = buffer.copy() as? AVAudioPCMBuffer else { + throw SpeechSessionError.conversionBufferCreationFailed + } + + let sendableBuffer = SendablePCMBuffer(buffer: bufferCopy) + + try await self.processAudioBuffer(sendableBuffer) + + processedFrames += AVAudioFramePosition(buffer.frameLength) + + if let progressHandler, totalFrames > 0 { + let progress = min(1.0, max(0.0, Double(processedFrames) / Double(totalFrames))) + await MainActor.run { + self.reportFileProgress(progress, handler: progressHandler, run: run) + } + } + } + + return !Task.isCancelled && processedFrames >= totalFrames + } + + nonisolated private static func incompleteAudioFileReadError() -> SpeechSessionError { + .audioFileReadFailed(CocoaError(.fileReadUnknown, userInfo: [ + NSLocalizedDescriptionKey: "Audio input ended before all declared frames were read." + ])) + } + + func shouldUseNativeFileAnalyzer(progressHandler: (@Sendable (Double) -> Void)?) -> Bool { +#if swift(>=6.4) + if #available(iOS 27.0, macOS 27.0, *) { + return inputProviderPreference == .automatic && progressHandler == nil + } +#endif + return false + } + + func reportFileProgress( + _ progress: Double, + handler: @Sendable (Double) -> Void, + run: FileTranscriptionRun + ) { + guard !Task.isCancelled, fileTranscription === run, !run.retired, + streamingMode == .filePlayback, status == .transcribing else { return } + handler(progress) + } + +} diff --git a/Sources/AuralKit/SpeechSession+FileLifecycle.swift b/Sources/AuralKit/SpeechSession+FileLifecycle.swift index df1cde8..2c90684 100644 --- a/Sources/AuralKit/SpeechSession+FileLifecycle.swift +++ b/Sources/AuralKit/SpeechSession+FileLifecycle.swift @@ -9,10 +9,13 @@ import OSLog @MainActor final class FileTranscriptionRun { var usesNativeFileAnalyzer = false + var ingestionCompleted = false + var resultsCompleted = false var setupTask: Task? var ingestionTask: Task? var recognizerTask: Task? var terminalTask: Task? + var cancellationRequested = false var retired = false } @@ -29,6 +32,41 @@ struct FileTranscriptionHooks { @available(iOS 26.0, macOS 26.0, *) @MainActor extension SpeechSession { + func startFileIngestion( + run: FileTranscriptionRun, + _ ingest: @escaping @MainActor (SpeechSession) async throws -> Void + ) { + guard fileTranscription === run, !run.retired else { return } + run.ingestionTask = Task { @MainActor [self] in + do { + try requireCurrentFileTranscription(run) + try await ingest(self) + try requireCurrentFileTranscription(run) + completeFileIngestion(run) + } catch { + // Independent cancellation is terminal unless retirement already owns it. + retireFileTranscription(run, error: error) + } + } + } + + func completeFileIngestion(_ run: FileTranscriptionRun) { + guard fileTranscription === run, !run.retired else { return } + run.ingestionCompleted = true + retireCompletedFile(run) + } + + func completeFileResults(_ run: FileTranscriptionRun) { + guard fileTranscription === run, !run.retired else { return } + run.resultsCompleted = true + retireCompletedFile(run) + } + + private func retireCompletedFile(_ run: FileTranscriptionRun) { + guard run.ingestionCompleted, run.resultsCompleted else { return } + retireFileTranscription(run, error: nil) + } + /// Ending an autonomous analyzer's input does not finish its analysis. /// Keep this run and its reader active while finalization publishes the /// last results. The reader requests retirement after draining them. @@ -38,7 +76,9 @@ extension SpeechSession { if let finalizeInput = fileTranscriptionHooks?.finalizeInput { try await finalizeInput() } else { - try await analyzer?.finalizeAndFinishThroughEndOfInput() + if try await !finishAnalyzerInput() { + retireFileTranscription(run, error: nil) + } } } @@ -57,10 +97,11 @@ extension SpeechSession { try self.requireCurrentFileTranscription(run) streamContinuation.yield(result) } + try Task.checkCancellation() if Self.shouldLog(.notice) { Self.logger.notice("File recognizer task completed without error") } - self.retireFileTranscription(run, error: nil) + self.completeFileResults(run) } catch is CancellationError { if Self.shouldLog(.debug) { Self.logger.debug("File recognizer task cancelled") @@ -107,15 +148,18 @@ extension SpeechSession { await run.setupTask?.value run.ingestionTask?.cancel() run.recognizerTask?.cancel() - await run.ingestionTask?.value guard self.fileTranscription === run else { return } // Finalization ends the result sequence before joining its reader; // do not assume an arbitrary result iterator wakes on cancellation. - await self.cleanupPipelineResources(cancelRecognizer: true, publishIdle: false) + // Cancel native analysis before joining an ingester suspended waiting for input. + // The shared cleanup keeps model leases until that child has returned. + await self.cleanupPipelineResources( + cancelRecognizer: true, publishIdle: false, inputTask: run.ingestionTask + ) await run.recognizerTask?.value self.fileTranscriptionHooks = nil self.setStatus(.idle) - await self.finishStream(error: error) + await self.finishStream(error: run.cancellationRequested ? CancellationError() : error) self.fileTranscription = nil run.setupTask = nil run.ingestionTask = nil diff --git a/Sources/AuralKit/SpeechSession+LiveLifecycle.swift b/Sources/AuralKit/SpeechSession+LiveLifecycle.swift index 75a45c9..79fdf4c 100644 --- a/Sources/AuralKit/SpeechSession+LiveLifecycle.swift +++ b/Sources/AuralKit/SpeechSession+LiveLifecycle.swift @@ -6,11 +6,20 @@ import Speech @available(iOS 26.0, macOS 26.0, *) @MainActor final class LiveTranscriptionRun { + var microphoneInput: MicrophoneAudioIngress? + var usesNativeInput = false + var inputCompleted = false + var resultsCompleted = false var inputTask: Task? var setupTask: Task? var recognizerTask: Task? var audioTasks: [UUID: Task] = [:] var terminalTask: Task? + var finishTask: Task? + var screenStopTask: Task? + var terminalError: Error? + var cancellationRequested = false + var finishing = false var retired = false } @@ -37,18 +46,21 @@ extension SpeechSession { func makeLiveRecognizerTask( run: LiveTranscriptionRun, results: Sequence, + vocabularyArtifacts: CustomVocabularyArtifacts? = nil, streamContinuation: AsyncThrowingStream.Continuation ) -> Task where Sequence: Sendable, Sequence.Element: Sendable { // Setup may already have started the analyzer. Retain its artifact owner // from task creation, including before this reader first runs. - Task { @MainActor [self] in + Task { @MainActor [self, vocabularyArtifacts] in + defer { withExtendedLifetime(vocabularyArtifacts) {} } do { for try await result in results { try self.requireCurrentLiveTranscription(run) streamContinuation.yield(result) } - self.retireLiveTranscription(run, error: nil) + try Task.checkCancellation() + self.completeLiveResults(run) } catch { // Independent result cancellation must also settle its stream. self.retireLiveTranscription(run, error: error) @@ -56,8 +68,22 @@ extension SpeechSession { } } - func enqueueLiveAudioBuffer(_ buffer: SendablePCMBuffer, run: LiveTranscriptionRun) { + func completeLiveInput(_ run: LiveTranscriptionRun) { + guard liveTranscription === run, !run.retired else { return } + run.inputCompleted = true + if run.resultsCompleted { retireLiveTranscription(run, error: nil) } + } + + private func completeLiveResults(_ run: LiveTranscriptionRun) { guard liveTranscription === run, !run.retired else { return } + run.resultsCompleted = true + if !run.usesNativeInput || run.inputCompleted { + retireLiveTranscription(run, error: nil) + } + } + + func enqueueLiveAudioBuffer(_ buffer: SendablePCMBuffer, run: LiveTranscriptionRun) { + guard liveTranscription === run, !run.retired, !run.finishing else { return } let id = UUID() run.audioTasks[id] = Task { @MainActor [weak self] in defer { run.audioTasks[id] = nil } @@ -80,20 +106,76 @@ extension SpeechSession { } } + func finishLivePipelineSetupFailure(_ error: Error, run: LiveTranscriptionRun) { + guard liveTranscription === run else { return } + if run.finishing, Task.isCancelled { return } + retireLiveTranscription(run, error: error) + } + + /// Finish drains accepted input; the same retirement owner still performs cleanup. + func finishLiveTranscription(_ run: LiveTranscriptionRun, sourceEnded: Bool = false) async { + guard liveTranscription === run else { return } + if let terminal = run.terminalTask { await terminal.value; return } + if let finish = run.finishTask { + await finish.value + await run.terminalTask?.value + return + } + guard (status != .preparing || sourceEnded), let results = run.recognizerTask else { + await retireLiveTranscription(run, error: nil)?.value + return + } + run.finishing = true + if status == .preparing { run.setupTask?.cancel() } + prepareForStop() + stopAudioStreaming() + let screenStop = beginStoppingScreenCapture(run: run) + let finish = Task { @MainActor in + do { + try await screenStop?.value + try self.requireCurrentLiveTranscription(run) + let audioTasks = Array(run.audioTasks.values) + for task in audioTasks { await task.value } + try self.requireCurrentLiveTranscription(run) + if let nativeInput = run.inputTask { + self.tearDownNativeCaptureStreaming() + await nativeInput.value + } else if try await !self.finishAnalyzerInput() { + self.retireLiveTranscription(run, error: nil) + } + await results.value + } catch { + // Producers request retirement without joining their own finish task. + self.retireLiveTranscription(run, error: error) + } + } + run.finishTask = finish + await finish.value + await run.terminalTask?.value + } + @discardableResult func retireLiveTranscription(_ run: LiveTranscriptionRun, error: Error?) -> Task? { guard liveTranscription === run else { return nil } if let terminal = run.terminalTask { return terminal } run.retired = true + // Cancellation closes input immediately; teardown still joins capture and setup. + inputBuilder?.finish() + inputBuilder = nil + run.terminalError = error prepareForStop() stopAudioStreaming() run.inputTask?.cancel() run.setupTask?.cancel() run.recognizerTask?.cancel() + run.finishTask?.cancel() run.audioTasks.values.forEach { $0.cancel() } + let screenStop = beginStoppingScreenCapture(run: run) let terminal = Task { @MainActor in // Dismiss pending selection before joining setup, which may be waiting on it. - await self.stopScreenCaptureStreamingIfNeeded() + if case .failure(let stopError)? = await screenStop?.result, run.terminalError == nil { + run.terminalError = stopError + } await run.setupTask?.value run.inputTask?.cancel() // Setup may install a result reader after cancellation was requested. @@ -105,19 +187,22 @@ extension SpeechSession { for task in audioTasks { await task.value } guard self.liveTranscription === run else { return } await self.cleanupPipelineResources( - cancelRecognizer: true, publishIdle: false, inputTask: run.inputTask + cancelRecognizer: true, publishIdle: false, inputTask: run.inputTask, + finishTask: run.finishTask ) await run.recognizerTask?.value await detectorTask?.value guard self.liveTranscription === run else { return } self.setStatus(.idle) - await self.finishStream(error: error) + await self.finishStream(error: run.cancellationRequested ? CancellationError() : run.terminalError) self.liveTranscription = nil run.inputTask = nil run.setupTask = nil run.recognizerTask = nil run.audioTasks.removeAll() run.terminalTask = nil + run.finishTask = nil + run.screenStopTask = nil } run.terminalTask = terminal return terminal diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift new file mode 100644 index 0000000..6e2b104 --- /dev/null +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -0,0 +1,142 @@ +#if swift(>=6.4) +import AVFoundation +import CoreMedia +import Foundation +import Speech + +@available(iOS 27.0, macOS 27.0, *) +public extension SpeechSession { + /// Stream transcription results from one audio track of a local media file, such as a movie. + /// + /// - Parameters: + /// - mediaFile: A local file URL in one of `options.allowedDirectories`. + /// - audioTrackID: An ID from the file's audio tracks. Pass `nil` to use its first audio track. + /// - options: Contextual strings, allowed directories, and the maximum selected track duration. + /// - Returns: An async throwing stream of transcription results on the media timeline. + /// + /// The audio must be stored inside the media file and the session must use `.automatic` input. + func streamTranscription( + fromMediaFile mediaFile: URL, + audioTrackID: CMPersistentTrackID? = nil, + options: FileTranscriptionOptions = .init() + ) -> AsyncThrowingStream { + startFileTranscription(mode: .mediaPlayback) { session, continuation, run in + await session.startMediaFilePipeline( + mediaFile, audioTrackID: audioTrackID, options: options, + continuation: continuation, run: run + ) + } + } +} + +@available(iOS 27.0, macOS 27.0, *) +private extension SpeechSession { + func startMediaFilePipeline( + _ mediaFile: URL, + audioTrackID: CMPersistentTrackID?, + options: FileTranscriptionOptions, + continuation: FileResultContinuation, + run: FileTranscriptionRun + ) async { + do { + try requireCurrentFileTranscription(run) + guard inputProviderPreference == .automatic else { + throw MediaTranscriptionConfigurationError() + } + let url = try sanitizeAudioFileURL(mediaFile, allowedDirectories: options.allowedDirectories) + let asset = Self.makeMediaAsset(url: url, needsPreciseDuration: options.maxDuration != nil) + let track = try await loadAudioTrack(from: asset, id: audioTrackID, maxDuration: options.maxDuration) + try requireCurrentFileTranscription(run) + try await ensureSpeechRecognitionAuthorization(context: "for media file transcription") + try requireCurrentFileTranscription(run) + run.usesNativeFileAnalyzer = true + try await setUpFilePipeline( + run: run, with: continuation, + contextualStrings: options.contextualStrings, + mode: .mediaPlayback + ) + try requireCurrentFileTranscription(run) + guard let analyzer, let activeModules else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: activeModules) else { + throw SpeechSessionError.invalidAudioDataType + } + try requireCurrentFileTranscription(run) + let provider = AssetInputSequenceProvider(asset: asset, track: track, analyzerFormat: format) + let inputs = provider.analyzerInputs + startFileIngestion(run: run) { session in + try await session.prepareAnalyzerForStartIfNeeded(in: format) + try session.requireCurrentFileTranscription(run) + session.startSpeechDetectorMonitoringIfNeeded() + + let endTime = try await analyzer.analyzeSequence(inputs) + try session.requireCurrentFileTranscription(run) + if let endTime { + try await analyzer.finalizeAndFinish(through: endTime) + } else { + // With no input samples, Speech may leave the module's results stream open. + session.retireFileTranscription(run, error: nil) + } + } + } catch { + retireFileTranscription(run, error: error) + } + } + + static func makeMediaAsset(url: URL, needsPreciseDuration: Bool) -> AVURLAsset { + var options: [String: Any] = [ + AVURLAssetReferenceRestrictionsKey: AVAssetReferenceRestrictions.forbidAll.rawValue + ] + if needsPreciseDuration { + options[AVURLAssetPreferPreciseDurationAndTimingKey] = true + } + return AVURLAsset(url: url, options: options) + } + + func loadAudioTrack( + from asset: AVAsset, + id: CMPersistentTrackID?, + maxDuration: TimeInterval? + ) async throws -> AVAssetTrack { + let tracks = try await asset.loadTracks(withMediaType: .audio) + guard let track = tracks.first(where: { id == nil || $0.trackID == id }) else { + let reason = if let id { + String.localizedStringWithFormat(NSLocalizedString( + "audio track ID %d was not found", comment: "The requested audio track is missing" + ), id) + } else { + NSLocalizedString("the media file has no audio tracks", comment: "The media asset has no audio track") + } + throw SpeechSessionError.audioFileUnsupportedFormat(reason) + } + let duration = try await track.load(.timeRange).duration.seconds + guard duration.isFinite, duration > 0 else { + throw SpeechSessionError.audioFileUnsupportedFormat(NSLocalizedString( + "the audio track has no finite, positive duration", + comment: "The media audio track has no usable duration" + )) + } + if let maxDuration, duration > maxDuration { + throw SpeechSessionError.audioFileTooLong(maximum: maxDuration, actual: duration) + } + return track + } +} + +private struct MediaTranscriptionConfigurationError: LocalizedError { + var errorDescription: String? { + NSLocalizedString( + "Media transcription requires the automatic input provider.", + comment: "Media files cannot use the legacy audio input pipeline" + ) + } + + var recoverySuggestion: String? { + NSLocalizedString( + "Create a SpeechSession with inputProviderPreference set to .automatic.", + comment: "How to enable media transcription" + ) + } +} +#endif diff --git a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift index db8ca83..52b67aa 100644 --- a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift @@ -62,6 +62,8 @@ extension SpeechSession { guard let modules = activeModules, let analyzer else { throw SpeechSessionError.recognitionStreamSetupFailed } + let vocabularyArtifacts = activeCustomVocabularyArtifacts + defer { withExtendedLifetime(vocabularyArtifacts) {} } guard let captureDevice = AVCaptureDevice.default(for: .audio) else { throw SpeechSessionError.recognitionStreamSetupFailed } @@ -78,15 +80,20 @@ extension SpeechSession { try requireCurrentLiveTranscription(run) let analyzerInputs = provider.analyzerInputs - run.inputTask = Task { @MainActor [self, analyzer, analyzerInputs] in + run.inputTask = Task { @MainActor [self, analyzer, analyzerInputs, vocabularyArtifacts] in + defer { withExtendedLifetime(vocabularyArtifacts) {} } do { let lastAudioTime = try await analyzer.analyzeSequence(analyzerInputs) + try Task.checkCancellation() if let lastAudioTime { try await analyzer.finalizeAndFinish(through: lastAudioTime) } else { - try await analyzer.finalizeAndFinishThroughEndOfInput() + // Empty analysis has no finalizer or final results to drain. + self.retireLiveTranscription(run, error: nil) + return } - // Input completion is owned by the result reader, which drains final results. + try self.requireCurrentLiveTranscription(run) + self.completeLiveInput(run) } catch { self.retireLiveTranscription(run, error: error) } diff --git a/Sources/AuralKit/SpeechSession+NativeFileInput.swift b/Sources/AuralKit/SpeechSession+NativeFileInput.swift index a412ba2..d720f9f 100644 --- a/Sources/AuralKit/SpeechSession+NativeFileInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeFileInput.swift @@ -19,20 +19,28 @@ extension SpeechSession { ) async throws -> Bool { guard !Task.isCancelled else { return false } - guard let analyzer = await MainActor.run(body: { analyzer }) else { - throw SpeechSessionError.recognitionStreamSetupFailed + let (run, analyzer) = try await MainActor.run { + guard let run = fileTranscription, let analyzer else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + try requireCurrentFileTranscription(run) + return (run, analyzer) } try await prepareAnalyzerForStartIfNeeded(in: file.processingFormat) - await MainActor.run { + try Task.checkCancellation() + try await MainActor.run { + try requireCurrentFileTranscription(run) startSpeechDetectorMonitoringIfNeeded() } + try Task.checkCancellation() let lastAudioTime = try await analyzer.analyzeSequence(from: file) + try await MainActor.run { try requireCurrentFileTranscription(run) } if let lastAudioTime { try await analyzer.finalizeAndFinish(through: lastAudioTime) } else { - try await analyzer.finalizeAndFinishThroughEndOfInput() + await MainActor.run { retireFileTranscription(run, error: nil) } } return !Task.isCancelled diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 3db9b47..4f1f503 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -2,8 +2,6 @@ import Foundation import AVFoundation import Speech -// swiftlint:disable file_length - @available(iOS 26.0, macOS 26.0, *) @MainActor extension SpeechSession { @@ -53,7 +51,7 @@ extension SpeechSession { Self.logger.notice("Requesting speech recognition permission\(suffix)") } let granted = await withCheckedContinuation { continuation in - SFSpeechRecognizer.requestAuthorization { status in + SFSpeechRecognizer.requestAuthorization { @Sendable status in continuation.resume(returning: status == .authorized) } } @@ -100,13 +98,14 @@ extension SpeechSession { contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil ) async { await startLivePipeline(run: run, kind: .dictation) { - let transcriber = try await self.setUpDictationTranscriber( + let prepared = try await self.setUpDictationTranscriber( contextualStrings: contextualStrings, startAnalyzerImmediately: !self.shouldUseNativeCaptureInputProvider ) try self.requireCurrentLiveTranscription(run) return self.makeLiveRecognizerTask( - run: run, results: transcriber.results, streamContinuation: streamContinuation + run: run, results: prepared.transcriber.results, + vocabularyArtifacts: prepared.artifacts, streamContinuation: streamContinuation ) } } @@ -129,6 +128,7 @@ extension SpeechSession { } else { try await setupAudioSession(liveRun: run) try requireCurrentLiveTranscription(run) + run.usesNativeInput = self.shouldUseNativeCaptureInputProvider run.recognizerTask = try await prepareRecognizer() } try requireCurrentLiveTranscription(run) @@ -145,13 +145,14 @@ extension SpeechSession { setStatus(.transcribing) } catch { // A producer requests retirement and returns; it never joins itself. - retireLiveTranscription(run, error: error) + finishLivePipelineSetupFailure(error, run: run) } } func cleanupPipelineResources( cancelRecognizer: Bool, publishIdle: Bool = true, - inputTask: Task? = nil + inputTask: Task? = nil, + finishTask: Task? = nil ) async { if Self.shouldLog(.debug) { Self.logger.debug("Cleanup started (cancelRecognizer: \(cancelRecognizer, privacy: .public))") @@ -178,11 +179,12 @@ extension SpeechSession { screenCaptureAnalysisFinalizer = nil let detached = detachTranscriberState() await stopScreenCaptureStreamingIfNeeded() - await finalizeDetachedTranscriberState(detached) + await cleanUpDetachedTranscriberState(detached, cancelAnalyzer: cancelRecognizer) await analysisFinalizer?() // Finalization wakes native analysis before joining it. Keep model leases // until that task can no longer use the detached analyzer. await inputTask?.value + await finishTask?.value await modelManager.releaseLocales() if publishIdle { setStatus(.idle) } diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index b167ff1..55e6479 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -2,49 +2,65 @@ import AVFoundation import CoreMedia import Foundation import Speech +import OSLog +import Synchronization // swiftlint:disable file_length -/// Internal capture lifetime boundary; production uses ScreenCaptureKit below. +/// Run-owned capture boundary shared by the native provider and controlled fixtures. @available(iOS 26.0, macOS 26.0, *) protocol ScreenCaptureInput: AnyObject { @MainActor func start() async throws - @MainActor func pause() async - @MainActor func resume() async throws - @MainActor func resumeOutcome() async -> ScreenCaptureResumeOutcome - @MainActor func stop() async -} - -@available(iOS 26.0, macOS 26.0, *) -extension ScreenCaptureInput { - @MainActor - func resumeOutcome() async -> ScreenCaptureResumeOutcome { - do { - try await resume() - return ScreenCaptureResumeOutcome(isCurrent: { true }, error: nil) - } catch { - return ScreenCaptureResumeOutcome(isCurrent: { true }, error: error) - } - } + @MainActor func pause() async -> Bool + @MainActor func resume(onCompletion: @escaping @MainActor (Result) -> Void) async -> Error? + @MainActor func stop() -> Task } @available(iOS 26.0, macOS 26.0, *) extension SpeechSession { - func pauseScreenCaptureStreamingIfNeeded() async { - await screenCaptureInputProvider?.pause() + func pauseScreenCaptureStreamingIfNeeded(run: LiveTranscriptionRun) async { + guard liveTranscription === run, !run.retired, + let provider = screenCaptureInputProvider else { return } + guard await provider.pause(), liveTranscription === run, !run.retired, + status == .transcribing, streamingMode == .screenCapture else { return } + setStatus(.paused) } - func resumeScreenCaptureStreamingIfNeeded() async throws -> ScreenCaptureResumeOutcome { + func resumeScreenCaptureStreamingIfNeeded(run: LiveTranscriptionRun) async throws { + try requireCurrentLiveTranscription(run) guard let provider = screenCaptureInputProvider else { throw SpeechSessionError.recognitionStreamSetupFailed } - return await provider.resumeOutcome() + var captureFailure: Error? + let terminalFailure = await provider.resume { result in + guard self.liveTranscription === run, !run.retired, + self.status == .paused, self.streamingMode == .screenCapture else { return } + switch result { + case .success: self.setStatus(.transcribing) + case .failure(let error): + captureFailure = error + self.prepareForStop() + } + } + if let error = captureFailure ?? terminalFailure { + await retireLiveTranscription(run, error: error)?.value + throw error + } } - func stopScreenCaptureStreamingIfNeeded() async { + func beginStoppingScreenCapture(run: LiveTranscriptionRun? = nil) -> Task? { + let run = run ?? liveTranscription + if let pending = run?.screenStopTask { return pending } let provider = screenCaptureInputProvider screenCaptureInputProvider = nil - await provider?.stop() + guard let provider else { return nil } + let task = provider.stop() + run?.screenStopTask = task + return task + } + + func stopScreenCaptureStreamingIfNeeded() async { + _ = await beginStoppingScreenCapture()?.result } } @@ -93,10 +109,11 @@ public extension SpeechSession { let run = LiveTranscriptionRun() liveTranscription = run - newContinuation.onTermination = { [weak self, weak run] _ in + newContinuation.onTermination = { [weak self, weak run] termination in + guard case .cancelled = termination else { return } Task { @MainActor [weak self, weak run] in guard let self, let run else { return } - self.retireLiveTranscription(run, error: nil) + self.retireLiveTranscription(run, error: CancellationError()) } } @@ -173,28 +190,36 @@ extension SpeechSession { Self.logger.info("Pipeline started (mode: screen capture)") } } catch { - retireLiveTranscription(run, error: error) + finishLivePipelineSetupFailure(error, run: run) } } - func setUpScreenCaptureStreaming(options: ScreenCaptureTranscriptionOptions, run: LiveTranscriptionRun) async throws { + func setUpScreenCaptureStreaming( + options: ScreenCaptureTranscriptionOptions, run: LiveTranscriptionRun + ) async throws { guard let analyzerFormat, let inputBuilder else { throw SpeechSessionError.invalidAudioDataType } - let onFailure: @Sendable (Error) -> Void = { [weak self, weak run] error in + let onTermination: @Sendable (Error?) -> Task = { [weak self, weak run] error in Task { @MainActor [weak self, weak run] in guard let self, let run else { return } - self.retireLiveTranscription(run, error: error) + if let error { + await self.retireLiveTranscription(run, error: error)?.value + } else { + await self.finishLiveTranscription(run, sourceEnded: true) + } } } let provider: any ScreenCaptureInput if let makeProvider = screenCapturePipelineHooks?.makeProvider { - provider = makeProvider(analyzerFormat, inputBuilder, onFailure) + provider = makeProvider(analyzerFormat, inputBuilder, onTermination) } else { provider = ScreenCaptureAudioInputProvider( options: options, targetFormat: analyzerFormat, - inputContinuation: inputBuilder, onFailure: onFailure + inputContinuation: inputBuilder, + useNativeConversion: inputProviderPreference == .automatic, + onTermination: onTermination ) } screenCaptureInputProvider = provider @@ -202,22 +227,100 @@ extension SpeechSession { } } -/// Keeps ScreenCaptureKit calls on the same tested transition boundary. +// ScreenCaptureKit can call its delegate before the asynchronous stop returns while the +// delegate's main-actor work is still queued. Keep the ingress error until stop observes it. +@available(iOS 26.0, macOS 26.0, *) +final class ScreenCaptureStopErrors: Sendable { + private struct State { + var streamID: ObjectIdentifier? + var error: Error? + } + + private let state = Mutex(State()) + + func start(_ streamID: ObjectIdentifier) { + state.withLock { $0 = State(streamID: streamID) } + } + + func record(_ error: Error, for streamID: ObjectIdentifier) { + state.withLock { + guard $0.streamID == streamID, $0.error == nil else { return } + $0.error = error + } + } + + @MainActor + func stop(_ streamID: ObjectIdentifier, nativeStop: () async throws -> Void) async throws { + let nativeError: Error? + do { + try await nativeStop() + nativeError = nil + } catch { + nativeError = error + } + let delegateError = state.withLock { + guard $0.streamID == streamID else { return nil as Error? } + let error = $0.error + if error != nil || nativeError == nil { $0 = State() } + return error + } + if let delegateError { + throw SpeechSessionError.screenCaptureFailed(delegateError) + } + if let nativeError { throw nativeError } + } +} + @available(iOS 27.0, macOS 26.0, *) @MainActor private final class NativeScreenCaptureStream: ScreenCaptureStream { let stream: SCStream - let willStop: @MainActor (SCStream) -> Void + private let audio: ScreenCaptureAudioProcessor + private let stopErrors: ScreenCaptureStopErrors - init(stream: SCStream, willStop: @escaping @MainActor (SCStream) -> Void) { + init(stream: SCStream, audio: ScreenCaptureAudioProcessor, stopErrors: ScreenCaptureStopErrors) { self.stream = stream - self.willStop = willStop + self.audio = audio + self.stopErrors = stopErrors + } + + func startCapture() async throws { + defer { logCaptureState(after: "startCapture") } + let id = ObjectIdentifier(stream) + stopErrors.start(id) + audio.start(id) + do { + try await stream.startCapture() + } catch { + audio.discard(id) + throw error + } } - func startCapture() async throws { try await stream.startCapture() } func stopCapture() async throws { - willStop(stream) - try await stream.stopCapture() + defer { logCaptureState(after: "stopCapture") } + let id = ObjectIdentifier(stream) + try await stopErrors.stop(id) { try await stream.stopCapture() } + if let error = audio.drain(id) { + throw ScreenCaptureDrainFailure(underlyingError: error) + } + } + +#if os(macOS) || targetEnvironment(macCatalyst) + func updateContentFilter(_ filter: SCContentFilter) async throws { + defer { logCaptureState(after: "updateContentFilter") } + try await stream.updateContentFilter(filter) + } +#endif + + private func logCaptureState(after operation: String) { +#if compiler(>=6.4) + guard #available(iOS 27.0, macOS 27.0, macCatalyst 27.0, *), + SpeechSession.shouldLog(.debug) else { return } + SpeechSession.logger.debug( + "SCStream.isCapturing after \(operation, privacy: .public): \(self.stream.isCapturing, privacy: .public)" + ) +#endif } } @@ -227,27 +330,27 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr private let options: SpeechSession.ScreenCaptureTranscriptionOptions private let targetFormat: AVAudioFormat - private let inputContinuation: AsyncStream.Continuation - private let onFailure: @Sendable (Error) -> Void - private let sampleQueue = DispatchQueue(label: "com.auralkit.screencapture.audio", qos: .userInitiated) - // Only touched on `sampleQueue`, which serializes access. - private let bufferConverter = BufferConverter() + private let onTermination: @Sendable (Error?) -> Task + private let audio: ScreenCaptureAudioProcessor + private let stopErrors = ScreenCaptureStopErrors() @MainActor private let transitions: ScreenCaptureTransitions + @MainActor private var terminalCleanupTask: Task? + @MainActor private var captureTasks: [UUID: Task] = [:] private let presentPicker: @MainActor (ScreenCaptureAudioInputProvider) -> Void private let dismissPicker: @MainActor (any SCContentSharingPickerObserver) -> Void private var selectionContinuation: CheckedContinuation? private var stopped = false - @MainActor private var captureTasks: [UUID: Task] = [:] - @MainActor private var pickerUpdateID: UUID? - private var intentionallyStoppingStreams = Set() + private var pickerUpdateID: UUID? + private var filterUpdateID: UUID? @MainActor init( options: SpeechSession.ScreenCaptureTranscriptionOptions, targetFormat: AVAudioFormat, inputContinuation: AsyncStream.Continuation, - onFailure: @escaping @Sendable (Error) -> Void, + useNativeConversion: Bool = true, + onTermination: @escaping @Sendable (Error?) -> Task, transitions: ScreenCaptureTransitions = ScreenCaptureTransitions(), presentPicker: @escaping @MainActor (ScreenCaptureAudioInputProvider) -> Void = { provider in let picker = SCContentSharingPicker.shared @@ -266,11 +369,15 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr ) { self.options = options self.targetFormat = targetFormat - self.inputContinuation = inputContinuation - self.onFailure = onFailure + self.onTermination = onTermination + self.audio = ScreenCaptureAudioProcessor( + targetFormat: targetFormat, useNativeConversion: useNativeConversion, input: inputContinuation + ) { error in + _ = onTermination(error) + } self.transitions = transitions - self.presentPicker = presentPicker self.dismissPicker = dismissPicker + self.presentPicker = presentPicker super.init() } @@ -278,8 +385,6 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr func start() async throws { try Task.checkCancellation() guard !stopped else { throw CancellationError() } - // The run's terminal task stops this provider before joining setup. - // stop() resumes pending selection and joins admitted picker updates. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in selectionContinuation = continuation presentPicker(self) @@ -288,38 +393,47 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr } @MainActor - func pause() async { - _ = try? await transitions.pause().value - } - - @MainActor - func resume() async throws { - guard !stopped else { throw CancellationError() } - let outcome = await resumeOutcome() - guard outcome.isCurrent() else { return } - if let error = outcome.error { throw error } + func pause() async -> Bool { + do { + try await transitions.pause().value + return transitions.desiredState == .paused + } catch let error as ScreenCaptureDrainFailure { + if !stopped { + _ = onTermination(SpeechSessionError.screenCaptureFailed(error.underlyingError)) + } + return false + } catch { + return false + } } @MainActor - func resumeOutcome() async -> ScreenCaptureResumeOutcome { - await transitions.resume().value + func resume(onCompletion: @escaping @MainActor (Result) -> Void) async -> Error? { + let failure = await transitions.resume(onCompletion: onCompletion).value + if failure != nil { await terminalCleanupTask?.value } + return failure } @MainActor - func stop() async { + func stop() -> Task { stopped = true + let operation = transitions.stop() dismissPicker(self) - - if let selectionContinuation { - selectionContinuation.resume(throwing: SpeechSessionError.screenCaptureSelectionCancelled) - self.selectionContinuation = nil - } - - // Joins internal start/resume/pause/replacement operations, including a late - // start's compensating stop, before the run can release analyzer/model owners. - _ = try? await transitions.stop().value + resumeSelection(throwing: SpeechSessionError.screenCaptureSelectionCancelled) let tasks = Array(captureTasks.values) - for task in tasks { await task.value } + return Task { + let result = await operation.result + for task in tasks { await task.value } + do { + try result.get() + } catch { + audio.discard() + if let drainFailure = error as? ScreenCaptureDrainFailure { + throw SpeechSessionError.screenCaptureFailed(drainFailure.underlyingError) + } + throw error + } + } } func contentSharingPicker( @@ -332,22 +446,24 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr Task { @MainActor [weak self] in guard let self, !self.stopped else { return } if let updatedStream { - guard (self.transitions.stream as? NativeScreenCaptureStream)?.stream === updatedStream else { return } + guard let current = self.transitions.stream as? NativeScreenCaptureStream, + current.stream === updatedStream else { return } +#if os(macOS) || targetEnvironment(macCatalyst) + self.updateStream(current) { try await current.updateContentFilter(selectedFilter) } + return +#endif } self.selectStream { [self] in - let streamConfiguration = SCStreamConfiguration() - streamConfiguration.capturesAudio = true - streamConfiguration.sampleRate = Int(targetFormat.sampleRate) - streamConfiguration.channelCount = Int(targetFormat.channelCount) - streamConfiguration.excludesCurrentProcessAudio = options.excludesCurrentProcessAudio - streamConfiguration.width = 2 - streamConfiguration.height = 2 - - let captureStream = SCStream(filter: selectedFilter, configuration: streamConfiguration, delegate: self) - try captureStream.addStreamOutput(self, type: .audio, sampleHandlerQueue: sampleQueue) - return NativeScreenCaptureStream(stream: captureStream) { [weak self] stream in - self?.markStreamForIntentionalStop(stream) - } + let configuration = SCStreamConfiguration() + configuration.capturesAudio = true + configuration.sampleRate = Int(targetFormat.sampleRate) + configuration.channelCount = Int(targetFormat.channelCount) + configuration.excludesCurrentProcessAudio = options.excludesCurrentProcessAudio + configuration.width = 2 + configuration.height = 2 + let capture = SCStream(filter: selectedFilter, configuration: configuration, delegate: self) + try capture.addStreamOutput(self, type: .audio, sampleHandlerQueue: audio.queue) + return NativeScreenCaptureStream(stream: capture, audio: audio, stopErrors: stopErrors) } } } @@ -363,64 +479,78 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr guard let self else { return } let wrappedError = SpeechSessionError.screenCaptureFailed(error) if !self.resumeSelection(throwing: wrappedError) { - self.onFailure(wrappedError) + _ = self.onTermination(wrappedError) } } } func stream(_ stream: SCStream, didStopWithError error: any Error) { + if !Self.isUserStop(error) { + stopErrors.record(error, for: ObjectIdentifier(stream)) + } Task { @MainActor [weak self] in - guard let self, !self.consumeIntentionalStop(for: stream), - !self.stopped, - (self.transitions.stream as? NativeScreenCaptureStream)?.stream === stream else { return } - self.onFailure(SpeechSessionError.screenCaptureFailed(error)) + guard let self, let current = self.transitions.stream as? NativeScreenCaptureStream, + current.stream === stream else { return } + self.streamDidStop(current, error: error) } } func stream(_ stream: SCStream, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, of type: SCStreamOutputType) { - guard type == .audio, sampleBuffer.isValid, sampleBuffer.numSamples > 0 else { return } - guard let sourceFormat = makeSourceFormat(from: sampleBuffer) else { return } + guard type == .audio else { return } + audio.receive(sampleBuffer, from: ObjectIdentifier(stream)) + } - do { - try sampleBuffer.withAudioBufferList { audioBufferList, _ in - guard let sourceBuffer = AVAudioPCMBuffer( - pcmFormat: sourceFormat, - bufferListNoCopy: audioBufferList.unsafePointer - ) else { return } - - guard let bufferCopy = sourceBuffer.copy() as? AVAudioPCMBuffer else { - onFailure(SpeechSessionError.conversionBufferCreationFailed) - return - } + @discardableResult + @MainActor + func selectStream(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) -> Task { + guard !stopped else { return Task {} } + return observeSelection(transitions.replace(makeStream: makeStream)) + } - processAudioBuffer(bufferCopy) + @discardableResult + @MainActor + func updateStream( + _ stream: any ScreenCaptureStream, + operation: @escaping @MainActor () async throws -> Void + ) -> Task { + guard !stopped, transitions.isCurrent(stream) else { return Task {} } + let update = transitions.update(stream, operation: operation) + let id = UUID() + filterUpdateID = id + let task = Task { @MainActor in + defer { self.captureTasks[id] = nil } + do { + try await update.value + } catch { + guard !self.stopped, self.filterUpdateID == id, self.transitions.isCurrent(stream) else { return } + _ = self.onTermination(SpeechSessionError.screenCaptureFailed(error)) } - } catch { - onFailure(SpeechSessionError.screenCaptureFailed(error)) } + captureTasks[id] = task + return task } - /// Common admission for the native picker callback and controlled capture collaborators. @MainActor - func selectStream(makeStream: @escaping @MainActor () throws -> any ScreenCaptureStream) { - guard !stopped else { return } - let operation = transitions.replace(makeStream: makeStream) + private func observeSelection(_ operation: Task) -> Task { let id = UUID() - self.pickerUpdateID = id - self.captureTasks[id] = Task { @MainActor in + pickerUpdateID = id + let task = Task { @MainActor in defer { self.captureTasks[id] = nil } - guard !self.stopped, self.pickerUpdateID == id else { return } do { try await operation.value guard !self.stopped, self.pickerUpdateID == id else { return } self.resumeSelection() } catch { guard !self.stopped, self.pickerUpdateID == id else { return } - if !self.resumeSelection(throwing: error) { - self.onFailure(SpeechSessionError.screenCaptureFailed(error)) + let drainFailure = error as? ScreenCaptureDrainFailure + let selectionError = drainFailure.map { SpeechSessionError.screenCaptureFailed($0.underlyingError) } + if !self.resumeSelection(throwing: selectionError ?? error) { + _ = self.onTermination(selectionError ?? SpeechSessionError.screenCaptureFailed(error)) } } } + captureTasks[id] = task + return task } @discardableResult @@ -436,36 +566,28 @@ final class ScreenCaptureAudioInputProvider: NSObject, ScreenCaptureInput, SCStr return true } - private func makeSourceFormat(from sampleBuffer: CMSampleBuffer) -> AVAudioFormat? { - guard let formatDescription = sampleBuffer.formatDescription, - var sourceDescription = formatDescription.audioStreamBasicDescription else { - return nil - } - - return AVAudioFormat(streamDescription: &sourceDescription) - } - - /// Convert and forward a captured buffer synchronously on `sampleQueue`. - /// - /// Inline conversion preserves capture order for the analyzer; the caller passes an - /// already-copied buffer, so a passthrough conversion is safe to forward directly. - private func processAudioBuffer(_ buffer: AVAudioPCMBuffer) { - do { - let converted = try bufferConverter.convertBuffer(buffer, to: targetFormat) - inputContinuation.yield(AnalyzerInput(buffer: converted)) - } catch { - onFailure(error) - } - } - @MainActor - private func markStreamForIntentionalStop(_ stream: SCStream) { - intentionallyStoppingStreams.insert(ObjectIdentifier(stream)) + func streamDidStop(_ stream: any ScreenCaptureStream, error: Error) { + let userStopped = Self.isUserStop(error) + var failure: Error? = userStopped ? nil : SpeechSessionError.screenCaptureFailed(error) + if let nativeStream = stream as? NativeScreenCaptureStream { + let id = ObjectIdentifier(nativeStream.stream) + if userStopped { + failure = audio.drain(id).map { SpeechSessionError.screenCaptureFailed($0) } + } else { + audio.discard(id) + } + } + let isCurrent = transitions.didStop(stream, error: failure) + guard !stopped, isCurrent else { return } + stopped = true + terminalCleanupTask = onTermination(failure) } - @MainActor - private func consumeIntentionalStop(for stream: SCStream) -> Bool { - intentionallyStoppingStreams.remove(ObjectIdentifier(stream)) != nil + private static func isUserStop(_ error: Error) -> Bool { + let nativeError = error as NSError + return nativeError.domain == SCStreamError.errorDomain + && nativeError.code == SCStreamError.Code.userStopped.rawValue } } #else diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index 60d0dcb..7181a25 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -1,5 +1,6 @@ import Foundation import AVFoundation +import CoreMedia import Speech // SpeechDetector gained native SpeechModule and Sendable conformances in Xcode 26.2. @@ -15,6 +16,8 @@ extension SpeechSession { // MARK: - Transcriber Setup and Cleanup + typealias PreparedDictation = (transcriber: DictationTranscriber, artifacts: CustomVocabularyArtifacts?) + func setUpSpeechTranscriber( contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil, startAnalyzerImmediately: Bool = true @@ -41,15 +44,17 @@ extension SpeechSession { func setUpDictationTranscriber( contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil, startAnalyzerImmediately: Bool = true - ) async throws -> DictationTranscriber { + ) async throws -> PreparedDictation { let admitSetup = captureAnalyzerSetupAdmission() try admitSetup() if Self.shouldLog(.notice) { Self.logger.notice("Setting up dictation transcriber") } - let transcriber = try createDictationTranscriber() - let modules = configureModules(transcriber: transcriber) + let prepared = try await createDictationTranscriber() + defer { withExtendedLifetime(prepared.artifacts) {} } + try admitSetup() + let modules = configureModules(transcriber: prepared.transcriber) try await ensureModels(modules: modules) try admitSetup() try await configureAnalyzerContext(contextualStrings: contextualStrings) @@ -58,7 +63,7 @@ extension SpeechSession { try await startAnalyzer(modules: modules, admitSetup: admitSetup) } - return transcriber + return prepared } private func createSpeechTranscriber() throws -> SpeechTranscriber { @@ -80,7 +85,20 @@ extension SpeechSession { return transcriber } - private func createDictationTranscriber() throws -> DictationTranscriber { + func createDictationTranscriber() async throws -> PreparedDictation { + let admitSetup = captureAnalyzerSetupAdmission() + try admitSetup() + if let descriptor = customVocabularyDescriptor, !customVocabularyFilesExist { + let requestID = customVocabularyRequestID + let compilation = try await compileCustomVocabulary(descriptor) + try Task.checkCancellation() + try admitSetup() + guard requestID == customVocabularyRequestID else { + throw CancellationError() + } + applyCustomVocabularyCompilation(compilation, descriptor: descriptor) + } + try Task.checkCancellation() let basePreset = DictationTranscriber.Preset.progressiveShortDictation var contentHints = basePreset.contentHints var reportingOptions = basePreset.reportingOptions @@ -91,6 +109,7 @@ extension SpeechSession { reportingOptions.insert(.frequentFinalization) } + activeCustomVocabularyArtifacts = customVocabularyArtifacts dictationTranscriber = DictationTranscriber( locale: locale, contentHints: contentHints, @@ -103,7 +122,7 @@ extension SpeechSession { throw SpeechSessionError.recognitionStreamSetupFailed } - return dictationTranscriber + return (dictationTranscriber, activeCustomVocabularyArtifacts) } @discardableResult @@ -227,6 +246,7 @@ extension SpeechSession { guard let format = selectedFormat else { throw SpeechSessionError.invalidAudioDataType } + try Task.checkCancellation() analyzerFormat = format if Self.shouldLog(.debug) { @@ -248,8 +268,9 @@ extension SpeechSession { try await prepareAnalyzerForStartIfNeeded(in: format) try admitSetup() - try await analyzer.start(inputSequence: inputSequence) - try admitSetup() + startAnalyzingInput(admitSetup: admitSetup) { + try await analyzer.analyzeSequence(inputSequence) + } if Self.shouldLog(.info) { Self.logger.info("Analyzer started") } @@ -257,6 +278,26 @@ extension SpeechSession { startSpeechDetectorMonitoringIfNeeded() } + func startAnalyzingInput( + admitSetup: @escaping @MainActor () throws -> Void, + analyze: @escaping @MainActor () async throws -> CMTime? + ) { + let liveRun = liveTranscription + let fileRun = fileTranscription + let vocabularyArtifacts = activeCustomVocabularyArtifacts + analyzerInputTask = Task { @MainActor [self, vocabularyArtifacts] in + defer { withExtendedLifetime(vocabularyArtifacts) {} } + do { + try admitSetup() + return try await analyze() + } catch { + if let liveRun { self.retireLiveTranscription(liveRun, error: error) } + if let fileRun { self.retireFileTranscription(fileRun, error: error) } + throw error + } + } + } + func processAudioBuffer(_ buffer: SendablePCMBuffer, liveRun: LiveTranscriptionRun? = nil) async throws { if let liveRun { try requireCurrentLiveTranscription(liveRun) } guard let inputBuilder, let analyzerFormat else { @@ -273,10 +314,21 @@ extension SpeechSession { inputBuilder.yield(input) } - /// State captured by `detachTranscriberState()` for asynchronous finalization. + func finishAnalyzerInput() async throws -> Bool { + inputBuilder?.finish() + guard let analyzer, let analyzerInputTask else { return true } + guard let endTime = try await analyzerInputTask.value else { return false } + try Task.checkCancellation() + try await analyzer.finalizeAndFinish(through: endTime) + return true + } + + /// State captured by `detachTranscriberState()` for asynchronous cleanup. struct DetachedTranscriberState { let inputBuilder: AsyncStream.Continuation? let analyzer: SpeechAnalyzer? + let inputTask: Task? + let vocabularyArtifacts: CustomVocabularyArtifacts? } /// Synchronously clear all transcriber-related session state and return the pieces that @@ -288,7 +340,13 @@ extension SpeechSession { if Self.shouldLog(.debug) { Self.logger.debug("Stopping transcriber and cleaning up") } - let detached = DetachedTranscriberState(inputBuilder: inputBuilder, analyzer: analyzer) + let inputTask = analyzerInputTask + analyzerInputTask = nil + let detached = DetachedTranscriberState( + inputBuilder: inputBuilder, analyzer: analyzer, inputTask: inputTask, + vocabularyArtifacts: activeCustomVocabularyArtifacts + ) + activeCustomVocabularyArtifacts = nil tearDownSpeechDetectorStream() speechDetector = nil @@ -304,20 +362,13 @@ extension SpeechSession { return detached } - /// Finish the detached analyzer input and finalize the detached analyzer. - /// - /// Operates only on the captured references, never on live session state, so it is safe to - /// run even after a newer session has started. - func finalizeDetachedTranscriberState(_ detached: DetachedTranscriberState) async { + func cleanUpDetachedTranscriberState(_ detached: DetachedTranscriberState, cancelAnalyzer: Bool) async { + defer { withExtendedLifetime(detached.vocabularyArtifacts) {} } detached.inputBuilder?.finish() - do { - try await detached.analyzer?.finalizeAndFinishThroughEndOfInput() - } catch { - // Finalization failed, but we still need to clean up resources - // Log for debugging but don't propagate since stop() is best-effort cleanup - } - if Self.shouldLog(.debug) { - Self.logger.debug("Transcriber cleanup complete") + if cancelAnalyzer { + detached.inputTask?.cancel() + await detached.analyzer?.cancelAndFinishNow() } + _ = await detached.inputTask?.result } } diff --git a/Sources/AuralKit/SpeechSession+Types.swift b/Sources/AuralKit/SpeechSession+Types.swift index ad63157..909905d 100644 --- a/Sources/AuralKit/SpeechSession+Types.swift +++ b/Sources/AuralKit/SpeechSession+Types.swift @@ -19,6 +19,7 @@ extension SpeechSession { case inactive case liveMicrophone case filePlayback + case mediaPlayback case screenCapture } diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 1bbd91b..a5c44f1 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -1,5 +1,6 @@ import Foundation import AVFoundation +import CoreMedia import Speech // MARK: - SpeechSession @@ -69,6 +70,7 @@ public final class SpeechSession { var dictationTranscriber: DictationTranscriber? var speechDetector: SpeechDetector? var analyzer: SpeechAnalyzer? + var analyzerInputTask: Task? var activeModules: [any SpeechModule]? var inputSequence: AsyncStream? var inputBuilder: AsyncStream.Continuation? @@ -82,6 +84,8 @@ public final class SpeechSession { var customVocabularyConfiguration: SFSpeechLanguageModel.Configuration? var customVocabularyCacheKey: String? var customVocabularyOutputDirectory: URL? + var customVocabularyArtifacts: CustomVocabularyArtifacts? + var activeCustomVocabularyArtifacts: CustomVocabularyArtifacts? var activeResultKind: TranscriptionResultKind? // MARK: - Public Observables @@ -267,7 +271,7 @@ public final class SpeechSession { /// /// The returned `AsyncThrowingStream` yields `SpeechTranscriber.Result` chunks containing both text and /// timing metadata (`.audioTimeRange`), as well as whether the result is final or volatile (partial). - /// Consume the stream with `for try await` and call `stopTranscribing()` to finish early. + /// Consume the stream with `for try await` and call `finishTranscribing()` to finish capture. /// /// - Parameter contextualStrings: Optional dictionary mapping contextual strings tags /// to arrays of contextual words that help improve transcription accuracy. For example, @@ -307,10 +311,11 @@ public final class SpeechSession { let run = LiveTranscriptionRun() liveTranscription = run - newContinuation.onTermination = { [weak self, weak run] _ in + newContinuation.onTermination = { [weak self, weak run] termination in + guard case .cancelled = termination else { return } Task { @MainActor [weak self, weak run] in guard let self, let run else { return } - self.retireLiveTranscription(run, error: nil) + self.retireLiveTranscription(run, error: CancellationError()) } } @@ -346,66 +351,7 @@ public final class SpeechSession { public func startTranscribing( contextualStrings: [String] ) -> AsyncThrowingStream { - return startTranscribing(contextualStrings: [.general: contextualStrings]) - } - - /// Stop capturing audio and finish the current transcription stream. - /// - /// Safe to call even if `startTranscribing()` has not been invoked or the stream has already - /// completed; the method simply waits for cleanup and returns. - /// For live transcription, waits for setup, admitted audio processing and result - /// delivery to exit. For file transcription, also waits for setup, file ingestion and result - /// delivery to exit before returning. The caller may then release its audio - /// file lease or remove its request-owned workspace. - public func stopTranscribing() async { - if let run = liveTranscription { - await retireLiveTranscription(run, error: nil)?.value - return - } - if let run = fileTranscription { - await retireFileTranscription(run, error: nil)?.value - return - } - // Every accepted transcription owns a run before setup can suspend. - // An idle stop must not start unowned cleanup that can overlap a new run. - } - - /// Pause capture without tearing down the analyzer pipeline. - /// - /// Safe to call only when the session is actively transcribing live audio (microphone or - /// screen capture). Calls during file transcription or in any other state are ignored. - public func pauseTranscribing() async { - guard status == .transcribing, isPausableStreamingMode, - let run = liveTranscription, !run.retired else { return } - if streamingMode == .screenCapture { - await pauseScreenCaptureStreamingIfNeeded() - } else { - stopAudioStreaming() - } - guard liveTranscription === run, !run.retired else { return } - setStatus(.paused) - } - - /// Resume a paused capture session. - /// - Throws: `SpeechSessionError` if audio streaming cannot restart. - public func resumeTranscribing() async throws { - guard status == .paused, isPausableStreamingMode, - let run = liveTranscription else { return } - do { - try requireCurrentLiveTranscription(run) - if streamingMode == .screenCapture { - let outcome = try await resumeScreenCaptureStreamingIfNeeded() - guard outcome.isCurrent() else { return } - if let error = outcome.error { throw error } - try requireCurrentLiveTranscription(run) - } else { - try startAudioStreaming() - } - setStatus(.transcribing) - } catch { - await retireLiveTranscription(run, error: error)?.value - throw error - } + startTranscribing(contextualStrings: [.general: contextualStrings]) } } diff --git a/Tests/AuralKitTests/AuralKitTests.swift b/Tests/AuralKitTests/AuralKitTests.swift index 6255733..86e9e64 100644 --- a/Tests/AuralKitTests/AuralKitTests.swift +++ b/Tests/AuralKitTests/AuralKitTests.swift @@ -44,6 +44,8 @@ struct SpeechSessionStateTests { func stopTranscribingWithoutSessionIsNoOp() async { guard #available(iOS 26.0, macOS 26.0, *) else { return } let session = SpeechSession() + await session.finishTranscribing() + await session.cancelTranscribing() await session.stopTranscribing() #expect(await session.modelDownloadProgress == nil) #expect(session.status == .idle) @@ -344,18 +346,21 @@ actor MockCustomVocabularyCompiler: CustomVocabularyCompiling { lastDescriptor = descriptor let cacheKey = try descriptor.stableCacheKey() - let outputDirectory = baseDirectory.appendingPathComponent(cacheKey, isDirectory: true) - try? fileManager.createDirectory(at: outputDirectory, withIntermediateDirectories: true) + let outputDirectory = baseDirectory + .appendingPathComponent("\(cacheKey)-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: outputDirectory, withIntermediateDirectories: true) - let configuration = SFSpeechLanguageModel.Configuration( - languageModel: outputDirectory.appendingPathComponent("languageModel.bin"), - vocabulary: outputDirectory.appendingPathComponent("vocabulary.bin") - ) + let model = outputDirectory.appendingPathComponent("languageModel.bin") + let vocabulary = outputDirectory.appendingPathComponent("vocabulary.bin") + try Data("model".utf8).write(to: model) + try Data("vocabulary".utf8).write(to: vocabulary) + let configuration = SFSpeechLanguageModel.Configuration(languageModel: model, vocabulary: vocabulary) return CustomVocabularyCompilation( configuration: configuration, cacheKey: cacheKey, - outputDirectory: outputDirectory + outputDirectory: outputDirectory, + artifacts: CustomVocabularyArtifacts(directory: outputDirectory) ) } diff --git a/Tests/AuralKitTests/CustomVocabularyArtifactTests.swift b/Tests/AuralKitTests/CustomVocabularyArtifactTests.swift new file mode 100644 index 0000000..ae18f7b --- /dev/null +++ b/Tests/AuralKitTests/CustomVocabularyArtifactTests.swift @@ -0,0 +1,227 @@ +import Foundation +import Speech +import Testing +@testable import AuralKit + +extension CustomVocabularyOwnershipTests { + @Test("Production allocation isolates equal descriptors across sessions", arguments: [false, true]) + @MainActor + func productionDirectoriesArePrivate(replace: Bool) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + // Only Apple model work is substituted. The actual compiler allocates + // and transfers real Application Support directories for both sessions. + let compiler = CustomVocabularyCompiler(prepareModel: { _, asset, _ in + let directory = asset.deletingLastPathComponent() + try Data("model".utf8).write(to: directory.appendingPathComponent("languageModel.bin")) + try Data("vocabulary".utf8).write(to: directory.appendingPathComponent("vocabulary.bin")) + try Data("source".utf8).write(to: asset) + }) + let first = SpeechSession(locale: Locale(identifier: "en_US")) + let second = SpeechSession(locale: Locale(identifier: "en_US")) + first.customVocabularyCompiler = compiler + second.customVocabularyCompiler = compiler + let descriptor = SpeechSession.CustomVocabulary( + locale: Locale(identifier: "en_US"), identifier: "private-ownership", version: "1" + ) + do { + try await first.configureCustomVocabulary(descriptor) + try await second.configureCustomVocabulary(descriptor) + let firstDirectory = try #require(first.customVocabularyOutputDirectory) + let secondDirectory = try #require(second.customVocabularyOutputDirectory) + #expect(firstDirectory != secondDirectory) + #expect(first.customVocabularyCacheKey == second.customVocabularyCacheKey) + try await second.configureCustomVocabulary(descriptor) + #expect(second.customVocabularyOutputDirectory == secondDirectory) + if replace { + try await first.configureCustomVocabulary(.init( + locale: descriptor.locale, identifier: "replacement", version: "1" + )) + } else { + try await first.configureCustomVocabulary(nil) + } + #expect(!FileManager.default.fileExists(atPath: firstDirectory.path)) + let model = secondDirectory.appendingPathComponent("languageModel.bin") + let vocabulary = secondDirectory.appendingPathComponent("vocabulary.bin") + let source = secondDirectory.appendingPathComponent("source.bin") + #expect(try Data(contentsOf: model) == Data("model".utf8)) + #expect(try Data(contentsOf: vocabulary) == Data("vocabulary".utf8)) + #expect(!FileManager.default.fileExists(atPath: source.path)) + try await second.configureCustomVocabulary(nil) + #expect(!FileManager.default.fileExists(atPath: secondDirectory.path)) + } catch { + try? await first.configureCustomVocabulary(nil) + try? await second.configureCustomVocabulary(nil) + throw error + } + try await first.configureCustomVocabulary(nil) + } + + @Test("Releasing idle sessions retires only their own production output") + @MainActor + func idleSessionReleaseRetiresPrivateOutput() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let compiler = CustomVocabularyCompiler(prepareModel: { _, asset, _ in + let directory = asset.deletingLastPathComponent() + try Data("model".utf8).write(to: directory.appendingPathComponent("languageModel.bin")) + try Data("vocabulary".utf8).write(to: directory.appendingPathComponent("vocabulary.bin")) + try Data("source".utf8).write(to: asset) + }) + var first: SpeechSession? = SpeechSession(locale: Locale(identifier: "en_US")) + var second: SpeechSession? = SpeechSession(locale: Locale(identifier: "en_US")) + weak var firstOwner = first + weak var secondOwner = second + defer { first = nil; second = nil } + first?.customVocabularyCompiler = compiler + second?.customVocabularyCompiler = compiler + let descriptor = SpeechSession.CustomVocabulary( + locale: Locale(identifier: "en_US"), identifier: "idle-release-ownership", version: "1" + ) + try await first?.configureCustomVocabulary(descriptor) + try await second?.configureCustomVocabulary(descriptor) + let firstDirectory = try #require(first?.customVocabularyOutputDirectory) + let secondDirectory = try #require(second?.customVocabularyOutputDirectory) + let cacheKey = try #require(second?.customVocabularyCacheKey) + #expect(firstDirectory != secondDirectory) + #expect(first?.customVocabularyCacheKey == cacheKey) + + // No explicit clear, stop or direct filesystem cleanup retires either owner. + first = nil + #expect(firstOwner == nil) + #expect(!FileManager.default.fileExists(atPath: firstDirectory.path)) + try await second?.configureCustomVocabulary(descriptor) + #expect(second?.customVocabularyOutputDirectory == secondDirectory) + #expect(second?.customVocabularyCacheKey == cacheKey) + #expect(second?.customVocabularyConfiguration != nil) + let model = secondDirectory.appendingPathComponent("languageModel.bin") + let vocabulary = secondDirectory.appendingPathComponent("vocabulary.bin") + let source = secondDirectory.appendingPathComponent("source.bin") + #expect(try Data(contentsOf: model) == Data("model".utf8)) + #expect(try Data(contentsOf: vocabulary) == Data("vocabulary".utf8)) + #expect(!FileManager.default.fileExists(atPath: source.path)) + + second = nil + #expect(secondOwner == nil) + #expect(!FileManager.default.fileExists(atPath: secondDirectory.path)) + } + + @Test("A queued live result reader retains vocabulary through retirement") + @MainActor + func queuedReaderRetainsArtifactOwner() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + var session: SpeechSession? = SpeechSession(locale: Locale(identifier: "en_US")) + session?.customVocabularyCompiler = CustomVocabularyCompiler(prepareModel: { _, asset, _ in + try Data("model".utf8).write( + to: asset.deletingLastPathComponent().appendingPathComponent("languageModel.bin") + ) + }) + try await session?.configureCustomVocabulary(.init( + locale: Locale(identifier: "en_US"), identifier: "queued-reader-ownership", version: "1" + )) + let directory = try #require(session?.customVocabularyOutputDirectory) + let run = LiveTranscriptionRun() + let results = AsyncStream.makeStream() + let forwarded = AsyncThrowingStream.makeStream() + // Exercise the production reader and terminal join without native Speech work. + session?.liveTranscription = run + let reader = try #require(session?.makeLiveRecognizerTask( + run: run, results: results.stream, streamContinuation: forwarded.continuation + )) + run.recognizerTask = reader + weak var owner = session + session = nil + // No suspension since reader creation: it must own the session even + // before its first actor turn, not only after upgrading a weak capture. + #expect(owner != nil) + let model = directory.appendingPathComponent("languageModel.bin") + #expect(FileManager.default.fileExists(atPath: model.path)) + results.continuation.finish() + await reader.value + await run.terminalTask?.value + #expect(owner == nil) + #expect(!FileManager.default.fileExists(atPath: directory.path)) + forwarded.continuation.finish() + } + + @Test( + "Production compiler cleans failed and rejected output", + arguments: ["failed", "clear", "cancelled", "replacement"] + ) + @MainActor + func productionRejectedOutputIsRemoved(reason: String) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let gate = VocabularyPreparationGate() + let compiler = rejectingCompiler(reason: reason, gate: gate) + let session = SpeechSession(locale: Locale(identifier: "en_US")) + session.customVocabularyCompiler = compiler + let task = Task { @MainActor in + try await session.configureCustomVocabulary(.init( + locale: Locale(identifier: "en_US"), identifier: "rejected", version: "1" + )) + } + do { + let location = try await awaitResult { await gate.directory() } + let directory = try #require(location) + try await applyRejection(reason, to: session, task: task) + let currentDirectory = session.customVocabularyOutputDirectory + await gate.release() + do { + try await task.value + Issue.record("Expected rejected compilation") + } catch { + if reason == "failed" { + guard let error = error as? SpeechSessionError, + case .customVocabularyCompilationFailed = error else { + Issue.record("Expected compilation failure, got \(error)") + return + } + } else { #expect(error is CancellationError) } + } + #expect(!FileManager.default.fileExists(atPath: directory.path)) + if reason == "replacement" { + let current = try #require(currentDirectory) + #expect(session.customVocabularyOutputDirectory == current) + let model = current.appendingPathComponent("languageModel.bin") + #expect(try Data(contentsOf: model) == Data("model".utf8)) + } else { + #expect(session.customVocabularyConfiguration == nil) + } + } catch { + task.cancel() + await gate.release() + _ = await task.result + try? await session.configureCustomVocabulary(nil) + throw error + } + try await session.configureCustomVocabulary(nil) + } + + @MainActor + @available(iOS 26.0, macOS 26.0, *) + private func rejectingCompiler( + reason: String, gate: VocabularyPreparationGate + ) -> CustomVocabularyCompiler { + return CustomVocabularyCompiler(prepareModel: { descriptor, asset, _ in + try Data("partial".utf8).write(to: asset) + let model = asset.deletingLastPathComponent().appendingPathComponent("languageModel.bin") + try Data("model".utf8).write(to: model) + if descriptor.identifier == "rejected" { + await gate.enter(asset.deletingLastPathComponent()) + if reason == "failed" { throw VocabularyCompilationTestError.failed } + } + }) + } + + @MainActor + @available(iOS 26.0, macOS 26.0, *) + private func applyRejection( + _ reason: String, to session: SpeechSession, task: Task + ) async throws { + if reason == "clear" { try await session.configureCustomVocabulary(nil) } + if reason == "cancelled" { task.cancel() } + if reason == "replacement" { + try await session.configureCustomVocabulary(.init( + locale: Locale(identifier: "en_US"), identifier: "current", version: "1" + )) + } + } +} diff --git a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift index 483373e..fe58dff 100644 --- a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift +++ b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift @@ -189,482 +189,11 @@ struct CustomVocabularyOwnershipTests { } } - @Test("Production allocation isolates equal descriptors across sessions", arguments: [false, true]) - @MainActor - func productionDirectoriesArePrivate(replace: Bool) async throws { - guard #available(iOS 26.0, macOS 26.0, *) else { return } - // Only Apple model work is substituted. The actual compiler allocates - // and transfers real Application Support directories for both sessions. - let compiler = CustomVocabularyCompiler(prepareModel: { _, asset, _ in - let directory = asset.deletingLastPathComponent() - try Data("model".utf8).write(to: directory.appendingPathComponent("languageModel.bin")) - try Data("vocabulary".utf8).write(to: directory.appendingPathComponent("vocabulary.bin")) - try Data("source".utf8).write(to: asset) - }) - let first = SpeechSession(locale: Locale(identifier: "en_US")) - let second = SpeechSession(locale: Locale(identifier: "en_US")) - first.customVocabularyCompiler = compiler - second.customVocabularyCompiler = compiler - let descriptor = SpeechSession.CustomVocabulary( - locale: Locale(identifier: "en_US"), identifier: "private-ownership", version: "1" - ) - do { - try await first.configureCustomVocabulary(descriptor) - try await second.configureCustomVocabulary(descriptor) - let firstDirectory = try #require(first.customVocabularyOutputDirectory) - let secondDirectory = try #require(second.customVocabularyOutputDirectory) - #expect(firstDirectory != secondDirectory) - #expect(first.customVocabularyCacheKey == second.customVocabularyCacheKey) - try await second.configureCustomVocabulary(descriptor) - #expect(second.customVocabularyOutputDirectory == secondDirectory) - if replace { - try await first.configureCustomVocabulary(.init( - locale: descriptor.locale, identifier: "replacement", version: "1" - )) - } else { - try await first.configureCustomVocabulary(nil) - } - #expect(!FileManager.default.fileExists(atPath: firstDirectory.path)) - let model = secondDirectory.appendingPathComponent("languageModel.bin") - let vocabulary = secondDirectory.appendingPathComponent("vocabulary.bin") - let source = secondDirectory.appendingPathComponent("source.bin") - #expect(try Data(contentsOf: model) == Data("model".utf8)) - #expect(try Data(contentsOf: vocabulary) == Data("vocabulary".utf8)) - #expect(!FileManager.default.fileExists(atPath: source.path)) - try await second.configureCustomVocabulary(nil) - #expect(!FileManager.default.fileExists(atPath: secondDirectory.path)) - } catch { - try? await first.configureCustomVocabulary(nil) - try? await second.configureCustomVocabulary(nil) - throw error - } - try await first.configureCustomVocabulary(nil) - } - - @Test("Releasing idle sessions retires only their own production output") - @MainActor - func idleSessionReleaseRetiresPrivateOutput() async throws { - guard #available(iOS 26.0, macOS 26.0, *) else { return } - let compiler = CustomVocabularyCompiler(prepareModel: { _, asset, _ in - let directory = asset.deletingLastPathComponent() - try Data("model".utf8).write(to: directory.appendingPathComponent("languageModel.bin")) - try Data("vocabulary".utf8).write(to: directory.appendingPathComponent("vocabulary.bin")) - try Data("source".utf8).write(to: asset) - }) - var first: SpeechSession? = SpeechSession(locale: Locale(identifier: "en_US")) - var second: SpeechSession? = SpeechSession(locale: Locale(identifier: "en_US")) - weak var firstOwner = first - weak var secondOwner = second - defer { first = nil; second = nil } - first?.customVocabularyCompiler = compiler - second?.customVocabularyCompiler = compiler - let descriptor = SpeechSession.CustomVocabulary( - locale: Locale(identifier: "en_US"), identifier: "idle-release-ownership", version: "1" - ) - try await first?.configureCustomVocabulary(descriptor) - try await second?.configureCustomVocabulary(descriptor) - let firstDirectory = try #require(first?.customVocabularyOutputDirectory) - let secondDirectory = try #require(second?.customVocabularyOutputDirectory) - let cacheKey = try #require(second?.customVocabularyCacheKey) - #expect(firstDirectory != secondDirectory) - #expect(first?.customVocabularyCacheKey == cacheKey) - - // No explicit clear, stop or direct filesystem cleanup retires either owner. - first = nil - #expect(firstOwner == nil) - #expect(!FileManager.default.fileExists(atPath: firstDirectory.path)) - try await second?.configureCustomVocabulary(descriptor) - #expect(second?.customVocabularyOutputDirectory == secondDirectory) - #expect(second?.customVocabularyCacheKey == cacheKey) - #expect(second?.customVocabularyConfiguration != nil) - let model = secondDirectory.appendingPathComponent("languageModel.bin") - let vocabulary = secondDirectory.appendingPathComponent("vocabulary.bin") - let source = secondDirectory.appendingPathComponent("source.bin") - #expect(try Data(contentsOf: model) == Data("model".utf8)) - #expect(try Data(contentsOf: vocabulary) == Data("vocabulary".utf8)) - #expect(!FileManager.default.fileExists(atPath: source.path)) - - second = nil - #expect(secondOwner == nil) - #expect(!FileManager.default.fileExists(atPath: secondDirectory.path)) - } - - @Test("A queued live result reader retains vocabulary through retirement") - @MainActor - func queuedReaderRetainsArtifactOwner() async throws { - guard #available(iOS 26.0, macOS 26.0, *) else { return } - var session: SpeechSession? = SpeechSession(locale: Locale(identifier: "en_US")) - session?.customVocabularyCompiler = CustomVocabularyCompiler(prepareModel: { _, asset, _ in - try Data("model".utf8).write( - to: asset.deletingLastPathComponent().appendingPathComponent("languageModel.bin") - ) - }) - try await session?.configureCustomVocabulary(.init( - locale: Locale(identifier: "en_US"), identifier: "queued-reader-ownership", version: "1" - )) - let directory = try #require(session?.customVocabularyOutputDirectory) - let run = LiveTranscriptionRun() - let results = AsyncStream.makeStream() - let forwarded = AsyncThrowingStream.makeStream() - // Exercise the production reader and terminal join without native Speech work. - session?.liveTranscription = run - let reader = try #require(session?.makeLiveRecognizerTask( - run: run, results: results.stream, streamContinuation: forwarded.continuation - )) - run.recognizerTask = reader - weak var owner = session - session = nil - // No suspension since reader creation: it must own the session even - // before its first actor turn, not only after upgrading a weak capture. - #expect(owner != nil) - let model = directory.appendingPathComponent("languageModel.bin") - #expect(FileManager.default.fileExists(atPath: model.path)) - results.continuation.finish() - await reader.value - await run.terminalTask?.value - #expect(owner == nil) - #expect(!FileManager.default.fileExists(atPath: directory.path)) - forwarded.continuation.finish() - } - - @Test("Production compiler cleans failed and rejected output", arguments: ["failed", "clear", "cancelled", "replacement"]) - @MainActor - func productionRejectedOutputIsRemoved(reason: String) async throws { - guard #available(iOS 26.0, macOS 26.0, *) else { return } - let gate = VocabularyPreparationGate() - let compiler = CustomVocabularyCompiler(prepareModel: { descriptor, asset, _ in - try Data("partial".utf8).write(to: asset) - let model = asset.deletingLastPathComponent().appendingPathComponent("languageModel.bin") - try Data("model".utf8).write(to: model) - if descriptor.identifier == "rejected" { - await gate.enter(asset.deletingLastPathComponent()) - if reason == "failed" { throw VocabularyCompilationTestError.failed } - } - }) - let session = SpeechSession(locale: Locale(identifier: "en_US")) - session.customVocabularyCompiler = compiler - let task = Task { @MainActor in - try await session.configureCustomVocabulary(.init( - locale: Locale(identifier: "en_US"), identifier: "rejected", version: "1" - )) - } - do { - let location = try await awaitResult { await gate.directory() } - let directory = try #require(location) - if reason == "clear" { try await session.configureCustomVocabulary(nil) } - if reason == "cancelled" { task.cancel() } - if reason == "replacement" { - try await session.configureCustomVocabulary(.init( - locale: Locale(identifier: "en_US"), identifier: "current", version: "1" - )) - } - let currentDirectory = session.customVocabularyOutputDirectory - await gate.release() - do { - try await task.value - Issue.record("Expected rejected compilation") - } catch { - if reason == "failed" { - guard let error = error as? SpeechSessionError, - case .customVocabularyCompilationFailed = error else { - Issue.record("Expected compilation failure, got \(error)") - return - } - } else { #expect(error is CancellationError) } - } - #expect(!FileManager.default.fileExists(atPath: directory.path)) - if reason == "replacement" { - let current = try #require(currentDirectory) - #expect(session.customVocabularyOutputDirectory == current) - let model = current.appendingPathComponent("languageModel.bin") - #expect(try Data(contentsOf: model) == Data("model".utf8)) - } else { - #expect(session.customVocabularyConfiguration == nil) - } - } catch { - task.cancel() - await gate.release() - _ = await task.result - try? await session.configureCustomVocabulary(nil) - throw error - } - try await session.configureCustomVocabulary(nil) - } - @MainActor @available(iOS 26.0, macOS 26.0, *) - private func withFixture(_ operation: @MainActor (VocabularyFixture) async throws -> Void) async throws { + func withFixture(_ operation: @MainActor (VocabularyFixture) async throws -> Void) async throws { let fixture = VocabularyFixture() - do { try await operation(fixture) } - catch { await fixture.cleanup(); throw error } + do { try await operation(fixture) } catch { await fixture.cleanup(); throw error } await fixture.cleanup() } } - -private enum VocabularyCompilationTestError: Error, Equatable { - case failed -} - -@available(iOS 26.0, macOS 26.0, *) -private actor GatedVocabularyCompiler: CustomVocabularyCompiling { - private let directory = FileManager.default.temporaryDirectory - .appendingPathComponent("vocabulary-ownership-\(UUID().uuidString)", isDirectory: true) - private var pending: [String: CheckedContinuation] = [:] - private(set) var callCount = 0 - private var releasedAll = false - - func compile(descriptor: SpeechSession.CustomVocabulary) async throws -> CustomVocabularyCompilation { - callCount += 1 - let key = try descriptor.stableCacheKey() - let output = directory.appendingPathComponent("\(key)-\(UUID().uuidString)", isDirectory: true) - try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) - if !releasedAll { - await withCheckedContinuation { pending[descriptor.identifier] = $0 } - } - if descriptor.identifier == "failed" { - try? FileManager.default.removeItem(at: output) - throw VocabularyCompilationTestError.failed - } - return CustomVocabularyCompilation( - configuration: SFSpeechLanguageModel.Configuration( - languageModel: output.appendingPathComponent("model"), - vocabulary: output.appendingPathComponent("vocabulary") - ), - cacheKey: key, - outputDirectory: output - ) - } - - func hasEntered(_ identifier: String) -> Bool { pending[identifier] != nil } - - func release(_ identifier: String) { pending.removeValue(forKey: identifier)?.resume() } - - func releaseAll() { - releasedAll = true - let continuations = Array(pending.values) - pending.removeAll() - continuations.forEach { $0.resume() } - } - - func cleanup() { try? FileManager.default.removeItem(at: directory) } -} - -@available(iOS 26.0, macOS 26.0, *) -@MainActor -private final class VocabularyFixture { - let session = SpeechSession(locale: Locale(identifier: "en_US")) - let compiler = GatedVocabularyCompiler() - var starts = 0 - var errors: [Error] = [] - var authorizationEntered = false - var authorizeOpen = false - private var authorization: CheckedContinuation? - private var tasks: [Task] = [] - - init() { - session.customVocabularyCompiler = compiler - session.liveTranscriptionHooks = LiveTranscriptionHooks( - authorize: { [unowned self] in - authorizationEntered = true - if !authorizeOpen { await withCheckedContinuation { authorization = $0 } } - }, - preparePipeline: { _, _ in }, - startAudio: { [unowned self] in starts += 1 } - ) - } - - func descriptor(_ identifier: String) -> SpeechSession.CustomVocabulary { - .init(locale: Locale(identifier: "en_US"), identifier: identifier, version: "1") - } - - func task(_ operation: @escaping @MainActor () async -> Void) -> Task { - let task = Task { @MainActor in await operation() } - tasks.append(task) - return task - } - - func configure(_ identifier: String) -> Task { - task { - do { try await self.session.configureCustomVocabulary(self.descriptor(identifier)) } - catch { self.errors.append(error) } - } - } - - func startVocabulary(_ identifier: String) -> Task { - task { - do { - let stream = try await self.session.startTranscribing(customVocabulary: self.descriptor(identifier)) - for try await _ in stream {} - } catch { self.errors.append(error) } - } - } - - func startPlainDictation() { - let stream = session.startDictationTranscribing() - _ = task { - do { for try await _ in stream {} } - catch { self.errors.append(error) } - } - } - - func expectIdleRejection(_ vocabulary: SpeechSession.CustomVocabulary?) async throws { - var completed = false - let operation = task { - do { - try await self.session.configureCustomVocabulary(vocabulary) - Issue.record("Expected customVocabularyRequiresIdleSession") - } catch SpeechSessionError.customVocabularyRequiresIdleSession { - // The admitted stream retains its configuration. - } catch { Issue.record("Unexpected error: \(error)") } - completed = true - } - try await waitUntil { completed } - await operation.value - } - - func expectStartupIdleRejection() async throws { - var completed = false - let operation = task { - do { - _ = try await self.session.startTranscribing(customVocabulary: self.descriptor("blocked")) - Issue.record("Expected customVocabularyRequiresIdleSession") - } catch SpeechSessionError.customVocabularyRequiresIdleSession { - // The async wrapper preserves the configuration API's error. - } catch { Issue.record("Unexpected error: \(error)") } - completed = true - } - try await waitUntil { completed } - await operation.value - } - - func waitForCompilation(_ identifier: String) async throws { - let deadline = ContinuousClock.now.advanced(by: .seconds(2)) - while !(await compiler.hasEntered(identifier)) { - guard ContinuousClock.now < deadline else { throw TestTimeoutError.timedOut(seconds: 2) } - await Task.yield() - } - } - - func waitUntil(_ predicate: @MainActor () -> Bool) async throws { - let deadline = ContinuousClock.now.advanced(by: .seconds(2)) - while !predicate() { - guard ContinuousClock.now < deadline else { throw TestTimeoutError.timedOut(seconds: 2) } - await Task.yield() - } - } - - func cleanup() async { - authorizeOpen = true - authorization?.resume() - authorization = nil - tasks.forEach { $0.cancel() } - await compiler.releaseAll() - await session.stopTranscribing() - for task in tasks { await task.value } - try? await session.configureCustomVocabulary(nil) - await compiler.cleanup() - session.liveTranscriptionHooks = nil - } -} - -@available(iOS 26.0, macOS 26.0, *) -private actor VocabularyPreparationGate { - private let locations = AsyncStream.makeStream() - private var pending: CheckedContinuation? - private var released = false - - func enter(_ directory: URL) async { - locations.continuation.yield(directory) - locations.continuation.finish() - if !released { await withCheckedContinuation { pending = $0 } } - } - - func directory() async -> URL? { - var iterator = locations.stream.makeAsyncIterator() - return await iterator.next() - } - - func release() { - released = true - pending?.resume() - pending = nil - } -} - -@Suite("Test timeout task ownership") -struct TestTimeoutOwnershipTests { - @Test("Timeout and caller cancellation join stream consumers and producers", arguments: [false, true]) - @MainActor - func cancellationJoinsActualTasks(cancelCaller: Bool) async throws { - let values = AsyncStream.makeStream() - let control = AsyncStream.makeStream() - let ready = AsyncStream.makeStream() - var producerJoined = false - var consumerJoined = false - let producer = Task { @MainActor in - defer { - values.continuation.finish() - producerJoined = true - } - for await _ in control.stream { values.continuation.yield(1) } - } - values.continuation.onTermination = { _ in producer.cancel() } - let consumer = Task { @MainActor in - defer { consumerJoined = true } - var iterator = values.stream.makeAsyncIterator() - ready.continuation.yield(()) - _ = await iterator.next() - } - try await withOwnedTasks([producer, consumer]) { - try await awaitResult { - var iterator = ready.stream.makeAsyncIterator() - _ = await iterator.next() - } - let wait = Task { @MainActor in - try await awaitResult(of: consumer, timeout: cancelCaller ? 60 : 0.01) - } - if cancelCaller { wait.cancel() } - do { - try await wait.value - Issue.record("Expected timeout or cancellation") - } catch { - if cancelCaller { #expect(error is CancellationError) } - else { - guard let timeout = error as? TestTimeoutError, - case .timedOut(seconds: 0.01) = timeout else { - Issue.record("Expected timeout, got \(error)") - return - } - } - } - #expect(consumerJoined) - try await awaitResult(of: producer) - } - #expect(producerJoined) - #expect(consumerJoined) - } - - @Test("Fixture tasks join on successful and throwing operations", arguments: [false, true]) - @MainActor - func fixtureCleanupJoins(throwsError: Bool) async throws { - let values = AsyncStream.makeStream() - var joined = false - let consumer = Task { @MainActor in - defer { joined = true } - var iterator = values.stream.makeAsyncIterator() - _ = await iterator.next() - } - do { - try await withOwnedTasks([consumer]) { - if throwsError { throw VocabularyCompilationTestError.failed } - values.continuation.yield(1) - try await awaitResult(of: consumer) - } - #expect(!throwsError) - } catch { - #expect(throwsError) - #expect(error as? VocabularyCompilationTestError == .failed) - } - #expect(joined) - } -} diff --git a/Tests/AuralKitTests/CustomVocabularyRecoveryTests.swift b/Tests/AuralKitTests/CustomVocabularyRecoveryTests.swift new file mode 100644 index 0000000..5048d7d --- /dev/null +++ b/Tests/AuralKitTests/CustomVocabularyRecoveryTests.swift @@ -0,0 +1,87 @@ +import Foundation +import Testing +@testable import AuralKit + +extension UpstreamCustomVocabularyOwnershipTests { + @Test("Already-cancelled configuration leaves the pending request intact") + func cancelledRequestDoesNotSupersede() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let preparation = VocabularyPreparation() + let session = session(preparation) + let pending = Task { @MainActor in + defer { preparation.ready.continuation.finish() } + try await session.configureCustomVocabulary(descriptor("blocked")) + } + var ready = preparation.ready.stream.makeAsyncIterator() + #expect(await ready.next() != nil) + let cancelled = Task { @MainActor in + try await session.configureCustomVocabulary(descriptor("replacement")) + } + cancelled.cancel() + let cancelledResult = await cancelled.result + preparation.release.continuation.finish() + let pendingResult = await pending.result + do { + try cancelledResult.get() + Issue.record("Expected cancellation") + } catch is CancellationError { } + try pendingResult.get() + #expect(session.customVocabularyDescriptor?.version == "blocked") + } + + @Test("Caller cancellation takes precedence over a joined compiler failure") + func cancellationAfterCompilerFailure() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let session = SpeechSession(locale: Locale(identifier: "en_US")) + let compiler = CancellingVocabularyCompiler() + session.customVocabularyCompiler = compiler + let start = AsyncStream.makeStream() + let request = Task { @MainActor in + for await _ in start.stream { break } + try await session.configureCustomVocabulary(descriptor()) + } + await compiler.cancelOnFailure(request) + start.continuation.finish() + do { + try await request.value + Issue.record("Expected cancellation") + } catch is CancellationError { } + #expect(session.customVocabularyConfiguration == nil) + } + + enum Reuse: Sendable, CaseIterable { case configure, dictation } + + @Test("Purged files are rebuilt before configuration reuse or dictation", arguments: Reuse.allCases) + func purgedFilesAreRebuilt(reuse: Reuse) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let preparation = VocabularyPreparation() + let session = session(preparation) + try await session.configureCustomVocabulary(descriptor()) + let purged = try #require(session.customVocabularyOutputDirectory) + try FileManager.default.removeItem(at: purged.appendingPathComponent("vocabulary.bin")) + switch reuse { + case .configure: + try await session.configureCustomVocabulary(descriptor()) + case .dictation: + _ = try await session.createDictationTranscriber() + } + let rebuilt = try #require(session.customVocabularyOutputDirectory) + #expect(await preparation.count == 2) + #expect(rebuilt != purged) + #expect(!FileManager.default.fileExists(atPath: purged.path)) + try assertFiles(in: rebuilt) + } +} + +@available(iOS 26.0, macOS 26.0, *) +private actor CancellingVocabularyCompiler: CustomVocabularyCompiling { + private var request: Task? + + func cancelOnFailure(_ request: Task) { self.request = request } + + func compile(descriptor: SpeechSession.CustomVocabulary) async throws -> CustomVocabularyCompilation { + request?.cancel() + request = nil + throw VocabularyPreparation.Failure.expected + } +} diff --git a/Tests/AuralKitTests/CustomVocabularyTestFixtures.swift b/Tests/AuralKitTests/CustomVocabularyTestFixtures.swift new file mode 100644 index 0000000..2c7dd7d --- /dev/null +++ b/Tests/AuralKitTests/CustomVocabularyTestFixtures.swift @@ -0,0 +1,196 @@ +import Foundation +import Speech +import Testing +@testable import AuralKit + +enum VocabularyCompilationTestError: Error, Equatable { + case failed +} + +@available(iOS 26.0, macOS 26.0, *) +actor GatedVocabularyCompiler: CustomVocabularyCompiling { + private let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("vocabulary-ownership-\(UUID().uuidString)", isDirectory: true) + private var pending: [String: CheckedContinuation] = [:] + private(set) var callCount = 0 + private var releasedAll = false + + func compile(descriptor: SpeechSession.CustomVocabulary) async throws -> CustomVocabularyCompilation { + callCount += 1 + let key = try descriptor.stableCacheKey() + let output = directory.appendingPathComponent("\(key)-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) + if !releasedAll { + await withCheckedContinuation { pending[descriptor.identifier] = $0 } + } + if descriptor.identifier == "failed" { + try? FileManager.default.removeItem(at: output) + throw VocabularyCompilationTestError.failed + } + let model = output.appendingPathComponent("model") + let vocabulary = output.appendingPathComponent("vocabulary") + try Data("model".utf8).write(to: model) + try Data("vocabulary".utf8).write(to: vocabulary) + return CustomVocabularyCompilation( + configuration: SFSpeechLanguageModel.Configuration(languageModel: model, vocabulary: vocabulary), + cacheKey: key, + outputDirectory: output, + artifacts: CustomVocabularyArtifacts(directory: output) + ) + } + + func hasEntered(_ identifier: String) -> Bool { pending[identifier] != nil } + + func release(_ identifier: String) { pending.removeValue(forKey: identifier)?.resume() } + + func releaseAll() { + releasedAll = true + let continuations = Array(pending.values) + pending.removeAll() + continuations.forEach { $0.resume() } + } + + func cleanup() { try? FileManager.default.removeItem(at: directory) } +} + +@available(iOS 26.0, macOS 26.0, *) +@MainActor +final class VocabularyFixture { + let session = SpeechSession(locale: Locale(identifier: "en_US")) + let compiler = GatedVocabularyCompiler() + var starts = 0 + var errors: [Error] = [] + var authorizationEntered = false + var authorizeOpen = false + private var authorization: CheckedContinuation? + private var tasks: [Task] = [] + + init() { + session.customVocabularyCompiler = compiler + session.liveTranscriptionHooks = LiveTranscriptionHooks( + authorize: { [unowned self] in + authorizationEntered = true + if !authorizeOpen { await withCheckedContinuation { authorization = $0 } } + }, + preparePipeline: { _, _ in }, + startAudio: { [unowned self] in starts += 1 } + ) + } + + func descriptor(_ identifier: String) -> SpeechSession.CustomVocabulary { + .init(locale: Locale(identifier: "en_US"), identifier: identifier, version: "1") + } + + func task(_ operation: @escaping @MainActor () async -> Void) -> Task { + let task = Task { @MainActor in await operation() } + tasks.append(task) + return task + } + + func configure(_ identifier: String) -> Task { + task { + do { + try await self.session.configureCustomVocabulary(self.descriptor(identifier)) + } catch { self.errors.append(error) } + } + } + + func startVocabulary(_ identifier: String) -> Task { + task { + do { + let stream = try await self.session.startTranscribing(customVocabulary: self.descriptor(identifier)) + for try await _ in stream {} + } catch { self.errors.append(error) } + } + } + + func startPlainDictation() { + let stream = session.startDictationTranscribing() + _ = task { + do { for try await _ in stream {} } catch { self.errors.append(error) } + } + } + + func expectIdleRejection(_ vocabulary: SpeechSession.CustomVocabulary?) async throws { + var completed = false + let operation = task { + do { + try await self.session.configureCustomVocabulary(vocabulary) + Issue.record("Expected customVocabularyRequiresIdleSession") + } catch SpeechSessionError.customVocabularyRequiresIdleSession { + // The admitted stream retains its configuration. + } catch { Issue.record("Unexpected error: \(error)") } + completed = true + } + try await waitUntil { completed } + await operation.value + } + + func expectStartupIdleRejection() async throws { + var completed = false + let operation = task { + do { + _ = try await self.session.startTranscribing(customVocabulary: self.descriptor("blocked")) + Issue.record("Expected customVocabularyRequiresIdleSession") + } catch SpeechSessionError.customVocabularyRequiresIdleSession { + // The async wrapper preserves the configuration API's error. + } catch { Issue.record("Unexpected error: \(error)") } + completed = true + } + try await waitUntil { completed } + await operation.value + } + + func waitForCompilation(_ identifier: String) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(2)) + while !(await compiler.hasEntered(identifier)) { + guard ContinuousClock.now < deadline else { throw TestTimeoutError.timedOut(seconds: 2) } + await Task.yield() + } + } + + func waitUntil(_ predicate: @MainActor () -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(2)) + while !predicate() { + guard ContinuousClock.now < deadline else { throw TestTimeoutError.timedOut(seconds: 2) } + await Task.yield() + } + } + + func cleanup() async { + authorizeOpen = true + authorization?.resume() + authorization = nil + tasks.forEach { $0.cancel() } + await compiler.releaseAll() + await session.stopTranscribing() + for task in tasks { await task.value } + try? await session.configureCustomVocabulary(nil) + await compiler.cleanup() + session.liveTranscriptionHooks = nil + } +} + +@available(iOS 26.0, macOS 26.0, *) +actor VocabularyPreparationGate { + private let locations = AsyncStream.makeStream() + private var pending: CheckedContinuation? + private var released = false + + func enter(_ directory: URL) async { + locations.continuation.yield(directory) + locations.continuation.finish() + if !released { await withCheckedContinuation { pending = $0 } } + } + + func directory() async -> URL? { + var iterator = locations.stream.makeAsyncIterator() + return await iterator.next() + } + + func release() { + released = true + pending?.resume() + pending = nil + } +} diff --git a/Tests/AuralKitTests/FileProgressTests.swift b/Tests/AuralKitTests/FileProgressTests.swift new file mode 100644 index 0000000..6ee4610 --- /dev/null +++ b/Tests/AuralKitTests/FileProgressTests.swift @@ -0,0 +1,48 @@ +import Speech +import Testing +@testable import AuralKit + +@Suite("File transcription progress") +struct FileProgressTests { + @Test("Progress stops with its file session", arguments: ["stopping", "stopped", "replacement", "cancelled"]) + @MainActor + func progressStopsWithItsFileSession(termination: String) async { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let session = SpeechSession() + let run = FileTranscriptionRun() + session.fileTranscription = run + let (_, continuation) = AsyncThrowingStream.makeStream() + session.continuation = .speech(continuation) + session.streamingMode = .filePlayback + session.setStatus(.transcribing) + + let (progress, progressContinuation) = AsyncStream.makeStream() + let handler: @Sendable (Double) -> Void = { progressContinuation.yield($0) } + session.reportFileProgress(0.25, handler: handler, run: run) + + switch termination { + case "stopping": + session.prepareForStop() + case "stopped": + await session.cancelTranscribing() + case "replacement": + session.fileTranscription = FileTranscriptionRun() + default: + break + } + + let delivery = Task { + if termination == "cancelled" { + withUnsafeCurrentTask { $0?.cancel() } + } + session.reportFileProgress(0.5, handler: handler, run: run) + session.reportFileProgress(1.0, handler: handler, run: run) + } + await delivery.value + progressContinuation.finish() + var received: [Double] = [] + for await value in progress { received.append(value) } + #expect(received == [0.25]) + await session.cancelTranscribing() + } +} diff --git a/Tests/AuralKitTests/FileTranscriptionFinalizationTests.swift b/Tests/AuralKitTests/FileTranscriptionFinalizationTests.swift index b1d01b2..1a4c22f 100644 --- a/Tests/AuralKitTests/FileTranscriptionFinalizationTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionFinalizationTests.swift @@ -1,5 +1,6 @@ import Testing import AVFoundation +import Speech @testable import AuralKit extension FileTranscriptionTests { @@ -25,9 +26,9 @@ extension FileTranscriptionTests { } } - @Test("independent results cancellation fails the public stream, joins ingestion and permits retry") + @Test("independent results cancellation fails, joins ingestion and permits retry", arguments: [false, true]) @MainActor - func independentFileResultsCancellationRetires() async throws { + func independentFileResultsCancellationRetires(throwsCancellation: Bool) async throws { guard #available(iOS 26.0, macOS 26.0, *) else { return } try await withFileLifecycleFixture { fixture in let ingestion = fixture.gate() @@ -46,7 +47,11 @@ extension FileTranscriptionTests { let consumer = fixture.transcribe() try await fixture.waitUntil { ingestion.entered } let run = try #require(fixture.session.fileTranscription) - analyzerResults.continuation.finish(throwing: CancellationError()) + if throwsCancellation { + analyzerResults.continuation.finish(throwing: CancellationError()) + } else { + run.recognizerTask?.cancel() + } try await fixture.waitUntil { run.retired } #expect(fixture.session.fileTranscription === run) ingestion.open() @@ -205,3 +210,86 @@ extension FileTranscriptionTests { } } + +extension FileTranscriptionTests { + @Test("A physical short read fails before closing analyzer input") + @MainActor + func physicalShortReadDoesNotSignalSuccessfulEOF() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + try await withFileLifecycleFixture { fixture in + let file = try AVAudioFile(forReading: fixture.audioURL) + let format = try #require(AVAudioFormat( + commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true + )) + let declaredFrames = file.length + 1 + let inputs = AsyncStream.makeStream() + defer { inputs.continuation.finish() } + let run = FileTranscriptionRun() + fixture.session.fileTranscription = run + fixture.session.inputBuilder = inputs.continuation + fixture.session.analyzerFormat = format + do { + _ = try await fixture.session.feedAudioFile( + (file: file, totalFrames: declaredFrames), run: run, + progressHandler: { _ in } + ) + Issue.record("A premature physical EOF must report audioFileReadFailed") + } catch SpeechSessionError.audioFileReadFailed { } + let probe = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 1)) + probe.frameLength = 1 + if case .terminated = inputs.continuation.yield(AnalyzerInput(buffer: probe)) { + Issue.record("The feeder signaled input EOF before its read failure was admitted") + } + } + } + + @Test("Early result EOF cannot hide a later ingestion or finalization failure", arguments: [false, true]) + @MainActor + func earlyResultEOFPreservesProducerFailure(finalization: Bool) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + try await withFileLifecycleFixture { fixture in + let failure = fixture.gate() + let results = AsyncThrowingStream.makeStream() + let forwarded = AsyncThrowingStream.makeStream() + fixture.session.fileTranscriptionHooks = FileTranscriptionHooks( + authorize: {}, + preparePipeline: { run in + run.recognizerTask = fixture.session.makeFileRecognizerTask( + run: run, results: results.stream, + streamContinuation: forwarded.continuation + ) + }, + ingest: { + if !finalization { + await failure.wait() + throw FileLifecycleProbeError.ingestion + } + return true + }, + finalizeInput: { + guard finalization else { + Issue.record("A failed ingester must not finalize input") + return + } + await failure.wait() + throw FileLifecycleProbeError.finalization + } + ) + let consumer = fixture.consume() + try await fixture.waitUntil { failure.entered } + let run = try #require(fixture.session.fileTranscription) + results.continuation.finish() + await run.recognizerTask?.value + #expect(!run.retired) + #expect(fixture.session.fileTranscription === run) + failure.open() + await consumer.value + forwarded.continuation.finish() + #expect(fixture.errors.count == 1) + #expect(fixture.errors.first as? FileLifecycleProbeError == + (finalization ? .finalization : .ingestion)) + #expect(fixture.session.fileTranscription == nil) + #expect(fixture.session.status == .idle) + } + } +} diff --git a/Tests/AuralKitTests/FileTranscriptionJoinTests.swift b/Tests/AuralKitTests/FileTranscriptionJoinTests.swift index 37b913b..4152031 100644 --- a/Tests/AuralKitTests/FileTranscriptionJoinTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionJoinTests.swift @@ -91,7 +91,7 @@ extension FileTranscriptionTests { preparePipeline: { run in run.recognizerTask = Task { @MainActor in await results.wait() - fixture.session.retireFileTranscription(run, error: nil) + fixture.session.completeFileResults(run) } }, ingest: { diff --git a/Tests/AuralKitTests/FileTranscriptionTestFixtures.swift b/Tests/AuralKitTests/FileTranscriptionTestFixtures.swift new file mode 100644 index 0000000..838381b --- /dev/null +++ b/Tests/AuralKitTests/FileTranscriptionTestFixtures.swift @@ -0,0 +1,99 @@ +import Foundation +import Testing +@testable import AuralKit + +enum FileLifecycleProbeError: Error, Equatable { case ingestion, finalization, arrivalTimeout } + +@available(iOS 26.0, macOS 26.0, *) +@MainActor +final class FileLifecycleGate { + private(set) var entered = false + private var isOpen = false + private var releases: [CheckedContinuation] = [] + + func wait() async { + entered = true + guard !isOpen else { return } + await withCheckedContinuation { releases.append($0) } + } + + func open() { + isOpen = true + let continuations = releases + releases.removeAll() + for continuation in continuations { continuation.resume() } + } +} + +@available(iOS 26.0, macOS 26.0, *) +@MainActor +final class FileLifecycleFixture { + let session = SpeechSession() + let audioURL: URL + var errors: [Error] = [] + var ingestionReturned = false + private var gates: [FileLifecycleGate] = [] + private var tasks: [Task] = [] + + init(audioURL: URL) { self.audioURL = audioURL } + + func gate() -> FileLifecycleGate { + let gate = FileLifecycleGate() + gates.append(gate) + return gate + } + + func task(_ operation: @escaping @MainActor () async -> Void) -> Task { + let task = Task { @MainActor in await operation() } + tasks.append(task) + return task + } + + func consume() -> Task { + // Admit synchronously so tests can immediately inspect the actual run. + let stream = session.streamTranscription(from: audioURL) + return task { + do { + for try await _ in stream {} + } catch { + self.errors.append(error) + } + } + } + + func transcribe() -> Task { + task { + do { + _ = try await self.session.transcribe(audioFile: self.audioURL) + } catch { + self.errors.append(error) + } + } + } + + func waitUntil(_ predicate: @MainActor () -> Bool) async throws { + let deadline = ContinuousClock.now + .seconds(5) + while !predicate() { + guard ContinuousClock.now < deadline else { throw FileLifecycleProbeError.arrivalTimeout } + try await Task.sleep(for: .milliseconds(1)) + } + } + + func expectSuccessfulRetirement(_ run: FileTranscriptionRun) { + #expect(errors.isEmpty) + #expect(session.fileTranscription == nil) + #expect(session.status == .idle) + #expect(run.ingestionTask == nil) + #expect(run.recognizerTask == nil) + } + + func cleanup() async { + // Open-before-stop also covers late task admission after a failed wait. + for gate in gates { gate.open() } + await session.stopTranscribing() + for task in tasks { await task.value } + session.fileTranscriptionHooks = nil + tasks.removeAll() + try? FileManager.default.removeItem(at: audioURL) + } +} diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 904427c..e9aab03 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -1,5 +1,6 @@ import Testing import AVFoundation +import Speech @testable import AuralKit @Suite("File transcription") @@ -90,6 +91,106 @@ struct FileTranscriptionTests { } } +#if swift(>=6.4) + @Test("Cancelling a media analyzer before it receives input closes the session", arguments: [false, true]) + @MainActor + func cancelBeforeAnalyzerInputClosesSession(analyzing: Bool) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let session = SpeechSession() + let run = FileTranscriptionRun() + session.fileTranscription = run + let (results, continuation) = AsyncThrowingStream.makeStream() + let analyzer = SpeechAnalyzer(modules: []) + session.analyzer = analyzer + session.continuation = .speech(continuation) + session.streamingMode = .mediaPlayback + session.setStatus(.preparing) + + let (input, inputBuilder) = AsyncStream.makeStream() + defer { inputBuilder.finish() } + if analyzing { + let ready = AsyncStream.makeStream() + session.startFileIngestion(run: run) { _ in + ready.continuation.finish() + _ = try await analyzer.analyzeSequence(input) + } + for await _ in ready.stream {} + } + + let watchdog = Task { + do { + try await Task.sleep(for: .seconds(3)) + Issue.record("Cancelling an analyzer with no input did not return") + await analyzer.cancelAndFinishNow() + } catch is CancellationError { + // Cancel completed before the deadline. + } + } + await session.cancelTranscribing() + watchdog.cancel() + try await watchdog.value + + await #expect(throws: CancellationError.self) { + for try await _ in results {} + } + #expect(session.status == .idle) + } + + @Test("A cancelled recognizer cannot hide a file read error") + @MainActor + func fileReadErrorSurvivesRecognizerCancellation() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let session = SpeechSession() + let output = AsyncThrowingStream.makeStream() + let transcriber = SpeechTranscriber(locale: Locale(identifier: "en-US"), preset: .transcription) + session.analyzer = SpeechAnalyzer(modules: [transcriber]) + let run = FileTranscriptionRun() + session.fileTranscription = run + session.continuation = .speech(output.continuation) + session.streamingMode = .mediaPlayback + session.setStatus(.transcribing) + let recognizer = session.makeFileRecognizerTask( + run: run, results: transcriber.results, streamContinuation: output.continuation + ) + run.recognizerTask = recognizer + session.recognizerTask = recognizer + session.startFileIngestion(run: run) { _ in + throw SpeechSessionError.audioFileReadFailed(nil) + } + let ingestion = try #require(run.ingestionTask) + + await recognizer.value + await ingestion.value + await run.terminalTask?.value + var iterator = output.stream.makeAsyncIterator() + do { + _ = try await iterator.next() + Issue.record("Expected the file read error to reach the transcription stream") + } catch SpeechSessionError.audioFileReadFailed { } + #expect(session.status == .idle) + } + + @Test("Media transcription rejects an unknown audio track without falling back") + @MainActor + func mediaTranscriptionRejectsUnknownTrack() async throws { + guard #available(iOS 27.0, macOS 27.0, *) else { return } + let url = try createSilenceAudioFile(duration: 2.0) + defer { try? FileManager.default.removeItem(at: url) } + let asset = AVURLAsset(url: url) + let tracks = try await asset.loadTracks(withMediaType: .audio) + let track = try #require(tracks.first) + let session = SpeechSession() + + let stream = session.streamTranscription(fromMediaFile: url, audioTrackID: track.trackID + 1) + do { + for try await _ in stream { } + Issue.record("Expected the unknown track to be rejected") + } catch SpeechSessionError.audioFileUnsupportedFormat(let reason) { + #expect(reason.contains("\(track.trackID + 1)")) + } + } +#endif + private func createSilenceAudioFile(duration: TimeInterval, sampleRate: Double = 44_100) throws -> URL { let tempURL = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString) @@ -155,102 +256,6 @@ struct FileTranscriptionTests { } } -enum FileLifecycleProbeError: Error, Equatable { case ingestion, finalization, arrivalTimeout } - -@available(iOS 26.0, macOS 26.0, *) -@MainActor -final class FileLifecycleGate { - private(set) var entered = false - private var isOpen = false - private var releases: [CheckedContinuation] = [] - - func wait() async { - entered = true - guard !isOpen else { return } - await withCheckedContinuation { releases.append($0) } - } - - func open() { - isOpen = true - let continuations = releases - releases.removeAll() - for continuation in continuations { continuation.resume() } - } -} - -@available(iOS 26.0, macOS 26.0, *) -@MainActor -final class FileLifecycleFixture { - let session = SpeechSession() - let audioURL: URL - var errors: [Error] = [] - var ingestionReturned = false - private var gates: [FileLifecycleGate] = [] - private var tasks: [Task] = [] - - init(audioURL: URL) { self.audioURL = audioURL } - - func gate() -> FileLifecycleGate { - let gate = FileLifecycleGate() - gates.append(gate) - return gate - } - - func task(_ operation: @escaping @MainActor () async -> Void) -> Task { - let task = Task { @MainActor in await operation() } - tasks.append(task) - return task - } - - func consume() -> Task { - // Admit synchronously so tests can immediately inspect the actual run. - let stream = session.streamTranscription(from: audioURL) - return task { - do { - for try await _ in stream {} - } catch { - self.errors.append(error) - } - } - } - - func transcribe() -> Task { - task { - do { - _ = try await self.session.transcribe(audioFile: self.audioURL) - } catch { - self.errors.append(error) - } - } - } - - func waitUntil(_ predicate: @MainActor () -> Bool) async throws { - let deadline = ContinuousClock.now + .seconds(5) - while !predicate() { - guard ContinuousClock.now < deadline else { throw FileLifecycleProbeError.arrivalTimeout } - try await Task.sleep(for: .milliseconds(1)) - } - } - - func expectSuccessfulRetirement(_ run: FileTranscriptionRun) { - #expect(errors.isEmpty) - #expect(session.fileTranscription == nil) - #expect(session.status == .idle) - #expect(run.ingestionTask == nil) - #expect(run.recognizerTask == nil) - } - - func cleanup() async { - // Open-before-stop also covers late task admission after a failed wait. - for gate in gates { gate.open() } - await session.stopTranscribing() - for task in tasks { await task.value } - session.fileTranscriptionHooks = nil - tasks.removeAll() - try? FileManager.default.removeItem(at: audioURL) - } -} - extension FileTranscriptionTests { @Test("independent file setup cancellation fails and permits retry", arguments: [false, true]) @MainActor diff --git a/Tests/AuralKitTests/LiveInputSettlementTests.swift b/Tests/AuralKitTests/LiveInputSettlementTests.swift new file mode 100644 index 0000000..71108d8 --- /dev/null +++ b/Tests/AuralKitTests/LiveInputSettlementTests.swift @@ -0,0 +1,143 @@ +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("Live input settlement") +@MainActor +struct LiveInputSettlementTests { + @Test("Native result EOF waits for input finalization", arguments: [false, true]) + func resultsWaitForInput(fails: Bool) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + try await withSession { runtime, fixture in + let release = fixture.gate() + let results = AsyncThrowingStream.makeStream() + let forwarded = AsyncThrowingStream.makeStream() + defer { forwarded.continuation.finish() } + runtime.run.usesNativeInput = true + let reader = fixture.track(runtime.session.makeLiveRecognizerTask( + run: runtime.run, results: results.stream, streamContinuation: forwarded.continuation + )) + runtime.run.recognizerTask = reader + runtime.session.recognizerTask = reader + runtime.run.inputTask = fixture.track(Task { @MainActor in + do { + try await release.wait() + if fails { throw SpeechSessionError.invalidAudioDataType } + try runtime.session.requireCurrentLiveTranscription(runtime.run) + runtime.session.completeLiveInput(runtime.run) + } catch { + runtime.session.retireLiveTranscription(runtime.run, error: error) + } + }) + results.continuation.finish() + await reader.value + #expect(!runtime.run.retired) + #expect(runtime.session.continuation != nil) + release.open() + if fails { + await #expect(throws: SpeechSessionError.self) { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + } + } else { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + } + #expect(runtime.session.liveTranscription == nil) + #expect(runtime.session.status == .idle) + } + } + + @Test("Native input completion waits for the final result drain") + func inputWaitsForResults() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + try await withSession { runtime, fixture in + let results = AsyncThrowingStream.makeStream() + let forwarded = AsyncThrowingStream.makeStream() + defer { forwarded.continuation.finish() } + runtime.run.usesNativeInput = true + let reader = fixture.track(runtime.session.makeLiveRecognizerTask( + run: runtime.run, results: results.stream, streamContinuation: forwarded.continuation + )) + runtime.run.recognizerTask = reader + runtime.session.recognizerTask = reader + runtime.session.completeLiveInput(runtime.run) + #expect(!runtime.run.retired) + #expect(runtime.session.continuation != nil) + results.continuation.finish() + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + await reader.value + #expect(runtime.session.liveTranscription == nil) + } + } + + @Test("Self-cancelled result EOF settles as cancellation") + func selfCancelledResultEOF() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + try await withSession { runtime, fixture in + let forwarded = AsyncThrowingStream.makeStream() + defer { forwarded.continuation.finish() } + let reader = fixture.track(runtime.session.makeLiveRecognizerTask( + run: runtime.run, results: SelfCancelledLiveResults(), + streamContinuation: forwarded.continuation + )) + runtime.run.recognizerTask = reader + runtime.session.recognizerTask = reader + await #expect(throws: CancellationError.self) { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + } + await reader.value + #expect(runtime.session.liveTranscription == nil) + } + } + + @available(iOS 26.0, macOS 26.0, *) + @MainActor + private struct Runtime { + let session = SpeechSession() + let run = LiveTranscriptionRun() + let results: AsyncThrowingStream + init() { + let output = AsyncThrowingStream.makeStream() + results = output.stream + session.liveTranscription = run + session.continuation = .speech(output.continuation) + session.streamingMode = .liveMicrophone + session.setStatus(.transcribing) + } + } + + @available(iOS 26.0, macOS 26.0, *) + private func withSession(_ body: (Runtime, CaptureFixture) async throws -> Void) async throws { + try await withCaptureFixture { fixture in + let runtime = Runtime() + do { + try await body(runtime, fixture) + } catch { + fixture.releaseAll() + await runtime.session.stopTranscribing() + throw error + } + fixture.releaseAll() + await runtime.session.stopTranscribing() + } + } +} + +private struct SelfCancelledLiveResults: AsyncSequence, Sendable { + typealias Element = Int + struct AsyncIterator: AsyncIteratorProtocol { + mutating func next() async -> Int? { + withUnsafeCurrentTask { $0?.cancel() } + return nil + } + } + func makeAsyncIterator() -> AsyncIterator { AsyncIterator() } +} diff --git a/Tests/AuralKitTests/LiveTranscriptionTests.swift b/Tests/AuralKitTests/LiveTranscriptionTests.swift index 76c2fe8..86069b8 100644 --- a/Tests/AuralKitTests/LiveTranscriptionTests.swift +++ b/Tests/AuralKitTests/LiveTranscriptionTests.swift @@ -190,8 +190,7 @@ struct LiveTranscriptionTests { let results = try #require(fixture.resultContinuations.last) results.yield("one") try await fixture.waitUntil { fixture.values == ["one"] } - if cancelled { results.finish(throwing: CancellationError()) } - else { results.finish() } + if cancelled { results.finish(throwing: CancellationError()) } else { results.finish() } try await fixture.waitUntil { fixture.session.liveTranscription == nil } await fixture.publicConsumers.last?.value #expect(fixture.session.status == .idle) @@ -205,8 +204,7 @@ struct LiveTranscriptionTests { @available(iOS 26.0, macOS 26.0, *) private func withFixture(_ operation: @MainActor (LiveFixture) async throws -> Void) async throws { let fixture = LiveFixture() - do { try await operation(fixture) } - catch { await fixture.cleanup(); throw error } + do { try await operation(fixture) } catch { await fixture.cleanup(); throw error } await fixture.cleanup() } } @@ -331,8 +329,7 @@ private final class LiveFixture { run: run, results: results, streamContinuation: continuation ) _ = task { - do { for try await value in output { self.values.append(value) } } - catch {} + do { for try await value in output { self.values.append(value) } } catch {} } }, startAudio: { [unowned self] in starts += 1 } @@ -344,14 +341,12 @@ private final class LiveFixture { if dictation { let stream = session.startDictationTranscribing() consumer = task { - do { for try await _ in stream {} } - catch { self.errors.append(error) } + do { for try await _ in stream {} } catch { self.errors.append(error) } } } else { let stream = session.startTranscribing() consumer = task { - do { for try await _ in stream {} } - catch { self.errors.append(error) } + do { for try await _ in stream {} } catch { self.errors.append(error) } } } publicConsumers.append(consumer) diff --git a/Tests/AuralKitTests/MicrophoneAudioIngressTests.swift b/Tests/AuralKitTests/MicrophoneAudioIngressTests.swift new file mode 100644 index 0000000..e5efff7 --- /dev/null +++ b/Tests/AuralKitTests/MicrophoneAudioIngressTests.swift @@ -0,0 +1,105 @@ +import AVFoundation +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("Microphone input ownership") +@MainActor +struct MicrophoneAudioIngressTests { + @Test("Borrowed tap buffers retain their samples and order after reuse") + func borrowedBuffersAreCopied() throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) + let output = PCMOutputProbe() + let ingress = MicrophoneAudioIngress( + format: format, deliver: { output.append($0) }, onError: { output.fail($0) } + ) + defer { ingress.close() } + let buffer = try pcm(format: format, frames: 160, value: 0.25) + ingress.receive(buffer) + buffer.floatChannelData?.pointee.initialize(repeating: 0.5, count: 160) + ingress.receive(buffer) + buffer.floatChannelData?.pointee.initialize(repeating: -1, count: 160) + #expect(output.values == [0.25, 0.5]) + #expect(!output.hasErrors) + ingress.close() + ingress.receive(buffer) + #expect(output.values == [0.25, 0.5]) + } + + @Test("Conversion delivers the captured analyzer format", arguments: [44_100.0, 48_000.0]) + func convertsNativePCM(rate: Double) throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let source = try #require(AVAudioFormat(standardFormatWithSampleRate: rate, channels: 1)) + let target = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) + let output = PCMOutputProbe() + let ingress = MicrophoneAudioIngress( + format: target, deliver: { output.append($0) }, onError: { output.fail($0) } + ) + defer { ingress.close() } + ingress.receive(try pcm(format: source, frames: 4_096, value: 0.25)) + let delivered = try #require(output.buffers.first) + #expect(output.buffers.count == 1) + #expect(delivered.format == target) + #expect(delivered.frameLength > 0) + #expect(!output.hasErrors) + } + + @Test("Public Finish drains admitted input and closes its producer") + func finishDrainsAcceptedPCM() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let session = SpeechSession() + let run = LiveTranscriptionRun() + let inputs = AsyncStream.makeStream() + let results = AsyncThrowingStream.makeStream() + let format = try #require(AVAudioFormat( + commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true + )) + let ingress = MicrophoneAudioIngress( + format: format, deliver: { inputs.continuation.yield(AnalyzerInput(buffer: $0)) }, + onError: { _ in Issue.record("Unexpected microphone conversion failure") } + ) + session.liveTranscription = run + run.microphoneInput = ingress + session.inputBuilder = inputs.continuation + session.continuation = .speech(results.continuation) + session.streamingMode = .liveMicrophone + session.setStatus(.transcribing) + var received = 0 + run.recognizerTask = Task { @MainActor in + for await _ in inputs.stream { received += 1 } + session.retireLiveTranscription(run, error: nil) + } + session.recognizerTask = run.recognizerTask + let buffer = try pcm(format: format, frames: 160, value: 0.25) + ingress.receive(buffer) + await session.finishTranscribing() + var iterator = results.stream.makeAsyncIterator() + #expect(try await iterator.next() == nil) + #expect(received == 1) + #expect(session.liveTranscription == nil) + ingress.receive(buffer) + #expect(received == 1) + } + + private func pcm(format: AVAudioFormat, frames: AVAudioFrameCount, value: Float) throws -> AVAudioPCMBuffer { + let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frames)) + buffer.frameLength = frames + buffer.floatChannelData?.pointee.initialize(repeating: value, count: Int(frames)) + buffer.int16ChannelData?.pointee.initialize(repeating: Int16(value * 32_767), count: Int(frames)) + return buffer + } +} + +private final class PCMOutputProbe: @unchecked Sendable { + private let lock = NSLock() + private var storage: [AVAudioPCMBuffer] = [] + private var errors: [Error] = [] + + func append(_ buffer: AVAudioPCMBuffer) { lock.withLock { storage.append(buffer) } } + func fail(_ error: Error) { lock.withLock { errors.append(error) } } + var buffers: [AVAudioPCMBuffer] { lock.withLock { storage } } + var values: [Float] { lock.withLock { storage.map { $0.floatChannelData?.pointee[0] ?? .nan } } } + var hasErrors: Bool { lock.withLock { !errors.isEmpty } } +} diff --git a/Tests/AuralKitTests/ScreenCaptureAudioTests.swift b/Tests/AuralKitTests/ScreenCaptureAudioTests.swift new file mode 100644 index 0000000..13ab949 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureAudioTests.swift @@ -0,0 +1,90 @@ +#if compiler(>=6.4) +import AVFoundation +import CoreMedia +import Speech +import Testing +@testable import AuralKit + +struct ScreenCaptureAudioTests { + @Test(arguments: [true, false]) + func conversionKeepsOneTimelineAcrossCaptureStreams(drain: Bool) async throws { + guard #available(iOS 27.0, macOS 27.0, *) else { return } + let target = try #require(AVAudioFormat( + commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true + )) + let source = try #require(AVAudioFormat( + commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 2, interleaved: true + )) + let (inputs, continuation) = AsyncStream.makeStream() + let processor = ScreenCaptureAudioProcessor( + targetFormat: target, useNativeConversion: true, input: continuation + ) { + Issue.record("Screen audio failed: \($0)") + } + let firstStream = NSObject(), secondStream = NSObject() + let first = ObjectIdentifier(firstStream) + let second = ObjectIdentifier(secondStream) + let convertible = try makeSample(format: source, frames: 3072, timestamp: 123) + let compatible = try makeSample(format: target, frames: 160, timestamp: 1) + + processor.start(first) + processor.queue.sync { processor.receive(convertible, from: first) } + if drain { + #expect(processor.drain(first) == nil) + } else { + processor.discard(first) + } + // Restart the same native stream, as when resuming from pause. + processor.queue.sync { processor.receive(compatible, from: first) } + processor.start(first) + processor.queue.sync { processor.receive(compatible, from: first) } + #expect(processor.drain(first) == nil) + processor.start(second) + processor.queue.sync { + processor.receive(compatible, from: first) + processor.receive(compatible, from: second) + } + #expect(processor.drain(second) == nil) + processor.queue.sync { processor.receive(compatible, from: second) } + continuation.finish() + + var nextTime = CMTime.zero + var durations: [CMTime] = [] + for await input in inputs { + #expect(input.bufferFormat == target) + #expect(input.bufferStartTime == nextTime) + nextTime = CMTimeAdd(nextTime, input.bufferDuration) + durations.append(input.bufferDuration) + } + let directDuration = CMTime(value: 160, timescale: 16_000) + #expect(durations.suffix(2).elementsEqual([directDuration, directDuration])) + let drainedEnd = CMTime(value: 1344, timescale: 16_000) + #expect(drain ? nextTime == drainedEnd : nextTime < drainedEnd) + withExtendedLifetime((firstStream, secondStream)) {} + } + + @available(iOS 27.0, macOS 27.0, *) + private func makeSample(format: AVAudioFormat, frames: Int, timestamp: Int64) throws -> CMSampleBuffer { + let byteCount = frames * Int(format.streamDescription.pointee.mBytesPerFrame) + var data: CMBlockBuffer? + let status = CMBlockBufferCreateWithMemoryBlock( + allocator: kCFAllocatorDefault, memoryBlock: nil, blockLength: byteCount, + blockAllocator: kCFAllocatorDefault, customBlockSource: nil, offsetToData: 0, + dataLength: byteCount, flags: kCMBlockBufferAssureMemoryNowFlag, blockBufferOut: &data + ) + #expect(status == noErr) + let block = try #require(data) + #expect(CMBlockBufferFillDataBytes(with: 0, blockBuffer: block, offsetIntoDestination: 0, dataLength: byteCount) + == noErr) + return try CMSampleBuffer( + dataBuffer: block, formatDescription: format.formatDescription, numSamples: frames, + sampleTimings: [CMSampleTimingInfo( + duration: CMTime(value: 1, timescale: CMTimeScale(format.sampleRate)), + presentationTimeStamp: CMTime(value: timestamp, timescale: 1), + decodeTimeStamp: .invalid + )], + sampleSizes: [Int(format.streamDescription.pointee.mBytesPerFrame)] + ) + } +} +#endif diff --git a/Tests/AuralKitTests/ScreenCaptureFinishTests.swift b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift new file mode 100644 index 0000000..df70330 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift @@ -0,0 +1,240 @@ +#if canImport(ScreenCaptureKit) +import AVFoundation +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("Finishing screen transcription") +struct ScreenCaptureFinishTests { + @Test("Finish drains screen input unless Cancel supersedes it", arguments: [false, true]) + @MainActor + func finishDrainsScreenSource(cancel: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + let (inputs, inputBuilder) = AsyncStream.makeStream() + runtime.session.inputBuilder = inputBuilder + let (results, resultContinuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(resultContinuation) + let resultsTask = Task { + for await _ in inputs {} + _ = runtime.session.retireLiveTranscription(runtime.run, error: nil) + } + defer { resultsTask.cancel() } + runtime.run.recognizerTask = resultsTask + runtime.session.recognizerTask = resultsTask + let finish = fixture.track(Task { await runtime.session.finishTranscribing() }) + try await stopEntered.wait() + #expect(runtime.session.status == .stopping) + let input = try makeAnalyzerInput() + if case .terminated = inputBuilder.yield(input) { + Issue.record("The input stream closed before the screen source stopped") + } + if cancel { + let cancelTask = fixture.track(Task { await runtime.session.cancelTranscribing() }) + try await waitForCaptureState { runtime.session.inputBuilder == nil } + switch inputBuilder.yield(input) { + case .terminated: break + default: Issue.record("Cancel left the input stream open") + } + stopRelease.open() + await cancelTask.value + await #expect(throws: CancellationError.self) { + for try await _ in results {} + } + } else { + stopRelease.open() + var iterator = results.makeAsyncIterator() + let result = try await iterator.next() + #expect(result == nil) + } + await finish.value + #expect(runtime.session.status == .idle) + } + } + + @Test("Finish reports a native screen stop failure") + @MainActor + func finishReportsScreenStopFailure() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + source.stopError = CaptureFixtureError.startFailed + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + runtime.run.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + runtime.session.recognizerTask = runtime.run.recognizerTask + + await runtime.session.finishTranscribing() + + await #expect(throws: CaptureFixtureError.self) { + for try await _ in results {} + } + #expect(runtime.session.status == .idle) + } + } + + @Test("A delegate failure during native stop reaches Finish unless Cancel wins", arguments: [false, true]) + @MainActor + func delegateErrorDuringFinish(cancel: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + source.stopError = CaptureFixtureError.deadline + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + runtime.run.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + runtime.session.recognizerTask = runtime.run.recognizerTask + + let finish = fixture.track(Task { await runtime.session.finishTranscribing() }) + try await stopEntered.wait() + runtime.provider.streamDidStop(source, error: CaptureFixtureError.startFailed) + if cancel { + fixture.track(Task { await runtime.session.cancelTranscribing() }) + try await waitForCaptureState { runtime.run.cancellationRequested } + } + stopRelease.open() + await finish.value + + do { + for try await _ in results {} + Issue.record("Expected terminal failure") + } catch is CancellationError { + #expect(cancel) + } catch SpeechSessionError.screenCaptureFailed(let underlyingError) { + #expect(!cancel) + #expect(underlyingError as? CaptureFixtureError == .startFailed) + } + #expect(source.stops == 1) + #expect(runtime.session.status == .idle) + } + } + + @Test("Cancel wins while the successful screen completion still owns cleanup") + @MainActor + func cancelDuringTerminalScreenCleanup() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + let completed = fixture.track(Task { + await runtime.session.retireLiveTranscription(runtime.run, error: nil)?.value + }) + try await stopEntered.wait() + let cancel = fixture.track(Task { await runtime.session.cancelTranscribing() }) + try await waitForCaptureState { runtime.run.cancellationRequested } + stopRelease.open() + await cancel.value + await completed.value + + await #expect(throws: CancellationError.self) { + for try await _ in results {} + } + #expect(source.stops == 1) + #expect(runtime.session.status == .idle) + } + } + + @Test("A source ending during picker setup finishes without a selection cancellation error") + @MainActor + func sourceEndedDuringSetup() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let source = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { source }).value + runtime.session.streamingMode = .inactive + runtime.session.setStatus(.preparing) + let (inputs, inputBuilder) = AsyncStream.makeStream() + runtime.session.inputBuilder = inputBuilder + let (results, resultBuilder) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(resultBuilder) + runtime.run.recognizerTask = fixture.track(Task { + for await _ in inputs {} + _ = runtime.session.retireLiveTranscription(runtime.run, error: nil) + }) + + runtime.session.recognizerTask = runtime.run.recognizerTask + let pickerError = fixture.gate(), reported = fixture.gate() + runtime.run.setupTask = fixture.track(Task { + await fixtureWaitForPickerError(pickerError) + runtime.session.finishLivePipelineSetupFailure( + SpeechSessionError.screenCaptureSelectionCancelled, run: runtime.run + ) + reported.open() + }) + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + let finish = fixture.track(Task { + await runtime.session.finishLiveTranscription(runtime.run, sourceEnded: true) + }) + try await stopEntered.wait() + pickerError.open() + try await reported.wait() + stopRelease.open() + await finish.value + + var iterator = results.makeAsyncIterator() + #expect(try await iterator.next() == nil) + } + } + + @MainActor + private func fixtureWaitForPickerError(_ gate: CaptureGate) async { + await Task { try? await gate.wait() }.value + } + + @Test("Native stop sees delegate ingress before its main actor hop", arguments: [false, true]) + @MainActor + func nativeStopSeesDelegateIngress(nativeThrows: Bool) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let active = NSObject(), stale = NSObject() + let activeID = ObjectIdentifier(active) + let errors = ScreenCaptureStopErrors() + errors.start(activeID) + errors.record(CaptureFixtureError.deadline, for: ObjectIdentifier(stale)) + do { + try await errors.stop(activeID) { + errors.record(CaptureFixtureError.startFailed, for: activeID) + if nativeThrows { throw CaptureFixtureError.deadline } + } + Issue.record("Expected the delegate failure") + } catch SpeechSessionError.screenCaptureFailed(let underlyingError) { + #expect(underlyingError as? CaptureFixtureError == .startFailed) + } + } + + @available(iOS 26.0, macOS 26.0, *) + private func makeAnalyzerInput() throws -> AnalyzerInput { + let format = try #require(AVAudioFormat( + commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true + )) + let pcm = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 160)) + pcm.frameLength = 160 + pcm.int16ChannelData?.pointee.initialize(repeating: 0, count: 160) + return AnalyzerInput(buffer: pcm) + } +} +#endif diff --git a/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift b/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift index 56f9c12..e002e9f 100644 --- a/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift +++ b/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift @@ -89,23 +89,38 @@ final class ControlledCaptureStream: ScreenCaptureStream { var starts = 0 var stops = 0 var capturing = false + var terminated = false var startEntered: CaptureGate? var startRelease: CaptureGate? var stopEntered: CaptureGate? var stopRelease: CaptureGate? var startError: Error? + var stopError: Error? + var onStop: (@MainActor () -> Void)? func startCapture() async throws { starts += 1 startEntered?.open() try await startRelease?.wait() if let startError { throw startError } - capturing = true + capturing = !terminated } func stopCapture() async throws { stops += 1 stopEntered?.open() try await stopRelease?.wait() + onStop?() + if let stopError { throw stopError } capturing = false } } + +@MainActor +func waitForCaptureState(_ predicate: () -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + while !predicate() { + guard ContinuousClock.now < deadline else { throw CaptureFixtureError.deadline } + try Task.checkCancellation() + await Task.yield() + } +} diff --git a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index 9371a69..b1f407c 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -60,9 +60,11 @@ struct ScreenCaptureTransitionTests { #expect(!owner.isRunning) #expect(!old.capturing) #expect(replacement.starts == 0) - let resumed = await fixture.track(owner.resume()).value - #expect(resumed.isCurrent()) - #expect(resumed.error == nil) + var resumed: Result? + let terminal = await fixture.track(owner.resume { resumed = $0 }).value + #expect(terminal == nil) + try #require(resumed).get() + #expect(owner.desiredState == .running) #expect(replacement.starts == 1) #expect(old.starts == 1) try await fixture.track(owner.stop()).value @@ -166,7 +168,7 @@ private final class PublicCaptureFixture { makeProvider: { [self] format, inputs, failure in let provider = ScreenCaptureAudioInputProvider( options: .init(), targetFormat: format, inputContinuation: inputs, - onFailure: failure, transitions: owner, + onTermination: failure, transitions: owner, presentPicker: { [self] _ in presented.open() }, dismissPicker: { [self] _ in dismissed.open() } ) @@ -288,7 +290,7 @@ extension ScreenCaptureTransitionTests { try await resume.value try await successorStarted.wait() #expect(!runtime.consumerFinished) - #expect(runtime.session.status == .paused) + #expect(runtime.session.status == .transcribing) #expect(runtime.owner.stream === successor) // Explicitly resume the current selection, then fail that current start. try await runtime.session.resumeTranscribing() diff --git a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift new file mode 100644 index 0000000..92ba0f4 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift @@ -0,0 +1,229 @@ +#if canImport(ScreenCaptureKit) +import ScreenCaptureKit +import Speech +import Testing +@testable import AuralKit + +@Suite("Screen capture updates and termination") +struct ScreenCaptureUpdateTests { + @Test("Terminal errors reach a pending resume unless explicit stop won", arguments: [false, true]) + @MainActor + func terminalErrorDuringResume(stopFirst: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let teardown = fixture.gate(), resumed = fixture.gate() + let runtime = try CaptureSessionFixture(fixture, terminationRelease: teardown) + let (_, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + let stream = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { stream }).value + await runtime.session.pauseTranscribing() + let started = fixture.gate(), release = fixture.gate() + stream.startEntered = started; stream.startRelease = release + let resume = fixture.track(Task { + defer { resumed.open() } + try await runtime.session.resumeTranscribing() + }) + try await started.wait() + if stopFirst { + fixture.track(Task { await runtime.session.cancelTranscribing() }) + } + await fixture.track(Task { @MainActor in + if stopFirst { #expect(runtime.session.status == .stopping) } + stream.terminated = true + runtime.provider.streamDidStop(stream, error: CaptureFixtureError.startFailed) + }).value + release.open() + if !stopFirst { + await #expect(throws: TestTimeoutError.self) { + try await awaitResult(timeout: 0.05) { try await resumed.wait() } + } + #expect(runtime.session.continuation != nil) + } + teardown.open() + if stopFirst { + try await resume.value + try await waitForCaptureState { runtime.session.status == .idle } + } else { + await #expect(throws: SpeechSessionError.self) { try await resume.value } + #expect(runtime.session.status == .idle && runtime.session.continuation == nil) + } + #expect(!runtime.owner.isRunning && stream.stops == 1) + } + } + + @Test("Filter updates cannot hide a pending start failure", arguments: [false, true]) + @MainActor + func updateDuringFailedStart(staleUpdate: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let old = ControlledCaptureStream(), pending = ControlledCaptureStream() + if staleUpdate { await fixture.track(runtime.provider.selectStream { old }).value } + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + let started = fixture.gate(), release = fixture.gate() + pending.startEntered = started; pending.startRelease = release + pending.startError = CaptureFixtureError.startFailed + let selection = fixture.track(runtime.provider.selectStream { pending }) + try await started.wait() + let update = fixture.track(runtime.provider.updateStream(staleUpdate ? old : pending) {}) + release.open() + await selection.value; await update.value + await #expect(throws: SpeechSessionError.self) { + try await awaitResult(timeout: 1) { for try await _ in results {} } + } + #expect(runtime.session.status == .idle && !pending.capturing) + await runtime.close(fixture) + } + } + + @Test("Repeated filter updates retain the selected stream", arguments: [false, true]) + @MainActor + func repeatedUpdates(paused: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { stream }).value + if paused { await runtime.session.pauseTranscribing() } + var filters: [Int] = [] + for filter in [1, 2] { + await fixture.track(runtime.provider.updateStream(stream) { filters.append(filter) }).value + } + #expect(filters == [1, 2] && runtime.owner.stream === stream) + #expect(stream.starts == 1 && stream.stops == (paused ? 1 : 0)) + #expect(stream.capturing == !paused) + #expect(runtime.session.status == (paused ? .paused : .transcribing)) + if paused { try await runtime.session.resumeTranscribing() } + let successor = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { successor }).value + await fixture.track(runtime.provider.updateStream(stream) { filters.append(3) }).value + runtime.provider.streamDidStop(stream, error: CaptureFixtureError.startFailed) + #expect(filters == [1, 2] && successor.capturing) + #expect(runtime.session.status == .transcribing) + await runtime.close(fixture) + } + } + + @Test("Filter updates serialize with pending start and pause or stop", arguments: [false, true]) + @MainActor + func updateDuringStart(stop: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + let started = fixture.gate(), startRelease = fixture.gate() + let updating = fixture.gate(), updateRelease = fixture.gate() + stream.startEntered = started; stream.startRelease = startRelease + let selection = fixture.track(runtime.provider.selectStream { stream }) + try await started.wait() + var updates = 0 + let update = fixture.track(runtime.provider.updateStream(stream) { + updates += 1; updating.open(); try await updateRelease.wait() + }) + startRelease.open() + try await updating.wait() + #expect(stream.capturing && stream.starts == 1 && stream.stops == 0) + let control = fixture.track(Task { + if stop { + await runtime.session.cancelTranscribing() + } else { + await runtime.session.pauseTranscribing() + } + }) + try await waitForCaptureState { runtime.owner.desiredState == (stop ? .stopped : .paused) } + let later = fixture.track(runtime.provider.updateStream(stream) { updates += 1 }) + updateRelease.open() + await selection.value; await update.value; await control.value; await later.value + #expect(updates == (stop ? 1 : 2)) + #expect(!stream.capturing && stream.stops == 1) + #expect(runtime.session.status == (stop ? .idle : .paused)) + await runtime.close(fixture) + } + } + + @Test("An obsolete filter failure does not terminate its replacement") + @MainActor + func supersededUpdateFailure() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let old = ControlledCaptureStream(), successor = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { old }).value + let updating = fixture.gate(), release = fixture.gate() + let update = fixture.track(runtime.provider.updateStream(old) { + updating.open(); try await release.wait(); throw CaptureFixtureError.startFailed + }) + try await updating.wait() + let replacement = fixture.track(runtime.provider.selectStream { successor }) + runtime.provider.streamDidStop(old, error: CaptureFixtureError.startFailed) + old.terminated = true; old.capturing = false + release.open() + await update.value; await replacement.value + #expect(successor.capturing && runtime.session.status == .transcribing) + await runtime.close(fixture) + } + } + + @Test("Terminal delegate errors survive a failed pause", arguments: [false, true]) + @MainActor + func failedPauseWithTerminalEvent(duringStop: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + await fixture.track(runtime.provider.selectStream { stream }).value + stream.stopError = CaptureFixtureError.startFailed + let terminate: @MainActor @Sendable () -> Void = { + stream.terminated = true; stream.capturing = false + runtime.provider.streamDidStop(stream, error: CaptureFixtureError.startFailed) + } + if duringStop { stream.onStop = terminate } + await runtime.session.pauseTranscribing() + if !duringStop { + #expect(runtime.session.status == .transcribing && stream.capturing) + terminate() + } + await #expect(throws: SpeechSessionError.self) { + try await awaitResult(timeout: 3) { for try await _ in results {} } + } + #expect(runtime.session.status == .idle && !runtime.owner.isRunning) + #expect(stream.stops == 1) + } + } + + @Test("A terminal event during start cannot resurrect capture", arguments: [false, true]) + @MainActor + func terminalEventDuringStart(userStopped: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + let started = fixture.gate(), release = fixture.gate() + stream.startEntered = started; stream.startRelease = release + let (results, continuation) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(continuation) + let selection = fixture.track(runtime.provider.selectStream { stream }) + try await started.wait() + stream.terminated = true + let error: Error = userStopped + ? NSError(domain: SCStreamError.errorDomain, code: SCStreamError.Code.userStopped.rawValue) + : CaptureFixtureError.startFailed + runtime.provider.streamDidStop(stream, error: error) + release.open() + await selection.value + do { + try await awaitResult(timeout: 3) { for try await _ in results {} } + #expect(userStopped) + } catch is SpeechSessionError { + #expect(!userStopped) + } + #expect(runtime.session.status == .idle && !runtime.owner.isRunning) + #expect(!stream.capturing && stream.stops == 0) + } + } +} +#endif diff --git a/Tests/AuralKitTests/SessionFinalizationTests.swift b/Tests/AuralKitTests/SessionFinalizationTests.swift new file mode 100644 index 0000000..a34c9b2 --- /dev/null +++ b/Tests/AuralKitTests/SessionFinalizationTests.swift @@ -0,0 +1,86 @@ +import Testing +import AVFoundation +import Speech +@testable import AuralKit + +extension SpeechSessionLifecycleTests { + @Test("Finish closes a preparing stream and Cancel reports cancellation", arguments: [false, true]) + @MainActor + func endPreparingTranscription(cancel: Bool) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let session = SpeechSession() + let stream = session.startTranscribing() + + if cancel { + await session.cancelTranscribing() + await #expect(throws: CancellationError.self) { + for try await _ in stream {} + } + } else { + await session.finishTranscribing() + var iterator = stream.makeAsyncIterator() + let result = try await iterator.next() + #expect(result == nil) + } + + #expect(session.status == .idle) + #expect(session.continuation == nil) + } + + @Test("Finish closes a live result stream with no analyzer input") + @MainActor + func finishEmptyLiveTranscription() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let session = SpeechSession() + let (inputs, inputBuilder) = AsyncStream.makeStream() + let (results, resultBuilder) = AsyncThrowingStream.makeStream() + let run = LiveTranscriptionRun() + session.liveTranscription = run + let analyzer = SpeechAnalyzer(modules: []) + session.inputBuilder = inputBuilder + session.analyzer = analyzer + session.analyzerInputTask = Task { try await analyzer.analyzeSequence(inputs) } + session.continuation = .speech(resultBuilder) + run.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + session.recognizerTask = run.recognizerTask + session.streamingMode = .liveMicrophone + session.setStatus(.transcribing) + + try await awaitResult(timeout: 3) { + async let finish: Void = session.finishTranscribing() + for try await _ in results { Issue.record("Expected no results") } + await finish + } + #expect(session.status == .idle) + #expect(session.recognizerTask == nil) + } + + @Test("Input analysis failure closes results before Finish is called") + @MainActor + func inputAnalysisFailureClosesResults() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let session = SpeechSession() + let run = LiveTranscriptionRun() + session.liveTranscription = run + let (results, resultBuilder) = AsyncThrowingStream.makeStream() + session.continuation = .speech(resultBuilder) + run.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + session.recognizerTask = run.recognizerTask + session.streamingMode = .liveMicrophone + session.setStatus(.transcribing) + + session.startAnalyzingInput(admitSetup: session.captureAnalyzerSetupAdmission()) { + throw SpeechSessionError.invalidAudioDataType + } + + do { + try await awaitResult(timeout: 3) { + for try await _ in results { Issue.record("Expected no results") } + } + Issue.record("Expected input analysis to fail") + } catch SpeechSessionError.invalidAudioDataType {} + #expect(session.status == .idle) + #expect(session.recognizerTask == nil) + } + +} diff --git a/Tests/AuralKitTests/SessionLifecycleTests.swift b/Tests/AuralKitTests/SessionLifecycleTests.swift index 5811132..5ea811d 100644 --- a/Tests/AuralKitTests/SessionLifecycleTests.swift +++ b/Tests/AuralKitTests/SessionLifecycleTests.swift @@ -308,14 +308,19 @@ private final class PendingScreenInput: ScreenCaptureInput { await waiter.value try Task.checkCancellation() } - func pause() async { + func pause() async -> Bool { pauseEntered?.finish() if let pauseGate { for await _ in pauseGate {} } + return true } - func resume() async throws {} - func stop() async { + func resume(onCompletion: @escaping @MainActor (Result) -> Void) async -> Error? { + onCompletion(.success(())) + return nil + } + func stop() -> Task { stopped = true endSelection.finish() + return Task {} } } diff --git a/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift b/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift new file mode 100644 index 0000000..f6a47d6 --- /dev/null +++ b/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift @@ -0,0 +1,111 @@ +import Foundation +import AVFoundation +import Speech +@testable import AuralKit + +actor UpstreamAssetGate { + private var entered = false + private var arrivals: [CheckedContinuation] = [] + private var isOpen = false + private var waiters: [CheckedContinuation] = [] + + func wait() async { + entered = true + let pending = arrivals + arrivals.removeAll() + for arrival in pending { arrival.resume() } + guard !isOpen else { return } + await withCheckedContinuation { waiters.append($0) } + } + + func waitOnce() async { + guard !entered else { return } + await wait() + } + + func waitForEntry() async { + guard !entered else { return } + await withCheckedContinuation { arrivals.append($0) } + } + + var hasOpened: Bool { isOpen } + + func open() { + isOpen = true + let pending = waiters + waiters.removeAll() + for waiter in pending { waiter.resume() } + } +} + +@available(iOS 26.0, macOS 26.0, *) +actor UpstreamAssetInventoryProbe { + struct Snapshot: Sendable { + let locales: Set + let reserves: [String] + let releases: [String] + } + + private var stored: [String: Locale] + private let variants: [String: Locale] + private var reserveCalls: [String] = [] + private var releaseCalls: [String] = [] + private var reserveGate: UpstreamAssetGate? + private var releaseGate: UpstreamAssetGate? + + init(initial: [Locale] = [], variants: [String: Locale] = [:]) { + stored = Dictionary(initial.map { ($0.identifier(.bcp47), $0) }, + uniquingKeysWith: { first, _ in first }) + self.variants = variants + } + + nonisolated var client: SpeechAssetReservations.Inventory { + .init(locales: { await self.locales() }, + reserve: { await self.reserve($0) }, + release: { await self.release($0) }) + } + + var snapshot: Snapshot { + Snapshot(locales: Set(stored.keys), reserves: reserveCalls, releases: releaseCalls) + } + + func holdReserve(at gate: UpstreamAssetGate) { reserveGate = gate } + func holdRelease(at gate: UpstreamAssetGate) { releaseGate = gate } + private func locales() -> [Locale] { Array(stored.values) } + + private func reserve(_ locale: Locale) async -> Bool { + let requested = locale.identifier(.bcp47) + reserveCalls.append(requested) + await reserveGate?.wait() + let actual = variants[requested] ?? locale + let key = actual.identifier(.bcp47) + guard stored[key] == nil else { return false } + stored[key] = actual + return true + } + + private func release(_ locale: Locale) async -> Bool { + let key = locale.identifier(.bcp47) + releaseCalls.append(key) + await releaseGate?.wait() + return stored.removeValue(forKey: key) != nil + } +} + +@available(iOS 26.0, macOS 26.0, *) +final class ReservationModule: LocaleDependentSpeechModule { + struct Result: SpeechModuleResult, Sendable { + let range = CMTimeRange.zero + let resultsFinalizationTime = CMTime.zero + } + + let selectedLocales: [Locale] + init(locales: [Locale]) { selectedLocales = locales } + + static var supportedLocales: [Locale] { get async { [] } } + static func supportedLocale(equivalentTo locale: Locale) async -> Locale? { nil } + var availableCompatibleAudioFormats: [AVAudioFormat] { get async { [] } } + var results: AsyncThrowingStream { + AsyncThrowingStream { $0.finish() } + } +} diff --git a/Tests/AuralKitTests/SpeechAssetReservationTests.swift b/Tests/AuralKitTests/SpeechAssetReservationTests.swift index e6ad237..87ed740 100644 --- a/Tests/AuralKitTests/SpeechAssetReservationTests.swift +++ b/Tests/AuralKitTests/SpeechAssetReservationTests.swift @@ -264,7 +264,7 @@ struct SpeechAssetReservationTests { } } - @Test("manager download failure returns its explicitly acquired locale") + @Test("failed installation acquires no explicit locale reservation") @MainActor func downloadFailure() async throws { guard #available(iOS 26.0, macOS 26.0, *) else { return } @@ -274,8 +274,8 @@ struct SpeechAssetReservationTests { let operation = fixture.start { try await manager.ensureAssets(for: [module]) } if case .success = await operation.result { Issue.record("Download failure was ignored") } let state = await fixture.inventory.snapshot - #expect(!state.reserves.isEmpty) - #expect(state.releases.count == state.reserves.count) + #expect(state.reserves.isEmpty) + #expect(state.releases.isEmpty) #expect(state.locales.isEmpty) } } @@ -288,7 +288,7 @@ struct SpeechAssetReservationTests { let gate = fixture.gate() await fixture.inventory.holdReserve(at: gate) let module = SpeechTranscriber(locale: Locale(identifier: "en-US"), preset: .transcription) - let manager = fixture.manager { _ in Issue.record("Canceled acquisition started a download") } + let manager = fixture.manager { _ in } let operation = fixture.start { try await manager.ensureAssets(for: [module]) } try await fixture.waitUntil { await gate.entered } operation.cancel() @@ -308,7 +308,7 @@ struct SpeechAssetReservationTests { let gate = fixture.gate() await fixture.inventory.holdReserve(at: gate) let module = SpeechTranscriber(locale: Locale(identifier: "en-US"), preset: .transcription) - let manager = fixture.manager { _ in Issue.record("Retired preparation started a download") } + let manager = fixture.manager { _ in } let operation = fixture.start { try await manager.ensureAssets(for: [module]) } try await fixture.waitUntil { await gate.entered } let cleanup = fixture.start { await manager.releaseLocales() } @@ -333,15 +333,23 @@ struct SpeechAssetReservationTests { let manager = fixture.manager { _ in await gate.wait() } let operation = fixture.start { try await manager.ensureAssets(for: [module]) } try await fixture.waitUntil { await gate.entered } - let cleanup = fixture.start { await manager.releaseLocales() } + var cleanupReturned = false + let cleanup = fixture.start { + await manager.releaseLocales() + cleanupReturned = true + } try await fixture.waitUntil { await manager.cleanupTask != nil } var state = await fixture.inventory.snapshot + #expect(state.reserves.isEmpty) #expect(state.releases.isEmpty) + #expect(!cleanupReturned) await gate.open() if case .success = await operation.result { Issue.record("Retired download was admitted") } try await cleanup.value state = await fixture.inventory.snapshot - #expect(state.releases.count == 1) + #expect(cleanupReturned) + #expect(state.reserves.isEmpty) + #expect(state.releases.isEmpty) #expect(state.locales.isEmpty) } } diff --git a/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift b/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift index 97e6105..066220e 100644 --- a/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift +++ b/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift @@ -48,8 +48,7 @@ struct SpeechDetectorLifecycleTests { let currentID = try #require(fixture.session.speechDetectorMonitorID) input.yield(false) try await fixture.waitUntil { fixture.values == [false] } - if failed { await source.fail() } - else { await source.finish() } + if failed { await source.fail() } else { await source.finish() } await old.value #expect(!fixture.session.isSpeechDetected) #expect(fixture.session.speechDetectorMonitorID == currentID) @@ -70,8 +69,7 @@ struct SpeechDetectorLifecycleTests { input.yield(false) try await fixture.waitUntil { fixture.values == [false] } #expect(!fixture.session.isSpeechDetected) - if failed { input.finish(throwing: DetectorTestError.failed) } - else { input.finish() } + if failed { input.finish(throwing: DetectorTestError.failed) } else { input.finish() } await task.value #expect(fixture.session.isSpeechDetected) #expect(fixture.session.speechDetectorMonitorID == nil) @@ -85,8 +83,7 @@ struct SpeechDetectorLifecycleTests { @available(iOS 26.0, macOS 26.0, *) private func withFixture(_ operation: @MainActor (DetectorFixture) async throws -> Void) async throws { let fixture = DetectorFixture() - do { try await operation(fixture) } - catch { await fixture.cleanup(); throw error } + do { try await operation(fixture) } catch { await fixture.cleanup(); throw error } await fixture.cleanup() } } diff --git a/Tests/AuralKitTests/TestTimeoutOwnershipTests.swift b/Tests/AuralKitTests/TestTimeoutOwnershipTests.swift new file mode 100644 index 0000000..f5d3b03 --- /dev/null +++ b/Tests/AuralKitTests/TestTimeoutOwnershipTests.swift @@ -0,0 +1,81 @@ +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("Test timeout task ownership") +struct TestTimeoutOwnershipTests { + @Test("Timeout and caller cancellation join stream consumers and producers", arguments: [false, true]) + @MainActor + func cancellationJoinsActualTasks(cancelCaller: Bool) async throws { + let values = AsyncStream.makeStream() + let control = AsyncStream.makeStream() + let ready = AsyncStream.makeStream() + var producerJoined = false + var consumerJoined = false + let producer = Task { @MainActor in + defer { + values.continuation.finish() + producerJoined = true + } + for await _ in control.stream { values.continuation.yield(1) } + } + values.continuation.onTermination = { _ in producer.cancel() } + let consumer = Task { @MainActor in + defer { consumerJoined = true } + var iterator = values.stream.makeAsyncIterator() + ready.continuation.yield(()) + _ = await iterator.next() + } + try await withOwnedTasks([producer, consumer]) { + try await awaitResult { + var iterator = ready.stream.makeAsyncIterator() + _ = await iterator.next() + } + let wait = Task { @MainActor in + try await awaitResult(of: consumer, timeout: cancelCaller ? 60 : 0.01) + } + if cancelCaller { wait.cancel() } + do { + try await wait.value + Issue.record("Expected timeout or cancellation") + } catch { + if cancelCaller { #expect(error is CancellationError) } else { + guard let timeout = error as? TestTimeoutError, + case .timedOut(seconds: 0.01) = timeout else { + Issue.record("Expected timeout, got \(error)") + return + } + } + } + #expect(consumerJoined) + try await awaitResult(of: producer) + } + #expect(producerJoined) + #expect(consumerJoined) + } + + @Test("Fixture tasks join on successful and throwing operations", arguments: [false, true]) + @MainActor + func fixtureCleanupJoins(throwsError: Bool) async throws { + let values = AsyncStream.makeStream() + var joined = false + let consumer = Task { @MainActor in + defer { joined = true } + var iterator = values.stream.makeAsyncIterator() + _ = await iterator.next() + } + do { + try await withOwnedTasks([consumer]) { + if throwsError { throw VocabularyCompilationTestError.failed } + values.continuation.yield(1) + try await awaitResult(of: consumer) + } + #expect(!throwsError) + } catch { + #expect(throwsError) + #expect(error as? VocabularyCompilationTestError == .failed) + } + #expect(joined) + } +} diff --git a/Tests/AuralKitTests/UpstreamCustomVocabularyOwnershipTests.swift b/Tests/AuralKitTests/UpstreamCustomVocabularyOwnershipTests.swift new file mode 100644 index 0000000..de9d7ba --- /dev/null +++ b/Tests/AuralKitTests/UpstreamCustomVocabularyOwnershipTests.swift @@ -0,0 +1,206 @@ +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("Custom vocabulary artifact retention") +@MainActor +struct UpstreamCustomVocabularyOwnershipTests { + @available(iOS 26.0, macOS 26.0, *) + func descriptor(_ version: String = "1") -> SpeechSession.CustomVocabulary { + .init(locale: Locale(identifier: "en_US"), identifier: "ownership-test", version: version, weight: 0.4) + } + + @available(iOS 26.0, macOS 26.0, *) + func session(_ preparation: VocabularyPreparation) -> SpeechSession { + let session = SpeechSession(locale: Locale(identifier: "en_US")) + session.customVocabularyCompiler = CustomVocabularyCompiler { descriptor, asset, configuration in + try await preparation.prepare(descriptor, asset: asset, configuration: configuration) + } + return session + } + + @Test("Equal descriptors have private production outputs and independent retirement") + func twoSessionsRetireIndependently() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let preparation = VocabularyPreparation() + var first: SpeechSession? = session(preparation) + var second: SpeechSession? = session(preparation) + defer { first = nil; second = nil } + weak var weakFirst = first + weak var weakSecond = second + try await first!.configureCustomVocabulary(descriptor()) + try await second!.configureCustomVocabulary(descriptor()) + let firstDirectory = try #require(first?.customVocabularyOutputDirectory) + let secondDirectory = try #require(second?.customVocabularyOutputDirectory) + #expect(firstDirectory.path.hasPrefix(FileManager.default.temporaryDirectory.path)) + #expect(firstDirectory != secondDirectory) + #expect(first?.customVocabularyCacheKey == second?.customVocabularyCacheKey) + #expect(second?.customVocabularyConfiguration?.weight?.doubleValue == 0.4) + try await second!.configureCustomVocabulary(descriptor()) + #expect(second?.customVocabularyOutputDirectory == secondDirectory) + #expect(await preparation.count == 2) + + try await first!.configureCustomVocabulary(nil) + #expect(!FileManager.default.fileExists(atPath: firstDirectory.path)) + try assertFiles(in: secondDirectory) + try await first!.configureCustomVocabulary(descriptor()) + let retired = try #require(first?.customVocabularyOutputDirectory) + try await first!.configureCustomVocabulary(descriptor("replacement")) + let replacement = try #require(first?.customVocabularyOutputDirectory) + #expect(!FileManager.default.fileExists(atPath: retired.path)) + try assertFiles(in: secondDirectory) + first = nil + #expect(weakFirst == nil) + #expect(!FileManager.default.fileExists(atPath: replacement.path)) + try assertFiles(in: secondDirectory) + second = nil + #expect(weakSecond == nil) + #expect(!FileManager.default.fileExists(atPath: secondDirectory.path)) + } + + enum Rejection: Sendable, CaseIterable { case clear, replacement, cancellation } + + @Test("Pending compilation cannot publish after clear, replacement or cancellation", arguments: Rejection.allCases) + func rejectedCompilationRetires(rejection: Rejection) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let preparation = VocabularyPreparation() + let session = session(preparation) + let request = Task { @MainActor in + defer { preparation.ready.continuation.finish() } + try await session.configureCustomVocabulary(descriptor("blocked")) + } + do { + // The collaborator signals only after production paths/configuration and real files exist. + var ready = preparation.ready.stream.makeAsyncIterator() + let rejectedDirectory = try #require(await ready.next()) + switch rejection { + case .clear: try await session.configureCustomVocabulary(nil) + case .replacement: try await session.configureCustomVocabulary(descriptor("replacement")) + case .cancellation: request.cancel() + } + preparation.release.continuation.yield(()) + // Always join the actual request before any throwing assertion or fixture exit. + let result = await request.result + do { + try result.get() + Issue.record("Expected rejection") + } catch is CancellationError { } + #expect(!FileManager.default.fileExists(atPath: rejectedDirectory.path)) + if rejection == .replacement { + let retained = try #require(session.customVocabularyOutputDirectory) + try assertFiles(in: retained) + #expect(session.customVocabularyDescriptor?.version == "replacement") + try await session.configureCustomVocabulary(nil) + #expect(!FileManager.default.fileExists(atPath: retained.path)) + } else { + #expect(session.customVocabularyConfiguration == nil) + } + } catch { + request.cancel() + preparation.release.continuation.finish() + _ = await request.result + throw error + } + } + + @Test("Failed preparation removes partial production output") + func failedCompilationRetires() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let preparation = VocabularyPreparation() + let session = session(preparation) + do { + try await session.configureCustomVocabulary(descriptor("failure")) + Issue.record("Expected preparation error") + } catch SpeechSessionError.customVocabularyCompilationFailed { } + let failed = try #require(await preparation.directories.first) + #expect(!FileManager.default.fileExists(atPath: failed.path)) + #expect(session.customVocabularyConfiguration == nil) + } + + @Test("Detached transcriber state retains files after session retirement") + func detachedStateRetainsArtifacts() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let preparation = VocabularyPreparation() + var owner: SpeechSession? = session(preparation) + defer { owner = nil } + try await owner!.configureCustomVocabulary(descriptor()) + let directory = try #require(owner?.customVocabularyOutputDirectory) + // Constructs the real customized module; no asset install or analyzer start. + _ = try await owner!.createDictationTranscriber() + var detached: SpeechSession.DetachedTranscriberState? = owner!.detachTranscriberState() + try await owner!.configureCustomVocabulary(nil) + owner = nil + try assertFiles(in: directory) + await SpeechSession().cleanUpDetachedTranscriberState(try #require(detached), cancelAnalyzer: true) + try assertFiles(in: directory) + detached = nil + #expect(!FileManager.default.fileExists(atPath: directory.path)) + } + + @Test("Queued result consumer retains artifacts through terminal cleanup") + func resultConsumerRetainsArtifacts() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let preparation = VocabularyPreparation() + var owner: SpeechSession? = session(preparation) + defer { owner = nil } + weak var weakOwner = owner + try await owner!.configureCustomVocabulary(descriptor()) + let directory = try #require(owner?.customVocabularyOutputDirectory) + let results = AsyncStream.makeStream() + let output = AsyncThrowingStream.makeStream() + let run = LiveTranscriptionRun() + owner!.liveTranscription = run + let reader = owner!.makeLiveRecognizerTask( + run: run, + results: results.stream, + vocabularyArtifacts: owner?.customVocabularyArtifacts, + streamContinuation: output.continuation + ) + run.recognizerTask = reader + // Drop the session's ownership before the queued reader's first actor turn. + owner!.clearCustomVocabularyArtifacts(removeDescriptor: true) + owner = nil + #expect(weakOwner != nil) + #expect(FileManager.default.fileExists(atPath: directory.path)) + results.continuation.finish() + await reader.value + await run.terminalTask?.value + #expect(weakOwner == nil) + #expect(!FileManager.default.fileExists(atPath: directory.path)) + } + + func assertFiles(in directory: URL) throws { + #expect(try Data(contentsOf: directory.appendingPathComponent("languageModel.bin")) == Data("model".utf8)) + #expect(try Data(contentsOf: directory.appendingPathComponent("vocabulary.bin")) == Data("vocabulary".utf8)) + } +} + +/// Substitutes only Apple export/preparation, keeping production allocation and configuration. +@available(iOS 26.0, macOS 26.0, *) +actor VocabularyPreparation { + enum Failure: Error { case expected } + nonisolated let ready = AsyncStream.makeStream() + nonisolated let release = AsyncStream.makeStream() + private(set) var directories: [URL] = [] + var count: Int { directories.count } + + func prepare( + _ descriptor: SpeechSession.CustomVocabulary, + asset: URL, + configuration: SFSpeechLanguageModel.Configuration + ) async throws { + let directory = configuration.languageModel.deletingLastPathComponent() + directories.append(directory) + try Data("source".utf8).write(to: asset) + try Data("model".utf8).write(to: configuration.languageModel) + try Data("vocabulary".utf8).write(to: #require(configuration.vocabulary)) + if descriptor.version == "failure" { throw Failure.expected } + if descriptor.version == "blocked" { + ready.continuation.yield(directory) + var iterator = release.stream.makeAsyncIterator() + _ = await iterator.next() + try Task.checkCancellation() + } + } +} diff --git a/Tests/AuralKitTests/UpstreamScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/UpstreamScreenCaptureTransitionTests.swift new file mode 100644 index 0000000..471798e --- /dev/null +++ b/Tests/AuralKitTests/UpstreamScreenCaptureTransitionTests.swift @@ -0,0 +1,236 @@ +#if canImport(ScreenCaptureKit) +import AVFoundation +import Speech +import Testing +@testable import AuralKit + +@available(iOS 27.0, macOS 26.0, *) +@MainActor +final class CaptureSessionFixture { + let session = SpeechSession() + let run = LiveTranscriptionRun() + let owner = ScreenCaptureTransitions() + let provider: ScreenCaptureAudioInputProvider + let dismissed: CaptureGate + + init(_ fixture: CaptureFixture, terminationRelease: CaptureGate? = nil) throws { + dismissed = fixture.gate() + let (_, inputs) = AsyncStream.makeStream() + let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) + session.liveTranscription = run + provider = ScreenCaptureAudioInputProvider( + options: .init(), targetFormat: format, inputContinuation: inputs, + onTermination: { [session, run] error in + Task { @MainActor in + try? await terminationRelease?.wait() + await session.retireLiveTranscription(run, error: error)?.value + } + }, transitions: owner, + dismissPicker: { [dismissed] _ in dismissed.open() } + ) + session.screenCaptureInputProvider = provider + session.streamingMode = .screenCapture + session.setStatus(.transcribing) + } + + func close(_ fixture: CaptureFixture) async { + fixture.releaseAll() + await session.cancelTranscribing() + } +} + +@Suite("Screen capture replacement and failure propagation") +struct UpstreamScreenCaptureTransitionTests { + @Test("Replacing a pending picker start stops it before starting its successor") + @MainActor + func replacementDuringStart() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let old = ControlledCaptureStream(), successor = ControlledCaptureStream() + let entered = fixture.gate(), release = fixture.gate() + let stopping = fixture.gate(), stopped = fixture.gate() + old.startEntered = entered; old.startRelease = release + old.stopEntered = stopping; old.stopRelease = stopped + let first = fixture.track(runtime.provider.selectStream { old }) + try await entered.wait() + let second = fixture.track(runtime.provider.selectStream { successor }) + release.open() + try await stopping.wait() + #expect(old.capturing && successor.starts == 0) + stopped.open() + await first.value; await second.value + #expect(!old.capturing && old.stops == 1) + #expect(successor.capturing && successor.starts == 1) + await runtime.close(fixture) + } + } + + @Test("Public pause during replacement prevents queued selections from starting") + @MainActor + func pauseDuringReplacement() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let old = ControlledCaptureStream(), replacement = ControlledCaptureStream() + let latest = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { old }).value + let entered = fixture.gate(), release = fixture.gate() + old.stopEntered = entered; old.stopRelease = release + let first = fixture.track(runtime.provider.selectStream { replacement }) + try await entered.wait() + let pause = fixture.track(Task { await runtime.session.pauseTranscribing() }) + try await waitForCaptureState { runtime.owner.desiredState == .paused } + let second = fixture.track(runtime.provider.selectStream { latest }) + release.open() + await first.value; await second.value; await pause.value + #expect(runtime.session.status == .paused) + #expect(!old.capturing && replacement.starts == 0 && latest.starts == 0) + try await runtime.session.resumeTranscribing() + #expect(latest.capturing && runtime.session.status == .transcribing) + await runtime.close(fixture) + } + } + + @Test("Concurrent public stops join a replacement start and its compensating stop") + @MainActor + func stopDuringReplacementStart() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let previous = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { previous }).value + let stream = ControlledCaptureStream() + let entered = fixture.gate(), release = fixture.gate() + let stopping = fixture.gate(), stopped = fixture.gate() + stream.startEntered = entered; stream.startRelease = release + stream.stopEntered = stopping; stream.stopRelease = stopped + let selection = fixture.track(runtime.provider.selectStream { stream }) + try await entered.wait() + var firstReturned = false, secondReturned = false + let first = fixture.track(Task { + await runtime.session.cancelTranscribing(); firstReturned = true + }) + try await runtime.dismissed.wait() + let secondEntered = fixture.gate() + let second = fixture.track(Task { + secondEntered.open() + await runtime.session.cancelTranscribing(); secondReturned = true + }) + try await secondEntered.wait() + #expect(!firstReturned && !secondReturned) + release.open() + try await stopping.wait() + #expect(!firstReturned && !secondReturned) + #expect(runtime.session.status == .stopping) + stopped.open() + await first.value; await second.value; await selection.value + #expect(firstReturned && secondReturned) + #expect(!previous.capturing && !stream.capturing && runtime.owner.stream == nil) + #expect(runtime.session.status == .idle) + } + } + + @Test("Superseded public resume publishes running and allows pause", arguments: [false, true]) + @MainActor + func supersededPublicResumeFailure(fails: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let old = ControlledCaptureStream(), successor = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { old }).value + await runtime.session.pauseTranscribing() + let entered = fixture.gate(), release = fixture.gate() + old.startEntered = entered; old.startRelease = release + old.startError = fails ? CaptureFixtureError.startFailed : nil + var resumeReturned = false + let resume = fixture.track(Task { + try await runtime.session.resumeTranscribing(); resumeReturned = true + }) + try await entered.wait() + let successorEntered = fixture.gate(), successorRelease = fixture.gate() + successor.startEntered = successorEntered; successor.startRelease = successorRelease + let replacement = fixture.track(runtime.provider.selectStream { successor }) + release.open() + try await successorEntered.wait() + #expect(!resumeReturned && runtime.session.status == .paused) + successorRelease.open() + try await resume.value + await replacement.value + #expect(runtime.session.status == .transcribing && successor.capturing) + #expect(!old.capturing) + await runtime.session.pauseTranscribing() + #expect(runtime.session.status == .paused && !successor.capturing) + #expect(successor.stops == 1) + await runtime.close(fixture) + } + } + + @Test("Current resume failure still propagates and tears down") + @MainActor + func currentResumeFailure() async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { stream }).value + await runtime.session.pauseTranscribing() + stream.startError = CaptureFixtureError.startFailed + await #expect(throws: CaptureFixtureError.self) { + try await runtime.session.resumeTranscribing() + } + #expect(runtime.session.status == .idle && !stream.capturing) + } + } + + @Test("A terminal stop receives a drain failure from an in-flight pause") + @MainActor + func stopReceivesDrainFailureFromPause() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let transitions = ScreenCaptureTransitions() + let stream = ControlledCaptureStream() + try await transitions.replace { stream }.value + let entered = fixture.gate(), release = fixture.gate() + stream.stopEntered = entered + stream.stopRelease = release + stream.onStop = { stream.capturing = false } + stream.stopError = ScreenCaptureDrainFailure(underlyingError: CaptureFixtureError.startFailed) + + let pause = fixture.track(transitions.pause()) + try await entered.wait() + let stop = fixture.track(transitions.stop()) + release.open() + + let pauseError = await pause.result + let stopError = await stop.result + #expect(throws: ScreenCaptureDrainFailure.self) { try pauseError.get() } + #expect(throws: ScreenCaptureDrainFailure.self) { try stopError.get() } + #expect(!stream.capturing && stream.stops == 1 && transitions.stream == nil) + } + } + + @Test("A failed native pause keeps the public status transcribing", arguments: [false, true]) + @MainActor + func failedPause(replaceAfterFailure: Bool) async throws { + guard #available(iOS 27.0, macOS 26.0, *) else { return } + try await withCaptureFixture { fixture in + let runtime = try CaptureSessionFixture(fixture) + let stream = ControlledCaptureStream() + await fixture.track(runtime.provider.selectStream { stream }).value + stream.stopError = CaptureFixtureError.startFailed + await runtime.session.pauseTranscribing() + #expect(runtime.session.status == .transcribing && stream.capturing) + stream.stopError = nil + let active = replaceAfterFailure ? ControlledCaptureStream() : stream + if replaceAfterFailure { + await fixture.track(runtime.provider.selectStream { active }).value + #expect(active.capturing && runtime.session.status == .transcribing) + } + await runtime.session.pauseTranscribing() + #expect(runtime.session.status == .paused && !active.capturing && !stream.capturing) + await runtime.close(fixture) + } + } +} +#endif diff --git a/Tests/AuralKitTests/UpstreamSpeechAssetReservationTests.swift b/Tests/AuralKitTests/UpstreamSpeechAssetReservationTests.swift new file mode 100644 index 0000000..f76dab1 --- /dev/null +++ b/Tests/AuralKitTests/UpstreamSpeechAssetReservationTests.swift @@ -0,0 +1,149 @@ +import Foundation +import Testing +@testable import AuralKit + +@Suite("Speech installation and borrowed reservations") +struct UpstreamSpeechAssetReservationTests { + @Test("overlapping managers retain the locale until the final owner stops") + func overlappingManagers() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let inventory = UpstreamAssetInventoryProbe() + let reservations = SpeechAssetReservations(inventory: inventory.client) + let first = ModelManager(reservations: reservations, assetDownloader: { _ in }) + let second = ModelManager(reservations: reservations, assetDownloader: { _ in }) + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + try await first.ensureAssets(for: [module]) + try await second.ensureAssets(for: [module]) + await first.releaseLocales() + #expect(await inventory.snapshot.releases.isEmpty) + await second.releaseLocales() + await second.releaseLocales() + let state = await inventory.snapshot + #expect(state.reserves == ["en-US"]) + #expect(state.releases == ["en-US"]) + #expect(state.locales.isEmpty) + } + + @Test("borrowed external reservations survive cleanup", arguments: ["en-US", "en-AU"]) + func borrowedReservation(alias: String) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let inventory = UpstreamAssetInventoryProbe(initial: [Locale(identifier: "en-US")], + variants: ["en-AU": Locale(identifier: "en-US")]) + let reservations = SpeechAssetReservations(inventory: inventory.client) + let manager = ModelManager(reservations: reservations, assetDownloader: { _ in }) + try await manager.ensureAssets(for: [ReservationModule(locales: [Locale(identifier: alias)])]) + await manager.releaseLocales() + #expect(await inventory.snapshot.releases.isEmpty) + #expect(await inventory.snapshot.locales == ["en-US"]) + } + + @Test("variant holders protect the observed native reservation") + func canonicalVariant() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let inventory = UpstreamAssetInventoryProbe(variants: ["en-AU": Locale(identifier: "en-US"), + "en-GB": Locale(identifier: "en-US")]) + let reservations = SpeechAssetReservations(inventory: inventory.client) + let owner = try await reservations.acquire(Locale(identifier: "en-AU")) + let borrower = try await reservations.acquire(Locale(identifier: "en-GB")) + let canonical = try await reservations.acquire(Locale(identifier: "en-US")) + await reservations.release(owner) + await reservations.release(canonical) + #expect(await inventory.snapshot.releases.isEmpty) + await reservations.release(borrower) + #expect(await inventory.snapshot.locales.isEmpty) + } + + @Test("canceled or retired installation work cannot reserve a locale", arguments: [true, false]) + func canceledQueuedInstallation(cancel: Bool) async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let inventory = UpstreamAssetInventoryProbe() + let native = inventory.client + let reservations = SpeechAssetReservations(inventory: native) + let blockerGate = UpstreamAssetGate() + let blocker = Task { + try await reservations.withInventoryAccess { await blockerGate.wait() } + } + await blockerGate.waitForEntry() + let manager = ModelManager(reservations: reservations, installationRequest: { _ in + _ = try await native.reserve(Locale(identifier: "en-US")) + return nil + }) + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let preparation = Task { try await manager.ensureAssets(for: [module]) } + let deadline = ContinuousClock.now + .seconds(1) + while await reservations.queuedOperations < 2, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(1)) + } + #expect(await reservations.queuedOperations == 2) + var cleanup: Task? + if cancel { + preparation.cancel() + } else { + cleanup = Task { await manager.releaseLocales() } + let cleanupDeadline = ContinuousClock.now + .seconds(1) + while await manager.cleanupTask == nil, ContinuousClock.now < cleanupDeadline { + await Task.yield() + } + #expect(await manager.cleanupTask != nil) + } + await blockerGate.open() + try await blocker.value + if case .success = await preparation.result { Issue.record("Retired preparation succeeded") } + await cleanup?.value + await manager.releaseLocales() + #expect(await inventory.snapshot.locales.isEmpty) + let successor = ModelManager(reservations: reservations, assetDownloader: { _ in }) + try await successor.ensureAssets(for: [module]) + await successor.releaseLocales() + #expect(await inventory.snapshot.locales.isEmpty) + } + + @Test("implicit installation reservations cannot invalidate an explicit acquisition") + func concurrentInstallationRequest() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let inventory = UpstreamAssetInventoryProbe() + let native = inventory.client + let gate = UpstreamAssetGate() + let reservations = SpeechAssetReservations(inventory: .init( + locales: native.locales, + reserve: { locale in + let created = try await native.reserve(locale) + await gate.wait() + return created + }, release: native.release + )) + let owner = Task { try await reservations.acquire(Locale(identifier: "en-US")) } + await gate.waitForEntry() + let installation = Task { + try await reservations.withInventoryAccess { + _ = try await native.reserve(Locale(identifier: "fr-FR")) + } + } + await gate.open() + let lease = try await owner.value + try await installation.value + await reservations.release(lease) + #expect(await inventory.snapshot.releases == ["en-US"]) + #expect(await inventory.snapshot.locales == ["fr-FR"]) + } + + @Test("reacquisition waits for a pending native release") + func reacquisitionDuringRelease() async throws { + guard #available(iOS 26.0, macOS 26.0, *) else { return } + let inventory = UpstreamAssetInventoryProbe() + let reservations = SpeechAssetReservations(inventory: inventory.client) + let lease = try await reservations.acquire(Locale(identifier: "en-US")) + let gate = UpstreamAssetGate() + await inventory.holdRelease(at: gate) + let release = Task { await reservations.release(lease) } + await gate.waitForEntry() + let next = Task { try await reservations.acquire(Locale(identifier: "en-US")) } + await gate.open() + await release.value + let nextLease = try await next.value + #expect(await inventory.snapshot.locales == ["en-US"]) + await reservations.release(nextLease) + #expect(await inventory.snapshot.reserves == ["en-US", "en-US"]) + #expect(await inventory.snapshot.releases == ["en-US", "en-US"]) + } +} diff --git a/codemagic.yaml b/codemagic.yaml deleted file mode 100644 index 3a752db..0000000 --- a/codemagic.yaml +++ /dev/null @@ -1,40 +0,0 @@ -definitions: - triggering: - push: &events - events: - - push - - pull_request - -workflows: - auralkit: - name: AuralKit Workflow - environment: - xcode: edge - vars: - XCODE_SCHEME: "AuralKit" - APP_ID: "AuralKit" - when: - changeset: - includes: - - "Sources" - - "Tests" - - "Aural" - - "Package.swift" - triggering: - <<: *events - scripts: - - name: Download Metal Toolchain - script: | - xcodebuild -downloadComponent MetalToolchain - - name: Install SwiftLint - script: | - brew install swiftlint - - name: Run SwiftLint - script: | - swiftlint --strict - - name: Build Swift Package - script: | - swift build - - name: Build Aural App - script: | - xcodebuild -scheme Aural -configuration Debug -destination "platform=iOS Simulator,name=iPhone 17 Pro" build