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 8f1be50..5634d6f 100644 --- a/Agents.md +++ b/Agents.md @@ -145,6 +145,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/LICENSE-Apple-SpeechExample.txt b/LICENSE-Apple-SpeechExample.txt new file mode 100644 index 0000000..de2de43 --- /dev/null +++ b/LICENSE-Apple-SpeechExample.txt @@ -0,0 +1,8 @@ +Copyright © 2025 Apple Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/README.md b/README.md index cd6302c..43e9ab5 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 14+ - 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) @@ -54,8 +56,12 @@ AuralKit is a simple, lightweight Swift wrapper for speech-to-text transcription This project would not have been possible without Apple's excellent sample code. The implementation is heavily inspired by [Bringing advanced speech-to-text capabilities to your app](https://developer.apple.com/documentation/Speech/bringing-advanced-speech-to-text-capabilities-to-your-app), which shows how to add live speech-to-text transcription with `SpeechAnalyzer`. +`BufferConverter` adapts the sample's `Helpers/BufferConversion.swift`. Apple's original notice is retained in [LICENSE-Apple-SpeechExample.txt](LICENSE-Apple-SpeechExample.txt), from the [published sample download](https://docs-assets.developer.apple.com/published/e40c20fc5641/BringingAdvancedSpeechToTextCapabilitiesToYourApp.zip). AuralKit adds concurrency annotations, package-specific errors and input-format invalidation; the converter is not an unchanged copy. + ## Quick Start +The examples below use the AuralKit 3.0 API. + ```swift import AuralKit @@ -78,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 } ``` @@ -94,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") ] ``` @@ -138,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: @@ -274,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: @@ -303,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: @@ -449,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/ModelManager.swift b/Sources/AuralKit/ModelManager.swift index 70041b9..4f29f20 100644 --- a/Sources/AuralKit/ModelManager.swift +++ b/Sources/AuralKit/ModelManager.swift @@ -10,8 +10,23 @@ actor ModelManager { private(set) var currentDownloadProgress: Progress? - // Track locales reserved by this ModelManager instance to avoid releasing others' reservations - private var reservedLocales: Set = [] + 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 + + init( + reservations: SpeechAssetReservations = .shared, + 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 func ensureModel(module: any LocaleDependentSpeechModule, locale: Locale) async throws { @@ -35,7 +50,9 @@ actor ModelManager { return } - try await downloadAssetsIfNeeded(for: [module]) + try await prepareAssets(for: [module]) { manager, generation in + try await manager.downloadAssetsIfNeeded(for: [module], generation: generation) + } } private func ensureLocaleAssets( @@ -44,19 +61,19 @@ actor ModelManager { supportedLocales: @escaping @Sendable () async -> [Locale], installedLocales: @escaping @Sendable () async -> [Locale] ) async throws { - guard await localeMatches(provider: supportedLocales, locale: locale) else { - throw SpeechSessionError.unsupportedLocale(locale) - } - - if await localeMatches(provider: installedLocales, locale: locale) { - logger.notice("Locale \(locale.identifier(.bcp47)) already installed") - currentDownloadProgress = nil - } else { - logger.info("Ensuring model download for locale \(locale.identifier(.bcp47))") - try await downloadAssetsIfNeeded(for: [module]) + try await prepareAssets(for: [module]) { manager, generation in + guard await manager.localeMatches(provider: supportedLocales, locale: locale) else { + throw SpeechSessionError.unsupportedLocale(locale) + } + 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], generation: generation) + } } - - try await reserveLocaleIfNeeded(locale) } private func localeMatches( @@ -68,40 +85,30 @@ actor ModelManager { return locales.contains { $0.identifier(.bcp47) == target } } - private func reserveLocaleIfNeeded(_ locale: Locale) async throws { - let existingReservations = await AssetInventory.reservedLocales - let target = locale.identifier(.bcp47) - if existingReservations.contains(where: { $0.identifier(.bcp47) == target }) { - logger.debug("Locale \(target) already reserved") - // Don't track it - it was reserved by another session - return - } - - do { - try await AssetInventory.reserve(locale: locale) - logger.info("Reserved locale \(target)") - reservedLocales.insert(target) - } catch { - logger.error("Failed to reserve locale \(target): \(error.localizedDescription, privacy: .public)") - throw SpeechSessionError.modelReservationFailed(locale, error) - } - } - func ensureAssets(for modules: [any SpeechModule]) async throws { guard !modules.isEmpty else { return } - try await 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 { - if let downloader = try await AssetInventory.assetInstallationRequest(supporting: modules) { + private func downloadAssetsIfNeeded(for modules: [any SpeechModule], generation: Int) async throws { + try requireCurrent(generation) + if let assetDownloader { + try await assetDownloader(modules) + return + } + 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 @@ -113,27 +120,66 @@ 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") } } - /// Release reserved locales so other clients can access them - /// Only releases locales that were reserved by this ModelManager instance + private func requestInstallation( + for modules: [any SpeechModule], generation: Int + ) async throws -> AssetInstallationRequest? { + try requireCurrent(generation) + return try await installationRequest(modules) + } + + /// Retire pending preparation without waiting for a native download to finish. func releaseLocales() async { - let allReserved = await AssetInventory.reservedLocales - // Only release locales tracked by this instance - var releasedCount = 0 - for locale in allReserved { - let target = locale.identifier(.bcp47) - if reservedLocales.contains(target) { - await AssetInventory.release(reservedLocale: locale) - reservedLocales.remove(target) - releasedCount += 1 + generation &+= 1 + let pending = leases + leases.removeAll() + currentDownloadProgress = nil + for lease in pending { await reservations.release(lease) } + } + + private func prepareAssets( + for modules: [any SpeechModule], + install: @Sendable (isolated ModelManager, Int) async throws -> Void + ) async throws { + let generation = self.generation + try requireCurrent(generation) + // 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 { + let locales = modules.compactMap { $0 as? any LocaleDependentSpeechModule } + .flatMap { $0.selectedLocales } + var requested = Set() + for locale in locales where requested.insert(locale.identifier(.bcp47)).inserted { + do { + acquired.append(try await reservations.acquire(locale)) + } catch is CancellationError { + throw CancellationError() + } catch { + throw SpeechSessionError.modelReservationFailed(locale, error) + } + try requireCurrent(generation) } + leases.formUnion(acquired) + } catch { + for lease in acquired { await reservations.release(lease) } + throw error } - currentDownloadProgress = nil - logger.debug("Released \(releasedCount) reserved locale(s)") + } + + private func requireCurrent(_ generation: Int) throws { + try Task.checkCancellation() + guard self.generation == generation else { throw CancellationError() } } } diff --git a/Sources/AuralKit/ScreenCaptureAudioProcessor.swift b/Sources/AuralKit/ScreenCaptureAudioProcessor.swift new file mode 100644 index 0000000..8d8c45c --- /dev/null +++ b/Sources/AuralKit/ScreenCaptureAudioProcessor.swift @@ -0,0 +1,190 @@ +import AVFoundation +import CoreMedia +import Foundation +import Speech + +/// Serializes audio conversion and admits callbacks only from the currently running stream. +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) } + } +} + +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/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift new file mode 100644 index 0000000..268fbfd --- /dev/null +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -0,0 +1,201 @@ +import Foundation + +@available(iOS 26.0, macOS 14.0, *) +@MainActor +protocol ScreenCaptureStream: AnyObject { + func startCapture() async throws + func stopCapture() async throws +} + +// 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 session cleanup. +@available(iOS 26.0, macOS 14.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 { + guard desiredState != .stopped else { return Task { throw CancellationError() } } + let admitted = UUID() + revision = admitted + return enqueue { + do { + guard self.desiredState != .stopped, self.revision == admitted else { return } + 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. + guard self.desiredState != .stopped, self.revision == admitted else { return } + throw error + } + } + } + + 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 { + do { + try await self.stopCurrent() + } catch { + if self.controlRevision == control, !(error is ScreenCaptureDrainFailure) { + self.desiredState = .running + } + throw error + } + } + } + + func resume( + onCompletion: @escaping @MainActor (Result) -> Void + ) -> Task { + let control = UUID() + controlRevision = control + desiredState = desiredState == .stopped ? .stopped : .running + let admitted = revision + 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 + } + } + } + + func stop() -> Task { + controlRevision = UUID() + desiredState = .stopped + explicitStopPending = true + return enqueue { + 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 } + } + } + + private func enqueue(_ body: @escaping @MainActor () async throws -> Void) -> Task { + let previous = tail + let operation = Task { @MainActor in + // Failure must not bypass the join or prevent a later terminal stop. + _ = try? await previous?.value + try await body() + } + tail = operation + return operation + } + + private func stopCurrent() async throws { + guard isRunning, let stream else { return } + 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 + if desiredState != .running || revision != admitted { + try await stopCurrent() + } + } +} diff --git a/Sources/AuralKit/SpeechAssetReservations.swift b/Sources/AuralKit/SpeechAssetReservations.swift new file mode 100644 index 0000000..16a8b3e --- /dev/null +++ b/Sources/AuralKit/SpeechAssetReservations.swift @@ -0,0 +1,166 @@ +import Foundation +import Speech + +/// 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. +actor SpeechAssetReservations { + struct Inventory: Sendable { + var locales: @Sendable () async -> [Locale] + var reserve: @Sendable (Locale) async throws -> Bool + var release: @Sendable (Locale) async -> Bool + + static let live = Inventory( + locales: { await AssetInventory.reservedLocales }, + reserve: { try await AssetInventory.reserve(locale: $0) }, + release: { await AssetInventory.release(reservedLocale: $0) } + ) + } + + struct Lease: Hashable, Sendable { + fileprivate let id = UUID() + fileprivate let alias: String + fileprivate let protectedKeys: Set + } + + enum ReservationError: Error { + case ambiguousInventoryChange + } + + static let shared = SpeechAssetReservations() + + private let inventory: Inventory + private var reservations: [String: Locale] = [:] + private var leases: Set = [] + private var tail: Task? + private(set) var queuedOperations = 0 + + init(inventory: Inventory = .live) { + self.inventory = inventory + } + + func acquire(_ locale: Locale) async throws -> Lease { + try Task.checkCancellation() + let lease = try await enqueue { try await self.acquireSerially(locale) }.value + do { + try Task.checkCancellation() + return lease + } catch { + // A shared native reserve can finish after its caller is canceled. + // Do not abandon the successful acquisition at that boundary. + await release(lease) + throw error + } + } + + 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 task = Task { + await previous?.value + return try await operation() + } + tail = Task { + _ = await task.result + self.operationFinished() + } + return task + } + + private func operationFinished() { + queuedOperations -= 1 + if queuedOperations == 0 { + // Completed tasks must not become a retained operation history. + tail = nil + } + } + + private func acquireSerially(_ locale: Locale) async throws -> Lease { + let alias = Self.key(locale) + if let known = leases.first(where: { $0.alias == alias }) { + return admit(alias: alias, protecting: known.protectedKeys) + } + if reservations[alias] != nil { + return admit(alias: alias, protecting: [alias]) + } + + 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 + if created { + 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 inventory client changed it. + guard added.count == 1, let key = added.first, let actual = after[key] else { + throw ReservationError.ambiguousInventoryChange + } + if reservations[key] == nil { + reservations[key] = actual + } + protectedKeys = [key] + } else if after[alias] != nil { + // An exact native identity can be borrowed without protecting + // unrelated reservations that this coordinator happens to own. + protectedKeys = reservations[alias] == nil ? [] : [alias] + } else { + guard !after.isEmpty else { throw ReservationError.ambiguousInventoryChange } + // Native inventory can report a variant of the requested locale. + // Do not guess language/region equivalence. An unknown borrowed + // alias protects only currently owned candidates until it ends. + protectedKeys = Set(reservations.keys).intersection(after.keys) + } + return admit(alias: alias, protecting: protectedKeys) + } + + private func admit(alias: String, protecting keys: Set) -> Lease { + let lease = Lease(alias: alias, protectedKeys: keys) + leases.insert(lease) + return lease + } + + private func releaseSerially(_ lease: Lease) async { + guard leases.remove(lease) != nil else { return } + for key in lease.protectedKeys where !leases.contains(where: { $0.protectedKeys.contains(key) }) { + guard let locale = reservations.removeValue(forKey: key) else { continue } + _ = await inventory.release(locale) + } + } + + private static func key(_ locale: Locale) -> String { + locale.identifier(.bcp47) + } + + private static func index(_ locales: [Locale]) -> [String: Locale] { + Dictionary(locales.map { (key($0), $0) }, uniquingKeysWith: { first, _ in first }) + } +} diff --git a/Sources/AuralKit/SpeechSession+Audio.swift b/Sources/AuralKit/SpeechSession+Audio.swift index ef7396f..4d5e394 100644 --- a/Sources/AuralKit/SpeechSession+Audio.swift +++ b/Sources/AuralKit/SpeechSession+Audio.swift @@ -28,22 +28,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(inputBuilder: inputBuilder, analyzerFormat: analyzerFormat) - ) + try installMicrophoneTap(inputBuilder: inputBuilder, analyzerFormat: analyzerFormat) audioEngine.prepare() try audioEngine.start() @@ -53,6 +38,42 @@ extension SpeechSession { } } + private func installMicrophoneTap( + inputBuilder: AsyncStream.Continuation, + analyzerFormat: AVAudioFormat + ) 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 + } + + // Use the smallest supported tap duration of 100 ms. + let bufferSize = AVAudioFrameCount((inputFormat.sampleRate / 10).rounded(.up)) + let processBuffer = makeAudioTapHandler( + inputBuilder: inputBuilder, + analyzerFormat: analyzerFormat, + 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 = makeAudioTapHandler(inputBuilder: inputBuilder, analyzerFormat: analyzerFormat) + let tap: @Sendable (AVAudioPCMBuffer, AVAudioTime) -> Void = { buffer, _ in + processBuffer(buffer) + } + inputNode.installTap(onBus: 0, bufferSize: Self.microphoneTapBufferSize, format: inputFormat, block: tap) + } + func stopAudioStreaming() { guard isAudioStreaming else { return } @@ -116,7 +137,7 @@ extension SpeechSession { #endif } - /// Build a tap block that converts and forwards buffers synchronously on the tap thread. + /// Convert and forward buffers synchronously on the tap thread. /// /// Converting inline (rather than hopping through per-buffer tasks) guarantees analyzer /// input arrives in capture order and keeps working across cleanup: yields into a finished @@ -124,15 +145,16 @@ extension SpeechSession { /// device change (which reinstalls the tap with a new format) never reuses a stale converter. private func makeAudioTapHandler( inputBuilder: AsyncStream.Continuation, - analyzerFormat: AVAudioFormat - ) -> AVAudioNodeTapBlock { + analyzerFormat: AVAudioFormat, + ownsTapBuffer: Bool = false + ) -> @Sendable (AVAudioPCMBuffer) -> Void { let converter = BufferConverter() - return { buffer, _ in + return { buffer in do { let converted = try converter.convertBuffer(buffer, to: analyzerFormat) let input: AVAudioPCMBuffer - if converted === buffer { - // Passthrough: the engine reuses the tap buffer, so hand the analyzer a copy. + if converted === buffer, !ownsTapBuffer { + // The older tap reuses its buffer, so give the analyzer a copy. guard let bufferCopy = buffer.copy() as? AVAudioPCMBuffer else { Task { @MainActor in if Self.shouldLog(.error) { @@ -218,7 +240,7 @@ extension SpeechSession { } private func handleInterruptionEnded(options: AVAudioSession.InterruptionOptions) async { - guard shouldResumeAfterInterruption else { return } + guard shouldResumeAfterInterruption, status == .paused else { return } shouldResumeAfterInterruption = false let generation = sessionGeneration @@ -231,10 +253,7 @@ extension SpeechSession { } do { - try await setupAudioSession() - // The session can be stopped and restarted while the audio session is being - // reconfigured; a stale interruption must not resume or tear down the newer stream. - guard generation == sessionGeneration else { return } + try setupAudioSession() try startAudioStreaming() setStatus(.transcribing) if Self.shouldLog(.notice) { @@ -255,10 +274,7 @@ extension SpeechSession { /// to a session that has already been stopped cannot mark a newer session `.stopping` or /// finish its stream. private func finishInterruptedSession(error: Error?, generation: Int) async { - guard generation == sessionGeneration else { return } - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: error, generation: generation) + await endTranscription(error: error, generation: generation) } #elseif os(macOS) func handleEngineConfigurationChange() async { diff --git a/Sources/AuralKit/SpeechSession+CustomVocabulary.swift b/Sources/AuralKit/SpeechSession+CustomVocabulary.swift index b80a798..a543a29 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabulary.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabulary.swift @@ -146,6 +146,22 @@ 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. +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) + } + } } protocol CustomVocabularyCompiling: Sendable { @@ -161,48 +177,53 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send let assetURL: URL } - private let fileManager: FileManager + typealias PrepareModel = @Sendable ( + SpeechSession.CustomVocabulary, URL, SFSpeechLanguageModel.Configuration + ) async throws -> Void - init(fileManager: FileManager = .default) { + private let fileManager: FileManager + private let prepareModel: PrepareModel + + init( + fileManager: FileManager = .default, + 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) + let artifacts = CustomVocabularyArtifacts(directory: paths.outputDirectory) + defer { withExtendedLifetime(artifacts) {} } let configuration = makeConfiguration(for: descriptor, paths: paths) try await exportModelData(descriptor, with: paths, configuration: configuration) + try Task.checkCancellation() 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, isDirectory: true) + .appendingPathComponent("\(cacheKey)-\(UUID().uuidString)", isDirectory: true) - if !fileManager.fileExists(atPath: outputDirectory.path) { - try fileManager.createDirectory(at: outputDirectory, withIntermediateDirectories: true) - } + try fileManager.createDirectory(at: outputDirectory, withIntermediateDirectories: true) let languageModelURL = outputDirectory.appendingPathComponent("languageModel.bin") let vocabularyURL = outputDirectory.appendingPathComponent("vocabulary.bin") - // Use UUID to ensure unique temp file per compilation invocation, preventing races - let uniqueID = UUID().uuidString - let assetURL = fileManager.temporaryDirectory - .appendingPathComponent("auralkit-custom-vocabulary-\(uniqueID).bin") - - // Clean up any existing temp file before creating new one - try? fileManager.removeItem(at: assetURL) + let assetURL = outputDirectory.appendingPathComponent("source.bin") return CompilationPaths( outputDirectory: outputDirectory, @@ -235,8 +256,6 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send with paths: CompilationPaths, configuration: SFSpeechLanguageModel.Configuration ) async throws { - let modelData = descriptor.makeModelData() - defer { // Best-effort cleanup of temp asset file do { @@ -254,15 +273,12 @@ final class CustomVocabularyCompiler: CustomVocabularyCompiling, @unchecked Send } do { - // Offload heavy I/O work to background to avoid blocking main actor - try await Task.detached(priority: .userInitiated) { - try await modelData.export(to: paths.assetURL) - try await SFSpeechLanguageModel.prepareCustomLanguageModel( - for: paths.assetURL, - configuration: configuration - ) - }.value + // 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 78d7997..2c6149f 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift @@ -8,12 +8,17 @@ extension SpeechSession { /// Configure the session's custom vocabulary, compiling assets as needed. /// + /// Compiled files are temporary and are rebuilt before reuse if the system purges them. + /// Cancelling compilation waits for preparation to finish, then throws `CancellationError` + /// without replacing the current configuration. Superseded compilation results are discarded. + /// /// - Parameter vocabulary: The vocabulary descriptor to activate, or `nil` to clear the current /// configuration. /// - Throws: A `SpeechSessionError` when the session is active, the descriptor locale mismatches, or /// compilation fails. public func configureCustomVocabulary(_ vocabulary: CustomVocabulary?) async throws { - if streamingMode != .inactive { + try Task.checkCancellation() + if streamingMode != .inactive || continuation != nil || pipelineTask != nil || recognizerTask != nil { throw SpeechSessionError.customVocabularyRequiresIdleSession } @@ -35,36 +40,54 @@ extension SpeechSession { throw SpeechSessionError.customVocabularyCompilationFailed(error) } + try Task.checkCancellation() + let requestID = UUID() + customVocabularyRequestID = requestID + if cacheKey == customVocabularyCacheKey, - customVocabularyConfiguration != nil { + customVocabularyFilesExist { customVocabularyDescriptor = vocabulary return } + let compilation = try await compileCustomVocabulary(vocabulary) + try Task.checkCancellation() + guard customVocabularyRequestID == requestID else { throw CancellationError() } + guard streamingMode == .inactive, continuation == nil, pipelineTask == nil, recognizerTask == nil else { + throw SpeechSessionError.customVocabularyRequiresIdleSession + } + 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 { // Offload compilation to background task to avoid blocking main actor UI // Capture compiler before detached task to avoid cross-actor access let compiler = customVocabularyCompiler - let compilation = try await Task.detached(priority: .userInitiated) { + let task = Task.detached(priority: .userInitiated) { try await compiler.compile(descriptor: vocabulary) - }.value - - 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() + } + // Rejected results release their private artifacts after the compiler has joined. + 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. @@ -83,7 +106,8 @@ extension SpeechSession { } let generation = beginStreamGeneration() - newContinuation.onTermination = { [weak self] _ in + newContinuation.onTermination = { [weak self] termination in + guard case .cancelled = termination else { return } Task { @MainActor [weak self] in await self?.handleStreamTermination(generation: generation) } @@ -120,18 +144,9 @@ extension SpeechSession { } func clearCustomVocabularyArtifacts(removeDescriptor: Bool) { - 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 - ) - } - } + customVocabularyRequestID = nil + // Dropping the session's owner cannot delete files retained by native consumers. + customVocabularyArtifacts = nil customVocabularyConfiguration = nil customVocabularyCacheKey = nil diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 56ebbcb..a8e62e5 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -66,35 +66,15 @@ public extension SpeechSession { options: FileTranscriptionOptions = .init(), progressHandler: (@Sendable (Double) -> Void)? = nil ) -> AsyncThrowingStream { - let (stream, newContinuation) = AsyncThrowingStream.makeStream() - - guard continuation == nil, recognizerTask == nil, streamingMode == .inactive else { - newContinuation.finish(throwing: SpeechSessionError.recognitionStreamSetupFailed) - return stream - } - - let generation = beginStreamGeneration() - newContinuation.onTermination = { [weak self] _ in - Task { @MainActor [weak self] in - await self?.handleStreamTermination(generation: generation) - } - } - - setStatus(.preparing) - continuation = .speech(newContinuation) - - pipelineTask = Task { @MainActor [weak self] in - guard let self else { return } - await self.startFilePipeline( - with: newContinuation, + startFileTranscription { session, continuation, generation in + await session.startFilePipeline( + with: continuation, audioFileURL: audioFile, options: options, progressHandler: progressHandler, generation: generation ) } - - return stream } /// Convenience wrapper that collects final results from file transcription. @@ -125,6 +105,7 @@ public extension SpeechSession { } let finalResults = try await stream.reduce(into: [SpeechTranscriber.Result](), accumulator) + try Task.checkCancellation() return finalResults } } @@ -152,33 +133,21 @@ private extension SpeechSession { generation: generation ) try Task.checkCancellation() - let handler = progressHandler - fileIngestionTask = Task { [weak self] in - guard let self else { return } - - do { - let completed = try await self.feedAudioFile(validation, progressHandler: handler) - - if completed, let handler { - await MainActor.run { - handler(1.0) - } - } - } catch is CancellationError { - // Swallow cancellation triggered by cleanup. - } catch { - await self.finishWithStartupError(error, generation: generation) + startFileIngestion(generation: generation) { session in + let completed = try await session.feedAudioFile( + validation, progressHandler: progressHandler, generation: generation + ) + if completed, let progressHandler { + session.reportFileProgress(1.0, handler: progressHandler, generation: generation) } } } catch is CancellationError { - pipelineTask = nil - await finishCancelledPipelineSetup(generation: generation) + await finishFailedPipelineSetup(CancellationError(), generation: generation) } catch { if Self.shouldLog(.error) { Self.logger.error("File transcription pipeline failed: \(error.localizedDescription, privacy: .public)") } - pipelineTask = nil - await finishWithStartupError(error, generation: generation) + await finishFailedPipelineSetup(error, generation: generation) } } @@ -215,7 +184,9 @@ private extension SpeechSession { return (audioFile, totalFrames) } +} +extension SpeechSession { func sanitizeAudioFileURL( _ url: URL, allowedDirectories: [URL] @@ -249,6 +220,7 @@ private extension SpeechSession { with streamContinuation: AsyncThrowingStream.Continuation, contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]?, startAnalyzerImmediately: Bool, + mode: StreamingMode = .filePlayback, generation: Int ) async throws { if Self.shouldLog(.notice) { @@ -268,22 +240,25 @@ private extension SpeechSession { generation: generation ) - streamingMode = .filePlayback + streamingMode = mode setStatus(.transcribing) if Self.shouldLog(.info) { Self.logger.info("File transcription pipeline active (mode: file playback)") } } +} +extension SpeechSession { nonisolated func feedAudioFile( _ payload: (file: AVAudioFile, totalFrames: AVAudioFramePosition), - progressHandler: (@Sendable (Double) -> Void)? + progressHandler: (@Sendable (Double) -> Void)?, + generation: Int ) 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) + return try await feedAudioFileWithNativeAnalyzer(payload.file, generation: generation) } #endif @@ -300,8 +275,7 @@ private extension SpeechSession { while processedFrames < totalFrames { if Task.isCancelled { break } - let framesRemaining = AVAudioFrameCount(totalFrames - processedFrames) - let framesToRead = min(frameCapacity, framesRemaining) + let framesToRead = AVAudioFrameCount(min(Int64(frameCapacity), totalFrames - processedFrames)) buffer.frameLength = framesToRead @@ -312,7 +286,7 @@ private extension SpeechSession { } if buffer.frameLength == 0 { - break + throw SpeechSessionError.audioFileReadFailed(CocoaError(.fileReadCorruptFile)) } guard let bufferCopy = buffer.copy() as? AVAudioPCMBuffer else { @@ -321,25 +295,26 @@ private extension SpeechSession { let sendableBuffer = SendablePCMBuffer(buffer: bufferCopy) - try await self.processAudioBuffer(sendableBuffer) + try await processAudioBuffer(sendableBuffer, generation: generation) processedFrames += AVAudioFramePosition(buffer.frameLength) if let progressHandler, totalFrames > 0 { let progress = min(1.0, max(0.0, Double(processedFrames) / Double(totalFrames))) - await MainActor.run { - progressHandler(progress) - } + await reportFileProgress(progress, handler: progressHandler, generation: generation) } } guard !Task.isCancelled else { return false } - try await self.finishAnalyzerInput() + try await finishFileInput(generation: generation) return !Task.isCancelled && processedFrames >= totalFrames } +} + +private extension SpeechSession { func shouldUseNativeFileAnalyzer(progressHandler: (@Sendable (Double) -> Void)?) -> Bool { #if swift(>=6.4) if #available(iOS 27.0, macOS 27.0, *) { @@ -348,5 +323,76 @@ private extension SpeechSession { #endif return false } +} +extension SpeechSession { + typealias FileResultContinuation = AsyncThrowingStream.Continuation + + func startFileTranscription( + mode: StreamingMode = .filePlayback, + _ setup: @escaping @MainActor (SpeechSession, FileResultContinuation, Int) async -> Void + ) -> AsyncThrowingStream { + let (stream, newContinuation) = AsyncThrowingStream.makeStream() + guard continuation == nil, recognizerTask == nil, streamingMode == .inactive else { + newContinuation.finish(throwing: SpeechSessionError.recognitionStreamSetupFailed) + return stream + } + + let generation = beginStreamGeneration() + newContinuation.onTermination = { [weak self] termination in + guard case .cancelled = termination else { return } + Task { @MainActor [weak self] in + await self?.handleStreamTermination(generation: generation) + } + } + if mode == .mediaPlayback { streamingMode = mode } + setStatus(.preparing) + continuation = .speech(newContinuation) + pipelineTask = Task { @MainActor [weak self] in + guard let self else { return } + await setup(self, newContinuation, generation) + } + return stream + } + + func startFileIngestion( + generation: Int, + _ ingest: @escaping @MainActor (SpeechSession) async throws -> Void + ) { + fileIngestionTask = Task { [weak self] in + guard let self else { return } + do { + try await ingest(self) + try Task.checkCancellation() + guard generation == sessionGeneration, continuation != nil else { return } + fileIngestionCompleted = true + if fileResultsCompleted { + await endTranscription(error: nil, generation: generation, cancelRecognizer: false) + } + } catch is CancellationError { + // Only an existing terminal owner may suppress child cancellation. + await finishWithStartupError(CancellationError(), generation: generation) + } catch { + await finishWithStartupError(error, generation: generation) + } + } + } + + func finishFileInput(generation: Int) async throws { + try Task.checkCancellation() + guard generation == sessionGeneration else { throw CancellationError() } + if try await !finishAnalyzerInput() { + await finishWithoutInput(generation: generation) + } + } + + func reportFileProgress( + _ progress: Double, + handler: @Sendable (Double) -> Void, + generation: Int + ) { + guard !Task.isCancelled, generation == sessionGeneration, + streamingMode == .filePlayback, status == .transcribing else { return } + handler(progress) + } } diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift new file mode 100644 index 0000000..69f2e8c --- /dev/null +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -0,0 +1,143 @@ +#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, generation in + await session.startMediaFilePipeline( + mediaFile, audioTrackID: audioTrackID, options: options, + continuation: continuation, generation: generation + ) + } + } +} + +@available(iOS 27.0, macOS 27.0, *) +private extension SpeechSession { + func startMediaFilePipeline( + _ mediaFile: URL, + audioTrackID: CMPersistentTrackID?, + options: FileTranscriptionOptions, + continuation: FileResultContinuation, + generation: Int + ) async { + do { + try Task.checkCancellation() + 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 Task.checkCancellation() + try await ensureSpeechRecognitionAuthorization(context: "for media file transcription") + try Task.checkCancellation() + try await setUpFilePipeline( + with: continuation, + contextualStrings: options.contextualStrings, + startAnalyzerImmediately: false, + mode: .mediaPlayback, + generation: generation + ) + try Task.checkCancellation() + guard let analyzer, let activeModules else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: activeModules) else { + throw SpeechSessionError.invalidAudioDataType + } + try Task.checkCancellation() + let provider = AssetInputSequenceProvider(asset: asset, track: track, analyzerFormat: format) + let inputs = provider.analyzerInputs + startFileIngestion(generation: generation) { session in + try await session.prepareAnalyzerForStartIfNeeded(in: format) + try Task.checkCancellation() + session.startSpeechDetectorMonitoringIfNeeded() + + let endTime = try await analyzer.analyzeSequence(inputs) + try Task.checkCancellation() + if let endTime { + try await analyzer.finalizeAndFinish(through: endTime) + } else { + // With no input samples, Speech may leave the module's results stream open. + await session.finishWithoutInput(generation: generation) + } + } + } catch { + await finishFailedPipelineSetup(error, generation: generation) + } + } + + 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 858f92d..0f28e52 100644 --- a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift @@ -61,6 +61,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 } @@ -77,13 +79,15 @@ extension SpeechSession { try Task.checkCancellation() let analyzerInputs = provider.analyzerInputs - nativeCaptureAnalysisTask = Task { [weak self, analyzer, analyzerInputs] in + nativeCaptureAnalysisTask = Task { [weak 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() + await self?.finishWithoutInput(generation: generation) } } catch is CancellationError { // Cancellation is expected during explicit cleanup. @@ -130,7 +134,7 @@ extension SpeechSession { func finishFromNativeCaptureAnalysis(_ error: Error, generation: Int) async { guard generation == sessionGeneration else { return } nativeCaptureAnalysisTask = nil - await finishFromRecognizerTask(error: error, generation: generation) + await endTranscription(error: error, generation: generation) } } #endif diff --git a/Sources/AuralKit/SpeechSession+NativeFileInput.swift b/Sources/AuralKit/SpeechSession+NativeFileInput.swift index a412ba2..a8d5c60 100644 --- a/Sources/AuralKit/SpeechSession+NativeFileInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeFileInput.swift @@ -15,24 +15,28 @@ extension SpeechSession { nonisolated func feedAudioFileWithNativeAnalyzer( _ file: AVAudioFile, - progressHandler _: (@Sendable (Double) -> Void)? + generation: Int ) async throws -> Bool { guard !Task.isCancelled else { return false } - guard let analyzer = await MainActor.run(body: { analyzer }) else { + guard let analyzer = await MainActor.run(body: { generation == sessionGeneration ? analyzer : nil }) else { throw SpeechSessionError.recognitionStreamSetupFailed } try await prepareAnalyzerForStartIfNeeded(in: file.processingFormat) + try Task.checkCancellation() await MainActor.run { + guard !Task.isCancelled, generation == sessionGeneration else { return } startSpeechDetectorMonitoringIfNeeded() } + try Task.checkCancellation() let lastAudioTime = try await analyzer.analyzeSequence(from: file) + try Task.checkCancellation() if let lastAudioTime { try await analyzer.finalizeAndFinish(through: lastAudioTime) } else { - try await analyzer.finalizeAndFinishThroughEndOfInput() + await finishWithoutInput(generation: generation) } return !Task.isCancelled diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 9025f0c..f77fe75 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -52,7 +52,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) } } @@ -78,6 +78,8 @@ extension SpeechSession { /// session moved on to another stream) cannot tear down state it no longer owns. func beginStreamGeneration() -> Int { sessionGeneration &+= 1 + fileIngestionCompleted = false + fileResultsCompleted = false return sessionGeneration } @@ -86,10 +88,7 @@ extension SpeechSession { /// Runs only when the terminating stream is still the current one; stale handlers /// (from streams that were already replaced or finished) are ignored. func handleStreamTermination(generation: Int) async { - guard generation == sessionGeneration else { return } - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: nil, generation: generation) + await endTranscription(error: CancellationError(), generation: generation) } var isPausableStreamingMode: Bool { @@ -108,7 +107,7 @@ extension SpeechSession { try Task.checkCancellation() try await ensurePermissions() try Task.checkCancellation() - try await setupAudioSession() + try setupAudioSession() try Task.checkCancellation() let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider @@ -140,14 +139,12 @@ extension SpeechSession { Self.logger.info("Pipeline started (mode: live microphone)") } } catch is CancellationError { - pipelineTask = nil - await finishCancelledPipelineSetup(generation: generation) + await finishFailedPipelineSetup(CancellationError(), generation: generation) } catch { if Self.shouldLog(.error) { Self.logger.error("Pipeline setup failed: \(error.localizedDescription, privacy: .public)") } - pipelineTask = nil - await finishWithStartupError(error, generation: generation) + await finishFailedPipelineSetup(error, generation: generation) } } @@ -163,21 +160,23 @@ extension SpeechSession { try Task.checkCancellation() try await ensurePermissions() try Task.checkCancellation() - try await setupAudioSession() + try setupAudioSession() try Task.checkCancellation() let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider - let transcriber = try await setUpDictationTranscriber( + let prepared = try await setUpDictationTranscriber( contextualStrings: contextualStrings, startAnalyzerImmediately: !shouldUseNativeCapture ) + defer { withExtendedLifetime(prepared.artifacts) {} } try Task.checkCancellation() if Self.shouldLog(.info) { Self.logger.info("Dictation transcriber prepared with modules") } recognizerTask = createDictationRecognizerTask( - transcriber: transcriber, + transcriber: prepared.transcriber, + vocabularyArtifacts: prepared.artifacts, streamContinuation: streamContinuation, generation: generation ) @@ -195,65 +194,141 @@ extension SpeechSession { Self.logger.info("Dictation pipeline started (mode: live microphone)") } } catch is CancellationError { - pipelineTask = nil - await finishCancelledPipelineSetup(generation: generation) + await finishFailedPipelineSetup(CancellationError(), generation: generation) } catch { if Self.shouldLog(.error) { Self.logger.error("Dictation pipeline setup failed: \(error.localizedDescription, privacy: .public)") } - pipelineTask = nil - await finishWithStartupError(error, generation: generation) + await finishFailedPipelineSetup(error, generation: generation) } } - /// Unwind a pipeline whose setup task was cancelled by `cleanup` (stop or stream termination). - /// - /// The canceller already ran `cleanup`, but this task may have created additional state - /// (transcriber, analyzer, audio taps) after that cleanup finished, so run it once more. - /// `finishStream` is a no-op when the canceller already finished the stream, and both steps - /// are skipped when a newer stream generation owns the session state. - func finishCancelledPipelineSetup(generation: Int) async { + func finishFailedPipelineSetup(_ error: Error, generation: Int) async { + guard generation == sessionGeneration, terminationTask == nil else { return } + pipelineTask = nil + guard finishTask == nil || !Task.isCancelled else { return } + await finishWithStartupError(error, generation: generation) + } + + func finishWithStartupError(_ error: Error, generation: Int) async { + guard generation == sessionGeneration, terminationTask == nil else { return } + await endTranscription(error: Task.isCancelled ? CancellationError() : error, generation: generation) + } + + func finishFromRecognizerTask(error: Error?, generation: Int) async { guard generation == sessionGeneration else { return } - if Self.shouldLog(.debug) { - Self.logger.debug("Pipeline setup cancelled; unwinding") + if error == nil, streamingMode == .filePlayback || streamingMode == .mediaPlayback { + fileResultsCompleted = true + guard fileIngestionCompleted else { return } } - await cleanup(cancelRecognizer: true, generation: generation) - guard generation == sessionGeneration else { return } - await finishStream(error: nil, generation: generation) + await endTranscription(error: error, generation: generation, cancelRecognizer: error != nil) } - func finishWithStartupError(_ error: Error, generation: Int) async { + func finishWithoutInput(generation: Int) async { + await endTranscription(error: nil, generation: generation) + } + + func finishTranscribing(generation: Int, sourceEnded: Bool = false) async { guard generation == sessionGeneration else { return } - // A cancelled setup task means another teardown already owns the stream; unwind - // quietly instead of surfacing a spurious error to a stream that was stopped on purpose. - if Task.isCancelled { - await finishCancelledPipelineSetup(generation: generation) + if let terminationTask { + await terminationTask.value + return + } + if let finishTask { + await finishTask.value return } - if Self.shouldLog(.error) { - Self.logger.error("Finishing due to startup error: \(error.localizedDescription, privacy: .public)") + guard let recognizerTask, sourceEnded || status != .preparing else { + await endTranscription(error: nil, generation: generation) + return + } + if streamingMode == .filePlayback || streamingMode == .mediaPlayback { + await pipelineTask?.value + guard generation == sessionGeneration else { return } + await fileIngestionTask?.value + await recognizerTask.value + return + } + + if status == .preparing { + // Picker teardown can resume its pending selection with a cancellation error. + pipelineTask?.cancel() } prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: error, generation: generation) + let screenStop = beginStoppingScreenCapture() + let task = Task { + await finishLiveTranscription(results: recognizerTask, screenStop: screenStop, generation: generation) + } + finishTask = task + await task.value } - func finishFromRecognizerTask(error: Error?, generation: Int) async { + private func finishLiveTranscription( + results: Task, + screenStop: Task?, + generation: Int + ) async { guard generation == sessionGeneration else { return } - if let error { - if Self.shouldLog(.error) { - Self.logger.error( - "Finishing from recognizer with error: \(error.localizedDescription, privacy: .public)" - ) - } + if let terminationTask { + await terminationTask.value + return + } + guard continuation != nil else { return } + stopAudioStreaming() + if let nativeCaptureAnalysisTask { + // The provider's sequence reaches EOF when its audio data output is deallocated. + nativeCaptureSession = nil + await nativeCaptureAnalysisTask.value } else { - if Self.shouldLog(.notice) { - Self.logger.notice("Finishing from recognizer without error") + do { + try await screenStop?.value + guard generation == sessionGeneration else { return } + if let terminationTask { + await terminationTask.value + return + } + guard continuation != nil else { return } + if try await !finishAnalyzerInput() { + await finishWithoutInput(generation: generation) + } + } catch { + await endTranscription(error: error, generation: generation) + return } } + + await results.value + } + + func endTranscription( + error: Error?, + generation: Int, + cancelRecognizer: Bool = true, + requestedByCaller: Bool = false + ) async { + guard generation == sessionGeneration else { return } + if requestedByCaller, continuation != nil { cancellationRequested = true } + if let terminationTask { + await terminationTask.value + return + } + guard continuation != nil || pipelineTask != nil || status != .idle || streamingMode != .inactive else { + return + } prepareForStop() - await cleanup(cancelRecognizer: false, generation: generation) - await finishStream(error: error, generation: generation) + pipelineTask?.cancel() + let screenStop = beginStoppingScreenCapture() + let task = Task { + await cleanup(cancelRecognizer: cancelRecognizer, screenStop: screenStop, generation: generation) + guard generation == sessionGeneration else { return } + let terminalError = cancellationRequested ? CancellationError() : error + cancellationRequested = false + finishTask = nil + terminationTask = nil + finishStream(error: terminalError, generation: generation) + } + terminationTask = task + await task.value } /// Tear down the active pipeline. @@ -263,7 +338,11 @@ extension SpeechSession { /// slow finalization steps then operate on the detached references. Steps that touch shared /// state after a suspension re-check `generation` so a stale teardown cannot damage a newer /// session. - func cleanup(cancelRecognizer: Bool, generation: Int) async { + func cleanup( + cancelRecognizer: Bool, + screenStop: Task? = nil, + generation: Int + ) async { guard generation == sessionGeneration else { return } if Self.shouldLog(.debug) { Self.logger.debug("Cleanup started (cancelRecognizer: \(cancelRecognizer, privacy: .public))") @@ -297,8 +376,9 @@ extension SpeechSession { shouldResumeAfterInterruption = false #endif let detached = detachTranscriberState() - await stopScreenCaptureStreamingIfNeeded() - await finalizeDetachedTranscriberState(detached) + await cleanUpDetachedTranscriberState(detached, cancelAnalyzer: cancelRecognizer) + _ = await screenStop?.result + if screenCaptureStopTask?.generation == generation { screenCaptureStopTask = nil } guard generation == sessionGeneration else { return } await modelManager.releaseLocales() @@ -314,7 +394,7 @@ extension SpeechSession { /// /// Generation-guarded so a teardown belonging to an older stream can never finish (or /// error out) the stream of a session that has since started. - func finishStream(error: Error?, generation: Int) async { + func finishStream(error: Error?, generation: Int) { guard generation == sessionGeneration else { return } guard let continuation else { return } self.continuation = nil @@ -353,18 +433,16 @@ extension SpeechSession { // MARK: - Helper Methods - func setupAudioSession() async throws { + func setupAudioSession() throws { #if os(iOS) - try await MainActor.run { - let audioSession = AVAudioSession.sharedInstance() - try audioSession.setCategory( - audioConfig.category, - mode: audioConfig.mode, - options: audioConfig.options - ) - try audioSession.setActive(true) - isAudioSessionActive = true - } + let audioSession = AVAudioSession.sharedInstance() + try audioSession.setCategory( + audioConfig.category, + mode: audioConfig.mode, + options: audioConfig.options + ) + try audioSession.setActive(true) + isAudioSessionActive = true #endif #if os(iOS) || os(macOS) publishCurrentAudioInputInfo() @@ -406,31 +484,37 @@ extension SpeechSession { private func createDictationRecognizerTask( transcriber: DictationTranscriber, + vocabularyArtifacts: CustomVocabularyArtifacts?, streamContinuation: AsyncThrowingStream.Continuation, generation: Int ) -> Task { createRecognizerTask( label: "Dictation recognizer task", + vocabularyArtifacts: vocabularyArtifacts, results: transcriber.results, streamContinuation: streamContinuation, generation: generation ) } - private func createRecognizerTask( + func createRecognizerTask( label: String, + vocabularyArtifacts: CustomVocabularyArtifacts? = nil, results: Sequence, streamContinuation: AsyncThrowingStream.Continuation, generation: Int ) -> Task where Sequence: Sendable, Sequence.Element: Sendable { - Task { [weak self] in - guard let self else { return } + Task { [self, vocabularyArtifacts] in + // Retain the session before the first turn so EOF can still retire the analyzer. + defer { withExtendedLifetime(vocabularyArtifacts) {} } do { for try await result in results { + guard generation == sessionGeneration, terminationTask == nil else { return } streamContinuation.yield(result) } + try Task.checkCancellation() if Self.shouldLog(.notice) { Self.logger.notice("\(label, privacy: .public) completed without error") } @@ -439,6 +523,7 @@ extension SpeechSession { if Self.shouldLog(.debug) { Self.logger.debug("\(label, privacy: .public) cancelled") } + await self.finishFromRecognizerTask(error: CancellationError(), generation: generation) } catch { if Self.shouldLog(.error) { Self.logger.error( diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index e6432fc..6a5e467 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -1,10 +1,51 @@ import AVFoundation import CoreMedia import Foundation +import OSLog import Speech +import Synchronization // swiftlint:disable file_length +@MainActor +extension SpeechSession { + func resumeScreenCaptureStreamingIfNeeded(generation: Int) async throws { + guard generation == sessionGeneration, status == .paused, streamingMode == .screenCapture else { return } + var captureFailure: Error? + var terminalFailure: Error? + do { +#if canImport(ScreenCaptureKit) + guard #available(iOS 27.0, macOS 14.0, *) else { + throw SpeechSessionError.screenCaptureUnavailable + } + guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { + throw SpeechSessionError.recognitionStreamSetupFailed + } + terminalFailure = await provider.resume { result in + guard generation == self.sessionGeneration, + 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 captureFailure { throw captureFailure } +#else + throw SpeechSessionError.screenCaptureUnavailable +#endif + } catch { + let canFinish = status == .paused || (captureFailure != nil && status == .stopping) + guard generation == sessionGeneration, canFinish, streamingMode == .screenCapture else { throw error } + await endTranscription(error: error, generation: generation) + throw error + } + if let terminalFailure { throw terminalFailure } + } +} + #if canImport(ScreenCaptureKit) @preconcurrency import ScreenCaptureKit @@ -26,9 +67,8 @@ public extension SpeechSession { /// Start transcribing audio from content selected with ScreenCaptureKit's system picker. /// /// Screen capture transcription is available on platforms where ScreenCaptureKit can stream - /// audio as `CMSampleBuffer` values. AuralKit configures the stream for audio capture, converts - /// incoming audio samples into analyzer-compatible `AVAudioPCMBuffer`s, and emits normal - /// `SpeechTranscriber.Result` values. + /// audio as `CMSampleBuffer` values. AuralKit supplies analyzer-compatible audio to Speech + /// and emits normal `SpeechTranscriber.Result` values. /// /// Apps using this API must include `NSScreenCaptureUsageDescription` in their Info.plist. /// @@ -48,7 +88,8 @@ public extension SpeechSession { } let generation = beginStreamGeneration() - newContinuation.onTermination = { [weak self] _ in + newContinuation.onTermination = { [weak self] termination in + guard case .cancelled = termination else { return } Task { @MainActor [weak self] in await self?.handleStreamTermination(generation: generation) } @@ -111,6 +152,7 @@ extension SpeechSession { ) try await setUpScreenCaptureStreaming(options: options, generation: generation) try Task.checkCancellation() + guard status == .preparing else { return } streamingMode = .screenCapture setStatus(.transcribing) @@ -119,14 +161,12 @@ extension SpeechSession { Self.logger.info("Pipeline started (mode: screen capture)") } } catch is CancellationError { - pipelineTask = nil - await finishCancelledPipelineSetup(generation: generation) + await finishFailedPipelineSetup(CancellationError(), generation: generation) } catch { if Self.shouldLog(.error) { Self.logger.error("Screen capture pipeline failed: \(error.localizedDescription, privacy: .public)") } - pipelineTask = nil - await finishWithStartupError(error, generation: generation) + await finishFailedPipelineSetup(error, generation: generation) } } @@ -139,9 +179,14 @@ extension SpeechSession { options: options, targetFormat: analyzerFormat, inputContinuation: inputBuilder, - onFailure: { [weak self] error in + useNativeConversion: inputProviderPreference == .automatic, + onTermination: { [weak self] error in Task { @MainActor [weak self] in - await self?.finishFromRecognizerTask(error: error, generation: generation) + if let error { + await self?.endTranscription(error: error, generation: generation) + } else { + await self?.finishTranscribing(generation: generation, sourceEnded: true) + } } } ) @@ -152,66 +197,175 @@ extension SpeechSession { @MainActor extension SpeechSession { - func pauseScreenCaptureStreamingIfNeeded() async { + func pauseScreenCaptureStreamingIfNeeded(generation: Int) async { + guard generation == sessionGeneration else { return } guard #available(iOS 27.0, macOS 14.0, *) else { return } guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { return } - await provider.pause() + guard await provider.pause(), generation == sessionGeneration, + status == .transcribing, streamingMode == .screenCapture else { return } + setStatus(.paused) } - func resumeScreenCaptureStreamingIfNeeded() async throws { - guard #available(iOS 27.0, macOS 14.0, *) else { - throw SpeechSessionError.screenCaptureUnavailable + func beginStoppingScreenCapture() -> Task? { + let generation = sessionGeneration + if let pending = screenCaptureStopTask, pending.generation == generation { + return pending.task } - guard let provider = screenCaptureInputProvider as? ScreenCaptureAudioInputProvider else { - throw SpeechSessionError.recognitionStreamSetupFailed + let detachedProvider = screenCaptureInputProvider + screenCaptureInputProvider = nil + guard #available(iOS 27.0, macOS 14.0, *) else { return nil } + guard let provider = detachedProvider as? ScreenCaptureAudioInputProvider else { return nil } + let task = provider.stop() + screenCaptureStopTask = (generation, task) + return task + } +} + +// 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. +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 } - try await provider.resume() } - func stopScreenCaptureStreamingIfNeeded() async { - // Detach synchronously so concurrent teardowns or a subsequent session never observe - // a provider that is already being stopped. - let detachedProvider = screenCaptureInputProvider - screenCaptureInputProvider = nil + @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 } + } +} - guard #available(iOS 27.0, macOS 14.0, *) else { return } - guard let provider = detachedProvider as? ScreenCaptureAudioInputProvider else { return } - await provider.stop() +@available(iOS 27.0, macOS 14.0, *) +@MainActor +private final class NativeScreenCaptureStream: ScreenCaptureStream { + let stream: SCStream + private let audio: ScreenCaptureAudioProcessor + private let stopErrors: ScreenCaptureStopErrors + + init(stream: SCStream, audio: ScreenCaptureAudioProcessor, stopErrors: ScreenCaptureStopErrors) { + self.stream = stream + 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 stopCapture() async throws { + 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 } } @available(iOS 27.0, macOS 14.0, *) -private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamDelegate, +final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamDelegate, SCContentSharingPickerObserver, @unchecked Sendable { 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() - private var stream: SCStream? + @MainActor private let transitions: ScreenCaptureTransitions + @MainActor private var terminalCleanupTask: Task? + private let dismissPicker: @MainActor (any SCContentSharingPickerObserver) -> Void private var selectionContinuation: CheckedContinuation? - private var isRunning = false - private var intentionallyStoppingStreams = Set() + private var stopped = false + 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(), + dismissPicker: @escaping @MainActor (any SCContentSharingPickerObserver) -> Void = { observer in + let picker = SCContentSharingPicker.shared + picker.isActive = false + picker.remove(observer) + } ) { 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.dismissPicker = dismissPicker super.init() } @MainActor func start() async throws { + try Task.checkCancellation() + guard !stopped else { throw CancellationError() } let picker = SCContentSharingPicker.shared let configuration = SCContentSharingPickerConfiguration() picker.configuration = configuration @@ -223,42 +377,48 @@ private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, S selectionContinuation = continuation picker.present() } + try Task.checkCancellation() } @MainActor - func pause() async { - guard isRunning, let stream else { return } - markStreamForIntentionalStop(stream) - try? await stream.stopCapture() - isRunning = false + 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 resume() async throws { - guard !isRunning, let stream else { - throw SpeechSessionError.recognitionStreamSetupFailed - } - try await stream.startCapture() - isRunning = true + 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 { - let picker = SCContentSharingPicker.shared - picker.isActive = false - picker.remove(self) - - if let selectionContinuation { - selectionContinuation.resume(throwing: SpeechSessionError.screenCaptureSelectionCancelled) - self.selectionContinuation = nil - } - - if isRunning, let stream { - markStreamForIntentionalStop(stream) - try? await stream.stopCapture() + func stop() -> Task { + stopped = true + let operation = transitions.stop() + dismissPicker(self) + resumeSelection(throwing: SpeechSessionError.screenCaptureSelectionCancelled) + return Task { + do { + try await operation.value + } catch { + audio.discard() + if let drainFailure = error as? ScreenCaptureDrainFailure { + throw SpeechSessionError.screenCaptureFailed(drainFailure.underlyingError) + } + throw error + } } - stream = nil - isRunning = false } func contentSharingPicker( @@ -267,15 +427,28 @@ private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, S for stream: SCStream? ) { nonisolated(unsafe) let selectedFilter = filter + nonisolated(unsafe) let updatedStream = stream Task { @MainActor [weak self] in - guard let self else { return } - do { - try await beginCapture(with: selectedFilter) - resumeSelection() - } catch { - if !resumeSelection(throwing: error) { - onFailure(SpeechSessionError.screenCaptureFailed(error)) - } + guard let self, !self.stopped else { return } + if let updatedStream { + 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 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) } } } @@ -291,63 +464,72 @@ private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, S 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) else { return } - self.isRunning = false - 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 + return Task { @MainActor in + 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)) } } @MainActor - private func beginCapture(with filter: SCContentFilter) async throws { - if isRunning, let stream { - markStreamForIntentionalStop(stream) - try await stream.stopCapture() - isRunning = false + private func observeSelection(_ operation: Task) -> Task { + let id = UUID() + pickerUpdateID = id + return Task { @MainActor in + do { + try await operation.value + guard !self.stopped, self.pickerUpdateID == id else { return } + self.resumeSelection() + } catch { + guard !self.stopped, self.pickerUpdateID == id else { return } + 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)) + } + } } - - 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: filter, configuration: streamConfiguration, delegate: self) - try captureStream.addStreamOutput(self, type: .audio, sampleHandlerQueue: sampleQueue) - self.stream = captureStream - try await captureStream.startCapture() - isRunning = true } @discardableResult @@ -363,36 +545,28 @@ private final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, S 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 @@ -417,14 +591,11 @@ public extension SpeechSession { @MainActor extension SpeechSession { - func pauseScreenCaptureStreamingIfNeeded() async {} - - func resumeScreenCaptureStreamingIfNeeded() async throws { - throw SpeechSessionError.screenCaptureUnavailable - } + func pauseScreenCaptureStreamingIfNeeded(generation: Int) async {} - func stopScreenCaptureStreamingIfNeeded() async { + func beginStoppingScreenCapture() -> Task? { screenCaptureInputProvider = nil + return nil } } #endif diff --git a/Sources/AuralKit/SpeechSession+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index e2d5f2e..81eb1d5 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. @@ -13,6 +14,8 @@ extension SpeechSession { // MARK: - Transcriber Setup and Cleanup + typealias PreparedDictation = (transcriber: DictationTranscriber, artifacts: CustomVocabularyArtifacts?) + func setUpSpeechTranscriber( contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil, startAnalyzerImmediately: Bool = true @@ -37,13 +40,17 @@ extension SpeechSession { func setUpDictationTranscriber( contextualStrings: [AnalysisContext.ContextualStringsTag: [String]]? = nil, startAnalyzerImmediately: Bool = true - ) async throws -> DictationTranscriber { + ) async throws -> PreparedDictation { if Self.shouldLog(.notice) { Self.logger.notice("Setting up dictation transcriber") } - let transcriber = try createDictationTranscriber() - let modules = configureModules(transcriber: transcriber) + let generation = sessionGeneration + let prepared = try await createDictationTranscriber() + defer { withExtendedLifetime(prepared.artifacts) {} } + try Task.checkCancellation() + guard generation == sessionGeneration else { throw CancellationError() } + let modules = configureModules(transcriber: prepared.transcriber) try await ensureModels(modules: modules) try Task.checkCancellation() try await configureAnalyzerContext(contextualStrings: contextualStrings) @@ -52,7 +59,7 @@ extension SpeechSession { try await startAnalyzer(modules: modules) } - return transcriber + return prepared } private func createSpeechTranscriber() throws -> SpeechTranscriber { @@ -74,7 +81,18 @@ extension SpeechSession { return transcriber } - private func createDictationTranscriber() throws -> DictationTranscriber { + func createDictationTranscriber() async throws -> PreparedDictation { + if let descriptor = customVocabularyDescriptor, !customVocabularyFilesExist { + let generation = sessionGeneration + let requestID = customVocabularyRequestID + let compilation = try await compileCustomVocabulary(descriptor) + try Task.checkCancellation() + guard generation == sessionGeneration, 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 @@ -85,6 +103,7 @@ extension SpeechSession { reportingOptions.insert(.frequentFinalization) } + activeCustomVocabularyArtifacts = customVocabularyArtifacts dictationTranscriber = DictationTranscriber( locale: locale, contentHints: contentHints, @@ -97,7 +116,7 @@ extension SpeechSession { throw SpeechSessionError.recognitionStreamSetupFailed } - return dictationTranscriber + return (dictationTranscriber, activeCustomVocabularyArtifacts) } @discardableResult @@ -194,6 +213,7 @@ extension SpeechSession { guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: modules) else { throw SpeechSessionError.invalidAudioDataType } + try Task.checkCancellation() analyzerFormat = format if Self.shouldLog(.debug) { @@ -213,8 +233,11 @@ extension SpeechSession { } try await prepareAnalyzerForStartIfNeeded(in: format) + try Task.checkCancellation() - try await analyzer.start(inputSequence: inputSequence) + startAnalyzingInput(generation: sessionGeneration) { + try await analyzer.analyzeSequence(inputSequence) + } if Self.shouldLog(.info) { Self.logger.info("Analyzer started") } @@ -222,7 +245,25 @@ extension SpeechSession { startSpeechDetectorMonitoringIfNeeded() } - func processAudioBuffer(_ buffer: SendablePCMBuffer) async throws { + func startAnalyzingInput( + generation: Int, + analyze: @escaping @MainActor () async throws -> CMTime? + ) { + analyzerInputTask = Task { [weak self] in + do { + return try await analyze() + } catch { + if !Task.isCancelled { + await self?.endTranscription(error: error, generation: generation) + } + throw error + } + } + } + + func processAudioBuffer(_ buffer: SendablePCMBuffer, generation: Int) async throws { + try Task.checkCancellation() + guard generation == sessionGeneration else { throw CancellationError() } guard let inputBuilder, let analyzerFormat else { throw SpeechSessionError.invalidAudioDataType } @@ -231,18 +272,24 @@ extension SpeechSession { from: buffer, analyzerFormat: analyzerFormat ) + try Task.checkCancellation() inputBuilder.yield(input) } - func finishAnalyzerInput() async throws { + func finishAnalyzerInput() async throws -> Bool { inputBuilder?.finish() - try await analyzer?.finalizeAndFinishThroughEndOfInput() + 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 finalization. + /// State captured by `detachTranscriberState()` for asynchronous cleanup. struct DetachedTranscriberState { let inputBuilder: AsyncStream.Continuation? let analyzer: SpeechAnalyzer? + let vocabularyArtifacts: CustomVocabularyArtifacts? } /// Synchronously clear all transcriber-related session state and return the pieces that @@ -254,7 +301,13 @@ extension SpeechSession { if Self.shouldLog(.debug) { Self.logger.debug("Stopping transcriber and cleaning up") } - let detached = DetachedTranscriberState(inputBuilder: inputBuilder, analyzer: analyzer) + analyzerInputTask?.cancel() + analyzerInputTask = nil + let detached = DetachedTranscriberState( + inputBuilder: inputBuilder, analyzer: analyzer, + vocabularyArtifacts: activeCustomVocabularyArtifacts + ) + activeCustomVocabularyArtifacts = nil tearDownSpeechDetectorStream() speechDetector = nil @@ -270,20 +323,9 @@ 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 { await detached.analyzer?.cancelAndFinishNow() } } } diff --git a/Sources/AuralKit/SpeechSession+Types.swift b/Sources/AuralKit/SpeechSession+Types.swift index a874707..6576642 100644 --- a/Sources/AuralKit/SpeechSession+Types.swift +++ b/Sources/AuralKit/SpeechSession+Types.swift @@ -18,6 +18,7 @@ extension SpeechSession { case inactive case liveMicrophone case filePlayback + case mediaPlayback case screenCapture } diff --git a/Sources/AuralKit/SpeechSession+VoiceActivation.swift b/Sources/AuralKit/SpeechSession+VoiceActivation.swift index cc93f31..ee1f117 100644 --- a/Sources/AuralKit/SpeechSession+VoiceActivation.swift +++ b/Sources/AuralKit/SpeechSession+VoiceActivation.swift @@ -28,6 +28,7 @@ extension SpeechSession { } func tearDownSpeechDetectorStream() { + speechDetectorMonitorID = nil speechDetectorResultsTask?.cancel() speechDetectorResultsTask = nil speechDetectorResultsContinuation?.finish() @@ -42,29 +43,26 @@ extension SpeechSession { func startSpeechDetectorMonitoring() { guard let detector = speechDetector else { return } + let monitorID = UUID() + speechDetectorMonitorID = monitorID speechDetectorResultsTask?.cancel() if Self.shouldLog(.debug) { Self.logger.debug("Starting speech detector monitoring") } - speechDetectorResultsTask = Task { [weak self] in + speechDetectorResultsTask = Task { @MainActor [weak self] in guard let self else { return } do { for try await result in detector.results { - await MainActor.run { - self.handleSpeechDetectorResult(result) - } + guard self.speechDetectorMonitorID == monitorID else { return } + self.handleSpeechDetectorResult(result) } } catch { let finalError = (error as? CancellationError) != nil ? nil : error - await MainActor.run { - self.handleSpeechDetectorStreamCompletion(error: finalError) - } + self.handleSpeechDetectorStreamCompletion(error: finalError, monitorID: monitorID) return } - await MainActor.run { - self.handleSpeechDetectorStreamCompletion(error: nil) - } + self.handleSpeechDetectorStreamCompletion(error: nil, monitorID: monitorID) if Self.shouldLog(.notice) { Self.logger.notice("Speech detector monitoring completed") } @@ -86,7 +84,9 @@ extension SpeechSession { } } - func handleSpeechDetectorStreamCompletion(error: Error?) { + func handleSpeechDetectorStreamCompletion(error: Error?, monitorID: UUID) { + guard speechDetectorMonitorID == monitorID else { return } + speechDetectorMonitorID = nil defer { speechDetectorResultsTask = nil } if let continuation = speechDetectorResultsContinuation { diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index 03c211c..51eec39 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 @@ -28,8 +29,7 @@ import Speech /// } /// ``` /// -/// Call `stopTranscribing()` to end capture and unwind the stream. The same instance may be reused -/// for subsequent transcription sessions. +/// Use `finishTranscribing()` to receive final results or `cancelTranscribing()` to abandon the run. @MainActor public final class SpeechSession { @@ -67,6 +67,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? @@ -74,11 +75,15 @@ public final class SpeechSession { var nativeCaptureSession: AVCaptureSession? var nativeCaptureAnalysisTask: Task? var screenCaptureInputProvider: AnyObject? + var screenCaptureStopTask: (generation: Int, task: Task)? var voiceActivationConfiguration: VoiceActivationConfiguration? var customVocabularyDescriptor: CustomVocabulary? var customVocabularyConfiguration: SFSpeechLanguageModel.Configuration? var customVocabularyCacheKey: String? var customVocabularyOutputDirectory: URL? + var customVocabularyArtifacts: CustomVocabularyArtifacts? + var activeCustomVocabularyArtifacts: CustomVocabularyArtifacts? + var customVocabularyRequestID: UUID? var activeResultKind: TranscriptionResultKind? // MARK: - Public Observables @@ -92,11 +97,14 @@ public final class SpeechSession { /// Reflects the speech detector's most recent state; defaults to `true` when monitoring is inactive. public internal(set) var isSpeechDetected: Bool = true - // Stream state management var continuation: TranscriptionContinuation? var recognizerTask: Task? var pipelineTask: Task? + var finishTask: Task? + var terminationTask: Task? + var cancellationRequested = false var fileIngestionTask: Task? + var fileIngestionCompleted = false, fileResultsCompleted = false var streamingMode: StreamingMode = .inactive /// Incremented for every accepted start so stale termination handlers can be ignored. var sessionGeneration: Int = 0 @@ -107,6 +115,7 @@ public final class SpeechSession { // Voice activation state var speechDetectorResultsContinuation: AsyncStream.Continuation? var speechDetectorResultsTask: Task? + var speechDetectorMonitorID: UUID? // MARK: - Init @@ -262,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, @@ -300,7 +309,8 @@ public final class SpeechSession { } let generation = beginStreamGeneration() - newContinuation.onTermination = { [weak self] _ in + newContinuation.onTermination = { [weak self] termination in + guard case .cancelled = termination else { return } Task { @MainActor [weak self] in await self?.handleStreamTermination(generation: generation) } @@ -340,18 +350,21 @@ public final class SpeechSession { public func startTranscribing( contextualStrings: [String] ) -> AsyncThrowingStream { - return startTranscribing(contextualStrings: [.general: contextualStrings]) + startTranscribing(contextualStrings: [.general: contextualStrings]) } - /// Stop capturing audio and finish the current transcription stream. + /// End live capture and deliver final results for audio already queued for analysis. /// - /// Safe to call even if `startTranscribing()` has not been invoked or the stream has already - /// completed; the method simply waits for cleanup and returns. - public func stopTranscribing() async { - let generation = sessionGeneration - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: nil, generation: generation) + /// Keep consuming the stream for final results and errors. Finish waits for active file + /// transcription to reach EOF and closes a preparing session without starting capture. + public func finishTranscribing() async { + await finishTranscribing(generation: sessionGeneration) + } + + /// Abort without finalizing pending audio. The result stream ends with `CancellationError`. + /// Results already yielded may still be read. + public func cancelTranscribing() async { + await endTranscription(error: CancellationError(), generation: sessionGeneration, requestedByCaller: true) } /// Pause capture without tearing down the analyzer pipeline. @@ -361,10 +374,9 @@ public final class SpeechSession { public func pauseTranscribing() async { guard status == .transcribing, isPausableStreamingMode else { return } if streamingMode == .screenCapture { - await pauseScreenCaptureStreamingIfNeeded() - } else { - stopAudioStreaming() + return await pauseScreenCaptureStreamingIfNeeded(generation: sessionGeneration) } + stopAudioStreaming() setStatus(.paused) } @@ -374,19 +386,15 @@ public final class SpeechSession { public func resumeTranscribing() async throws { guard status == .paused, isPausableStreamingMode else { return } let generation = sessionGeneration + if streamingMode == .screenCapture { + return try await resumeScreenCaptureStreamingIfNeeded(generation: generation) + } do { - if streamingMode == .screenCapture { - try await resumeScreenCaptureStreamingIfNeeded() - } else { - try startAudioStreaming() - } + try startAudioStreaming() setStatus(.transcribing) } catch { - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: error, generation: generation) + await endTranscription(error: error, generation: generation) throw error } } - } diff --git a/Tests/AuralKitTests/AuralKitTests.swift b/Tests/AuralKitTests/AuralKitTests.swift index 07a9833..b52533f 100644 --- a/Tests/AuralKitTests/AuralKitTests.swift +++ b/Tests/AuralKitTests/AuralKitTests.swift @@ -36,11 +36,12 @@ struct SpeechSessionStateTests { #expect(session.analyzerConfiguration == configuration) } - @Test("Stop transcribing without session is a no-op") + @Test("Finish and Cancel without a session are no-ops") @MainActor - func stopTranscribingWithoutSessionIsNoOp() async { + func endingTranscriptionWithoutSessionIsNoOp() async { let session = SpeechSession() - await session.stopTranscribing() + await session.finishTranscribing() + await session.cancelTranscribing() #expect(await session.modelDownloadProgress == nil) #expect(session.status == .idle) } @@ -85,25 +86,9 @@ struct SpeechSessionStateTests { #expect(firstA == .some(.idle)) #expect(firstB == .some(.idle)) - let nextA = Task { - await probeA.next() - } - let nextB = Task { - await probeB.next() - } - defer { - nextA.cancel() - nextB.cancel() - } - session.setStatus(.preparing) - - let valueA = try await awaitResult { - await nextA.value - } - let valueB = try await awaitResult { - await nextB.value - } + let valueA = try await awaitResult { await probeA.next() } + let valueB = try await awaitResult { await probeB.next() } #expect(valueA == .some(.preparing)) #expect(valueB == .some(.preparing)) } @@ -156,26 +141,17 @@ struct SpeechSessionAudioInputStreamTests { let probeA = AsyncStreamProbe(session.audioInputConfigurationStream) let probeB = AsyncStreamProbe(session.audioInputConfigurationStream) - let valueA = Task { - await probeA.next() + try await awaitResult { + while session.audioInputContinuations.count < 2 { + try Task.checkCancellation() + await Task.yield() + } } - let valueB = Task { - await probeB.next() - } - defer { - valueA.cancel() - valueB.cancel() - } - - await Task.yield() session.broadcastAudioInputInfo(nil) - - let firstA = try await awaitResult { - await valueA.value - } - let firstB = try await awaitResult { - await valueB.value - } + let firstA = try await awaitResult { await probeA.next() } + let firstB = try await awaitResult { await probeB.next() } + #expect(firstA != nil) + #expect(firstB != nil) let flattenedA = firstA?.flatMap { $0 } let flattenedB = firstB?.flatMap { $0 } #expect(flattenedA == nil) @@ -338,11 +314,14 @@ actor MockCustomVocabularyCompiler: CustomVocabularyCompiling { languageModel: outputDirectory.appendingPathComponent("languageModel.bin"), vocabulary: outputDirectory.appendingPathComponent("vocabulary.bin") ) + try Data().write(to: configuration.languageModel) + try Data().write(to: outputDirectory.appendingPathComponent("vocabulary.bin")) return CustomVocabularyCompilation( configuration: configuration, cacheKey: cacheKey, - outputDirectory: outputDirectory + outputDirectory: outputDirectory, + artifacts: CustomVocabularyArtifacts(directory: outputDirectory) ) } diff --git a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift new file mode 100644 index 0000000..0315234 --- /dev/null +++ b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift @@ -0,0 +1,195 @@ +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("Custom vocabulary artifact ownership") +@MainActor +struct CustomVocabularyOwnershipTests { + func descriptor(_ version: String = "1") -> SpeechSession.CustomVocabulary { + .init(locale: Locale(identifier: "en_US"), identifier: "ownership-test", version: version, weight: 0.4) + } + + 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 { + 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 { + 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 { + 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 { + 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 { + 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 reader = owner!.createRecognizerTask( + label: "Ownership fixture", + vocabularyArtifacts: owner?.customVocabularyArtifacts, + results: results.stream, + streamContinuation: output.continuation, + generation: owner!.sessionGeneration + ) + // 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 + #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. +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/CustomVocabularyRecoveryTests.swift b/Tests/AuralKitTests/CustomVocabularyRecoveryTests.swift new file mode 100644 index 0000000..3450de6 --- /dev/null +++ b/Tests/AuralKitTests/CustomVocabularyRecoveryTests.swift @@ -0,0 +1,83 @@ +import Foundation +import Testing +@testable import AuralKit + +extension CustomVocabularyOwnershipTests { + @Test("Already-cancelled configuration leaves the pending request intact") + func cancelledRequestDoesNotSupersede() async throws { + 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 { + 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 { + 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) + } +} + +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/FileIngestionSettlementTests.swift b/Tests/AuralKitTests/FileIngestionSettlementTests.swift new file mode 100644 index 0000000..892a45f --- /dev/null +++ b/Tests/AuralKitTests/FileIngestionSettlementTests.swift @@ -0,0 +1,177 @@ +import AVFoundation +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("File ingestion settlement") +@MainActor +struct FileIngestionSettlementTests { + @Test("Independent ingestion cancellation settles the public stream", arguments: [false, true]) + func independentCancellation(throwsCancellation: Bool) async throws { + try await withSession { runtime, fixture in + runtime.session.startFileIngestion(generation: runtime.generation) { _ in + if throwsCancellation { throw CancellationError() } + withUnsafeCurrentTask { $0?.cancel() } + } + let input = fixture.track(try #require(runtime.session.fileIngestionTask)) + await #expect(throws: CancellationError.self) { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + } + await input.value + #expect(runtime.session.status == .idle) + #expect(runtime.session.continuation == nil) + } + } + + @Test("Result EOF preserves a later input or finalization error", arguments: [false, true]) + func resultEOFDoesNotAdmitPrematureSuccess(finalization: Bool) async throws { + try await withSession { runtime, fixture in + let release = fixture.gate() + let results = AsyncThrowingStream.makeStream() + let forwarded = AsyncThrowingStream.makeStream() + defer { forwarded.continuation.finish() } + let reader = fixture.track(runtime.session.createRecognizerTask( + label: "File result fixture", results: results.stream, + streamContinuation: forwarded.continuation, generation: runtime.generation + )) + runtime.session.recognizerTask = reader + if finalization { + runtime.session.analyzer = SpeechAnalyzer(modules: []) + runtime.session.analyzerInputTask = Task { + try await release.wait() + throw SpeechSessionError.invalidAudioDataType + } + } + runtime.session.startFileIngestion(generation: runtime.generation) { session in + if finalization { + try await session.finishFileInput(generation: runtime.generation) + } else { + try await release.wait() + throw SpeechSessionError.audioFileReadFailed(nil) + } + } + let input = fixture.track(try #require(runtime.session.fileIngestionTask)) + results.continuation.finish() + await reader.value + #expect(runtime.session.continuation != nil) + release.open() + await input.value + do { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + Issue.record("Expected the producer failure") + } catch SpeechSessionError.invalidAudioDataType { + #expect(finalization) + } catch SpeechSessionError.audioFileReadFailed { + #expect(!finalization) + } + #expect(runtime.session.status == .idle) + } + } + + @Test("A result iterator that cancels itself before EOF fails the public stream") + func selfCancelledResultEOF() async throws { + try await withSession { runtime, fixture in + let forwarded = AsyncThrowingStream.makeStream() + defer { forwarded.continuation.finish() } + runtime.session.startFileIngestion(generation: runtime.generation) { _ in } + let reader = fixture.track(runtime.session.createRecognizerTask( + label: "Self-cancelled results", results: SelfCancelledResults(), + streamContinuation: forwarded.continuation, generation: runtime.generation + )) + 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.status == .idle) + } + } + + @Test("A physical short read fails before closing analyzer input") + func physicalShortRead() async throws { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("Aural-short-read-\(UUID().uuidString).caf") + defer { try? FileManager.default.removeItem(at: url) } + let format = try #require(AVAudioFormat( + commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true + )) + let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 160)) + buffer.frameLength = 160 + buffer.int16ChannelData?.pointee.initialize(repeating: 0, count: 160) + try autoreleasepool { + let writer = try AVAudioFile( + forWriting: url, settings: format.settings, commonFormat: .pcmFormatInt16, interleaved: true + ) + try writer.write(from: buffer) + } + try await withSession { runtime, _ in + let file = try AVAudioFile(forReading: url, commonFormat: .pcmFormatInt16, interleaved: true) + let declaredFrames = file.length + 1 + let input = AsyncStream.makeStream() + defer { input.continuation.finish() } + runtime.session.inputBuilder = input.continuation + runtime.session.analyzerFormat = format + do { + _ = try await runtime.session.feedAudioFile( + (file: file, totalFrames: declaredFrames), progressHandler: { _ in }, + generation: runtime.generation + ) + Issue.record("Expected audioFileReadFailed for premature physical EOF") + } catch SpeechSessionError.audioFileReadFailed { } + if case .terminated = input.continuation.yield(AnalyzerInput(buffer: buffer)) { + Issue.record("Physical input closed before its read failure was admitted") + } + } + } + + @MainActor + private struct Runtime { + let session: SpeechSession + let results: AsyncThrowingStream + let generation: Int + + init() { + let session = SpeechSession() + let output = AsyncThrowingStream.makeStream() + self.session = session + results = output.stream + generation = session.beginStreamGeneration() + session.continuation = .speech(output.continuation) + session.streamingMode = .filePlayback + session.setStatus(.transcribing) + } + } + + 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.cancelTranscribing() + throw error + } + fixture.releaseAll() + await runtime.session.cancelTranscribing() + } + } +} + +private struct SelfCancelledResults: 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/FileProgressTests.swift b/Tests/AuralKitTests/FileProgressTests.swift new file mode 100644 index 0000000..04721db --- /dev/null +++ b/Tests/AuralKitTests/FileProgressTests.swift @@ -0,0 +1,46 @@ +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 { + let session = SpeechSession() + let generation = session.beginStreamGeneration() + 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, generation: generation) + + switch termination { + case "stopping": + session.prepareForStop() + case "stopped": + await session.cancelTranscribing() + case "replacement": + _ = session.beginStreamGeneration() + default: + break + } + + let delivery = Task { + if termination == "cancelled" { + withUnsafeCurrentTask { $0?.cancel() } + } + session.reportFileProgress(0.5, handler: handler, generation: generation) + session.reportFileProgress(1.0, handler: handler, generation: generation) + } + 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/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 68fd118..d9c931b 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") @@ -30,6 +31,88 @@ struct FileTranscriptionTests { } } +#if swift(>=6.4) + @Test("Cancelling a media analyzer before it receives input closes the session") + @MainActor + func cancelBeforeAnalyzerInputClosesSession() async throws { + let session = SpeechSession() + let (results, continuation) = AsyncThrowingStream.makeStream() + let analyzer = SpeechAnalyzer(modules: []) + session.analyzer = analyzer + session.continuation = .speech(continuation) + session.streamingMode = .mediaPlayback + session.setStatus(.preparing) + + 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 { + let session = SpeechSession() + let output = AsyncThrowingStream.makeStream() + let transcriber = SpeechTranscriber(locale: Locale(identifier: "en-US"), preset: .transcription) + session.analyzer = SpeechAnalyzer(modules: [transcriber]) + let generation = session.beginStreamGeneration() + session.continuation = .speech(output.continuation) + session.streamingMode = .mediaPlayback + session.setStatus(.transcribing) + let recognizer = session.createSpeechRecognizerTask( + transcriber: transcriber, streamContinuation: output.continuation, generation: generation + ) + session.recognizerTask = recognizer + session.startFileIngestion(generation: generation) { _ in + throw SpeechSessionError.audioFileReadFailed(nil) + } + let ingestion = try #require(session.fileIngestionTask) + + await recognizer.value + await ingestion.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) + } + + @available(iOS 27.0, macOS 27.0, *) + @Test("Media transcription rejects an unknown audio track without falling back") + @MainActor + func mediaTranscriptionRejectsUnknownTrack() async throws { + 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) diff --git a/Tests/AuralKitTests/ScreenCaptureAudioTests.swift b/Tests/AuralKitTests/ScreenCaptureAudioTests.swift new file mode 100644 index 0000000..23bcf75 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureAudioTests.swift @@ -0,0 +1,89 @@ +#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)) {} + } + + 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..f670bc9 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureFinishTests.swift @@ -0,0 +1,237 @@ +#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 generation = runtime.session.sessionGeneration + let resultsTask = Task { + for await _ in inputs {} + await runtime.session.finishFromRecognizerTask(error: nil, generation: generation) + } + defer { resultsTask.cancel() } + 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.session.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + + 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.session.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + + 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.session.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 generation = runtime.session.sessionGeneration + let completed = fixture.track(Task { + await runtime.session.finishFromRecognizerTask(error: nil, generation: generation) + }) + try await stopEntered.wait() + let cancel = fixture.track(Task { await runtime.session.cancelTranscribing() }) + try await waitForCaptureState { runtime.session.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 generation = runtime.session.sessionGeneration + let (inputs, inputBuilder) = AsyncStream.makeStream() + runtime.session.inputBuilder = inputBuilder + let (results, resultBuilder) = AsyncThrowingStream.makeStream() + runtime.session.continuation = .speech(resultBuilder) + runtime.session.recognizerTask = fixture.track(Task { + for await _ in inputs {} + await runtime.session.finishFromRecognizerTask(error: nil, generation: generation) + }) + + let pickerError = fixture.gate(), reported = fixture.gate() + runtime.session.pipelineTask = fixture.track(Task { + await fixtureWaitForPickerError(pickerError) + await runtime.session.finishFailedPipelineSetup( + SpeechSessionError.screenCaptureSelectionCancelled, generation: generation + ) + reported.open() + }) + let stopEntered = fixture.gate(), stopRelease = fixture.gate() + source.stopEntered = stopEntered + source.stopRelease = stopRelease + let finish = fixture.track(Task { + await runtime.session.finishTranscribing(generation: generation, 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 { + 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) + } + } + + 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 new file mode 100644 index 0000000..1c1e489 --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureTestFixtures.swift @@ -0,0 +1,100 @@ +import Foundation +@testable import AuralKit + +enum CaptureFixtureError: Error { case deadline, startFailed } + +@MainActor +final class CaptureGate { + private let stream: AsyncStream + private let continuation: AsyncStream.Continuation + + init() { (stream, continuation) = AsyncStream.makeStream() } + + func wait() async throws { + try await awaitResult(timeout: 3) { + for await _ in self.stream {} + try Task.checkCancellation() + } + } + + func open() { continuation.finish() } +} + +// Release suspended capture calls before joining tasks, including when an assertion fails. +@MainActor +final class CaptureFixture { + private var gates: [CaptureGate] = [] + private var joins: [Task] = [] + private var cancellations: [() -> Void] = [] + func gate() -> CaptureGate { + let gate = CaptureGate() + gates.append(gate) + return gate + } + @discardableResult + func track(_ task: Task) -> Task { + cancellations.append { task.cancel() } + joins.append(Task { _ = await task.result }) + return task + } + func releaseAll() { gates.forEach { $0.open() } } + func cleanUp() async { + releaseAll() + cancellations.forEach { $0() } + for join in joins { await join.value } + } +} + +@MainActor +func withCaptureFixture(_ body: (CaptureFixture) async throws -> Void) async throws { + let fixture = CaptureFixture() + do { + try await body(fixture) + await fixture.cleanUp() + } catch { + await fixture.cleanUp() + throw error + } +} + +@available(iOS 26.0, macOS 26.0, *) +@MainActor +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 = !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 new file mode 100644 index 0000000..876b70d --- /dev/null +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -0,0 +1,234 @@ +#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 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)) + let generation = session.sessionGeneration + provider = ScreenCaptureAudioInputProvider( + options: .init(), targetFormat: format, inputContinuation: inputs, + onTermination: { [session] error in + Task { @MainActor in + try? await terminationRelease?.wait() + await session.finishFromRecognizerTask(error: error, generation: generation) + } + }, 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 transitions") +struct ScreenCaptureTransitionTests { + @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 { + 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/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/SessionLifecycleTests.swift b/Tests/AuralKitTests/SessionLifecycleTests.swift index 7532d07..b30fe30 100644 --- a/Tests/AuralKitTests/SessionLifecycleTests.swift +++ b/Tests/AuralKitTests/SessionLifecycleTests.swift @@ -113,15 +113,105 @@ struct SpeechSessionLifecycleTests { let (_, continuation) = AsyncThrowingStream.makeStream() session.continuation = .speech(continuation) - await session.finishStream(error: SpeechSessionError.invalidAudioDataType, generation: staleGeneration) + session.finishStream(error: SpeechSessionError.invalidAudioDataType, generation: staleGeneration) #expect(session.continuation != nil) // The current generation still owns the stream and can finish it. - await session.finishStream(error: nil, generation: session.sessionGeneration) + session.finishStream(error: nil, generation: session.sessionGeneration) #expect(session.continuation == nil) } + @Test("Stale setup failures preserve the successor setup task") + @MainActor + func staleSetupFailurePreservesSuccessorTask() async { + let session = SpeechSession() + let staleGeneration = session.beginStreamGeneration() + _ = session.beginStreamGeneration() + let successor = Task {} + session.pipelineTask = successor + + await session.finishFailedPipelineSetup(CancellationError(), generation: staleGeneration) + #expect(session.pipelineTask == successor) + await session.finishFailedPipelineSetup( + SpeechSessionError.invalidAudioDataType, generation: staleGeneration + ) + #expect(session.pipelineTask == successor) + + await session.cancelTranscribing() + await successor.value + } + + @Test("Finish closes a preparing stream and Cancel reports cancellation", arguments: [false, true]) + @MainActor + func endPreparingTranscription(cancel: Bool) async throws { + 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 { + let session = SpeechSession() + let (inputs, inputBuilder) = AsyncStream.makeStream() + let (results, resultBuilder) = AsyncThrowingStream.makeStream() + let analyzer = SpeechAnalyzer(modules: []) + session.inputBuilder = inputBuilder + session.analyzer = analyzer + session.analyzerInputTask = Task { try await analyzer.analyzeSequence(inputs) } + session.continuation = .speech(resultBuilder) + session.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + 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 { + let session = SpeechSession() + let (results, resultBuilder) = AsyncThrowingStream.makeStream() + session.continuation = .speech(resultBuilder) + session.recognizerTask = Task { try? await Task.sleep(for: .seconds(10)) } + session.streamingMode = .liveMicrophone + session.setStatus(.transcribing) + + session.startAnalyzingInput(generation: session.sessionGeneration) { + 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) + } + /// Pausing is only meaningful for live capture; during file transcription it must be /// refused (previously, resuming a "paused" file session started the microphone). @Test("Pause is refused during file transcription") diff --git a/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift b/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift new file mode 100644 index 0000000..7d5d48b --- /dev/null +++ b/Tests/AuralKitTests/SpeechAssetReservationTestFixtures.swift @@ -0,0 +1,109 @@ +import Foundation +import AVFoundation +import Speech +@testable import AuralKit + +actor AssetGate { + 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() } + } +} + +actor AssetInventoryProbe { + 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: AssetGate? + private var releaseGate: AssetGate? + + 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: AssetGate) { reserveGate = gate } + func holdRelease(at gate: AssetGate) { 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 + } +} + +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 new file mode 100644 index 0000000..d402b1a --- /dev/null +++ b/Tests/AuralKitTests/SpeechAssetReservationTests.swift @@ -0,0 +1,184 @@ +import Foundation +import Testing +@testable import AuralKit + +@Suite("Speech asset reservations") +struct SpeechAssetReservationTests { + @Test("overlapping managers retain the locale until the final owner stops") + func overlappingManagers() async throws { + let inventory = AssetInventoryProbe() + 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("cleanup returns before a noncooperative download and rejects its late completion") + func cleanupDuringDownload() async throws { + let inventory = AssetInventoryProbe() + let reservations = SpeechAssetReservations(inventory: inventory.client) + let gate = AssetGate() + let manager = ModelManager(reservations: reservations, assetDownloader: { _ in await gate.waitOnce() }) + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let old = Task { try await manager.ensureAssets(for: [module]) } + await gate.waitForEntry() + #expect(await inventory.snapshot.reserves.isEmpty) + let rescue = Task { + try? await Task.sleep(for: .seconds(1)) + await gate.open() + } + await manager.releaseLocales() + #expect(await !gate.hasOpened, "Cleanup waited for the noncooperative download") + try await manager.ensureAssets(for: [module]) + await gate.open() + rescue.cancel() + await rescue.value + if case .success = await old.result { Issue.record("Retired download acquired a lease") } + #expect(await inventory.snapshot.releases.isEmpty) + await manager.releaseLocales() + let state = await inventory.snapshot + #expect(state.reserves == ["en-US"]) + #expect(state.releases == ["en-US"]) + #expect(state.locales.isEmpty) + } + + @Test("a canceled late acquisition cannot release its successor's reservation") + func cleanupDuringAcquisition() async throws { + let inventory = AssetInventoryProbe() + let reservations = SpeechAssetReservations(inventory: inventory.client) + let gate = AssetGate() + await inventory.holdReserve(at: gate) + let manager = ModelManager(reservations: reservations, assetDownloader: { _ in }) + let module = ReservationModule(locales: [Locale(identifier: "en-US")]) + let old = Task { try await manager.ensureAssets(for: [module]) } + await gate.waitForEntry() + old.cancel() + await manager.releaseLocales() + let successor = Task { try await manager.ensureAssets(for: [module]) } + await gate.open() + if case .success = await old.result { Issue.record("Canceled acquisition succeeded") } + try await successor.value + #expect(await inventory.snapshot.locales == ["en-US"]) + await manager.releaseLocales() + let state = await inventory.snapshot + #expect(state.releases.count == state.reserves.count) + #expect(state.locales.isEmpty) + } + + @Test("borrowed external reservations survive cleanup", arguments: ["en-US", "en-AU"]) + func borrowedReservation(alias: String) async throws { + let inventory = AssetInventoryProbe(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 { + let inventory = AssetInventoryProbe(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 { + let inventory = AssetInventoryProbe() + let native = inventory.client + let reservations = SpeechAssetReservations(inventory: native) + let blockerGate = AssetGate() + 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) + if cancel { preparation.cancel() } else { await manager.releaseLocales() } + await blockerGate.open() + try await blocker.value + if case .success = await preparation.result { Issue.record("Retired preparation succeeded") } + 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 { + let inventory = AssetInventoryProbe() + let native = inventory.client + let gate = AssetGate() + 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 { + let inventory = AssetInventoryProbe() + let reservations = SpeechAssetReservations(inventory: inventory.client) + let lease = try await reservations.acquire(Locale(identifier: "en-US")) + let gate = AssetGate() + 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/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift b/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift new file mode 100644 index 0000000..f7fbd09 --- /dev/null +++ b/Tests/AuralKitTests/SpeechDetectorLifecycleTests.swift @@ -0,0 +1,74 @@ +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("Speech detector monitor identity") +@MainActor +struct SpeechDetectorLifecycleTests { + @Test("only the current monitor may complete the detector stream", arguments: [false, true]) + func replacementRejectsStaleCompletion(failed: Bool) throws { + let session = makeSessionWithMonitor() + defer { session.disableVoiceActivation() } + let oldID = try #require(session.speechDetectorMonitorID) + let oldTask = try #require(session.speechDetectorResultsTask) + + session.startSpeechDetectorMonitoring() + let currentID = try #require(session.speechDetectorMonitorID) + let currentTask = try #require(session.speechDetectorResultsTask) + session.isSpeechDetected = false + let error: Error? = failed ? DetectorTestError.failed : nil + session.handleSpeechDetectorStreamCompletion(error: error, monitorID: oldID) + + #expect(oldTask.isCancelled) + #expect(!currentTask.isCancelled) + #expect(currentID != oldID) + #expect(session.speechDetectorMonitorID == currentID) + #expect(session.speechDetectorResultsTask != nil) + #expect(session.speechDetectorResultsContinuation != nil) + #expect(session.speechDetectorResultsStream != nil) + #expect(!session.isSpeechDetected) + + session.handleSpeechDetectorStreamCompletion(error: error, monitorID: currentID) + #expect(session.speechDetectorMonitorID == nil) + #expect(session.speechDetectorResultsTask == nil) + #expect(session.speechDetectorResultsContinuation == nil) + #expect(session.speechDetectorResultsStream == nil) + #expect(session.isSpeechDetected) + currentTask.cancel() + } + + @Test("disable revokes a monitor before reporting is reconfigured") + func disableRejectsStaleCompletion() throws { + let session = makeSessionWithMonitor() + defer { session.disableVoiceActivation() } + let oldID = try #require(session.speechDetectorMonitorID) + let oldTask = try #require(session.speechDetectorResultsTask) + session.disableVoiceActivation() + session.configureVoiceActivation(reportResults: true) + + session.handleSpeechDetectorStreamCompletion(error: nil, monitorID: oldID) + + #expect(oldTask.isCancelled) + #expect(session.speechDetectorMonitorID == nil) + #expect(session.speechDetectorResultsTask == nil) + #expect(session.speechDetectorResultsContinuation != nil) + #expect(session.speechDetectorResultsStream != nil) + #expect(session.isSpeechDetected) + } + + private func makeSessionWithMonitor() -> SpeechSession { + let session = SpeechSession() + session.configureVoiceActivation(reportResults: true) + session.speechDetector = SpeechDetector( + detectionOptions: .init(sensitivityLevel: .medium), + reportResults: true + ) + session.startSpeechDetectorMonitoring() + return session + } +} + +private enum DetectorTestError: Error { + case failed +} 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