import Foundation import HydraulophoneCore /// One bounded, decoded head of a track. Each queue occurrence owns its own /// decoder, even when Repeat One prepares the same song again. @MainActor final class NativeOpusPreparedTrack { let id: UUID let stream: PlaybackResolvedStream var loudness: AudioLoudnessMetadata? let source: NativeOpusByteSource let pcm: NativeOpusPCMSource let firstChunk: NativeOpusPCMChunk private let metadataDuration: TimeInterval var decodedDuration: TimeInterval? var duration: TimeInterval { decodedDuration ?? metadataDuration } private init( id: UUID, stream: PlaybackResolvedStream, source: NativeOpusByteSource, pcm: NativeOpusPCMSource, firstChunk: NativeOpusPCMChunk, duration: TimeInterval ) { self.id = id self.stream = stream loudness = stream.loudness self.source = source self.pcm = pcm self.firstChunk = firstChunk metadataDuration = duration } static func prepare( stream: PlaybackResolvedStream, id: UUID = UUID(), cache: TrackCacheStore? = nil ) async throws -> NativeOpusPreparedTrack { let source = NativeOpusByteSource(stream: stream, cache: cache) let pcm = NativeOpusPCMSource(source: source) do { let track = try await pcm.prepare() guard let first = try await pcm.nextChunk() else { throw NativeOpusError.emptyStream } try Task.checkCancellation() return NativeOpusPreparedTrack( id: id, stream: stream, source: source, pcm: pcm, firstChunk: first, duration: stream.authoritativeDuration ?? PlaybackDurationPolicy.valid(track.duration) ?? 0) } catch { await source.cancel() throw error } } func cancel() { let source = source Task { await source.cancel() } } }