From dcba97f55856828d4e3756be33e6c56865f574f1 Mon Sep 17 00:00:00 2001 From: professorDeveloper <108933534+professorDeveloper@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:56:24 +0500 Subject: [PATCH 1/2] Apple TV: relay image-wrapped HLS segments through the backend Streams on the /stream/*.m3u8 route serve their TS segments as tiktokcdn .image files with a PNG prefix, which AVPlayer cannot play. Mobile and Android TV rewrite those segment URLs to /api/contents/media-segment; tvOS had no rewrite at all. The playlists now load through an AVAssetResourceLoaderDelegate on a custom scheme, which fetches them on the device with the source headers (their tokens are bound to its address) and rewrites allowlisted segments to the relay. Other sources keep the existing direct path. --- apple-tv/SozoTV/APIClient.swift | 2 + apple-tv/SozoTV/HLSPlaylistRelay.swift | 68 +++++++++++++++++++++ apple-tv/SozoTV/RelayedPlaylistLoader.swift | 58 ++++++++++++++++++ apple-tv/SozoTV/TVPlayerView.swift | 12 +++- apple-tv/Tests/HLSPlaylistRelay/main.swift | 53 ++++++++++++++++ apple-tv/scripts/check-profiles.sh | 3 + 6 files changed, 195 insertions(+), 1 deletion(-) create mode 100644 apple-tv/SozoTV/HLSPlaylistRelay.swift create mode 100644 apple-tv/SozoTV/RelayedPlaylistLoader.swift create mode 100644 apple-tv/Tests/HLSPlaylistRelay/main.swift diff --git a/apple-tv/SozoTV/APIClient.swift b/apple-tv/SozoTV/APIClient.swift index 7cf0adb7..197f90bb 100644 --- a/apple-tv/SozoTV/APIClient.swift +++ b/apple-tv/SozoTV/APIClient.swift @@ -14,6 +14,8 @@ actor APIClient { return URL(string: String(decoding: plain, as: UTF8.self))! }() + static let mediaSegmentEndpoint = defaultBase.appendingPathComponent("contents/media-segment") + init(base: URL = APIClient.defaultBase, session: URLSession? = nil) { self.base = base self.session = session ?? URLSession(configuration: .ephemeral, delegate: SameOriginRedirects(), delegateQueue: nil) diff --git a/apple-tv/SozoTV/HLSPlaylistRelay.swift b/apple-tv/SozoTV/HLSPlaylistRelay.swift new file mode 100644 index 00000000..694f1596 --- /dev/null +++ b/apple-tv/SozoTV/HLSPlaylistRelay.swift @@ -0,0 +1,68 @@ +import Foundation + +/// Image-wrapped TS segments go through the backend's media-segment relay, while +/// the playlists stay on the device: their tokens are bound to its address. +enum HLSPlaylistRelay { + static let scheme = "sozo-hls" + static let maximumPlaylistBytes = 4 * 1024 * 1024 + + /// The embed rotates CDN hosts; its stream route is the stable part. + static func needsManifestProxy(_ url: URL) -> Bool { + url.scheme?.lowercased() == "https" && url.path.hasPrefix("/stream/") && url.path.hasSuffix(".m3u8") + } + + static func loaderURL(_ url: URL) -> URL? { + guard url.scheme?.lowercased() == "https", var parts = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil } + parts.scheme = scheme + return parts.url + } + + static func upstreamURL(_ url: URL) -> URL? { + guard url.scheme?.lowercased() == scheme, var parts = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil } + parts.scheme = "https" + return parts.url + } + + /// Mirrors the backend allowlist in mediaSegmentRelay.js; anything else is left alone. + static func segmentRelay(_ url: URL, endpoint: URL) -> URL? { + let raw = url.absoluteString + guard raw.count <= 8192, url.scheme?.lowercased() == "https", url.user == nil, url.password == nil, + url.port == nil || url.port == 443, let host = url.host?.lowercased(), + host.range(of: #"^p(?:16|19)-ad-site-sign-sg\.tiktokcdn\.com$"#, options: .regularExpression) != nil, + url.path.hasPrefix("/ad-site-i18n-sg/"), url.path.hasSuffix(".image") else { return nil } + let allowed = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") + guard let encoded = raw.addingPercentEncoding(withAllowedCharacters: allowed) else { return nil } + return URL(string: endpoint.absoluteString + "?url=" + encoded) + } + + /// Every URI is made absolute because the playlist is served from a custom scheme. + /// Variant playlists come back through the loader; media playlist segments are + /// relayed when the backend allows it and otherwise fetched directly. + static func rewrite(_ playlist: String, base: URL, endpoint: URL) -> String? { + guard playlist.drop(while: { $0 == "\u{FEFF}" || $0.isWhitespace }).hasPrefix("#EXTM3U") else { return nil } + let master = playlist.contains("#EXT-X-STREAM-INF") + func target(_ raw: String, playlist: Bool) -> String? { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard let absolute = URL(string: trimmed, relativeTo: base)?.absoluteURL else { return nil } + if playlist { return (loaderURL(absolute) ?? absolute).absoluteString } + return (segmentRelay(absolute, endpoint: endpoint) ?? absolute).absoluteString + } + let attribute = try! NSRegularExpression(pattern: #"URI="([^"]+)""#) + return playlist.components(separatedBy: "\n").map { line -> String in + let stripped = line.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(.init(charactersIn: "\u{FEFF}"))) + if stripped.isEmpty { return line } + if stripped.hasPrefix("#") { + let renditions = master && (stripped.hasPrefix("#EXT-X-MEDIA:") || stripped.hasPrefix("#EXT-X-I-FRAME-STREAM-INF:")) + let text = line as NSString + var out = line + for match in attribute.matches(in: line, range: NSRange(location: 0, length: text.length)).reversed() { + let value = text.substring(with: match.range(at: 1)) + guard let replaced = target(value, playlist: renditions) else { continue } + out = (out as NSString).replacingCharacters(in: match.range(at: 1), with: replaced) + } + return out + } + return target(stripped, playlist: master) ?? line + }.joined(separator: "\n") + } +} diff --git a/apple-tv/SozoTV/RelayedPlaylistLoader.swift b/apple-tv/SozoTV/RelayedPlaylistLoader.swift new file mode 100644 index 00000000..18f430a1 --- /dev/null +++ b/apple-tv/SozoTV/RelayedPlaylistLoader.swift @@ -0,0 +1,58 @@ +import AVFoundation + +/// Serves the playlists of a relayed stream to AVPlayer after HLSPlaylistRelay +/// has rewritten them. AVFoundation only hands playlists and keys to a resource +/// loader, so segments keep plain https URLs. +final class RelayedPlaylistLoader: NSObject, AVAssetResourceLoaderDelegate, @unchecked Sendable { + let queue = DispatchQueue(label: "sozo.hls.playlists") + private let headers: [String: String] + private let endpoint: URL + private let session: URLSession + private let lock = NSLock() + private var tasks: [ObjectIdentifier: URLSessionDataTask] = [:] + + init(headers: [String: String], endpoint: URL) { + self.headers = headers + self.endpoint = endpoint + let config = URLSessionConfiguration.ephemeral + config.httpShouldSetCookies = false + session = URLSession(configuration: config) + super.init() + } + + deinit { session.invalidateAndCancel() } + + func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { + guard let url = loadingRequest.request.url, let upstream = HLSPlaylistRelay.upstreamURL(url) else { return false } + var request = URLRequest(url: upstream, timeoutInterval: 20) + headers.forEach { request.setValue($1, forHTTPHeaderField: $0) } + let key = ObjectIdentifier(loadingRequest) + let endpoint = endpoint + let task = session.dataTask(with: request) { [weak self] data, response, error in + self?.lock.withLock { _ = self?.tasks.removeValue(forKey: key) } + guard !loadingRequest.isCancelled else { return } + guard let data, data.count <= HLSPlaylistRelay.maximumPlaylistBytes, + let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode), + let text = String(data: data, encoding: .utf8), + let playlist = HLSPlaylistRelay.rewrite(text, base: http.url ?? upstream, endpoint: endpoint) else { + loadingRequest.finishLoading(with: error ?? URLError(.badServerResponse)) + return + } + let body = Data(playlist.utf8) + if let info = loadingRequest.contentInformationRequest { + info.contentType = "public.m3u-playlist" + info.contentLength = Int64(body.count) + info.isByteRangeAccessSupported = false + } + loadingRequest.dataRequest?.respond(with: body) + loadingRequest.finishLoading() + } + lock.withLock { tasks[key] = task } + task.resume() + return true + } + + func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) { + lock.withLock { tasks.removeValue(forKey: ObjectIdentifier(loadingRequest)) }?.cancel() + } +} diff --git a/apple-tv/SozoTV/TVPlayerView.swift b/apple-tv/SozoTV/TVPlayerView.swift index 0bf64f62..8e7d73bd 100644 --- a/apple-tv/SozoTV/TVPlayerView.swift +++ b/apple-tv/SozoTV/TVPlayerView.swift @@ -20,7 +20,16 @@ struct TVPlayerView: UIViewControllerRepresentable { func makeCoordinator() -> Coordinator { Coordinator(session: session, history: item.history, close: { dismiss() }, changeSource: changeSource, nextEpisode: nextEpisode, item: item) } func makeUIViewController(context: Context) -> AVPlayerViewController { - let asset = AVURLAsset(url: item.url, options: ["AVURLAssetHTTPHeaderFieldsKey": item.headers]) + let asset: AVURLAsset + if HLSPlaylistRelay.needsManifestProxy(item.url), let relayed = HLSPlaylistRelay.loaderURL(item.url) { + // Its playlists carry the source headers themselves; the relayed segments need none. + let loader = RelayedPlaylistLoader(headers: item.headers, endpoint: APIClient.mediaSegmentEndpoint) + asset = AVURLAsset(url: relayed) + asset.resourceLoader.setDelegate(loader, queue: loader.queue) + context.coordinator.playlistLoader = loader + } else { + asset = AVURLAsset(url: item.url, options: ["AVURLAssetHTTPHeaderFieldsKey": item.headers]) + } let playerItem = AVPlayerItem(asset: asset) let title = AVMutableMetadataItem() title.identifier = .commonIdentifierTitle @@ -65,6 +74,7 @@ struct TVPlayerView: UIViewControllerRepresentable { private let changeSource: ((Double?) -> Void)? private let nextEpisode: (() -> Void)? private let item: PlaybackItem + var playlistLoader: RelayedPlaylistLoader? #if DEBUG private var positionProbe: UILabel? #endif diff --git a/apple-tv/Tests/HLSPlaylistRelay/main.swift b/apple-tv/Tests/HLSPlaylistRelay/main.swift new file mode 100644 index 00000000..6193acef --- /dev/null +++ b/apple-tv/Tests/HLSPlaylistRelay/main.swift @@ -0,0 +1,53 @@ +import Foundation + +let endpoint = URL(string: "https://api.test/api/contents/media-segment")! +let segment = "https://p16-ad-site-sign-sg.tiktokcdn.com/ad-site-i18n-sg/abc/seg-1.image?x-expires=1&sig=a+b/c==" +let relayed = "https://api.test/api/contents/media-segment?url=" + segment.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"))! + +assert(HLSPlaylistRelay.needsManifestProxy(URL(string: "https://cdn-7.test/stream/abc/index.m3u8?t=1")!)) +assert(!HLSPlaylistRelay.needsManifestProxy(URL(string: "https://cdn.test/hls/index.m3u8")!)) +assert(!HLSPlaylistRelay.needsManifestProxy(URL(string: "https://cdn.test/stream/video.mp4")!)) +assert(!HLSPlaylistRelay.needsManifestProxy(URL(string: "http://cdn.test/stream/index.m3u8")!)) + +let loader = HLSPlaylistRelay.loaderURL(URL(string: "https://cdn.test/stream/a/index.m3u8?t=1")!)! +assert(loader.absoluteString == "sozo-hls://cdn.test/stream/a/index.m3u8?t=1") +assert(HLSPlaylistRelay.upstreamURL(loader)?.absoluteString == "https://cdn.test/stream/a/index.m3u8?t=1") +assert(HLSPlaylistRelay.upstreamURL(URL(string: "https://cdn.test/a.m3u8")!) == nil) + +assert(HLSPlaylistRelay.segmentRelay(URL(string: segment)!, endpoint: endpoint)?.absoluteString == relayed) +assert(HLSPlaylistRelay.segmentRelay(URL(string: "https://p19-ad-site-sign-sg.tiktokcdn.com:443/ad-site-i18n-sg/a.image")!, endpoint: endpoint) != nil) +for rejected in ["http://p16-ad-site-sign-sg.tiktokcdn.com/ad-site-i18n-sg/a.image", + "https://p17-ad-site-sign-sg.tiktokcdn.com/ad-site-i18n-sg/a.image", + "https://p16-ad-site-sign-sg.tiktokcdn.com.evil.test/ad-site-i18n-sg/a.image", + "https://user:pw@p16-ad-site-sign-sg.tiktokcdn.com/ad-site-i18n-sg/a.image", + "https://p16-ad-site-sign-sg.tiktokcdn.com:8443/ad-site-i18n-sg/a.image", + "https://p16-ad-site-sign-sg.tiktokcdn.com/other/a.image", + "https://p16-ad-site-sign-sg.tiktokcdn.com/ad-site-i18n-sg/a.ts"] { + assert(HLSPlaylistRelay.segmentRelay(URL(string: rejected)!, endpoint: endpoint) == nil, rejected) +} +print("HLS relay: manifest routing, loader scheme round trip and the backend segment allowlist passed") + +let master = """ +#EXTM3U +#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="a",NAME="en",URI="audio/en.m3u8" +#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=1280x720 +720/index.m3u8?t=1 +#EXT-X-STREAM-INF:BANDWIDTH=300000 +https://other.test/360.m3u8 +""" +let masterOut = HLSPlaylistRelay.rewrite(master, base: URL(string: "https://cdn.test/stream/a/master.m3u8")!, endpoint: endpoint)!.components(separatedBy: "\n") +assert(masterOut[1] == #"#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="a",NAME="en",URI="sozo-hls://cdn.test/stream/a/audio/en.m3u8""#) +assert(masterOut[2] == "#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=1280x720") +assert(masterOut[3] == "sozo-hls://cdn.test/stream/a/720/index.m3u8?t=1") +assert(masterOut[5] == "sozo-hls://other.test/360.m3u8") + +let media = "#EXTM3U\r\n#EXT-X-TARGETDURATION:6\r\n#EXT-X-KEY:METHOD=AES-128,URI=\"../key.bin\",IV=0x1\r\n#EXTINF:6.0,\r\n\(segment)\r\n#EXTINF:6.0,\r\nseg-2.ts\r\n\r\n#EXT-X-ENDLIST\r\n" +let mediaOut = HLSPlaylistRelay.rewrite(media, base: URL(string: "https://cdn.test/stream/a/720/index.m3u8")!, endpoint: endpoint)!.components(separatedBy: "\n") +assert(mediaOut[0] == "#EXTM3U\r" && mediaOut[1] == "#EXT-X-TARGETDURATION:6\r") +assert(mediaOut[2] == "#EXT-X-KEY:METHOD=AES-128,URI=\"https://cdn.test/stream/a/key.bin\",IV=0x1\r") +assert(mediaOut[4] == relayed) +assert(mediaOut[6] == "https://cdn.test/stream/a/720/seg-2.ts") +assert(mediaOut[7] == "\r" && mediaOut[8] == "#EXT-X-ENDLIST\r") +assert(HLSPlaylistRelay.rewrite("blocked", base: URL(string: "https://cdn.test/stream/a.m3u8")!, endpoint: endpoint) == nil) +assert(HLSPlaylistRelay.rewrite("\u{FEFF}#EXTM3U\nseg.ts", base: URL(string: "https://cdn.test/stream/a.m3u8")!, endpoint: endpoint) == "\u{FEFF}#EXTM3U\nhttps://cdn.test/stream/seg.ts") +print("HLS relay: master renditions through the loader, relayed and direct segments, keys, CRLF and non-playlists passed") diff --git a/apple-tv/scripts/check-profiles.sh b/apple-tv/scripts/check-profiles.sh index 1391ef00..270ede6d 100755 --- a/apple-tv/scripts/check-profiles.sh +++ b/apple-tv/scripts/check-profiles.sh @@ -39,3 +39,6 @@ swiftc SozoTV/ProfileColorContrast.swift Tests/ProfileColorContrast/main.swift - swiftc -parse-as-library SozoTV/BoundedArtworkData.swift Tests/ArtworkData/main.swift -o "$check_dir/artwork" "$check_dir/artwork" + +swiftc SozoTV/HLSPlaylistRelay.swift Tests/HLSPlaylistRelay/main.swift -o "$check_dir/hlsRelay" +"$check_dir/hlsRelay" From 1344df6e2924cb29a9cd0ff3e3f44879c822cf69 Mon Sep 17 00:00:00 2001 From: professorDeveloper <108933534+professorDeveloper@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:59:56 +0500 Subject: [PATCH 2/2] Apple TV: keep source headers on direct segments of relayed streams Segments outside the relay allowlist, EXT-X-KEY URIs and init segments are fetched by AVPlayer itself, so without the asset header option they lost Referer/Origin and any header-checked CDN that played before would now fail. Mobile and Android TV proxy them with the source headers. The loader also finishes its requests on the queue it was registered on rather than the URLSession delegate queue. --- apple-tv/SozoTV/RelayedPlaylistLoader.swift | 33 +++++++++++---------- apple-tv/SozoTV/TVPlayerView.swift | 4 +-- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/apple-tv/SozoTV/RelayedPlaylistLoader.swift b/apple-tv/SozoTV/RelayedPlaylistLoader.swift index 18f430a1..e87e43c4 100644 --- a/apple-tv/SozoTV/RelayedPlaylistLoader.swift +++ b/apple-tv/SozoTV/RelayedPlaylistLoader.swift @@ -28,24 +28,27 @@ final class RelayedPlaylistLoader: NSObject, AVAssetResourceLoaderDelegate, @unc headers.forEach { request.setValue($1, forHTTPHeaderField: $0) } let key = ObjectIdentifier(loadingRequest) let endpoint = endpoint + let queue = queue let task = session.dataTask(with: request) { [weak self] data, response, error in self?.lock.withLock { _ = self?.tasks.removeValue(forKey: key) } - guard !loadingRequest.isCancelled else { return } - guard let data, data.count <= HLSPlaylistRelay.maximumPlaylistBytes, - let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode), - let text = String(data: data, encoding: .utf8), - let playlist = HLSPlaylistRelay.rewrite(text, base: http.url ?? upstream, endpoint: endpoint) else { - loadingRequest.finishLoading(with: error ?? URLError(.badServerResponse)) - return + queue.async { + guard !loadingRequest.isCancelled else { return } + guard let data, data.count <= HLSPlaylistRelay.maximumPlaylistBytes, + let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode), + let text = String(data: data, encoding: .utf8), + let playlist = HLSPlaylistRelay.rewrite(text, base: http.url ?? upstream, endpoint: endpoint) else { + loadingRequest.finishLoading(with: error ?? URLError(.badServerResponse)) + return + } + let body = Data(playlist.utf8) + if let info = loadingRequest.contentInformationRequest { + info.contentType = "public.m3u-playlist" + info.contentLength = Int64(body.count) + info.isByteRangeAccessSupported = false + } + loadingRequest.dataRequest?.respond(with: body) + loadingRequest.finishLoading() } - let body = Data(playlist.utf8) - if let info = loadingRequest.contentInformationRequest { - info.contentType = "public.m3u-playlist" - info.contentLength = Int64(body.count) - info.isByteRangeAccessSupported = false - } - loadingRequest.dataRequest?.respond(with: body) - loadingRequest.finishLoading() } lock.withLock { tasks[key] = task } task.resume() diff --git a/apple-tv/SozoTV/TVPlayerView.swift b/apple-tv/SozoTV/TVPlayerView.swift index 8e7d73bd..ee776701 100644 --- a/apple-tv/SozoTV/TVPlayerView.swift +++ b/apple-tv/SozoTV/TVPlayerView.swift @@ -22,9 +22,9 @@ struct TVPlayerView: UIViewControllerRepresentable { func makeUIViewController(context: Context) -> AVPlayerViewController { let asset: AVURLAsset if HLSPlaylistRelay.needsManifestProxy(item.url), let relayed = HLSPlaylistRelay.loaderURL(item.url) { - // Its playlists carry the source headers themselves; the relayed segments need none. + // The loader sends the headers on playlists; the asset option still covers direct segments and keys. let loader = RelayedPlaylistLoader(headers: item.headers, endpoint: APIClient.mediaSegmentEndpoint) - asset = AVURLAsset(url: relayed) + asset = AVURLAsset(url: relayed, options: ["AVURLAssetHTTPHeaderFieldsKey": item.headers]) asset.resourceLoader.setDelegate(loader, queue: loader.queue) context.coordinator.playlistLoader = loader } else {