diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index ce73f0e..2fabcc5 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -44,3 +44,4 @@ {"id":"int-b2667330","kind":"field_change","created_at":"2026-05-25T23:44:07.439593Z","actor":"dirtydishes","issue_id":"dreamio-9gw","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Capped local range-cache responses to 1 MB chunks, trimmed cached overlap windows, added focused tests, and confirmed the iOS simulator build succeeds."}} {"id":"int-6ca684f7","kind":"field_change","created_at":"2026-05-26T04:00:46.072019Z","actor":"dirtydishes","issue_id":"dreamio-42s","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Fixed seek-time range-cache prefetching to prioritize the post-seek byte offset and avoid cancelling active prefetch work inside the same window; added focused coverage and validated with StreamResolverTests plus xcodebuild."}} {"id":"int-176e3ad2","kind":"field_change","created_at":"2026-05-26T04:14:19.812849Z","actor":"dirtydishes","issue_id":"dreamio-meh","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Fixed range-cache prefetch reprioritization so foreground VLC misses cancel stale speculative work and restart around VLC's actual requested byte range; added regression coverage for the observed jump mismatch."}} +{"id":"int-56a87fde","kind":"field_change","created_at":"2026-05-26T04:35:35.693504Z","actor":"dirtydishes","issue_id":"dreamio-3pn","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented backward-biased seek priming, global 1 MB range-cache chunk alignment, bounded protected eviction, partial foreground miss fetching/logging, main-actor VLC delegate handling, tests, and turn documentation."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 9ddaebb..a549252 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,5 +1,6 @@ {"_type":"issue","id":"dreamio-mun","title":"fix vlc cache loopback port startup","description":"Device logs showed local-cache playback opening http://127.0.0.1:0, because the NWListener ephemeral port was read before the listener reached ready. Wait for the real assigned port before returning the local cache URL.","status":"closed","priority":0,"issue_type":"bug","assignee":"dirtydishes","owner":"dishes@dpdrm.com","created_at":"2026-05-25T22:32:41Z","created_by":"dirtydishes","updated_at":"2026-05-25T22:33:15Z","started_at":"2026-05-25T22:33:14Z","closed_at":"2026-05-25T22:33:15Z","close_reason":"Wait for NWListener ready state before returning the local cache URL; verified tests and simulator build.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"dreamio-8cz","title":"fix stremio external subtitle loading regression","description":"After adding late subtitle forwarding for native playback, Stremio external subtitle loading is failing. Investigate the injected bridge and native subtitle forwarding path, then adjust behavior so Stremio can still load external subtitles while native playback receives late candidates.","status":"closed","priority":0,"issue_type":"bug","assignee":"dirtydishes","owner":"dishes@dpdrm.com","created_at":"2026-05-25T11:05:42Z","created_by":"dirtydishes","updated_at":"2026-05-25T11:07:35Z","started_at":"2026-05-25T11:05:55Z","closed_at":"2026-05-25T11:07:35Z","close_reason":"Hardened subtitle bridge network observers so non-text Stremio subtitle loads are not touched, and made parser traversal deterministic for metadata preservation.","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"dreamio-3pn","title":"reduce vlc seek buffering with range cache priming","description":"Improve VLC local range cache behavior after seek/jump by priming bytes behind the target, using stable global chunk boundaries, retaining useful cached ranges under a byte budget, and adding tests for the observed post-seek request pattern.","status":"closed","priority":1,"issue_type":"task","assignee":"dirtydishes","owner":"dishes@dpdrm.com","created_at":"2026-05-26T04:31:46Z","created_by":"dirtydishes","updated_at":"2026-05-26T04:35:36Z","started_at":"2026-05-26T04:31:51Z","closed_at":"2026-05-26T04:35:36Z","close_reason":"Implemented backward-biased seek priming, global 1 MB range-cache chunk alignment, bounded protected eviction, partial foreground miss fetching/logging, main-actor VLC delegate handling, tests, and turn documentation.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"dreamio-meh","title":"Use VLC range requests to reprioritize seek prefetch","description":"Jump logs show duration-based byteOffset estimates can be far behind VLC's actual post-seek range requests, so prefetch keeps warming stale bytes while VLC buffers on higher cache misses.","status":"closed","priority":1,"issue_type":"bug","assignee":"dirtydishes","owner":"dishes@dpdrm.com","created_at":"2026-05-26T04:11:38Z","created_by":"dirtydishes","updated_at":"2026-05-26T04:14:20Z","started_at":"2026-05-26T04:11:40Z","closed_at":"2026-05-26T04:14:20Z","close_reason":"Fixed range-cache prefetch reprioritization so foreground VLC misses cancel stale speculative work and restart around VLC's actual requested byte range; added regression coverage for the observed jump mismatch.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"dreamio-42s","title":"Reduce VLC range-cache buffering after seeks","description":"Logs show repeated local-cache misses and cancelled prefetch tasks after VLC jumps backward, causing buffering while the cache restarts speculative requests instead of preserving useful adjacent downloads.","status":"closed","priority":1,"issue_type":"bug","assignee":"dirtydishes","owner":"dishes@dpdrm.com","created_at":"2026-05-26T03:58:03Z","created_by":"dirtydishes","updated_at":"2026-05-26T04:00:46Z","started_at":"2026-05-26T03:58:10Z","closed_at":"2026-05-26T04:00:46Z","close_reason":"Fixed seek-time range-cache prefetching to prioritize the post-seek byte offset and avoid cancelling active prefetch work inside the same window; added focused coverage and validated with StreamResolverTests plus xcodebuild.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"dreamio-9gw","title":"Cap VLC local range cache memory","description":"Playback can be killed for memory when VLC asks the loopback cache for a very large byte range. The local range cache should answer with bounded partial ranges and trim cached segments to the active window.","status":"closed","priority":1,"issue_type":"bug","owner":"dishes@dpdrm.com","created_at":"2026-05-25T23:38:08Z","created_by":"dirtydishes","updated_at":"2026-05-25T23:44:07Z","closed_at":"2026-05-25T23:44:07Z","close_reason":"Capped local range-cache responses to 1 MB chunks, trimmed cached overlap windows, added focused tests, and confirmed the iOS simulator build succeeds.","dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/Dreamio/ProgressiveHTTPRangeCache.swift b/Dreamio/ProgressiveHTTPRangeCache.swift index a950b71..708080f 100644 --- a/Dreamio/ProgressiveHTTPRangeCache.swift +++ b/Dreamio/ProgressiveHTTPRangeCache.swift @@ -73,6 +73,12 @@ final class SparseHTTPByteRangeStore { } } + var cachedByteCount: Int64 { + lock.withLock { + segments.reduce(0) { $0 + Int64($1.data.count) } + } + } + func insert(data: Data, at start: Int64) { guard !data.isEmpty else { return @@ -117,6 +123,33 @@ final class SparseHTTPByteRangeStore { data(for: range) != nil } + func missingRanges(in range: HTTPByteRange) -> [HTTPByteRange] { + lock.withLock { + var cursor = range.start + var missing: [HTTPByteRange] = [] + + for segment in segments where segment.range.end >= cursor { + guard segment.range.start <= range.end else { + break + } + if segment.range.start > cursor { + missing.append(HTTPByteRange(start: cursor, end: min(range.end, segment.range.start - 1))) + } + if segment.range.end >= cursor { + cursor = max(cursor, segment.range.end + 1) + } + if cursor > range.end { + break + } + } + + if cursor <= range.end { + missing.append(HTTPByteRange(start: cursor, end: range.end)) + } + return missing + } + } + func evict(keeping window: HTTPByteRange) { lock.withLock { segments = segments.compactMap { segment in @@ -135,6 +168,61 @@ final class SparseHTTPByteRangeStore { } } + func evict(toByteBudget byteBudget: Int64, preserving protectedRanges: [HTTPByteRange]) -> [HTTPByteRange] { + lock.withLock { + guard byteBudget > 0 else { + let evicted = segments.map(\.range) + segments.removeAll() + return evicted + } + + var totalBytes = segments.reduce(0) { $0 + Int64($1.data.count) } + guard totalBytes > byteBudget else { + return [] + } + + var evicted: [HTTPByteRange] = [] + while totalBytes > byteBudget, + let index = evictionCandidateIndex(protectedRanges: protectedRanges) { + let removed = segments.remove(at: index) + totalBytes -= Int64(removed.data.count) + evicted.append(removed.range) + } + return evicted + } + } + + private func evictionCandidateIndex(protectedRanges: [HTTPByteRange]) -> Int? { + var bestIndex: Int? + var bestDistance: Int64 = .min + + for (index, segment) in segments.enumerated() { + if protectedRanges.contains(where: { $0.overlapsOrTouches(segment.range) }) { + continue + } + + let distance = protectedRanges + .map { rangeDistance(from: segment.range, to: $0) } + .min() ?? segment.range.start + if distance > bestDistance { + bestDistance = distance + bestIndex = index + } + } + + return bestIndex + } + + private func rangeDistance(from range: HTTPByteRange, to protectedRange: HTTPByteRange) -> Int64 { + if range.overlapsOrTouches(protectedRange) { + return 0 + } + if range.end < protectedRange.start { + return protectedRange.start - range.end + } + return range.start - protectedRange.end + } + private func mergeSegments() { guard !segments.isEmpty else { return @@ -257,14 +345,24 @@ final class ProgressiveHTTPRangeCacheSession { let durationProvider: () -> TimeInterval private let prefetchChunkSize: Int64 = 1_048_576 private let responseChunkSize: Int64 = 1_048_576 + private let seekPrimeBehindBytes: Int64 = 4 * 1_048_576 + private let cacheByteBudget: Int64 private var prefetchTask: Task? private var activePrefetchWindow: HTTPByteRange? private var activePrefetchPreferredOffset: Int64? + private var recentSeekRange: HTTPByteRange? + private var recentForegroundRange: HTTPByteRange? - init(fetcher: HTTPRangeRemoteFetcher, contentLength: Int64, durationProvider: @escaping () -> TimeInterval) { + init( + fetcher: HTTPRangeRemoteFetcher, + contentLength: Int64, + durationProvider: @escaping () -> TimeInterval, + cacheByteBudget: Int64 = 64 * 1_048_576 + ) { self.fetcher = fetcher self.contentLength = contentLength self.durationProvider = durationProvider + self.cacheByteBudget = cacheByteBudget } deinit { @@ -273,6 +371,7 @@ final class ProgressiveHTTPRangeCacheSession { func data(for requestedRange: HTTPByteRange) async throws -> Data { let bounded = clamp(requestedRange) + recentForegroundRange = bounded if let data = store.data(for: bounded) { #if DEBUG print("[DreamioRangeCache] cache=hit range=\(bounded.start)-\(bounded.end)") @@ -280,14 +379,18 @@ final class ProgressiveHTTPRangeCacheSession { return data } + let missingRanges = store.missingRanges(in: bounded) #if DEBUG - print("[DreamioRangeCache] cache=miss range=\(bounded.start)-\(bounded.end)") + let missKind = missingRanges.count == 1 && missingRanges[0] == bounded ? "uncached" : "partial-miss" + print("[DreamioRangeCache] cache=\(missKind) range=\(bounded.start)-\(bounded.end) missing=\(missingRanges.map { "\($0.start)-\($0.end)" }.joined(separator: ","))") #endif cancelPrefetchIfNeeded(forForegroundRange: bounded) - let data = try await fetcher.fetch(range: bounded) - store.insert(data: data, at: bounded.start) + for missingRange in missingRanges { + let data = try await fetcher.fetch(range: missingRange) + store.insert(data: data, at: missingRange.start) + } prefetch(aroundByteOffset: bounded.end + 1, forceRestart: true) - return store.data(for: bounded) ?? data + return store.data(for: bounded) ?? Data() } func responseRange(for requestedRange: HTTPByteRange) -> HTTPByteRange { @@ -299,30 +402,54 @@ final class ProgressiveHTTPRangeCacheSession { } func prefetch(aroundByteOffset offset: Int64) { - prefetch(aroundByteOffset: offset, forceRestart: false) + prefetch(aroundByteOffset: offset, forceRestart: false, startsAtWindowStart: false) + } + + func prefetchForSeek(aroundByteOffset offset: Int64) { + let window = seekPrimeWindow(aroundByteOffset: offset) + recentSeekRange = window + prefetch( + aroundByteOffset: offset, + forceRestart: true, + explicitWindow: window, + startsAtWindowStart: true + ) + } + + func seekPrimeWindow(aroundByteOffset offset: Int64) -> HTTPByteRange { + targetWindow(aroundByteOffset: offset, minimumBehind: seekPrimeBehindBytes) } func prefetch(aroundByteOffset offset: Int64, forceRestart: Bool) { + prefetch(aroundByteOffset: offset, forceRestart: forceRestart, startsAtWindowStart: false) + } + + private func prefetch( + aroundByteOffset offset: Int64, + forceRestart: Bool, + explicitWindow: HTTPByteRange? = nil, + startsAtWindowStart: Bool + ) { if !forceRestart, activePrefetchWindow?.contains(offset) == true, prefetchTask?.isCancelled == false { return } prefetchTask?.cancel() - let window = targetWindow(aroundByteOffset: offset) + let window = explicitWindow ?? targetWindow(aroundByteOffset: offset) activePrefetchWindow = window activePrefetchPreferredOffset = offset - store.evict(keeping: window) + evictOverBudget(protecting: window) guard !store.hasData(for: window) else { activePrefetchWindow = nil activePrefetchPreferredOffset = nil return } - prefetchTask = Task { [weak self] in + prefetchTask = Task(priority: startsAtWindowStart ? .userInitiated : .utility) { [weak self] in guard let self else { return } - for chunk in self.prefetchChunks(in: window, preferredOffset: offset) { + for chunk in self.prefetchChunks(in: window, preferredOffset: offset, startsAtWindowStart: startsAtWindowStart) { guard !Task.isCancelled else { return } @@ -330,6 +457,7 @@ final class ProgressiveHTTPRangeCacheSession { do { let data = try await fetcher.fetch(range: chunk) store.insert(data: data, at: chunk.start) + evictOverBudget(protecting: window) #if DEBUG print("[DreamioRangeCache] fetched range=\(chunk.start)-\(chunk.end) bytes=\(data.count)") #endif @@ -373,15 +501,25 @@ final class ProgressiveHTTPRangeCacheSession { } private func targetWindow(aroundByteOffset offset: Int64) -> HTTPByteRange { + targetWindow(aroundByteOffset: offset, minimumBehind: prefetchChunkSize) + } + + private func targetWindow(aroundByteOffset offset: Int64, minimumBehind: Int64) -> HTTPByteRange { let bytesPerSecond = estimatedBytesPerSecond() - let behind = max(prefetchChunkSize, bytesPerSecond * 30) + let behind = max(minimumBehind, bytesPerSecond * 30) let ahead = max(prefetchChunkSize * 2, bytesPerSecond * 60) - return clamp(HTTPByteRange(start: offset - behind, end: offset + ahead)) + let raw = clamp(HTTPByteRange(start: offset - behind, end: offset + ahead)) + return HTTPByteRange(start: alignedChunkStart(for: raw.start), end: alignedChunkEnd(for: raw.end)) } func prefetchChunks(in window: HTTPByteRange, preferredOffset offset: Int64) -> [HTTPByteRange] { + prefetchChunks(in: window, preferredOffset: offset, startsAtWindowStart: false) + } + + func prefetchChunks(in window: HTTPByteRange, preferredOffset offset: Int64, startsAtWindowStart: Bool) -> [HTTPByteRange] { let boundedOffset = max(window.start, min(window.end, offset)) - let preferredStart = window.start + ((boundedOffset - window.start) / prefetchChunkSize) * prefetchChunkSize + let windowStart = alignedChunkStart(for: window.start) + let preferredStart = startsAtWindowStart ? windowStart : alignedChunkStart(for: boundedOffset) var chunks: [HTTPByteRange] = [] var cursor = preferredStart @@ -391,7 +529,7 @@ final class ProgressiveHTTPRangeCacheSession { cursor = chunk.end + 1 } - cursor = window.start + cursor = windowStart while cursor < preferredStart { let chunk = HTTPByteRange(start: cursor, end: min(preferredStart - 1, cursor + prefetchChunkSize - 1)) chunks.append(chunk) @@ -401,6 +539,27 @@ final class ProgressiveHTTPRangeCacheSession { return chunks } + private func evictOverBudget(protecting range: HTTPByteRange) { + let headerRange = HTTPByteRange(start: 0, end: min(contentLength - 1, prefetchChunkSize - 1)) + let tailStart = max(0, contentLength - (4 * prefetchChunkSize)) + let tailRange = HTTPByteRange(start: tailStart, end: contentLength - 1) + let protectedRanges = [range, recentSeekRange, recentForegroundRange, activePrefetchWindow, headerRange, tailRange].compactMap { $0 } + let evicted = store.evict(toByteBudget: cacheByteBudget, preserving: protectedRanges) +#if DEBUG + if !evicted.isEmpty { + print("[DreamioRangeCache] evicted reason=budget ranges=\(evicted.map { "\($0.start)-\($0.end)" }.joined(separator: ",")) protected=\(protectedRanges.map { "\($0.start)-\($0.end)" }.joined(separator: ","))") + } +#endif + } + + private func alignedChunkStart(for offset: Int64) -> Int64 { + max(0, (offset / prefetchChunkSize) * prefetchChunkSize) + } + + private func alignedChunkEnd(for offset: Int64) -> Int64 { + min(contentLength - 1, alignedChunkStart(for: offset) + prefetchChunkSize - 1) + } + private func estimatedBytesPerSecond() -> Int64 { let duration = durationProvider() guard duration > 1 else { diff --git a/Dreamio/VLCNativePlaybackBackend.swift b/Dreamio/VLCNativePlaybackBackend.swift index 4dcb69a..1bb340a 100644 --- a/Dreamio/VLCNativePlaybackBackend.swift +++ b/Dreamio/VLCNativePlaybackBackend.swift @@ -151,7 +151,7 @@ final class VLCNativePlaybackBackend: NSObject, NativePlaybackBackend { return } let clamped = max(0, min(1, position)) - rangeCacheSession?.prefetch(aroundByteOffset: rangeCacheSession?.byteOffset(for: clamped) ?? 0) + rangeCacheSession?.prefetchForSeek(aroundByteOffset: rangeCacheSession?.byteOffset(for: clamped) ?? 0) #if DEBUG if let byteOffset = rangeCacheSession?.byteOffset(for: clamped) { print("[DreamioVLC] seek targetPosition=\(clamped) byteOffset=\(byteOffset) mode=local-cache") @@ -171,7 +171,7 @@ final class VLCNativePlaybackBackend: NSObject, NativePlaybackBackend { let nextTime = max(0, min(duration, currentTime + seconds)) if duration > 0 { let nextPosition = Float(nextTime / duration) - rangeCacheSession?.prefetch(aroundByteOffset: rangeCacheSession?.byteOffset(for: nextPosition) ?? 0) + rangeCacheSession?.prefetchForSeek(aroundByteOffset: rangeCacheSession?.byteOffset(for: nextPosition) ?? 0) #if DEBUG if let byteOffset = rangeCacheSession?.byteOffset(for: nextPosition) { print("[DreamioVLC] jump seconds=\(seconds) target=\(nextTime) byteOffset=\(byteOffset) mode=local-cache") @@ -604,6 +604,13 @@ final class VLCNativePlaybackBackend: NSObject, NativePlaybackBackend { #if canImport(MobileVLCKit) extension VLCNativePlaybackBackend: VLCMediaPlayerDelegate { func mediaPlayerStateChanged(_ aNotification: Notification) { + Task { @MainActor [weak self] in + self?.handleMediaPlayerStateChanged() + } + } + + @MainActor + private func handleMediaPlayerStateChanged() { #if DEBUG logPlaybackStateIfNeeded(stateName(mediaPlayer.state)) #endif diff --git a/Tests/StreamResolverTests.swift b/Tests/StreamResolverTests.swift index 3a00f2c..679675a 100644 --- a/Tests/StreamResolverTests.swift +++ b/Tests/StreamResolverTests.swift @@ -35,8 +35,11 @@ struct StreamResolverTests { testSparseRangeStoreHitPartialHitAndMiss() testSparseRangeStoreEvictsOutsideWindow() testSparseRangeStoreTrimsOverlappingWindow() + testSparseRangeStoreEvictsByBudgetWhilePreservingUsefulRanges() testRangeCacheSessionCapsResponseRange() testRangeCachePrefetchPrioritizesSeekOffset() + testRangeCacheSeekPrimingIncludesObservedVLCStart() + testRangeCachePrefetchUsesGlobalChunkBoundaries() await testRangeCacheForegroundMissReprioritizesPrefetch() await testRangeProbeFallsBackWhenServerIgnoresRange() await testRangeFetcherPreservesHeaders() @@ -334,6 +337,28 @@ struct StreamResolverTests { assert(store.data(for: HTTPByteRange(start: 0, end: 5)) == nil, "Expected trimmed bytes outside the window to be evicted") } + private static func testSparseRangeStoreEvictsByBudgetWhilePreservingUsefulRanges() { + let store = SparseHTTPByteRangeStore() + + store.insert(data: Data(repeating: 1, count: 4), at: 0) + store.insert(data: Data(repeating: 2, count: 4), at: 100) + store.insert(data: Data(repeating: 3, count: 4), at: 200) + + let evicted = store.evict( + toByteBudget: 8, + preserving: [ + HTTPByteRange(start: 0, end: 3), + HTTPByteRange(start: 190, end: 210) + ] + ) + + assertEqual(evicted, [HTTPByteRange(start: 100, end: 103)]) + assertEqual(store.cachedRanges, [ + HTTPByteRange(start: 0, end: 3), + HTTPByteRange(start: 200, end: 203) + ]) + } + private static func testRangeCacheSessionCapsResponseRange() { let session = ProgressiveHTTPRangeCacheSession( fetcher: HTTPRangeRemoteFetcher(url: URL(string: "https://example.test/video.mkv")!, headers: [:]), @@ -368,6 +393,50 @@ struct StreamResolverTests { ]) } + private static func testRangeCacheSeekPrimingIncludesObservedVLCStart() { + let session = ProgressiveHTTPRangeCacheSession( + fetcher: HTTPRangeRemoteFetcher(url: URL(string: "https://example.test/video.mkv")!, headers: [:]), + contentLength: 711_080_522, + durationProvider: { 0 } + ) + + let estimatedOffset: Int64 = 213_615_760 + let firstVLCRequest = HTTPByteRange(start: 212_942_432, end: 213_991_007) + let window = session.seekPrimeWindow(aroundByteOffset: estimatedOffset) + let chunks = session.prefetchChunks( + in: window, + preferredOffset: estimatedOffset, + startsAtWindowStart: true + ) + + let chunkContainingVLCStart = chunks.firstIndex { $0.contains(firstVLCRequest.start) } + let chunkContainingEstimatedOffset = chunks.firstIndex { $0.contains(estimatedOffset) } + + assert(chunkContainingVLCStart != nil, "Expected seek priming to include VLC's first request start") + assert(chunkContainingEstimatedOffset != nil, "Expected seek priming to include the estimated offset") + assert( + chunkContainingVLCStart! <= chunkContainingEstimatedOffset!, + "Expected bytes behind the seek target to be primed before ahead chunks" + ) + assertEqual(chunks[chunkContainingVLCStart!], HTTPByteRange(start: 212_860_928, end: 213_909_503)) + } + + private static func testRangeCachePrefetchUsesGlobalChunkBoundaries() { + let session = ProgressiveHTTPRangeCacheSession( + fetcher: HTTPRangeRemoteFetcher(url: URL(string: "https://example.test/video.mkv")!, headers: [:]), + contentLength: 711_080_522, + durationProvider: { 0 } + ) + + let chunks = session.prefetchChunks( + in: HTTPByteRange(start: 213_278_260, end: 216_000_000), + preferredOffset: 213_615_760 + ) + + assert(chunks.allSatisfy { $0.start % 1_048_576 == 0 }, "Expected prefetch chunk starts to use stable global 1 MB boundaries: \(chunks)") + assertEqual(chunks[0], HTTPByteRange(start: 212_860_928, end: 213_909_503)) + } + private static func testRangeCacheForegroundMissReprioritizesPrefetch() async { let queue = DispatchQueue(label: "dreamio.range-cache-test") var requestedRanges: [String] = [] @@ -406,8 +475,8 @@ struct StreamResolverTests { let ranges = queue.sync { requestedRanges } assert(ranges.contains("bytes=51818977-52867552"), "Expected foreground VLC range to be fetched") assert(ranges.contains { range in - range.hasPrefix("bytes=51936225-") - }, "Expected prefetch to restart near VLC's foreground range, got \(ranges)") + range.hasPrefix("bytes=52428800-") + }, "Expected prefetch to restart on a global chunk boundary near VLC's foreground range, got \(ranges)") session.cancelPrefetch() MockURLProtocol.handler = nil try? await Task.sleep(nanoseconds: 50_000_000) diff --git a/docs/turns/2026-05-26-reduce-vlc-seek-buffering.html b/docs/turns/2026-05-26-reduce-vlc-seek-buffering.html new file mode 100644 index 0000000..5d03339 --- /dev/null +++ b/docs/turns/2026-05-26-reduce-vlc-seek-buffering.html @@ -0,0 +1,298 @@ + + + + + +Dreamio Turn: VLC Seek Range Cache Priming + + + +
+
2026-05-26

VLC Seek Range Cache Priming

Dreamio now primes local VLC range-cache seeks from stable 1 MB boundaries behind the estimated target, retains useful nearby bytes under a bounded budget, and logs foreground misses with more precision.

+

Summary

Reduced post-seek buffering risk in native VLC playback by making seek and jump prefetch conservative behind the target instead of only racing ahead from the estimated byte offset.

+

Changes Made

  • Added seek-specific prefetch through prefetchForSeek, with a 4 MB backward prime window and user-initiated task priority for the first chunks.
  • Aligned prefetch chunks to global 1 MB boundaries so repeated VLC requests reuse stable cached ranges.
  • Replaced prefetch-window eviction with a 64 MB bounded cache budget that preserves active playback, recent seek, header, and tail/index ranges.
  • Changed foreground miss handling to fetch only missing subranges and log uncached versus partial-miss.
  • Routed VLC delegate state handling onto the main actor before reading player state or firing UI callbacks.
  • Added tests for the observed VLC request pattern, global chunk alignment, and budget retention.
+

Context

A 15-second skip estimated byte 213615760, while VLC’s first real read started at 212942432. The old prefetch overlapped the request but missed its front edge, then eviction could discard ranges that were still useful during the next VLC probes.

+

Important Implementation Details

  • The observed request and estimated seek offset both fall inside global chunk 212860928-213909503, so seek priming now warms that chunk before later ahead chunks.
  • Normal prefetch still prefers the playhead area, while seek prefetch starts at the backward-biased window start.
  • Cache eviction removes unprotected segments farthest from protected areas until the byte budget is met; protected ranges are not trimmed simply because a new prefetch window appears.
  • Foreground reads cancel or reprioritize normal prefetch when VLC asks outside the expected area.
+

Relevant Diff Snippets

Rendered with @pierre/diffs/ssr.

Dreamio/ProgressiveHTTPRangeCache.swift

Dreamio/ProgressiveHTTPRangeCache.swift
-15+174
72 unmodified lines
73
74
75
76
77
78
38 unmodified lines
117
118
119
120
121
122
12 unmodified lines
135
136
137
138
139
140
116 unmodified lines
257
258
259
260
261
262
263
264
265
266
267
268
269
270
2 unmodified lines
273
274
275
276
277
278
1 unmodified line
280
281
282
283
284
285
286
287
288
289
290
291
292
293
5 unmodified lines
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
1 unmodified line
330
331
332
333
334
335
37 unmodified lines
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
3 unmodified lines
391
392
393
394
395
396
397
3 unmodified lines
401
402
403
404
405
406
72 unmodified lines
}
}
+
func insert(data: Data, at start: Int64) {
guard !data.isEmpty else {
return
38 unmodified lines
data(for: range) != nil
}
+
func evict(keeping window: HTTPByteRange) {
lock.withLock {
segments = segments.compactMap { segment in
12 unmodified lines
}
}
+
private func mergeSegments() {
guard !segments.isEmpty else {
return
116 unmodified lines
let durationProvider: () -> TimeInterval
private let prefetchChunkSize: Int64 = 1_048_576
private let responseChunkSize: Int64 = 1_048_576
private var prefetchTask: Task<Void, Never>?
private var activePrefetchWindow: HTTPByteRange?
private var activePrefetchPreferredOffset: Int64?
+
init(fetcher: HTTPRangeRemoteFetcher, contentLength: Int64, durationProvider: @escaping () -> TimeInterval) {
self.fetcher = fetcher
self.contentLength = contentLength
self.durationProvider = durationProvider
}
+
deinit {
2 unmodified lines
+
func data(for requestedRange: HTTPByteRange) async throws -> Data {
let bounded = clamp(requestedRange)
if let data = store.data(for: bounded) {
#if DEBUG
print("[DreamioRangeCache] cache=hit range=\(bounded.start)-\(bounded.end)")
1 unmodified line
return data
}
+
#if DEBUG
print("[DreamioRangeCache] cache=miss range=\(bounded.start)-\(bounded.end)")
#endif
cancelPrefetchIfNeeded(forForegroundRange: bounded)
let data = try await fetcher.fetch(range: bounded)
store.insert(data: data, at: bounded.start)
prefetch(aroundByteOffset: bounded.end + 1, forceRestart: true)
return store.data(for: bounded) ?? data
}
+
func responseRange(for requestedRange: HTTPByteRange) -> HTTPByteRange {
5 unmodified lines
}
+
func prefetch(aroundByteOffset offset: Int64) {
prefetch(aroundByteOffset: offset, forceRestart: false)
}
+
func prefetch(aroundByteOffset offset: Int64, forceRestart: Bool) {
if !forceRestart, activePrefetchWindow?.contains(offset) == true, prefetchTask?.isCancelled == false {
return
}
+
prefetchTask?.cancel()
let window = targetWindow(aroundByteOffset: offset)
activePrefetchWindow = window
activePrefetchPreferredOffset = offset
store.evict(keeping: window)
guard !store.hasData(for: window) else {
activePrefetchWindow = nil
activePrefetchPreferredOffset = nil
return
}
+
prefetchTask = Task { [weak self] in
guard let self else {
return
}
for chunk in self.prefetchChunks(in: window, preferredOffset: offset) {
guard !Task.isCancelled else {
return
}
1 unmodified line
do {
let data = try await fetcher.fetch(range: chunk)
store.insert(data: data, at: chunk.start)
#if DEBUG
print("[DreamioRangeCache] fetched range=\(chunk.start)-\(chunk.end) bytes=\(data.count)")
#endif
37 unmodified lines
}
+
private func targetWindow(aroundByteOffset offset: Int64) -> HTTPByteRange {
let bytesPerSecond = estimatedBytesPerSecond()
let behind = max(prefetchChunkSize, bytesPerSecond * 30)
let ahead = max(prefetchChunkSize * 2, bytesPerSecond * 60)
return clamp(HTTPByteRange(start: offset - behind, end: offset + ahead))
}
+
func prefetchChunks(in window: HTTPByteRange, preferredOffset offset: Int64) -> [HTTPByteRange] {
let boundedOffset = max(window.start, min(window.end, offset))
let preferredStart = window.start + ((boundedOffset - window.start) / prefetchChunkSize) * prefetchChunkSize
var chunks: [HTTPByteRange] = []
+
var cursor = preferredStart
3 unmodified lines
cursor = chunk.end + 1
}
+
cursor = window.start
while cursor < preferredStart {
let chunk = HTTPByteRange(start: cursor, end: min(preferredStart - 1, cursor + prefetchChunkSize - 1))
chunks.append(chunk)
3 unmodified lines
return chunks
}
+
private func estimatedBytesPerSecond() -> Int64 {
let duration = durationProvider()
guard duration > 1 else {
72 unmodified lines
73
74
75
76
77
78
79
80
81
82
83
84
38 unmodified lines
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
12 unmodified lines
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
116 unmodified lines
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
2 unmodified lines
371
372
373
374
375
376
377
1 unmodified line
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
5 unmodified lines
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
1 unmodified line
457
458
459
460
461
462
463
37 unmodified lines
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
3 unmodified lines
529
530
531
532
533
534
535
3 unmodified lines
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
72 unmodified lines
}
}
+
var cachedByteCount: Int64 {
lock.withLock {
segments.reduce(0) { $0 + Int64($1.data.count) }
}
}
+
func insert(data: Data, at start: Int64) {
guard !data.isEmpty else {
return
38 unmodified lines
data(for: range) != nil
}
+
func missingRanges(in range: HTTPByteRange) -> [HTTPByteRange] {
lock.withLock {
var cursor = range.start
var missing: [HTTPByteRange] = []
+
for segment in segments where segment.range.end >= cursor {
guard segment.range.start <= range.end else {
break
}
if segment.range.start > cursor {
missing.append(HTTPByteRange(start: cursor, end: min(range.end, segment.range.start - 1)))
}
if segment.range.end >= cursor {
cursor = max(cursor, segment.range.end + 1)
}
if cursor > range.end {
break
}
}
+
if cursor <= range.end {
missing.append(HTTPByteRange(start: cursor, end: range.end))
}
return missing
}
}
+
func evict(keeping window: HTTPByteRange) {
lock.withLock {
segments = segments.compactMap { segment in
12 unmodified lines
}
}
+
func evict(toByteBudget byteBudget: Int64, preserving protectedRanges: [HTTPByteRange]) -> [HTTPByteRange] {
lock.withLock {
guard byteBudget > 0 else {
let evicted = segments.map(\.range)
segments.removeAll()
return evicted
}
+
var totalBytes = segments.reduce(0) { $0 + Int64($1.data.count) }
guard totalBytes > byteBudget else {
return []
}
+
var evicted: [HTTPByteRange] = []
while totalBytes > byteBudget,
let index = evictionCandidateIndex(protectedRanges: protectedRanges) {
let removed = segments.remove(at: index)
totalBytes -= Int64(removed.data.count)
evicted.append(removed.range)
}
return evicted
}
}
+
private func evictionCandidateIndex(protectedRanges: [HTTPByteRange]) -> Int? {
var bestIndex: Int?
var bestDistance: Int64 = .min
+
for (index, segment) in segments.enumerated() {
if protectedRanges.contains(where: { $0.overlapsOrTouches(segment.range) }) {
continue
}
+
let distance = protectedRanges
.map { rangeDistance(from: segment.range, to: $0) }
.min() ?? segment.range.start
if distance > bestDistance {
bestDistance = distance
bestIndex = index
}
}
+
return bestIndex
}
+
private func rangeDistance(from range: HTTPByteRange, to protectedRange: HTTPByteRange) -> Int64 {
if range.overlapsOrTouches(protectedRange) {
return 0
}
if range.end < protectedRange.start {
return protectedRange.start - range.end
}
return range.start - protectedRange.end
}
+
private func mergeSegments() {
guard !segments.isEmpty else {
return
116 unmodified lines
let durationProvider: () -> TimeInterval
private let prefetchChunkSize: Int64 = 1_048_576
private let responseChunkSize: Int64 = 1_048_576
private let seekPrimeBehindBytes: Int64 = 4 * 1_048_576
private let cacheByteBudget: Int64
private var prefetchTask: Task<Void, Never>?
private var activePrefetchWindow: HTTPByteRange?
private var activePrefetchPreferredOffset: Int64?
private var recentSeekRange: HTTPByteRange?
private var recentForegroundRange: HTTPByteRange?
+
init(
fetcher: HTTPRangeRemoteFetcher,
contentLength: Int64,
durationProvider: @escaping () -> TimeInterval,
cacheByteBudget: Int64 = 64 * 1_048_576
) {
self.fetcher = fetcher
self.contentLength = contentLength
self.durationProvider = durationProvider
self.cacheByteBudget = cacheByteBudget
}
+
deinit {
2 unmodified lines
+
func data(for requestedRange: HTTPByteRange) async throws -> Data {
let bounded = clamp(requestedRange)
recentForegroundRange = bounded
if let data = store.data(for: bounded) {
#if DEBUG
print("[DreamioRangeCache] cache=hit range=\(bounded.start)-\(bounded.end)")
1 unmodified line
return data
}
+
let missingRanges = store.missingRanges(in: bounded)
#if DEBUG
let missKind = missingRanges.count == 1 && missingRanges[0] == bounded ? "uncached" : "partial-miss"
print("[DreamioRangeCache] cache=\(missKind) range=\(bounded.start)-\(bounded.end) missing=\(missingRanges.map { "\($0.start)-\($0.end)" }.joined(separator: ","))")
#endif
cancelPrefetchIfNeeded(forForegroundRange: bounded)
for missingRange in missingRanges {
let data = try await fetcher.fetch(range: missingRange)
store.insert(data: data, at: missingRange.start)
}
prefetch(aroundByteOffset: bounded.end + 1, forceRestart: true)
return store.data(for: bounded) ?? Data()
}
+
func responseRange(for requestedRange: HTTPByteRange) -> HTTPByteRange {
5 unmodified lines
}
+
func prefetch(aroundByteOffset offset: Int64) {
prefetch(aroundByteOffset: offset, forceRestart: false, startsAtWindowStart: false)
}
+
func prefetchForSeek(aroundByteOffset offset: Int64) {
let window = seekPrimeWindow(aroundByteOffset: offset)
recentSeekRange = window
prefetch(
aroundByteOffset: offset,
forceRestart: true,
explicitWindow: window,
startsAtWindowStart: true
)
}
+
func seekPrimeWindow(aroundByteOffset offset: Int64) -> HTTPByteRange {
targetWindow(aroundByteOffset: offset, minimumBehind: seekPrimeBehindBytes)
}
+
func prefetch(aroundByteOffset offset: Int64, forceRestart: Bool) {
prefetch(aroundByteOffset: offset, forceRestart: forceRestart, startsAtWindowStart: false)
}
+
private func prefetch(
aroundByteOffset offset: Int64,
forceRestart: Bool,
explicitWindow: HTTPByteRange? = nil,
startsAtWindowStart: Bool
) {
if !forceRestart, activePrefetchWindow?.contains(offset) == true, prefetchTask?.isCancelled == false {
return
}
+
prefetchTask?.cancel()
let window = explicitWindow ?? targetWindow(aroundByteOffset: offset)
activePrefetchWindow = window
activePrefetchPreferredOffset = offset
evictOverBudget(protecting: window)
guard !store.hasData(for: window) else {
activePrefetchWindow = nil
activePrefetchPreferredOffset = nil
return
}
+
prefetchTask = Task(priority: startsAtWindowStart ? .userInitiated : .utility) { [weak self] in
guard let self else {
return
}
for chunk in self.prefetchChunks(in: window, preferredOffset: offset, startsAtWindowStart: startsAtWindowStart) {
guard !Task.isCancelled else {
return
}
1 unmodified line
do {
let data = try await fetcher.fetch(range: chunk)
store.insert(data: data, at: chunk.start)
evictOverBudget(protecting: window)
#if DEBUG
print("[DreamioRangeCache] fetched range=\(chunk.start)-\(chunk.end) bytes=\(data.count)")
#endif
37 unmodified lines
}
+
private func targetWindow(aroundByteOffset offset: Int64) -> HTTPByteRange {
targetWindow(aroundByteOffset: offset, minimumBehind: prefetchChunkSize)
}
+
private func targetWindow(aroundByteOffset offset: Int64, minimumBehind: Int64) -> HTTPByteRange {
let bytesPerSecond = estimatedBytesPerSecond()
let behind = max(minimumBehind, bytesPerSecond * 30)
let ahead = max(prefetchChunkSize * 2, bytesPerSecond * 60)
let raw = clamp(HTTPByteRange(start: offset - behind, end: offset + ahead))
return HTTPByteRange(start: alignedChunkStart(for: raw.start), end: alignedChunkEnd(for: raw.end))
}
+
func prefetchChunks(in window: HTTPByteRange, preferredOffset offset: Int64) -> [HTTPByteRange] {
prefetchChunks(in: window, preferredOffset: offset, startsAtWindowStart: false)
}
+
func prefetchChunks(in window: HTTPByteRange, preferredOffset offset: Int64, startsAtWindowStart: Bool) -> [HTTPByteRange] {
let boundedOffset = max(window.start, min(window.end, offset))
let windowStart = alignedChunkStart(for: window.start)
let preferredStart = startsAtWindowStart ? windowStart : alignedChunkStart(for: boundedOffset)
var chunks: [HTTPByteRange] = []
+
var cursor = preferredStart
3 unmodified lines
cursor = chunk.end + 1
}
+
cursor = windowStart
while cursor < preferredStart {
let chunk = HTTPByteRange(start: cursor, end: min(preferredStart - 1, cursor + prefetchChunkSize - 1))
chunks.append(chunk)
3 unmodified lines
return chunks
}
+
private func evictOverBudget(protecting range: HTTPByteRange) {
let headerRange = HTTPByteRange(start: 0, end: min(contentLength - 1, prefetchChunkSize - 1))
let tailStart = max(0, contentLength - (4 * prefetchChunkSize))
let tailRange = HTTPByteRange(start: tailStart, end: contentLength - 1)
let protectedRanges = [range, recentSeekRange, recentForegroundRange, activePrefetchWindow, headerRange, tailRange].compactMap { $0 }
let evicted = store.evict(toByteBudget: cacheByteBudget, preserving: protectedRanges)
#if DEBUG
if !evicted.isEmpty {
print("[DreamioRangeCache] evicted reason=budget ranges=\(evicted.map { "\($0.start)-\($0.end)" }.joined(separator: ",")) protected=\(protectedRanges.map { "\($0.start)-\($0.end)" }.joined(separator: ","))")
}
#endif
}
+
private func alignedChunkStart(for offset: Int64) -> Int64 {
max(0, (offset / prefetchChunkSize) * prefetchChunkSize)
}
+
private func alignedChunkEnd(for offset: Int64) -> Int64 {
min(contentLength - 1, alignedChunkStart(for: offset) + prefetchChunkSize - 1)
}
+
private func estimatedBytesPerSecond() -> Int64 {
let duration = durationProvider()
guard duration > 1 else {

Dreamio/VLCNativePlaybackBackend.swift

Dreamio/VLCNativePlaybackBackend.swift
-2+9
150 unmodified lines
151
152
153
154
155
156
157
13 unmodified lines
171
172
173
174
175
176
177
426 unmodified lines
604
605
606
607
608
609
150 unmodified lines
return
}
let clamped = max(0, min(1, position))
rangeCacheSession?.prefetch(aroundByteOffset: rangeCacheSession?.byteOffset(for: clamped) ?? 0)
#if DEBUG
if let byteOffset = rangeCacheSession?.byteOffset(for: clamped) {
print("[DreamioVLC] seek targetPosition=\(clamped) byteOffset=\(byteOffset) mode=local-cache")
13 unmodified lines
let nextTime = max(0, min(duration, currentTime + seconds))
if duration > 0 {
let nextPosition = Float(nextTime / duration)
rangeCacheSession?.prefetch(aroundByteOffset: rangeCacheSession?.byteOffset(for: nextPosition) ?? 0)
#if DEBUG
if let byteOffset = rangeCacheSession?.byteOffset(for: nextPosition) {
print("[DreamioVLC] jump seconds=\(seconds) target=\(nextTime) byteOffset=\(byteOffset) mode=local-cache")
426 unmodified lines
#if canImport(MobileVLCKit)
extension VLCNativePlaybackBackend: VLCMediaPlayerDelegate {
func mediaPlayerStateChanged(_ aNotification: Notification) {
#if DEBUG
logPlaybackStateIfNeeded(stateName(mediaPlayer.state))
#endif
150 unmodified lines
151
152
153
154
155
156
157
13 unmodified lines
171
172
173
174
175
176
177
426 unmodified lines
604
605
606
607
608
609
610
611
612
613
614
615
616
150 unmodified lines
return
}
let clamped = max(0, min(1, position))
rangeCacheSession?.prefetchForSeek(aroundByteOffset: rangeCacheSession?.byteOffset(for: clamped) ?? 0)
#if DEBUG
if let byteOffset = rangeCacheSession?.byteOffset(for: clamped) {
print("[DreamioVLC] seek targetPosition=\(clamped) byteOffset=\(byteOffset) mode=local-cache")
13 unmodified lines
let nextTime = max(0, min(duration, currentTime + seconds))
if duration > 0 {
let nextPosition = Float(nextTime / duration)
rangeCacheSession?.prefetchForSeek(aroundByteOffset: rangeCacheSession?.byteOffset(for: nextPosition) ?? 0)
#if DEBUG
if let byteOffset = rangeCacheSession?.byteOffset(for: nextPosition) {
print("[DreamioVLC] jump seconds=\(seconds) target=\(nextTime) byteOffset=\(byteOffset) mode=local-cache")
426 unmodified lines
#if canImport(MobileVLCKit)
extension VLCNativePlaybackBackend: VLCMediaPlayerDelegate {
func mediaPlayerStateChanged(_ aNotification: Notification) {
Task { @MainActor [weak self] in
self?.handleMediaPlayerStateChanged()
}
}
+
@MainActor
private func handleMediaPlayerStateChanged() {
#if DEBUG
logPlaybackStateIfNeeded(stateName(mediaPlayer.state))
#endif

Tests/StreamResolverTests.swift

Tests/StreamResolverTests.swift
-2+71
34 unmodified lines
35
36
37
38
39
40
41
42
291 unmodified lines
334
335
336
337
338
339
28 unmodified lines
368
369
370
371
372
373
32 unmodified lines
406
407
408
409
410
411
412
413
34 unmodified lines
testSparseRangeStoreHitPartialHitAndMiss()
testSparseRangeStoreEvictsOutsideWindow()
testSparseRangeStoreTrimsOverlappingWindow()
testRangeCacheSessionCapsResponseRange()
testRangeCachePrefetchPrioritizesSeekOffset()
await testRangeCacheForegroundMissReprioritizesPrefetch()
await testRangeProbeFallsBackWhenServerIgnoresRange()
await testRangeFetcherPreservesHeaders()
291 unmodified lines
assert(store.data(for: HTTPByteRange(start: 0, end: 5)) == nil, "Expected trimmed bytes outside the window to be evicted")
}
+
private static func testRangeCacheSessionCapsResponseRange() {
let session = ProgressiveHTTPRangeCacheSession(
fetcher: HTTPRangeRemoteFetcher(url: URL(string: "https://example.test/video.mkv")!, headers: [:]),
28 unmodified lines
])
}
+
private static func testRangeCacheForegroundMissReprioritizesPrefetch() async {
let queue = DispatchQueue(label: "dreamio.range-cache-test")
var requestedRanges: [String] = []
32 unmodified lines
let ranges = queue.sync { requestedRanges }
assert(ranges.contains("bytes=51818977-52867552"), "Expected foreground VLC range to be fetched")
assert(ranges.contains { range in
range.hasPrefix("bytes=51936225-")
}, "Expected prefetch to restart near VLC's foreground range, got \(ranges)")
session.cancelPrefetch()
MockURLProtocol.handler = nil
try? await Task.sleep(nanoseconds: 50_000_000)
34 unmodified lines
35
36
37
38
39
40
41
42
43
44
45
291 unmodified lines
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
28 unmodified lines
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
32 unmodified lines
475
476
477
478
479
480
481
482
34 unmodified lines
testSparseRangeStoreHitPartialHitAndMiss()
testSparseRangeStoreEvictsOutsideWindow()
testSparseRangeStoreTrimsOverlappingWindow()
testSparseRangeStoreEvictsByBudgetWhilePreservingUsefulRanges()
testRangeCacheSessionCapsResponseRange()
testRangeCachePrefetchPrioritizesSeekOffset()
testRangeCacheSeekPrimingIncludesObservedVLCStart()
testRangeCachePrefetchUsesGlobalChunkBoundaries()
await testRangeCacheForegroundMissReprioritizesPrefetch()
await testRangeProbeFallsBackWhenServerIgnoresRange()
await testRangeFetcherPreservesHeaders()
291 unmodified lines
assert(store.data(for: HTTPByteRange(start: 0, end: 5)) == nil, "Expected trimmed bytes outside the window to be evicted")
}
+
private static func testSparseRangeStoreEvictsByBudgetWhilePreservingUsefulRanges() {
let store = SparseHTTPByteRangeStore()
+
store.insert(data: Data(repeating: 1, count: 4), at: 0)
store.insert(data: Data(repeating: 2, count: 4), at: 100)
store.insert(data: Data(repeating: 3, count: 4), at: 200)
+
let evicted = store.evict(
toByteBudget: 8,
preserving: [
HTTPByteRange(start: 0, end: 3),
HTTPByteRange(start: 190, end: 210)
]
)
+
assertEqual(evicted, [HTTPByteRange(start: 100, end: 103)])
assertEqual(store.cachedRanges, [
HTTPByteRange(start: 0, end: 3),
HTTPByteRange(start: 200, end: 203)
])
}
+
private static func testRangeCacheSessionCapsResponseRange() {
let session = ProgressiveHTTPRangeCacheSession(
fetcher: HTTPRangeRemoteFetcher(url: URL(string: "https://example.test/video.mkv")!, headers: [:]),
28 unmodified lines
])
}
+
private static func testRangeCacheSeekPrimingIncludesObservedVLCStart() {
let session = ProgressiveHTTPRangeCacheSession(
fetcher: HTTPRangeRemoteFetcher(url: URL(string: "https://example.test/video.mkv")!, headers: [:]),
contentLength: 711_080_522,
durationProvider: { 0 }
)
+
let estimatedOffset: Int64 = 213_615_760
let firstVLCRequest = HTTPByteRange(start: 212_942_432, end: 213_991_007)
let window = session.seekPrimeWindow(aroundByteOffset: estimatedOffset)
let chunks = session.prefetchChunks(
in: window,
preferredOffset: estimatedOffset,
startsAtWindowStart: true
)
+
let chunkContainingVLCStart = chunks.firstIndex { $0.contains(firstVLCRequest.start) }
let chunkContainingEstimatedOffset = chunks.firstIndex { $0.contains(estimatedOffset) }
+
assert(chunkContainingVLCStart != nil, "Expected seek priming to include VLC's first request start")
assert(chunkContainingEstimatedOffset != nil, "Expected seek priming to include the estimated offset")
assert(
chunkContainingVLCStart! <= chunkContainingEstimatedOffset!,
"Expected bytes behind the seek target to be primed before ahead chunks"
)
assertEqual(chunks[chunkContainingVLCStart!], HTTPByteRange(start: 212_860_928, end: 213_909_503))
}
+
private static func testRangeCachePrefetchUsesGlobalChunkBoundaries() {
let session = ProgressiveHTTPRangeCacheSession(
fetcher: HTTPRangeRemoteFetcher(url: URL(string: "https://example.test/video.mkv")!, headers: [:]),
contentLength: 711_080_522,
durationProvider: { 0 }
)
+
let chunks = session.prefetchChunks(
in: HTTPByteRange(start: 213_278_260, end: 216_000_000),
preferredOffset: 213_615_760
)
+
assert(chunks.allSatisfy { $0.start % 1_048_576 == 0 }, "Expected prefetch chunk starts to use stable global 1 MB boundaries: \(chunks)")
assertEqual(chunks[0], HTTPByteRange(start: 212_860_928, end: 213_909_503))
}
+
private static func testRangeCacheForegroundMissReprioritizesPrefetch() async {
let queue = DispatchQueue(label: "dreamio.range-cache-test")
var requestedRanges: [String] = []
32 unmodified lines
let ranges = queue.sync { requestedRanges }
assert(ranges.contains("bytes=51818977-52867552"), "Expected foreground VLC range to be fetched")
assert(ranges.contains { range in
range.hasPrefix("bytes=52428800-")
}, "Expected prefetch to restart on a global chunk boundary near VLC's foreground range, got \(ranges)")
session.cancelPrefetch()
MockURLProtocol.handler = nil
try? await Task.sleep(nanoseconds: 50_000_000)
+

Expected Impact for End-Users

Short backward or forward skips in MKV/direct-file playback should resume with fewer full foreground misses, especially when VLC asks slightly before Dreamio’s estimated byte position.

+

Validation

  • Ran swiftc -parse-as-library Tests/StreamResolverTests.swift Dreamio/StreamCandidate.swift Dreamio/StreamResolver.swift Dreamio/ProgressiveHTTPRangeCache.swift Dreamio/ExternalSubtitleTrackParser.swift -o /tmp/StreamResolverTests && /tmp/StreamResolverTests: passed.
  • Ran DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild -workspace Dreamio.xcworkspace -scheme Dreamio -configuration Debug -sdk iphonesimulator build: passed.
+

Issues, Limitations, and Mitigations

  • No device playback check was run in this turn, so real MobileVLCKit timing still needs confirmation on hardware.
  • The cache remains memory-only. The 64 MB budget limits growth while retaining the ranges most likely to matter after seeks and MKV index probes.
  • The existing MobileVLCKit/OpenGLES warning is treated as internal unless it persists after the main-actor cleanup.
+

Follow-up Work

  • Manually test MKV skip behavior on device and compare DEBUG logs for post-seek hit, partial-miss, and uncached reads.
  • Consider exposing cache budget tuning if device memory pressure shows up in longer playback sessions.
  • Track any persistent VLCOpenGLES2VideoView warnings separately with device logs if they continue.
+
+ + \ No newline at end of file