status
This commit is contained in:
1 parent
c9c25f86eb
commit
40aaf4fea7
56 files changed
+5683
-179
No files matched your search
@@ -9,17 +9,52 @@ private let logger = Logger(subsystem: "dev.shane.voice", category: "media")
|
||||
/// (ignoring registered URLProtocol subclasses), so the asset uses a custom
|
||||
/// `pinned-media` scheme and this delegate answers every data request by
|
||||
/// fetching the real https URL through TLSPinning.session(), forwarding Range.
|
||||
///
|
||||
/// **Lifecycle invariants (Finding 11 / Iteration 06 Item 7):**
|
||||
/// - Tasks are keyed by `ObjectIdentifier(loadingRequest)` directly, not a
|
||||
/// derived hash, so two distinct requests can never collide.
|
||||
/// - All mutable state (`loaderURLs`, `activeTasks`) is accessed only on the
|
||||
/// main queue: the AVAssetResourceLoader delegate is set with `queue: .main`
|
||||
/// and the pinned URLSession uses `delegateQueue: .main`, so both the
|
||||
/// resource-loading callbacks and the data-task completion handlers run on
|
||||
/// the same serialization domain. This is enforced in code, not by comment.
|
||||
/// - For HTTP 206, `contentLength` is set only when `Content-Range` provides a
|
||||
/// known total; it never falls back to the range's `expectedContentLength`.
|
||||
/// - For HTTP 200, `expectedContentLength` is already the full resource size.
|
||||
/// - Cleanup (task removal) occurs on success, error, cancellation, and item
|
||||
/// replacement via `removeLoader`.
|
||||
final class PinnedMediaResourceLoader: NSObject, AVAssetResourceLoaderDelegate {
|
||||
|
||||
static let scheme = "pinned-media"
|
||||
|
||||
private let base: URL
|
||||
/// Maps each asset's resource loader to the real https URL it proxies.
|
||||
/// Accessed only on the main queue (the delegate queue).
|
||||
private var loaderURLs: [ObjectIdentifier: URL] = [:]
|
||||
/// Maps each loading request's identity to its upstream data task so
|
||||
/// cancellation can cancel the in-flight download. Keyed directly by
|
||||
/// `ObjectIdentifier(loadingRequest)` — no hash derivation, no collisions.
|
||||
private var activeTasks: [ObjectIdentifier: URLSessionDataTask] = [:]
|
||||
/// Shared pinned session, created once and invalidated on deinit.
|
||||
/// Uses `delegateQueue: .main` so all completion handlers (and therefore
|
||||
/// all mutations of `activeTasks`) run on the main queue — the same
|
||||
/// serialization domain as the AVAssetResourceLoader delegate callbacks
|
||||
/// (which are also dispatched to `.main`). This makes map access truly
|
||||
/// serialized in code, not just by convention.
|
||||
private lazy var pinnedSession: URLSession = {
|
||||
let config = URLSessionConfiguration.default
|
||||
config.timeoutIntervalForRequest = 30
|
||||
return URLSession(configuration: config, delegate: PinnedTrustDelegate(), delegateQueue: .main)
|
||||
}()
|
||||
|
||||
init(base: URL) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
deinit {
|
||||
pinnedSession.invalidateAndCancel()
|
||||
}
|
||||
|
||||
/// Maps a media URL (absolute https or /media/... path) to the pinned-media
|
||||
/// scheme so AVPlayer routes it through this delegate instead of loading
|
||||
/// https natively. Built as a string because URLComponents.url returns nil
|
||||
@@ -47,17 +82,38 @@ final class PinnedMediaResourceLoader: NSObject, AVAssetResourceLoaderDelegate {
|
||||
return c.url ?? url
|
||||
}
|
||||
|
||||
/// Creates an AVURLAsset that routes through this loader's delegate. The
|
||||
/// mapping from the asset's resource loader to the real URL is recorded so
|
||||
/// `resourceLoader(_:shouldWaitForLoadingOfRequestedResource:)` can resolve
|
||||
/// it. All mutations happen on the main queue (the delegate queue).
|
||||
func assetWithPinnedURL(_ pinned: URL) -> AVURLAsset {
|
||||
let asset = AVURLAsset(url: pinned)
|
||||
loaderURLs[ObjectIdentifier(asset.resourceLoader)] = resolve(pinned)
|
||||
let realURL = resolve(pinned)
|
||||
// The delegate queue is .main, so this runs on the main thread.
|
||||
loaderURLs[ObjectIdentifier(asset.resourceLoader)] = realURL
|
||||
asset.resourceLoader.setDelegate(self, queue: .main)
|
||||
return asset
|
||||
}
|
||||
|
||||
/// Removes the loader mapping and any in-flight tasks for an asset that is
|
||||
/// no longer needed. Called by MediaPlayerController when replacing or
|
||||
/// clearing media items to bound the dictionaries (Finding 11).
|
||||
func removeLoader(_ asset: AVURLAsset) {
|
||||
let key = ObjectIdentifier(asset.resourceLoader)
|
||||
loaderURLs[key] = nil
|
||||
// Cancel any in-flight tasks. URLSessionDataTask has no isCancelled
|
||||
// property; calling cancel() on an already-cancelled task is a no-op.
|
||||
for (_, task) in activeTasks {
|
||||
task.cancel()
|
||||
}
|
||||
activeTasks.removeAll()
|
||||
}
|
||||
|
||||
func resourceLoader(
|
||||
_ resourceLoader: AVAssetResourceLoader,
|
||||
shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest
|
||||
) -> Bool {
|
||||
// All state access is on the main queue (the delegate queue).
|
||||
guard let dataRequest = loadingRequest.dataRequest else { return false }
|
||||
guard let url = loaderURLs[ObjectIdentifier(resourceLoader)] else {
|
||||
logger.log("no resolved URL for resource loader")
|
||||
@@ -75,7 +131,16 @@ final class PinnedMediaResourceLoader: NSObject, AVAssetResourceLoaderDelegate {
|
||||
}
|
||||
logger.log("fetching \(url.absoluteString, privacy: .public) range=\(upstream.value(forHTTPHeaderField: "Range") ?? "-", privacy: .public)")
|
||||
|
||||
let task = TLSPinning.session().dataTask(with: upstream) { data, response, error in
|
||||
// Key the task by the loading request's identity directly — no hash
|
||||
// derivation, so two distinct requests can never collide.
|
||||
let requestKey = ObjectIdentifier(loadingRequest)
|
||||
let task = pinnedSession.dataTask(with: upstream) { [weak self] data, response, error in
|
||||
guard let self else { return }
|
||||
// Cleanup: remove the task from the active map regardless of outcome.
|
||||
// Runs on .main (the session's delegateQueue), same domain as all
|
||||
// other map mutations.
|
||||
self.activeTasks[requestKey] = nil
|
||||
|
||||
if let error {
|
||||
logger.log("fetch failed \(url.absoluteString, privacy: .public): \(error.localizedDescription, privacy: .public)")
|
||||
loadingRequest.finishLoading(with: error)
|
||||
@@ -85,10 +150,33 @@ final class PinnedMediaResourceLoader: NSObject, AVAssetResourceLoaderDelegate {
|
||||
loadingRequest.finishLoading(with: URLError(.badServerResponse))
|
||||
return
|
||||
}
|
||||
// Reject non-200/206 responses (404, 500, etc.) instead of feeding
|
||||
// error JSON into AVPlayer as media bytes.
|
||||
guard http.statusCode == 200 || http.statusCode == 206 else {
|
||||
logger.log("unexpected status \(http.statusCode) for \(url.absoluteString, privacy: .public)")
|
||||
loadingRequest.finishLoading(with: URLError(.badServerResponse))
|
||||
return
|
||||
}
|
||||
if let info = loadingRequest.contentInformationRequest {
|
||||
info.contentType = http.mimeType ?? "application/octet-stream"
|
||||
if http.expectedContentLength >= 0 {
|
||||
info.contentLength = Int64(http.expectedContentLength)
|
||||
// Content-length handling (Iteration 05 Item 7):
|
||||
// - For 206: set full content length ONLY when Content-Range
|
||||
// provides a known total. Never fall back to the range's
|
||||
// expectedContentLength (that would tell AVPlayer the total
|
||||
// resource is only as large as this one range).
|
||||
// - For 200: expectedContentLength is already the full size.
|
||||
if http.statusCode == 206 {
|
||||
if let total = Self.parseTotalLength(http), total >= 0 {
|
||||
info.contentLength = total
|
||||
}
|
||||
// If Content-Range has no known total (e.g. "bytes 0-1023/*"),
|
||||
// do NOT set contentLength — AVPlayer will handle it as
|
||||
// unknown-length, which is correct for a range response.
|
||||
} else {
|
||||
// 200: expectedContentLength is the full resource size.
|
||||
if http.expectedContentLength >= 0 {
|
||||
info.contentLength = Int64(http.expectedContentLength)
|
||||
}
|
||||
}
|
||||
info.isByteRangeAccessSupported = true
|
||||
}
|
||||
@@ -97,6 +185,7 @@ final class PinnedMediaResourceLoader: NSObject, AVAssetResourceLoaderDelegate {
|
||||
}
|
||||
loadingRequest.finishLoading()
|
||||
}
|
||||
activeTasks[requestKey] = task
|
||||
task.resume()
|
||||
return true
|
||||
}
|
||||
@@ -105,6 +194,27 @@ final class PinnedMediaResourceLoader: NSObject, AVAssetResourceLoaderDelegate {
|
||||
_ resourceLoader: AVAssetResourceLoader,
|
||||
didCancel loadingRequest: AVAssetResourceLoadingRequest
|
||||
) {
|
||||
logger.log("resource loader cancelled request")
|
||||
// Cancel the upstream data task so a seek or item swap doesn't keep
|
||||
// downloading cancelled ranges. Keyed by ObjectIdentifier directly.
|
||||
let key = ObjectIdentifier(loadingRequest)
|
||||
activeTasks[key]?.cancel()
|
||||
activeTasks[key] = nil
|
||||
logger.log("resource loader cancelled request, upstream task cancelled")
|
||||
}
|
||||
|
||||
/// Parses the total resource length from an HTTP 206 response's
|
||||
/// `Content-Range` header (e.g. "bytes 0-1023/4096" → 4096). Returns nil
|
||||
/// for non-206 responses, missing headers, unknown totals ("*"), or
|
||||
/// malformed values.
|
||||
static func parseTotalLength(_ response: HTTPURLResponse) -> Int64? {
|
||||
if response.statusCode == 206,
|
||||
let contentRange = response.value(forHTTPHeaderField: "Content-Range") {
|
||||
// Format: "bytes <start>-<end>/<total>" or "bytes <start>-<end>/*"
|
||||
let afterSlash = contentRange.split(separator: "/").last?.trimmingCharacters(in: .whitespaces)
|
||||
if let afterSlash, afterSlash != "*", let total = Int64(afterSlash) {
|
||||
return total
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user