geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
import Foundation
import HydraulophoneCore
/// 64 KiB ranges with a 512 KiB memory LRU and optional encoded disk cache.
/// Expiring media URLs and credentials remain in memory.
actor NativeOpusByteSource {
private let descriptor: StreamingMediaDescriptor
private let transport: URLSessionStreamingDataTransport
private let chunkSize = 64 * 1024
private var totalLength: Int64?
private var cache: [Int64: Data] = [:]
private var order: [Int64] = []
private var cancelled = false
private let diskCache: TrackCacheStore?
private let cachedFile: CachedTrackFile?
private let cacheIdentity: TrackAssetIdentity?
private let bitrate: Int?
private let duration: TimeInterval?
private let loudness: AudioLoudnessMetadata?
private let song: Song?
private var writeTicket: TrackCacheWrite?
private var requestedTicket = false
init(stream: PlaybackResolvedStream, cache: TrackCacheStore? = nil) {
diskCache = cache
cachedFile = stream.cachedFile
cacheIdentity = stream.cacheIdentity
bitrate = stream.bitrate
duration = stream.authoritativeDuration
loudness = stream.loudness
song = stream.song
totalLength = stream.cacheIdentity?.contentLength
var headers = stream.mediaHeaders
if let userAgent = stream.userAgent { headers["User-Agent"] = userAgent }
let descriptor = StreamingMediaDescriptor(url: stream.url, mediaHeaders: headers)
self.descriptor = descriptor
self.transport = URLSessionStreamingDataTransport(
descriptor: descriptor, maximumResponseBytes: 64 * 1024)
}
func cancel() {
cancelled = true
transport.cancelAll()
cache.removeAll()
order.removeAll()
}
func read(offset: Int64, count: Int) async throws -> Data {
try checkCancellation()
if let cachedFile {
return try await cachedFile.read(offset: offset, count: count)
}
guard offset >= 0, count >= 0, count <= 4 * 1024 * 1024,
offset <= Int64.max - Int64(count)
else { throw StreamingResourceLoaderError.invalidLoadingRequest }
var result = Data()
var position = offset
while result.count < count {
try checkCancellation()
if let totalLength, position >= totalLength { break }
let base = position / Int64(chunkSize) * Int64(chunkSize)
let bytes = try await chunk(at: base)
let local = Int(position - base)
guard local < bytes.count else { break }
let length = min(count - result.count, bytes.count - local)
result.append(bytes.subdata(in: local..<(local + length)))
position += Int64(length)
}
return result
}
private func chunk(at offset: Int64) async throws -> Data {
if let cached = cache[offset] {
touch(offset)
return cached
}
if !requestedTicket {
requestedTicket = true
if let cacheIdentity {
writeTicket = await diskCache?.writer(
identity: cacheIdentity, bitrate: bitrate, duration: duration, loudness: loudness,
song: song)
}
}
if let writeTicket, let bytes = await diskCache?.read(writeTicket, offset: offset) {
try checkCancellation()
remember(bytes, at: offset)
return bytes
}
guard StreamingURLPolicy.isAllowedMediaURL(descriptor.url) else {
throw StreamingResourceLoaderError.invalidMediaURL
}
let end = min(offset + Int64(chunkSize) - 1, totalLength.map { $0 - 1 } ?? Int64.max)
var request = URLRequest(
url: descriptor.url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
request.setValue("bytes=\(offset)-\(end)", forHTTPHeaderField: "Range")
for (name, value) in descriptor.mediaHeaders {
request.setValue(value, forHTTPHeaderField: name)
}
let (data, response) = try await transport.data(for: request)
try checkCancellation()
guard let http = response as? HTTPURLResponse else {
throw StreamingResourceLoaderError.transport
}
guard http.statusCode == 206 else {
if http.statusCode == 416, let totalLength, offset >= totalLength { return Data() }
throw StreamingResourceLoaderError.unexpectedHTTPStatus(status: http.statusCode)
}
guard let value = http.value(forHTTPHeaderField: "Content-Range"),
let parsed = StreamingResourceLoader.parseContentRange(value),
parsed.range.start == offset, parsed.range.end <= end,
parsed.range.length == Int64(data.count), !data.isEmpty
else { throw StreamingResourceLoaderError.contentRangeMismatch }
if let totalLength, totalLength != parsed.totalLength {
throw StreamingResourceLoaderError.metadataMismatch
}
totalLength = parsed.totalLength
if let writeTicket {
await diskCache?.store(
data, offset: offset, totalLength: parsed.totalLength, ticket: writeTicket)
}
try checkCancellation()
remember(data, at: offset)
return data
}
private func remember(_ data: Data, at offset: Int64) {
cache[offset] = data
touch(offset)
while order.count > 8 { cache.removeValue(forKey: order.removeFirst()) }
}
private func touch(_ offset: Int64) {
order.removeAll { $0 == offset }
order.append(offset)
}
private func checkCancellation() throws {
try Task.checkCancellation()
if cancelled { throw CancellationError() }
}
}