Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 88 additions & 5 deletions TypeTypeIOS/Core/Networking/LiveImageURLResolver.swift
Original file line number Diff line number Diff line change
@@ -1,34 +1,117 @@
import Foundation

// Where a picture is shown decides how large Bilibili's image service has to render it.
enum LiveImageSize {
// Lists, shelves, related videos and avatars.
case card
// The picture the player shows before the first frame.
case poster
}

enum LiveImageURLResolver {
static var baseURLProvider: () -> URL? = { nil }

static func resolve(_ reference: String?) -> URL? {
static func resolve(_ reference: String?, size: LiveImageSize = .card) -> URL? {
guard var reference = reference?.trimmingCharacters(
in: .whitespacesAndNewlines
), !reference.isEmpty
else { return nil }
// The server sometimes emits "httpss://".
if reference.hasPrefix("httpss://") {
reference = "https://" + reference.dropFirst("httpss://".count)
} else if reference.hasPrefix("//") {
reference = "https:" + reference
}
return resolve(URL(string: reference))
return resolve(URL(string: reference), size: size)
}

static func resolve(_ url: URL?) -> URL? {
static func resolve(_ url: URL?, size: LiveImageSize = .card) -> URL? {
guard let url else { return nil }
if url.scheme == "http" || url.scheme == "https" {
return url
return remoteImage(url, size: size)
}
let reference = url.absoluteString
if url.scheme == nil, reference.hasPrefix("//") {
return resolve(URL(string: "https:" + reference), size: size)
}
guard let base = baseURLProvider() else { return url }
let baseString = base.absoluteString.hasSuffix("/")
? String(base.absoluteString.dropLast())
: base.absoluteString
let reference = url.absoluteString
if reference.hasPrefix("/") {
return URL(string: baseString + reference) ?? url
}
guard let root = URL(string: baseString + "/") else { return url }
return URL(string: reference, relativeTo: root)?.absoluteURL ?? url
}

// Bilibili covers and avatars are several hundred kilobytes at full size; its image service scales them on
// request. Like the web client, the picture is asked for at the size it is shown, and it goes through the
// instance's /proxy, so the app never contacts the image host itself and ATS never sees an http address.
private static func remoteImage(_ url: URL, size: LiveImageSize) -> URL {
let target = proxiedTarget(of: url) ?? url
guard let sized = BilibiliImage(target)?.url(for: size) else { return url }
return throughInstance(sized)
}

private static func proxiedTarget(of url: URL) -> URL? {
guard url.path.hasSuffix("/proxy"),
let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let value = components.queryItems?.first(where: { $0.name == "url" })?.value
else { return nil }
return URL(string: value)
}

private static func throughInstance(_ url: URL) -> URL {
guard let base = baseURLProvider() else { return url }
let baseString = base.absoluteString.hasSuffix("/")
? String(base.absoluteString.dropLast())
: base.absoluteString
guard var components = URLComponents(string: baseString + "/proxy"),
let value = url.absoluteString.addingPercentEncoding(withAllowedCharacters: componentAllowed)
else { return url }
components.percentEncodedQuery = "url=" + value
return components.url ?? url
}

// The characters encodeURIComponent leaves alone, as the web client builds this address.
private static let componentAllowed = CharacterSet(
charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~*'()"
)
}

private struct BilibiliImage {
let host: String
let path: String
let query: String?

init?(_ url: URL) {
guard let host = url.host?.lowercased(),
host.hasSuffix("hdslb.com") || host.hasSuffix("biliimg.com"),
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
else { return nil }
// biliimg.com serves the same files as the hdslb image hosts.
self.host = host.hasSuffix("biliimg.com") ? "i0.hdslb.com" : host
self.path = components.percentEncodedPath
self.query = components.percentEncodedQuery
}

func url(for size: LiveImageSize) -> URL? {
var components = URLComponents()
components.scheme = "https"
components.host = host
components.percentEncodedPath = path + suffix(for: size)
components.percentEncodedQuery = query
return components.url
}

// An address that already names a size, or any path other than a cover or an avatar, stays as it is.
private func suffix(for size: LiveImageSize) -> String {
guard !path.contains("@") else { return "" }
if path.hasPrefix("/bfs/archive/") {
return size == .poster ? "@1280w_720h_1c.webp" : "@672w_378h_1c.webp"
}
if path.hasPrefix("/bfs/face/") { return "@240w_240h_1c.webp" }
return ""
}
}
8 changes: 5 additions & 3 deletions TypeTypeIOS/Features/Home/Views/LiveRemoteImage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ struct LiveRemoteImage: View {
@Environment(\.themePalette) private var palette
let url: URL?
let contentMode: ContentMode
let size: LiveImageSize
@State private var loaded: Loaded?
@State private var failedURL: URL?
@Environment(\.displayScale) private var displayScale
@Environment(\.imagePipeline) private var pipeline

init(url: URL?, contentMode: ContentMode = .fill) {
init(url: URL?, contentMode: ContentMode = .fill, size: LiveImageSize = .card) {
self.url = url
self.contentMode = contentMode
self.size = size
}

var body: some View {
Expand Down Expand Up @@ -54,7 +56,7 @@ struct LiveRemoteImage: View {
}

private func cached(_ pixels: CGFloat) -> UIImage? {
guard let url = LiveImageURLResolver.resolve(url), pixels > 0 else { return nil }
guard let url = LiveImageURLResolver.resolve(url, size: size), pixels > 0 else { return nil }
return pipeline.cachedImage(for: url, maxPixelSize: pixels)
}

Expand All @@ -63,7 +65,7 @@ struct LiveRemoteImage: View {
private func load(_ pixels: CGFloat) async {
let requested = url
guard pixels > 0 else { return }
guard let resolved = LiveImageURLResolver.resolve(requested) else {
guard let resolved = LiveImageURLResolver.resolve(requested, size: size) else {
failedURL = requested
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ struct LiveAudioOnlyPoster: View {
}

private func artwork(width: CGFloat) -> some View {
LiveRemoteImage(url: posterURL)
LiveRemoteImage(url: posterURL, size: .poster)
.frame(width: width, height: width * 9 / 16)
.clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
.shadow(color: .black.opacity(0.4), radius: 12, y: 6)
Expand Down
4 changes: 3 additions & 1 deletion TypeTypeIOS/Features/Watch/Models/LivePlaybackModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,9 @@ enum LivePlayerImageMode: String, CaseIterable, Identifiable {

enum LiveProviderPlayback {
case separateProgressive(videoURL: URL, audioURL: URL)
case separateHLS(videoURL: URL, audioURL: URL)
// `alternates` are the lighter qualities the master playlist offers next to `videoURL`, for the player to
// switch to when the connection is slow. Empty when one quality was asked for.
case separateHLS(videoURL: URL, audioURL: URL, alternates: [LiveProviderHLSVariant])
}

struct LivePlaybackPreparation {
Expand Down
42 changes: 39 additions & 3 deletions TypeTypeIOS/Features/Watch/Models/LivePlaybackSourceModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,22 @@ struct LivePlaybackVideoSource: Decodable, Hashable, Identifiable {
let manifestURL: String?

var id: String { selectionID }
// NicoNico lists several qualities that share itag, codec, height and bitrate (none of them reported): the
// address of an HLS playlist is what tells them apart, within one stream response.
var selectionID: String {
[
String(itag),
codec ?? "",
String(height),
String(bitrate ?? 0),
deliveryMethod,
isHLSDelivery ? url : "",
].joined(separator: ":")
}

var displayName: String {
if !resolution.isEmpty { return resolution }
if height > 0 { return "\(height)p" }
if effectiveHeight > 0 { return "\(effectiveHeight)p" }
return "Automatic"
}

Expand All @@ -45,12 +48,45 @@ struct LivePlaybackVideoSource: Decodable, Hashable, Identifiable {
deliveryMethod.caseInsensitiveCompare("sabr") == .orderedSame
}

// NicoNico sends height 0 for some qualities and names them only in the label ("360p"): the label is the
// truth there, as in the web client.
var effectiveHeight: Int {
height > 0 ? height : Self.height(fromResolution: resolution)
}

var isHLSDelivery: Bool {
deliveryMethod.caseInsensitiveCompare("hls") == .orderedSame || isHLSPlaylist
}

// The number before the "p" of a label: "360p", "480P 清晰", "1080p60 HDR".
static func height(fromResolution label: String) -> Int {
let characters = Array(label)
var index = 0
while index < characters.count {
guard characters[index].isASCII, characters[index].isNumber else {
index += 1
continue
}
var end = index
while end < characters.count, characters[end].isASCII, characters[end].isNumber {
end += 1
}
var next = end
while next < characters.count, characters[next] == " " { next += 1 }
if next < characters.count, characters[next] == "p" || characters[next] == "P",
let height = Int(String(characters[index..<end])) {
return height
}
index = end
}
return 0
}

var isAppleProviderVideo: Bool {
guard mimeType.lowercased().hasPrefix("video/mp4") else {
return false
}
if deliveryMethod.caseInsensitiveCompare("hls") == .orderedSame
|| isHLSPlaylist {
if isHLSDelivery {
return true
}
let codec = codec?.lowercased() ?? ""
Expand Down
94 changes: 94 additions & 0 deletions TypeTypeIOS/Features/Watch/Models/LiveProviderHLSVariants.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import Foundation

// One quality of a provider whose video comes as one HLS playlist per quality (NicoNico).
struct LiveProviderHLSVariant: Equatable {
let url: URL
let bandwidth: Int
let resolution: String?
var codecs = ""
}

// The master playlist lists every quality, so the player starts with the best one and drops to a lighter one
// when the connection cannot keep up, as the web client does with hls.js.
enum LiveProviderHLSVariants {
static let audioGroup = "provider-audio"

// The qualities listed next to the chosen one: never a better one than it, the best of them first.
static func alternates(
among candidates: [LivePlaybackVideoSource],
selected: LivePlaybackVideoSource,
heightCap: Int?
) -> [LivePlaybackVideoSource] {
let limit = selected.effectiveHeight > 0 ? selected.effectiveHeight : heightCap
var seen: Set<String> = [selected.url]
let kept = candidates.filter { source in
guard source.isHLSDelivery, !source.isSABR, !source.url.isEmpty else { return false }
if let limit, source.effectiveHeight > limit { return false }
return seen.insert(source.url).inserted
}
return kept.enumerated().sorted { lhs, rhs in
if lhs.element.effectiveHeight != rhs.element.effectiveHeight {
return lhs.element.effectiveHeight > rhs.element.effectiveHeight
}
let lhsBitrate = lhs.element.bitrate ?? 0
let rhsBitrate = rhs.element.bitrate ?? 0
if lhsBitrate != rhsBitrate { return lhsBitrate > rhsBitrate }
return lhs.offset < rhs.offset
}.map(\.element)
}

// The server reports kilobits for some providers and bits for others.
static func bits(_ bitrate: Int?) -> Int? {
guard let bitrate, bitrate > 0 else { return nil }
return bitrate < 10_000 ? bitrate * 1_000 : bitrate
}

// A quality without a reported bitrate gets the web client's estimate for its height.
static func bandwidth(videoBitrate: Int?, height: Int, audioBitrate: Int?) -> Int {
let video = bits(videoBitrate) ?? estimatedVideoBandwidth(height: height)
let audio = bits(audioBitrate) ?? 128_000
return max(video + audio, 256_000)
}

static func estimatedVideoBandwidth(height: Int) -> Int {
switch height {
case 1_080...: return 5_000_000
case 720...: return 2_500_000
case 480...: return 1_200_000
case 360...: return 800_000
default: return 500_000
}
}

// Listed the same way for every variant: Apple wants CODECS on all of them or on none.
static func codecs(video: String?, audio: String?) -> String {
[video, audio].compactMap { $0?.isEmpty == false ? $0 : nil }.joined(separator: ",")
}

static func resolution(width: Int, height: Int) -> String? {
guard height > 0, width > 0 else { return nil }
return "\(width)x\(height)"
}

static func streamInfo(
bandwidth: Int,
resolution: String?,
codecs: String,
hasSubtitles: Bool
) -> String {
var attributes = [
"BANDWIDTH=\(bandwidth)",
"AUDIO=\"\(audioGroup)\"",
]
if !codecs.isEmpty {
attributes.append("CODECS=\"\(codecs)\"")
}
if let resolution {
attributes.append("RESOLUTION=\(resolution)")
}
if hasSubtitles {
attributes.append("SUBTITLES=\"subs\"")
}
return "#EXT-X-STREAM-INF:\(attributes.joined(separator: ","))"
}
}
25 changes: 25 additions & 0 deletions TypeTypeIOS/Features/Watch/Models/LiveStreamRefreshClaim.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import Foundation

// A provider's media links expire. Before a failure is shown or a lower quality is tried, a stream loaded
// ten minutes ago or more is fetched again, once, and playback resumes at the same position: the web
// client's claimStreamRefresh.
struct LiveStreamRefreshClaim {
static let minimumAge: TimeInterval = 10 * 60

private(set) var refreshedFor: Date?

mutating func claim(loadedAt: Date, now: Date) -> Bool {
guard refreshedFor != loadedAt,
now.timeIntervalSince(loadedAt) >= Self.minimumAge
else { return false }
refreshedFor = loadedAt
return true
}

// Only the providers whose links expire; YouTube plays through its own session.
static func refreshesExpiredLinks(videoURL: String) -> Bool {
guard let host = URL(string: videoURL)?.host?.lowercased() else { return false }
return host == "nicovideo.jp" || host.hasSuffix(".nicovideo.jp")
|| host == "bilibili.com" || host.hasSuffix(".bilibili.com")
}
}
Loading
Loading