diff --git a/README.md b/README.md index 4359c19..ac6582d 100644 --- a/README.md +++ b/README.md @@ -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) @@ -276,6 +278,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: diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index 788925d..8e63ce9 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. @@ -152,22 +132,12 @@ 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, generation: generation - ) - - if completed, let handler { - self.reportFileProgress(1.0, handler: handler, generation: generation) - } - } 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 { @@ -213,7 +183,9 @@ private extension SpeechSession { return (audioFile, totalFrames) } +} +extension SpeechSession { func sanitizeAudioFileURL( _ url: URL, allowedDirectories: [URL] @@ -247,6 +219,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) { @@ -266,13 +239,15 @@ 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)") } } +} +private extension SpeechSession { nonisolated func feedAudioFile( _ payload: (file: AVAudioFile, totalFrames: AVAudioFramePosition), progressHandler: (@Sendable (Double) -> Void)?, @@ -344,10 +319,53 @@ 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] _ in + 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) + } catch is CancellationError { + // Cleanup cancelled the ingestion task. + } catch { + await finishWithStartupError(error, generation: generation) + } + } + } + func reportFileProgress( _ progress: Double, handler: @Sendable (Double) -> Void, diff --git a/Sources/AuralKit/SpeechSession+MediaFile.swift b/Sources/AuralKit/SpeechSession+MediaFile.swift new file mode 100644 index 0000000..56903fb --- /dev/null +++ b/Sources/AuralKit/SpeechSession+MediaFile.swift @@ -0,0 +1,145 @@ +#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. + session.prepareForStop() + await session.cleanup(cancelRecognizer: true, generation: generation) + await session.finishStream(error: nil, 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+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 97c0395..8487114 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -296,6 +296,7 @@ extension SpeechSession { task?.cancel() } + let cancelMediaAnalysis = cancelRecognizer && streamingMode == .mediaPlayback streamingMode = .inactive activeResultKind = nil stopAudioStreaming() @@ -306,7 +307,7 @@ extension SpeechSession { #endif let detached = detachTranscriberState() await stopScreenCaptureStreamingIfNeeded() - await finalizeDetachedTranscriberState(detached) + await finalizeDetachedTranscriberState(detached, cancelAnalysis: cancelMediaAnalysis) guard generation == sessionGeneration else { return } await modelManager.releaseLocales() @@ -443,6 +444,7 @@ extension SpeechSession { for try await result in results { streamContinuation.yield(result) } + try Task.checkCancellation() if Self.shouldLog(.notice) { Self.logger.notice("\(label, privacy: .public) completed without error") } @@ -452,6 +454,7 @@ extension SpeechSession { Self.logger.debug("\(label, privacy: .public) cancelled") } } 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+Transcriber.swift b/Sources/AuralKit/SpeechSession+Transcriber.swift index 460ddcf..057c112 100644 --- a/Sources/AuralKit/SpeechSession+Transcriber.swift +++ b/Sources/AuralKit/SpeechSession+Transcriber.swift @@ -297,9 +297,17 @@ extension SpeechSession { /// /// 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 finalizeDetachedTranscriberState( + _ detached: DetachedTranscriberState, + cancelAnalysis: Bool = false + ) 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 { 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/Tests/AuralKitTests/FileTranscriptionTests.swift b/Tests/AuralKitTests/FileTranscriptionTests.swift index 68fd118..b50701a 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("Stopping a media analyzer before it receives input closes the session") + @MainActor + func stopBeforeAnalyzerInputClosesSession() 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("Stopping an analyzer with no input did not return") + await analyzer.cancelAndFinishNow() + } catch is CancellationError { + // Stop completed before the deadline. + } + } + await session.stopTranscribing() + watchdog.cancel() + try await watchdog.value + + var iterator = results.makeAsyncIterator() + let nextResult = try await iterator.next() + #expect(nextResult == nil) + #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)