diff --git a/Dreamio/NativeStreamCacheProxy.swift b/Dreamio/NativeStreamCacheProxy.swift index 9200a71..97308b6 100644 --- a/Dreamio/NativeStreamCacheProxy.swift +++ b/Dreamio/NativeStreamCacheProxy.swift @@ -67,6 +67,7 @@ final class CachedRangeStore { private let directory: URL private let byteBudget: Int64 private let fileManager: FileManager + private let lock = NSLock() private var chunks: [Chunk] = [] init(sessionID: String, byteBudget: Int64, fileManager: FileManager = .default) { @@ -79,6 +80,8 @@ final class CachedRangeStore { } func lookup(range: HTTPRange, maximumLength: Int64) -> Lookup? { + lock.lock() + defer { lock.unlock() } let requestedEnd = range.end ?? range.start + maximumLength - 1 var cursor = range.start var data = Data() @@ -115,6 +118,8 @@ final class CachedRangeStore { } func store(data: Data, start: Int64) { + lock.lock() + defer { lock.unlock() } guard !data.isEmpty else { return } @@ -133,6 +138,8 @@ final class CachedRangeStore { } func evictKeepingBytesNear(offset: Int64) { + lock.lock() + defer { lock.unlock() } let lowerBound = max(0, offset - byteBudget) let removed = chunks.filter { $0.end < lowerBound } chunks.removeAll { $0.end < lowerBound } @@ -146,6 +153,8 @@ final class CachedRangeStore { } func removeAll() { + lock.lock() + defer { lock.unlock() } try? fileManager.removeItem(at: directory) chunks.removeAll() } @@ -200,11 +209,12 @@ final class NativeStreamCacheProxy { private let prefetchLength: Int64 private var listener: NWListener? private let queue = DispatchQueue(label: "dreamio.native-stream-cache-proxy") + private let workQueue = DispatchQueue(label: "dreamio.native-stream-cache-proxy.work", attributes: .concurrent) - init(session: Session, byteBudget: Int64? = nil, fetchLength: Int64 = 8 * 1024 * 1024) { + init(session: Session, byteBudget: Int64? = nil, fetchLength: Int64 = 1024 * 1024) { self.session = session self.fetchLength = fetchLength - prefetchLength = fetchLength + prefetchLength = 4 * fetchLength let budget = byteBudget ?? max(30 * 1024 * 1024, (session.estimatedBitrate ?? 0) * 30 / 8) store = CachedRangeStore(sessionID: session.id, byteBudget: budget) } @@ -260,12 +270,26 @@ final class NativeStreamCacheProxy { connection.cancel() return } - let range = HTTPRange.parse(request.headers["range"]) - self.respond(to: range, on: connection) + self.workQueue.async { + self.respond(to: request, on: connection) + } } } - private func respond(to requestedRange: HTTPRange?, on connection: NWConnection) { + private func respond(to request: HTTPRequest, on connection: NWConnection) { + guard request.path.hasPrefix("/stream/") else { + sendStatus(404, on: connection) + return + } + if request.method == "HEAD" { + respondToHead(on: connection) + return + } + guard request.method == "GET" else { + sendStatus(405, on: connection) + return + } + let requestedRange = HTTPRange.parse(request.headers["range"]) let range = requestedRange ?? HTTPRange(start: 0, end: fetchLength - 1) let maximumLength = range.length ?? fetchLength if let lookup = store.lookup(range: range, maximumLength: maximumLength), lookup.isComplete { @@ -292,8 +316,8 @@ final class NativeStreamCacheProxy { if responseStatus == 206 { store.store(data: response.data, start: range.start) store.evictKeepingBytesNear(offset: range.start) - let contentType = response.headers["Content-Type"] as? String - let totalLength = totalLength(from: response.headers["Content-Range"] as? String) + let contentType = headerValue(response.headers, named: "Content-Type") + let totalLength = totalLength(from: headerValue(response.headers, named: "Content-Range")) send(data: response.data, statusCode: 206, rangeStart: range.start, totalLength: totalLength, contentType: contentType, on: connection) prefetch(after: range.start + Int64(response.data.count)) } else { @@ -304,6 +328,31 @@ final class NativeStreamCacheProxy { } } + private func respondToHead(on connection: NWConnection) { + guard let response = fetchHead() ?? fetch(range: HTTPRange(start: 0, end: 0)) else { + sendStatus(502, on: connection) + return + } + var headers = [ + "Accept-Ranges": response.statusCode == 206 ? "bytes" : headerValue(response.headers, named: "Accept-Ranges") ?? "bytes", + "Connection": "close" + ] + if let contentType = headerValue(response.headers, named: "Content-Type") { + headers["Content-Type"] = contentType + } + if let length = headerValue(response.headers, named: "Content-Length") { + headers["Content-Length"] = length + } else if let total = totalLength(from: headerValue(response.headers, named: "Content-Range")) { + headers["Content-Length"] = "\(total)" + } else { + headers["Content-Length"] = "0" + } +#if DEBUG + print("[DreamioStreamProxy] head status=\(response.statusCode) length=\(headers["Content-Length"] ?? "unknown")") +#endif + send(statusCode: 200, headers: headers, body: Data(), on: connection) + } + private func prefetch(after offset: Int64) { let range = HTTPRange(start: offset, end: offset + prefetchLength - 1) queue.async { [weak self] in @@ -318,11 +367,21 @@ final class NativeStreamCacheProxy { } private func fetch(range: HTTPRange) -> UpstreamResponse? { + fetch(request: upstreamRequest(for: range)) + } + + private func fetchHead() -> UpstreamResponse? { + var request = upstreamRequest(for: nil) + request.httpMethod = "HEAD" + return fetch(request: request) + } + + private func fetch(request: URLRequest) -> UpstreamResponse? { let semaphore = DispatchSemaphore(value: 0) var result: UpstreamResponse? - URLSession.shared.dataTask(with: upstreamRequest(for: range)) { data, response, _ in - if let http = response as? HTTPURLResponse, let data { - result = UpstreamResponse(statusCode: http.statusCode, headers: http.allHeaderFields, data: data) + URLSession.shared.dataTask(with: request) { data, response, _ in + if let http = response as? HTTPURLResponse { + result = UpstreamResponse(statusCode: http.statusCode, headers: http.allHeaderFields, data: data ?? Data()) } semaphore.signal() }.resume() @@ -350,7 +409,7 @@ final class NativeStreamCacheProxy { "Accept-Ranges": "none", "Connection": "close" ] - if let contentType = upstreamHeaders["Content-Type"] as? String { + if let contentType = headerValue(upstreamHeaders, named: "Content-Type") { headers["Content-Type"] = contentType } send(statusCode: statusCode, headers: headers, body: data, on: connection) @@ -368,6 +427,12 @@ final class NativeStreamCacheProxy { connection.send(content: response, completion: .contentProcessed { _ in connection.cancel() }) } + private func headerValue(_ headers: [AnyHashable: Any], named name: String) -> String? { + headers.first { key, _ in + String(describing: key).caseInsensitiveCompare(name) == .orderedSame + }?.value as? String + } + private func totalLength(from contentRange: String?) -> Int64? { guard let contentRange, let slash = contentRange.lastIndex(of: "/") else { return nil @@ -378,6 +443,8 @@ final class NativeStreamCacheProxy { } private struct HTTPRequest { + let method: String + let path: String let headers: [String: String] init?(data: Data) { @@ -385,8 +452,16 @@ private struct HTTPRequest { let headerBlock = string.components(separatedBy: "\r\n\r\n").first else { return nil } + let lines = headerBlock.components(separatedBy: "\r\n") + guard let requestLine = lines.first else { + return nil + } + let parts = requestLine.split(separator: " ") + guard parts.count >= 2 else { + return nil + } var headers: [String: String] = [:] - for line in headerBlock.components(separatedBy: "\r\n").dropFirst() { + for line in lines.dropFirst() { guard let separator = line.firstIndex(of: ":") else { continue } @@ -394,6 +469,8 @@ private struct HTTPRequest { let value = line[line.index(after: separator)...].trimmingCharacters(in: .whitespacesAndNewlines) headers[key] = value } + method = String(parts[0]).uppercased() + path = String(parts[1]) self.headers = headers } } diff --git a/docs/turns/2026-05-25-local-seek-buffer-vlc-playback.html b/docs/turns/2026-05-25-local-seek-buffer-vlc-playback.html index 5ed8643..80b63a0 100644 --- a/docs/turns/2026-05-25-local-seek-buffer-vlc-playback.html +++ b/docs/turns/2026-05-25-local-seek-buffer-vlc-playback.html @@ -92,7 +92,7 @@ pre { overflow: auto; background: #22242d; color: #f4f1ea; padding: 14px; border
Dreamio/NativeStreamCacheProxy.swift
-12+89
66 unmodified lines
67
68
69
70
71
72
6 unmodified lines
79
80
81
82
83
84
30 unmodified lines
115
116
117
118
119
120
12 unmodified lines
133
134
135
136
137
138
7 unmodified lines
146
147
148
149
150
151
48 unmodified lines
200
201
202
203
204
205
206
207
208
209
210
49 unmodified lines
260
261
262
263
264
265
266
267
268
269
270
271
20 unmodified lines
292
293
294
295
296
297
298
299
4 unmodified lines
304
305
306
307
308
309
8 unmodified lines
318
319
320
321
322
323
324
325
326
327
328
21 unmodified lines
350
351
352
353
354
355
356
11 unmodified lines
368
369
370
371
372
373
4 unmodified lines
378
379
380
381
382
383
1 unmodified line
385
386
387
388
389
390
391
392
1 unmodified line
394
395
396
397
398
399
66 unmodified lines
private let directory: URL
private let byteBudget: Int64
private let fileManager: FileManager
private var chunks: [Chunk] = []
+
init(sessionID: String, byteBudget: Int64, fileManager: FileManager = .default) {
6 unmodified lines
}
+
func lookup(range: HTTPRange, maximumLength: Int64) -> Lookup? {
let requestedEnd = range.end ?? range.start + maximumLength - 1
var cursor = range.start
var data = Data()
30 unmodified lines
}
+
func store(data: Data, start: Int64) {
guard !data.isEmpty else {
return
}
12 unmodified lines
}
+
func evictKeepingBytesNear(offset: Int64) {
let lowerBound = max(0, offset - byteBudget)
let removed = chunks.filter { $0.end < lowerBound }
chunks.removeAll { $0.end < lowerBound }
7 unmodified lines
}
+
func removeAll() {
try? fileManager.removeItem(at: directory)
chunks.removeAll()
}
48 unmodified lines
private let prefetchLength: Int64
private var listener: NWListener?
private let queue = DispatchQueue(label: "dreamio.native-stream-cache-proxy")
+
init(session: Session, byteBudget: Int64? = nil, fetchLength: Int64 = 8 * 1024 * 1024) {
self.session = session
self.fetchLength = fetchLength
prefetchLength = fetchLength
let budget = byteBudget ?? max(30 * 1024 * 1024, (session.estimatedBitrate ?? 0) * 30 / 8)
store = CachedRangeStore(sessionID: session.id, byteBudget: budget)
}
49 unmodified lines
connection.cancel()
return
}
let range = HTTPRange.parse(request.headers["range"])
self.respond(to: range, on: connection)
}
}
+
private func respond(to requestedRange: HTTPRange?, on connection: NWConnection) {
let range = requestedRange ?? HTTPRange(start: 0, end: fetchLength - 1)
let maximumLength = range.length ?? fetchLength
if let lookup = store.lookup(range: range, maximumLength: maximumLength), lookup.isComplete {
20 unmodified lines
if responseStatus == 206 {
store.store(data: response.data, start: range.start)
store.evictKeepingBytesNear(offset: range.start)
let contentType = response.headers["Content-Type"] as? String
let totalLength = totalLength(from: response.headers["Content-Range"] as? String)
send(data: response.data, statusCode: 206, rangeStart: range.start, totalLength: totalLength, contentType: contentType, on: connection)
prefetch(after: range.start + Int64(response.data.count))
} else {
4 unmodified lines
}
}
+
private func prefetch(after offset: Int64) {
let range = HTTPRange(start: offset, end: offset + prefetchLength - 1)
queue.async { [weak self] in
8 unmodified lines
}
+
private func fetch(range: HTTPRange) -> UpstreamResponse? {
let semaphore = DispatchSemaphore(value: 0)
var result: UpstreamResponse?
URLSession.shared.dataTask(with: upstreamRequest(for: range)) { data, response, _ in
if let http = response as? HTTPURLResponse, let data {
result = UpstreamResponse(statusCode: http.statusCode, headers: http.allHeaderFields, data: data)
}
semaphore.signal()
}.resume()
21 unmodified lines
"Accept-Ranges": "none",
"Connection": "close"
]
if let contentType = upstreamHeaders["Content-Type"] as? String {
headers["Content-Type"] = contentType
}
send(statusCode: statusCode, headers: headers, body: data, on: connection)
11 unmodified lines
connection.send(content: response, completion: .contentProcessed { _ in connection.cancel() })
}
+
private func totalLength(from contentRange: String?) -> Int64? {
guard let contentRange, let slash = contentRange.lastIndex(of: "/") else {
return nil
4 unmodified lines
}
+
private struct HTTPRequest {
let headers: [String: String]
+
init?(data: Data) {
1 unmodified line
let headerBlock = string.components(separatedBy: "\r\n\r\n").first else {
return nil
}
var headers: [String: String] = [:]
for line in headerBlock.components(separatedBy: "\r\n").dropFirst() {
guard let separator = line.firstIndex(of: ":") else {
continue
}
1 unmodified line
let value = line[line.index(after: separator)...].trimmingCharacters(in: .whitespacesAndNewlines)
headers[key] = value
}
self.headers = headers
}
}
66 unmodified lines
67
68
69
70
71
72
73
6 unmodified lines
80
81
82
83
84
85
86
87
30 unmodified lines
118
119
120
121
122
123
124
125
12 unmodified lines
138
139
140
141
142
143
144
145
7 unmodified lines
153
154
155
156
157
158
159
160
48 unmodified lines
209
210
211
212
213
214
215
216
217
218
219
220
49 unmodified lines
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
20 unmodified lines
316
317
318
319
320
321
322
323
4 unmodified lines
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
8 unmodified lines
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
21 unmodified lines
409
410
411
412
413
414
415
11 unmodified lines
427
428
429
430
431
432
433
434
435
436
437
438
4 unmodified lines
443
444
445
446
447
448
449
450
1 unmodified line
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
1 unmodified line
469
470
471
472
473
474
475
476
66 unmodified lines
private let directory: URL
private let byteBudget: Int64
private let fileManager: FileManager
private let lock = NSLock()
private var chunks: [Chunk] = []
+
init(sessionID: String, byteBudget: Int64, fileManager: FileManager = .default) {
6 unmodified lines
}
+
func lookup(range: HTTPRange, maximumLength: Int64) -> Lookup? {
lock.lock()
defer { lock.unlock() }
let requestedEnd = range.end ?? range.start + maximumLength - 1
var cursor = range.start
var data = Data()
30 unmodified lines
}
+
func store(data: Data, start: Int64) {
lock.lock()
defer { lock.unlock() }
guard !data.isEmpty else {
return
}
12 unmodified lines
}
+
func evictKeepingBytesNear(offset: Int64) {
lock.lock()
defer { lock.unlock() }
let lowerBound = max(0, offset - byteBudget)
let removed = chunks.filter { $0.end < lowerBound }
chunks.removeAll { $0.end < lowerBound }
7 unmodified lines
}
+
func removeAll() {
lock.lock()
defer { lock.unlock() }
try? fileManager.removeItem(at: directory)
chunks.removeAll()
}
48 unmodified lines
private let prefetchLength: Int64
private var listener: NWListener?
private let queue = DispatchQueue(label: "dreamio.native-stream-cache-proxy")
private let workQueue = DispatchQueue(label: "dreamio.native-stream-cache-proxy.work", attributes: .concurrent)
+
init(session: Session, byteBudget: Int64? = nil, fetchLength: Int64 = 1024 * 1024) {
self.session = session
self.fetchLength = fetchLength
prefetchLength = 4 * fetchLength
let budget = byteBudget ?? max(30 * 1024 * 1024, (session.estimatedBitrate ?? 0) * 30 / 8)
store = CachedRangeStore(sessionID: session.id, byteBudget: budget)
}
49 unmodified lines
connection.cancel()
return
}
self.workQueue.async {
self.respond(to: request, on: connection)
}
}
}
+
private func respond(to request: HTTPRequest, on connection: NWConnection) {
guard request.path.hasPrefix("/stream/") else {
sendStatus(404, on: connection)
return
}
if request.method == "HEAD" {
respondToHead(on: connection)
return
}
guard request.method == "GET" else {
sendStatus(405, on: connection)
return
}
let requestedRange = HTTPRange.parse(request.headers["range"])
let range = requestedRange ?? HTTPRange(start: 0, end: fetchLength - 1)
let maximumLength = range.length ?? fetchLength
if let lookup = store.lookup(range: range, maximumLength: maximumLength), lookup.isComplete {
20 unmodified lines
if responseStatus == 206 {
store.store(data: response.data, start: range.start)
store.evictKeepingBytesNear(offset: range.start)
let contentType = headerValue(response.headers, named: "Content-Type")
let totalLength = totalLength(from: headerValue(response.headers, named: "Content-Range"))
send(data: response.data, statusCode: 206, rangeStart: range.start, totalLength: totalLength, contentType: contentType, on: connection)
prefetch(after: range.start + Int64(response.data.count))
} else {
4 unmodified lines
}
}
+
private func respondToHead(on connection: NWConnection) {
guard let response = fetchHead() ?? fetch(range: HTTPRange(start: 0, end: 0)) else {
sendStatus(502, on: connection)
return
}
var headers = [
"Accept-Ranges": response.statusCode == 206 ? "bytes" : headerValue(response.headers, named: "Accept-Ranges") ?? "bytes",
"Connection": "close"
]
if let contentType = headerValue(response.headers, named: "Content-Type") {
headers["Content-Type"] = contentType
}
if let length = headerValue(response.headers, named: "Content-Length") {
headers["Content-Length"] = length
} else if let total = totalLength(from: headerValue(response.headers, named: "Content-Range")) {
headers["Content-Length"] = "\(total)"
} else {
headers["Content-Length"] = "0"
}
#if DEBUG
print("[DreamioStreamProxy] head status=\(response.statusCode) length=\(headers["Content-Length"] ?? "unknown")")
#endif
send(statusCode: 200, headers: headers, body: Data(), on: connection)
}
+
private func prefetch(after offset: Int64) {
let range = HTTPRange(start: offset, end: offset + prefetchLength - 1)
queue.async { [weak self] in
8 unmodified lines
}
+
private func fetch(range: HTTPRange) -> UpstreamResponse? {
fetch(request: upstreamRequest(for: range))
}
+
private func fetchHead() -> UpstreamResponse? {
var request = upstreamRequest(for: nil)
request.httpMethod = "HEAD"
return fetch(request: request)
}
+
private func fetch(request: URLRequest) -> UpstreamResponse? {
let semaphore = DispatchSemaphore(value: 0)
var result: UpstreamResponse?
URLSession.shared.dataTask(with: request) { data, response, _ in
if let http = response as? HTTPURLResponse {
result = UpstreamResponse(statusCode: http.statusCode, headers: http.allHeaderFields, data: data ?? Data())
}
semaphore.signal()
}.resume()
21 unmodified lines
"Accept-Ranges": "none",
"Connection": "close"
]
if let contentType = headerValue(upstreamHeaders, named: "Content-Type") {
headers["Content-Type"] = contentType
}
send(statusCode: statusCode, headers: headers, body: data, on: connection)
11 unmodified lines
connection.send(content: response, completion: .contentProcessed { _ in connection.cancel() })
}
+
private func headerValue(_ headers: [AnyHashable: Any], named name: String) -> String? {
headers.first { key, _ in
String(describing: key).caseInsensitiveCompare(name) == .orderedSame
}?.value as? String
}
+
private func totalLength(from contentRange: String?) -> Int64? {
guard let contentRange, let slash = contentRange.lastIndex(of: "/") else {
return nil
4 unmodified lines
}
+
private struct HTTPRequest {
let method: String
let path: String
let headers: [String: String]
+
init?(data: Data) {
1 unmodified line
let headerBlock = string.components(separatedBy: "\r\n\r\n").first else {
return nil
}
let lines = headerBlock.components(separatedBy: "\r\n")
guard let requestLine = lines.first else {
return nil
}
let parts = requestLine.split(separator: " ")
guard parts.count >= 2 else {
return nil
}
var headers: [String: String] = [:]
for line in lines.dropFirst() {
guard let separator = line.firstIndex(of: ":") else {
continue
}
1 unmodified line
let value = line[line.index(after: separator)...].trimmingCharacters(in: .whitespacesAndNewlines)
headers[key] = value
}
method = String(parts[0]).uppercased()
path = String(parts[1])
self.headers = headers
}
}

Related issues or PRs

Follow-up Beads issue: dreamio-6bv.

\ No newline at end of file