import Foundation /// Audio-only manifest selection; all URLs remain ephemeral. struct HLSAudioSelection { struct Rendition { let url: URL private let advertisedBitrate: Int init(url: URL, bitrate: Int) { self.url = url advertisedBitrate = bitrate } /// YouTube audio-group tags omit BANDWIDTH. These two HLS format IDs are /// the HE-AAC 48 kb/s and AAC-LC 128 kb/s renditions, respectively. /// Keep this protocol fallback here, not in UI or player state. var bitrate: Int { if advertisedBitrate > 0 { return advertisedBitrate } switch formatID { case 233: return 48_000 case 234: return 128_000 default: return 0 } } var formatID: Int { let path = url.path.split(separator: "/") if let index = path.firstIndex(of: "itag"), index + 1 < path.count { return Int(path[index + 1]) ?? -1 } return URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems? .first(where: { $0.name == "itag" })?.value.flatMap(Int.init) ?? -1 } } let audio: [Rendition] let variantCount: Int let audioOnlyVariantCount: Int let audioGroupCount: Int struct PlaylistShape { let segmentCount: Int let transportStreamSegments: Int let fragmentedMP4Segments: Int let otherSegments: Int let aes128KeyCount: Int let sampleEncryptionKeyCount: Int let mapCount: Int let byteRangeCount: Int } static func manifestURL(from data: Data) -> URL? { guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let streaming = root["streamingData"] as? [String: Any], let raw = streaming["hlsManifestUrl"] as? String, let url = URL(string: raw), InnerTubeMediaURLPolicy.isAllowedMediaURL(url) else { return nil } return url } static func parse(_ text: String, relativeTo base: URL) throws -> Self { var audio: [Rendition] = [] var groups: [Rendition] = [] var pending: [String: String]? var variantCount = 0 for line in text.components(separatedBy: .newlines).map({ $0.trimmingCharacters(in: .whitespaces) }) { if line.hasPrefix("#EXT-X-MEDIA:") { let attributes = attributes(in: line) if attributes["TYPE"] == "AUDIO", let uri = attributes["URI"] { groups.append(Rendition(url: try checkedURL(uri, base: base), bitrate: 0)) } } else if line.hasPrefix("#EXT-X-STREAM-INF:") { pending = attributes(in: line) variantCount += 1 } else if !line.isEmpty, !line.hasPrefix("#"), let attributes = pending { pending = nil let codecs = (attributes["CODECS"] ?? "").lowercased().split(separator: ",") if !codecs.isEmpty, codecs.allSatisfy({ $0.hasPrefix("mp4a") }), attributes["RESOLUTION"] == nil { audio.append( Rendition( url: try checkedURL(line, base: base), bitrate: Int(attributes["AVERAGE-BANDWIDTH"] ?? attributes["BANDWIDTH"] ?? "") ?? 0 ) ) } } } return Self( audio: audio.isEmpty ? groups : audio, variantCount: variantCount, audioOnlyVariantCount: audio.count, audioGroupCount: groups.count) } /// Validate a finite playlist and every advertised segment/key/map URL /// before handing the selected audio rendition to native AVPlayer. static func validateVOD(_ text: String, relativeTo base: URL) throws -> TimeInterval { guard text.contains("#EXT-X-ENDLIST") else { throw InnerTubeError.playbackUnavailable("the audio playlist was not finite") } var duration = 0.0 var segmentCount = 0 for line in text.components(separatedBy: .newlines).map({ $0.trimmingCharacters(in: .whitespaces) }) { if line.hasPrefix("#EXTINF:") { let value = line.dropFirst("#EXTINF:".count).split(separator: ",").first ?? "" guard let seconds = Double(value), seconds.isFinite, seconds > 0 else { throw InnerTubeError.invalidResponse("invalid HLS segment duration") } duration += seconds } else if !line.isEmpty, !line.hasPrefix("#") { _ = try checkedURL(line, base: base) segmentCount += 1 } else if let uri = attributes(in: line)["URI"] { _ = try checkedURL(uri, base: base) } } guard segmentCount > 0, duration.isFinite, duration > 0 else { throw InnerTubeError.invalidResponse("empty HLS audio playlist") } return duration } static func playlistShape(_ text: String, relativeTo base: URL) -> PlaylistShape { var transportStreamSegments = 0 var fragmentedMP4Segments = 0 var otherSegments = 0 var aes128KeyCount = 0 var sampleEncryptionKeyCount = 0 var mapCount = 0 var byteRangeCount = 0 for line in text.components(separatedBy: .newlines).map({ $0.trimmingCharacters(in: .whitespaces) }) { if line.hasPrefix("#EXT-X-KEY:") { let method = attributes(in: line)["METHOD"]?.uppercased() if method == "AES-128" { aes128KeyCount += 1 } if method == "SAMPLE-AES" || method == "SAMPLE-AES-CTR" { sampleEncryptionKeyCount += 1 } } else if line.hasPrefix("#EXT-X-MAP:") { mapCount += 1 } else if line.hasPrefix("#EXT-X-BYTERANGE:") { byteRangeCount += 1 } else if line.hasPrefix("#EXT-X-PART:") { byteRangeCount += 1 } else if !line.isEmpty, !line.hasPrefix("#") { let pathExtension = URL(string: line, relativeTo: base)?.pathExtension.lowercased() switch pathExtension { case "ts": transportStreamSegments += 1 case "m4s", "mp4", "m4a": fragmentedMP4Segments += 1 default: otherSegments += 1 } } } return PlaylistShape( segmentCount: transportStreamSegments + fragmentedMP4Segments + otherSegments, transportStreamSegments: transportStreamSegments, fragmentedMP4Segments: fragmentedMP4Segments, otherSegments: otherSegments, aes128KeyCount: aes128KeyCount, sampleEncryptionKeyCount: sampleEncryptionKeyCount, mapCount: mapCount, byteRangeCount: byteRangeCount) } private static func checkedURL(_ raw: String, base: URL) throws -> URL { guard let url = URL(string: raw, relativeTo: base)?.absoluteURL, InnerTubeMediaURLPolicy.isAllowedMediaURL(url) else { throw InnerTubeError.playbackUnavailable("an HLS resource URL was not allowed") } return url } private static func attributes(in line: String) -> [String: String] { guard let colon = line.firstIndex(of: ":"), let regex = try? NSRegularExpression(pattern: #"([A-Z0-9-]+)=("[^"]*"|[^,]*)"#) else { return [:] } let payload = String(line[line.index(after: colon)...]) var result: [String: String] = [:] for match in regex.matches(in: payload, range: NSRange(payload.startIndex..., in: payload)) { guard let key = Range(match.range(at: 1), in: payload), let value = Range(match.range(at: 2), in: payload) else { continue } result[String(payload[key])] = String(payload[value]).trimmingCharacters( in: CharacterSet(charactersIn: "\"") ) } return result } }