diff --git a/Aural/CustomVocabularyDemoView.swift b/Aural/CustomVocabularyDemoView.swift index 71a7eba..3d42f1a 100644 --- a/Aural/CustomVocabularyDemoView.swift +++ b/Aural/CustomVocabularyDemoView.swift @@ -30,12 +30,13 @@ struct CustomVocabularyDemoView: View { TranscriptionControlsView( status: viewModel.status, error: viewModel.errorMessage, - showStopButton: showStopButton, buttonColor: buttonColor, buttonIcon: buttonIcon, statusMessage: statusMessage, onPrimaryAction: handlePrimaryAction, - onStopAction: handleStopAction + onFinishAction: { model.finishTranscription() }, + onCancelAction: { model.cancelTranscription() }, + isPreparing: model.isCompiling ) .padding(.horizontal) } @@ -256,15 +257,6 @@ private extension CustomVocabularyDemoView { } } - var showStopButton: Bool { - switch model.status { - case .idle, .stopping: - return false - case .preparing, .transcribing, .paused: - return true - } - } - var statusMessage: String { switch model.status { case .idle: @@ -274,9 +266,9 @@ private extension CustomVocabularyDemoView { case .transcribing: return "Listening..." case .paused: - return "Paused — tap to resume or stop" + return "Paused" case .stopping: - return "Stopping..." + return "Ending session..." } } @@ -285,7 +277,7 @@ private extension CustomVocabularyDemoView { case .idle: model.startTranscription() case .preparing: - model.stopTranscription() + model.cancelTranscription() case .transcribing: model.pauseTranscription() case .paused: @@ -295,7 +287,4 @@ private extension CustomVocabularyDemoView { } } - func handleStopAction() { - model.stopTranscription() - } } diff --git a/Aural/CustomVocabularyDemoViewModel.swift b/Aural/CustomVocabularyDemoViewModel.swift index 05e9ba2..ed54c5c 100644 --- a/Aural/CustomVocabularyDemoViewModel.swift +++ b/Aural/CustomVocabularyDemoViewModel.swift @@ -57,10 +57,9 @@ final class CustomVocabularyDemoViewModel { // MARK: - Intent Handlers func startTranscription() { - guard status != .transcribing, status != .preparing else { return } + guard status == .idle, transcriptionTask == nil else { return } resetTranscriptionState() - cancelExistingTasks() transcriptionTask = Task { @MainActor in do { @@ -68,7 +67,8 @@ final class CustomVocabularyDemoViewModel { monitorDownloadProgress() try await processTranscriptionStream(stream) } catch is CancellationError { - // expected when stopped + partialText = "" + currentTimeRange = "" } catch { errorMessage = error.localizedDescription isCompiling = false @@ -78,17 +78,15 @@ final class CustomVocabularyDemoViewModel { } } - func stopTranscription() { - progressTask?.cancel() - progressTask = nil - resetProgressObservation(clearFraction: true) - transcriptionTask?.cancel() - transcriptionTask = nil + func finishTranscription() { + Task { await session.finishTranscribing() } + } - Task { @MainActor in - await session.stopTranscribing() - partialText = "" - currentTimeRange = "" + func cancelTranscription() { + if session.status == .idle { + transcriptionTask?.cancel() + } else { + Task { await session.cancelTranscribing() } } } @@ -111,7 +109,7 @@ final class CustomVocabularyDemoViewModel { func handleToggleChange(_ isEnabled: Bool) { isCustomVocabularyEnabled = isEnabled if !isEnabled, status == .transcribing || status == .preparing { - stopTranscription() + cancelTranscription() } } @@ -124,7 +122,7 @@ final class CustomVocabularyDemoViewModel { } func teardown() { - stopTranscription() + cancelTranscription() statusTask?.cancel() statusTask = nil } @@ -153,10 +151,6 @@ final class CustomVocabularyDemoViewModel { isCompiling || status == .preparing || status == .transcribing } - var isStopDisabled: Bool { - status == .idle || status == .stopping - } - // MARK: - Private helpers private func bindStatusStream() { @@ -287,11 +281,6 @@ extension CustomVocabularyDemoViewModel { compilationDuration = nil } - private func cancelExistingTasks() { - transcriptionTask?.cancel() - progressTask?.cancel() - } - private func prepareTranscriptionStream() async throws -> AsyncThrowingStream { let startTime = Date() diff --git a/Aural/Info.plist b/Aural/Info.plist index 0881dfd..d7cb7ca 100644 --- a/Aural/Info.plist +++ b/Aural/Info.plist @@ -17,7 +17,7 @@ CFBundlePackageType APPL CFBundleShortVersionString - 2.1.1 + 3.0.0 CFBundleVersion 1 LSMinimumSystemVersion diff --git a/Aural/SettingsView.swift b/Aural/SettingsView.swift index f63b92b..56d0ea5 100644 --- a/Aural/SettingsView.swift +++ b/Aural/SettingsView.swift @@ -63,7 +63,7 @@ struct SettingsView: View { Text("AuralKit Demo") .font(.caption) .foregroundStyle(.secondary) - Text("Version 2.1.1") + Text("Version 3.0.0") .font(.caption2) .foregroundStyle(.secondary) } diff --git a/Aural/TranscriptionManager.swift b/Aural/TranscriptionManager.swift index ed48a85..d269138 100644 --- a/Aural/TranscriptionManager.swift +++ b/Aural/TranscriptionManager.swift @@ -14,7 +14,7 @@ class TranscriptionManager { var selectedPreset: DemoTranscriberPreset = .manual { didSet { if oldValue != selectedPreset, status != .idle { - stopTranscription() + finishTranscription() } } } @@ -66,7 +66,8 @@ class TranscriptionManager { currentTimeRange = "" isSpeechDetected = true - let session = SpeechSession(locale: selectedLocale, preset: selectedPreset.preset) + let sessionLocale = selectedLocale + let session = SpeechSession(locale: sessionLocale, preset: selectedPreset.preset) speechSession = session observeStatus(from: session) observeAudioInput(from: session) @@ -77,12 +78,12 @@ class TranscriptionManager { for try await result in session.startTranscribing() { self.handleTranscriptionResult(result) } - self.finishSession() + self.finishSession(locale: sessionLocale) } catch is CancellationError { self.cleanupSession() } catch { self.error = error.localizedDescription - self.finishSession() + self.finishSession(locale: sessionLocale) } } } @@ -122,12 +123,14 @@ class TranscriptionManager { return String(format: "%d:%02d.%02d", minutes, remainingSeconds, milliseconds) } - func stopTranscription() { - guard status != .idle, status != .stopping else { return } - Task { @MainActor in - await self.speechSession?.stopTranscribing() - } - stopAuxiliaryTasks() + func finishTranscription() { + guard let speechSession else { return } + Task { await speechSession.finishTranscribing() } + } + + func cancelTranscription() { + guard let speechSession else { return } + Task { await speechSession.cancelTranscribing() } } func pauseTranscription() { @@ -154,7 +157,7 @@ class TranscriptionManager { case .idle: startTranscription() case .preparing: - stopTranscription() + cancelTranscription() case .transcribing: pauseTranscription() case .paused: @@ -182,15 +185,22 @@ class TranscriptionManager { transcriptionHistory.removeAll { $0.id == record.id } } - private func finishSession() { - if !currentTranscript.isEmpty { + private func finishSession(locale: Locale) { + let transcript = String(finalizedText.characters) + if !transcript.isEmpty { + let ranges = finalizedText.runs.compactMap(\.audioTimeRange) + let timeRange = if let first = ranges.first, let last = ranges.last { + "\(formatTime(first.start)) - \(formatTime(last.end))" + } else { + "" + } let record = TranscriptionRecord( id: UUID(), - text: currentTranscript, - locale: selectedLocale, + text: transcript, + locale: locale, timestamp: Date(), alternatives: [], - timeRange: currentTimeRange + timeRange: timeRange ) transcriptionHistory.insert(record, at: 0) } diff --git a/Aural/TranscriptionView.swift b/Aural/TranscriptionView.swift index 07d3431..e8dc9f5 100644 --- a/Aural/TranscriptionView.swift +++ b/Aural/TranscriptionView.swift @@ -36,12 +36,12 @@ struct TranscriptionView: View { TranscriptionControlsView( status: manager.status, error: manager.error, - showStopButton: showStopButton, buttonColor: buttonColor, buttonIcon: buttonIcon, statusMessage: statusMessage, onPrimaryAction: { manager.primaryAction() }, - onStopAction: { manager.stopTranscription() }, + onFinishAction: { manager.finishTranscription() }, + onCancelAction: { manager.cancelTranscription() }, animationScale: animationScale ) .padding(.horizontal) @@ -166,15 +166,6 @@ struct TranscriptionView: View { } } - private var showStopButton: Bool { - switch manager.status { - case .idle, .stopping: - return false - case .preparing, .transcribing, .paused: - return true - } - } - private var statusMessage: String { switch manager.status { case .idle: @@ -184,9 +175,9 @@ struct TranscriptionView: View { case .transcribing: return "Listening..." case .paused: - return "Paused — tap to resume or stop" + return "Paused" case .stopping: - return "Stopping..." + return "Ending session..." } } } diff --git a/Aural/TranscriptionViewComponents.swift b/Aural/TranscriptionViewComponents.swift index 46b7d8d..8c30bbf 100644 --- a/Aural/TranscriptionViewComponents.swift +++ b/Aural/TranscriptionViewComponents.swift @@ -120,12 +120,13 @@ struct TranscriptionTextView: View { struct TranscriptionControlsView: View { let status: SpeechSession.Status let error: String? - let showStopButton: Bool let buttonColor: Color let buttonIcon: String let statusMessage: String let onPrimaryAction: () -> Void - let onStopAction: () -> Void + let onFinishAction: () -> Void + let onCancelAction: () -> Void + var isPreparing = false var animationScale: CGFloat = 1.0 var body: some View { @@ -153,12 +154,17 @@ struct TranscriptionControlsView: View { } .buttonStyle(.glass) .buttonBorderShape(.circle) - .disabled(error != nil || status == .stopping) + .disabled(error != nil || status == .stopping || isPreparing) - if showStopButton { - Button("Stop", action: onStopAction) - .buttonStyle(.borderedProminent) - .tint(.gray) + if status != .idle || isPreparing { + HStack { + if status == .transcribing || status == .paused { + Button("Finish", action: onFinishAction) + .buttonStyle(.borderedProminent) + } + Button("Cancel", action: onCancelAction) + .buttonStyle(.bordered) + } } Text(statusMessage) diff --git a/README.md b/README.md index 9c0f728..43e9ab5 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,8 @@ This project would not have been possible without Apple's excellent sample code. ## Quick Start +The examples below use the AuralKit 3.0 API. + ```swift import AuralKit @@ -82,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 } ``` @@ -98,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") ] ``` @@ -142,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: @@ -477,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/ScreenCaptureTransitions.swift b/Sources/AuralKit/ScreenCaptureTransitions.swift index de1b6ab..268fbfd 100644 --- a/Sources/AuralKit/ScreenCaptureTransitions.swift +++ b/Sources/AuralKit/ScreenCaptureTransitions.swift @@ -34,6 +34,8 @@ final class ScreenCaptureTransitions { 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 { @@ -83,6 +85,9 @@ final class ScreenCaptureTransitions { 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() @@ -140,10 +145,19 @@ final class ScreenCaptureTransitions { func stop() -> Task { controlRevision = UUID() desiredState = .stopped + explicitStopPending = true return enqueue { - defer { self.stream = nil } - try await self.stopCurrent() - if let drainFailure = self.drainFailure { throw drainFailure } + 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 } } } diff --git a/Sources/AuralKit/SpeechSession+Audio.swift b/Sources/AuralKit/SpeechSession+Audio.swift index 1842411..4d5e394 100644 --- a/Sources/AuralKit/SpeechSession+Audio.swift +++ b/Sources/AuralKit/SpeechSession+Audio.swift @@ -240,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 @@ -253,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) { @@ -277,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+CustomVocabularyConfiguration.swift b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift index 4513902..2c6149f 100644 --- a/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift +++ b/Sources/AuralKit/SpeechSession+CustomVocabularyConfiguration.swift @@ -106,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) } diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 8e63ce9..b4ffb1a 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -105,6 +105,7 @@ public extension SpeechSession { } let finalResults = try await stream.reduce(into: [SpeechTranscriber.Result](), accumulator) + try Task.checkCancellation() return finalResults } } @@ -257,7 +258,7 @@ private extension SpeechSession { 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 @@ -294,7 +295,7 @@ private extension SpeechSession { let sendableBuffer = SendablePCMBuffer(buffer: bufferCopy) - try await self.processAudioBuffer(sendableBuffer) + try await processAudioBuffer(sendableBuffer, generation: generation) processedFrames += AVAudioFramePosition(buffer.frameLength) @@ -306,7 +307,7 @@ private extension SpeechSession { guard !Task.isCancelled else { return false } - try await self.finishAnalyzerInput() + try await finishFileInput(generation: generation) return !Task.isCancelled && processedFrames >= totalFrames } @@ -335,7 +336,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) } @@ -366,6 +368,14 @@ extension SpeechSession { } } + 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, diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift index 56903fb..69f2e8c 100644 --- a/Sources/AuralKit/SpeechSession+MediaFile.swift +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -77,9 +77,7 @@ private extension SpeechSession { try await analyzer.finalizeAndFinish(through: endTime) } else { // With no input samples, Speech may leave the module's results stream open. - session.prepareForStop() - await session.cleanup(cancelRecognizer: true, generation: generation) - await session.finishStream(error: nil, generation: generation) + await session.finishWithoutInput(generation: generation) } } } catch { diff --git a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift index 76d063d..0f28e52 100644 --- a/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift +++ b/Sources/AuralKit/SpeechSession+NativeCaptureInput.swift @@ -83,10 +83,11 @@ extension SpeechSession { 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. @@ -133,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 925161e..7ed51f9 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -86,10 +86,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 +105,7 @@ extension SpeechSession { try Task.checkCancellation() try await ensurePermissions() try Task.checkCancellation() - try await setupAudioSession() + try setupAudioSession() try Task.checkCancellation() let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider @@ -161,7 +158,7 @@ extension SpeechSession { try Task.checkCancellation() try await ensurePermissions() try Task.checkCancellation() - try await setupAudioSession() + try setupAudioSession() try Task.checkCancellation() let shouldUseNativeCapture = shouldUseNativeCaptureInputProvider @@ -205,63 +202,123 @@ extension SpeechSession { } func finishFailedPipelineSetup(_ error: Error, generation: Int) async { - guard generation == sessionGeneration else { return } + guard generation == sessionGeneration, terminationTask == nil else { return } pipelineTask = nil - if error is CancellationError { - await finishCancelledPipelineSetup(generation: generation) - } else { - await finishWithStartupError(error, generation: generation) - } + guard finishTask == nil || !Task.isCancelled else { return } + await finishWithStartupError(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 { - guard generation == sessionGeneration else { return } - if Self.shouldLog(.debug) { - Self.logger.debug("Pipeline setup cancelled; unwinding") - } - await cleanup(cancelRecognizer: true, generation: generation) - guard generation == sessionGeneration else { return } - await finishStream(error: nil, 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 finishWithStartupError(_ error: Error, generation: Int) async { + func finishFromRecognizerTask(error: Error?, generation: Int) async { + await endTranscription(error: error, generation: generation, cancelRecognizer: error != nil) + } + + 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 + } + guard let recognizerTask, sourceEnded || status != .preparing else { + await endTranscription(error: nil, generation: generation) return } - if Self.shouldLog(.error) { - Self.logger.error("Finishing due to startup error: \(error.localizedDescription, privacy: .public)") + if streamingMode == .filePlayback || streamingMode == .mediaPlayback { + 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. @@ -271,7 +328,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))") @@ -296,7 +357,6 @@ extension SpeechSession { task?.cancel() } - let cancelMediaAnalysis = cancelRecognizer && streamingMode == .mediaPlayback streamingMode = .inactive activeResultKind = nil stopAudioStreaming() @@ -306,8 +366,9 @@ extension SpeechSession { shouldResumeAfterInterruption = false #endif let detached = detachTranscriberState() - await stopScreenCaptureStreamingIfNeeded() - await finalizeDetachedTranscriberState(detached, cancelAnalysis: cancelMediaAnalysis) + await cleanUpDetachedTranscriberState(detached, cancelAnalyzer: cancelRecognizer) + _ = await screenStop?.result + if screenCaptureStopTask?.generation == generation { screenCaptureStopTask = nil } guard generation == sessionGeneration else { return } await modelManager.releaseLocales() @@ -323,7 +384,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 @@ -362,18 +423,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() @@ -442,9 +501,9 @@ extension SpeechSession { 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") } @@ -453,8 +512,8 @@ extension SpeechSession { if Self.shouldLog(.debug) { Self.logger.debug("\(label, privacy: .public) cancelled") } + await self.finishFromRecognizerTask(error: CancellationError(), generation: generation) } catch { - guard !Task.isCancelled else { return } if Self.shouldLog(.error) { Self.logger.error( "\(label, privacy: .public) failed: \(error.localizedDescription, privacy: .public)" diff --git a/Sources/AuralKit/SpeechSession+ScreenCapture.swift b/Sources/AuralKit/SpeechSession+ScreenCapture.swift index 87afc9a..6a5e467 100644 --- a/Sources/AuralKit/SpeechSession+ScreenCapture.swift +++ b/Sources/AuralKit/SpeechSession+ScreenCapture.swift @@ -3,6 +3,7 @@ import CoreMedia import Foundation import OSLog import Speech +import Synchronization // swiftlint:disable file_length @@ -38,9 +39,7 @@ extension SpeechSession { } catch { let canFinish = status == .paused || (captureFailure != nil && status == .stopping) guard generation == sessionGeneration, canFinish, streamingMode == .screenCapture else { throw error } - prepareForStop() - await cleanup(cancelRecognizer: true, generation: generation) - await finishStream(error: error, generation: generation) + await endTranscription(error: error, generation: generation) throw error } if let terminalFailure { throw terminalFailure } @@ -89,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) } @@ -152,6 +152,7 @@ extension SpeechSession { ) try await setUpScreenCaptureStreaming(options: options, generation: generation) try Task.checkCancellation() + guard status == .preparing else { return } streamingMode = .screenCapture setStatus(.transcribing) @@ -181,7 +182,11 @@ extension SpeechSession { 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) + } } } ) @@ -201,20 +206,61 @@ extension SpeechSession { setStatus(.paused) } - func stopScreenCaptureStreamingIfNeeded() async { + func beginStoppingScreenCapture() -> Task? { let generation = sessionGeneration if let pending = screenCaptureStopTask, pending.generation == generation { - await pending.task.value - return + return pending.task } let detachedProvider = screenCaptureInputProvider screenCaptureInputProvider = nil - guard #available(iOS 27.0, macOS 14.0, *) else { return } - guard let provider = detachedProvider as? ScreenCaptureAudioInputProvider else { return } + 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) - await task.value - if screenCaptureStopTask?.generation == generation { screenCaptureStopTask = nil } + 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 + } + } + + @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 } } } @@ -223,15 +269,18 @@ extension SpeechSession { private final class NativeScreenCaptureStream: ScreenCaptureStream { let stream: SCStream private let audio: ScreenCaptureAudioProcessor + private let stopErrors: ScreenCaptureStopErrors - init(stream: SCStream, audio: ScreenCaptureAudioProcessor) { + 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() @@ -243,8 +292,9 @@ private final class NativeScreenCaptureStream: ScreenCaptureStream { func stopCapture() async throws { defer { logCaptureState(after: "stopCapture") } - try await stream.stopCapture() - if let error = audio.drain(ObjectIdentifier(stream)) { + let id = ObjectIdentifier(stream) + try await stopErrors.stop(id) { try await stream.stopCapture() } + if let error = audio.drain(id) { throw ScreenCaptureDrainFailure(underlyingError: error) } } @@ -275,6 +325,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD private let targetFormat: AVAudioFormat private let onTermination: @Sendable (Error?) -> Task private let audio: ScreenCaptureAudioProcessor + private let stopErrors = ScreenCaptureStopErrors() @MainActor private let transitions: ScreenCaptureTransitions @MainActor private var terminalCleanupTask: Task? @@ -352,7 +403,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } @MainActor - func stop() -> Task { + func stop() -> Task { stopped = true let operation = transitions.stop() dismissPicker(self) @@ -362,6 +413,10 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD try await operation.value } catch { audio.discard() + if let drainFailure = error as? ScreenCaptureDrainFailure { + throw SpeechSessionError.screenCaptureFailed(drainFailure.underlyingError) + } + throw error } } } @@ -393,7 +448,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD 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) + return NativeScreenCaptureStream(stream: capture, audio: audio, stopErrors: stopErrors) } } } @@ -415,6 +470,9 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD } 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, let current = self.transitions.stream as? NativeScreenCaptureStream, current.stream === stream else { return } @@ -489,9 +547,7 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD @MainActor func streamDidStop(_ stream: any ScreenCaptureStream, error: Error) { - let nativeError = error as NSError - let userStopped = nativeError.domain == SCStreamError.errorDomain - && nativeError.code == SCStreamError.Code.userStopped.rawValue + let userStopped = Self.isUserStop(error) var failure: Error? = userStopped ? nil : SpeechSessionError.screenCaptureFailed(error) if let nativeStream = stream as? NativeScreenCaptureStream { let id = ObjectIdentifier(nativeStream.stream) @@ -506,6 +562,12 @@ final class ScreenCaptureAudioInputProvider: NSObject, SCStreamOutput, SCStreamD stopped = true terminalCleanupTask = onTermination(failure) } + + private static func isUserStop(_ error: Error) -> Bool { + let nativeError = error as NSError + return nativeError.domain == SCStreamError.errorDomain + && nativeError.code == SCStreamError.Code.userStopped.rawValue + } } #else public extension SpeechSession { @@ -531,8 +593,9 @@ public extension SpeechSession { extension SpeechSession { 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 057c112..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. @@ -212,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) { @@ -231,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") } @@ -240,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 } @@ -249,15 +272,20 @@ 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? @@ -273,6 +301,8 @@ extension SpeechSession { if Self.shouldLog(.debug) { Self.logger.debug("Stopping transcriber and cleaning up") } + analyzerInputTask?.cancel() + analyzerInputTask = nil let detached = DetachedTranscriberState( inputBuilder: inputBuilder, analyzer: analyzer, vocabularyArtifacts: activeCustomVocabularyArtifacts @@ -293,29 +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, - cancelAnalysis: Bool = false - ) async { + func cleanUpDetachedTranscriberState(_ detached: DetachedTranscriberState, cancelAnalyzer: Bool) async { defer { withExtendedLifetime(detached.vocabularyArtifacts) {} } detached.inputBuilder?.finish() - if cancelAnalysis { - // Finalizing waits for EOF, which may never arrive if setup was cancelled. - await detached.analyzer?.cancelAndFinishNow() - return - } - 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.swift b/Sources/AuralKit/SpeechSession.swift index 8c3008d..a02d504 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,7 +75,7 @@ public final class SpeechSession { var nativeCaptureSession: AVCaptureSession? var nativeCaptureAnalysisTask: Task? var screenCaptureInputProvider: AnyObject? - var screenCaptureStopTask: (generation: Int, task: Task)? + var screenCaptureStopTask: (generation: Int, task: Task)? var voiceActivationConfiguration: VoiceActivationConfiguration? var customVocabularyDescriptor: CustomVocabulary? var customVocabularyConfiguration: SFSpeechLanguageModel.Configuration? @@ -100,6 +101,9 @@ public final class SpeechSession { var continuation: TranscriptionContinuation? var recognizerTask: Task? var pipelineTask: Task? + var finishTask: Task? + var terminationTask: Task? + var cancellationRequested = false var fileIngestionTask: Task? var streamingMode: StreamingMode = .inactive /// Incremented for every accepted start so stale termination handlers can be ignored. @@ -267,7 +271,7 @@ public final class SpeechSession { /// /// The returned `AsyncThrowingStream` yields `SpeechTranscriber.Result` chunks containing both text and /// timing metadata (`.audioTimeRange`), as well as whether the result is final or volatile (partial). - /// Consume the stream with `for try await` and call `stopTranscribing()` to finish early. + /// Consume the stream with `for try await` and call `finishTranscribing()` to finish capture. /// /// - Parameter contextualStrings: Optional dictionary mapping contextual strings tags /// to arrays of contextual words that help improve transcription accuracy. For example, @@ -305,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) } @@ -345,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. @@ -385,11 +393,8 @@ public final class SpeechSession { 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 2b1d8ff..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) } diff --git a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift index 6efec35..0315234 100644 --- a/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift +++ b/Tests/AuralKitTests/CustomVocabularyOwnershipTests.swift @@ -126,7 +126,7 @@ struct CustomVocabularyOwnershipTests { try await owner!.configureCustomVocabulary(nil) owner = nil try assertFiles(in: directory) - await SpeechSession().finalizeDetachedTranscriberState(try #require(detached)) + await SpeechSession().cleanUpDetachedTranscriberState(try #require(detached), cancelAnalyzer: true) try assertFiles(in: directory) detached = nil #expect(!FileManager.default.fileExists(atPath: directory.path)) diff --git a/Tests/AuralKitTests/FileProgressTests.swift b/Tests/AuralKitTests/FileProgressTests.swift index 0a86f0e..04721db 100644 --- a/Tests/AuralKitTests/FileProgressTests.swift +++ b/Tests/AuralKitTests/FileProgressTests.swift @@ -22,7 +22,7 @@ struct FileProgressTests { case "stopping": session.prepareForStop() case "stopped": - await session.stopTranscribing() + await session.cancelTranscribing() case "replacement": _ = session.beginStreamGeneration() default: @@ -41,6 +41,6 @@ struct FileProgressTests { var received: [Double] = [] for await value in progress { received.append(value) } #expect(received == [0.25]) - await session.stopTranscribing() + await session.cancelTranscribing() } } diff --git a/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index b50701a..d9c931b 100644 --- a/Tests/AuralKitTests/FileTranscriptionTests.swift +++ b/Tests/AuralKitTests/FileTranscriptionTests.swift @@ -32,9 +32,9 @@ struct FileTranscriptionTests { } #if swift(>=6.4) - @Test("Stopping a media analyzer before it receives input closes the session") + @Test("Cancelling a media analyzer before it receives input closes the session") @MainActor - func stopBeforeAnalyzerInputClosesSession() async throws { + func cancelBeforeAnalyzerInputClosesSession() async throws { let session = SpeechSession() let (results, continuation) = AsyncThrowingStream.makeStream() let analyzer = SpeechAnalyzer(modules: []) @@ -46,19 +46,19 @@ struct FileTranscriptionTests { let watchdog = Task { do { try await Task.sleep(for: .seconds(3)) - Issue.record("Stopping an analyzer with no input did not return") + Issue.record("Cancelling an analyzer with no input did not return") await analyzer.cancelAndFinishNow() } catch is CancellationError { - // Stop completed before the deadline. + // Cancel completed before the deadline. } } - await session.stopTranscribing() + await session.cancelTranscribing() watchdog.cancel() try await watchdog.value - var iterator = results.makeAsyncIterator() - let nextResult = try await iterator.next() - #expect(nextResult == nil) + await #expect(throws: CancellationError.self) { + for try await _ in results {} + } #expect(session.status == .idle) } 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/ScreenCaptureTransitionTests.swift b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift index e7ac85a..876b70d 100644 --- a/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureTransitionTests.swift @@ -34,7 +34,7 @@ final class CaptureSessionFixture { func close(_ fixture: CaptureFixture) async { fixture.releaseAll() - await session.stopTranscribing() + await session.cancelTranscribing() } } @@ -108,13 +108,13 @@ struct ScreenCaptureTransitionTests { try await entered.wait() var firstReturned = false, secondReturned = false let first = fixture.track(Task { - await runtime.session.stopTranscribing(); firstReturned = true + 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.stopTranscribing(); secondReturned = true + await runtime.session.cancelTranscribing(); secondReturned = true }) try await secondEntered.wait() #expect(!firstReturned && !secondReturned) diff --git a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift index d65ef4d..92ba0f4 100644 --- a/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift +++ b/Tests/AuralKitTests/ScreenCaptureUpdateTests.swift @@ -26,7 +26,7 @@ struct ScreenCaptureUpdateTests { }) try await started.wait() if stopFirst { - fixture.track(Task { await runtime.session.stopTranscribing() }) + fixture.track(Task { await runtime.session.cancelTranscribing() }) } await fixture.track(Task { @MainActor in if stopFirst { #expect(runtime.session.status == .stopping) } @@ -126,7 +126,11 @@ struct ScreenCaptureUpdateTests { try await updating.wait() #expect(stream.capturing && stream.starts == 1 && stream.stops == 0) let control = fixture.track(Task { - if stop { await runtime.session.stopTranscribing() } else { await runtime.session.pauseTranscribing() } + 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 }) diff --git a/Tests/AuralKitTests/SessionLifecycleTests.swift b/Tests/AuralKitTests/SessionLifecycleTests.swift index bc50a4f..b30fe30 100644 --- a/Tests/AuralKitTests/SessionLifecycleTests.swift +++ b/Tests/AuralKitTests/SessionLifecycleTests.swift @@ -113,12 +113,12 @@ 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) } @@ -138,10 +138,80 @@ struct SpeechSessionLifecycleTests { ) #expect(session.pipelineTask == successor) - await session.stopTranscribing() + 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")