~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/hydraulophone

An unofficial YouTube Music app for iPhone, iPad, and Mac.

0
0
main
1404 lines · 48.9 KB Raw History
import Foundation
import OSLog

public enum InnerTubeBrowseID {
  /// The Music library's Playlists tab, not the liked/songs tab.
  public static let libraryPlaylists = "FEmusic_liked_playlists"

  public static func library(_ category: LibraryCategory) -> String {
    switch category {
    case .playlists: "FEmusic_liked_playlists"
    case .songs: "FEmusic_liked_videos"
    case .albums: "FEmusic_liked_albums"
    case .artists: "FEmusic_library_corpus_artists"
    }
  }

  /// AuraMusic's playlist operation browses the `VL` view of a playlist.
  public static func playlist(_ id: String) -> String {
    id.hasPrefix("VL") ? id : "VL\(id)"
  }
}

/// Optional playback extension for a worker that observes AVPlayer readiness.
/// A failed AVPlayer item should request one fresh URL instead of retrying the
/// same expiring media URL.
public protocol StreamRefreshingMusicService: MusicService {
  func refreshStream(for song: Song) async throws -> URL
}

/// A stream URL together with the profile user-agent that produced it.
///
/// AVURLAsset can apply this value through Apple's public
/// `AVURLAssetHTTPUserAgentKey` option. The URL remains ephemeral and is not
/// persisted by Core.
public enum AudioStreamDelivery: Equatable, Sendable {
  case progressive
  case hls
}

public struct ResolvedAudioStream: Equatable, Sendable {
  public let url: URL
  public let userAgent: String
  public let mediaOrigin: String
  public let mediaReferer: String
  /// Duration reported by the selected InnerTube audio format, or by
  /// `videoDetails.lengthSeconds` when that format omits valid
  /// `approxDurationMs`. This is metadata about the complete track, not proof
  /// that AVPlayer has parsed or can seek to every byte.
  public let authoritativeDuration: TimeInterval?
  public let delivery: AudioStreamDelivery
  public let codec: AudioStreamCodec
  public let bitrate: Int?
  public let hlsFormatID: Int?
  public let cacheIdentity: TrackAssetIdentity?
  public let loudness: AudioLoudnessMetadata?
  private let hasMediaHeaders: Bool

  public init(
    url: URL,
    userAgent: String,
    mediaOrigin: String? = nil,
    mediaReferer: String? = nil,
    authoritativeDuration: TimeInterval? = nil,
    delivery: AudioStreamDelivery = .progressive,
    codec: AudioStreamCodec = .aac,
    bitrate: Int? = nil,
    hlsFormatID: Int? = nil,
    cacheIdentity: TrackAssetIdentity? = nil,
    loudness: AudioLoudnessMetadata? = nil
  ) {
    self.url = url
    self.userAgent = userAgent
    self.authoritativeDuration = Self.validDuration(authoritativeDuration)
    self.delivery = delivery
    self.codec = codec
    self.bitrate = bitrate
    self.hlsFormatID = hlsFormatID
    self.cacheIdentity = cacheIdentity
    self.loudness = loudness
    self.hasMediaHeaders = mediaOrigin != nil || mediaReferer != nil
    let usesMusicOrigin = mediaOrigin == "https://music.youtube.com"
    self.mediaOrigin =
      usesMusicOrigin
      ? "https://music.youtube.com"
      : "https://www.youtube.com"
    let usesMusicReferer =
      mediaReferer == "https://music.youtube.com/" && usesMusicOrigin
    self.mediaReferer =
      usesMusicReferer
      ? "https://music.youtube.com/"
      : "https://www.youtube.com/"
  }

  private static func validDuration(_ value: TimeInterval?) -> TimeInterval? {
    guard let value, value.isFinite, value > 0 else {
      return nil
    }
    return value
  }

  /// Headers allowed for the public AVURLAsset resource-loader path.
  ///
  /// This intentionally excludes cookies, Authorization, and all
  /// request-specific session material.
  public var mediaHeaders: [String: String] {
    guard hasMediaHeaders else {
      return [:]
    }
    return PlaybackMediaHeaders.make(
      userAgent: userAgent, origin: mediaOrigin, referer: mediaReferer
    )
  }
}

/// Optional playback extension for clients that can pass the resolved profile
/// user-agent to AVURLAsset.
public protocol AudioStreamResolving: Sendable {
  func resolveAudioStream(
    for song: Song,
    refreshing: Bool
  ) async throws -> ResolvedAudioStream
}

public protocol QualityAudioStreamResolving: AudioStreamResolving {
  func resolveAudioStream(
    for song: Song,
    refreshing: Bool,
    quality: AudioQualityPreference
  ) async throws -> ResolvedAudioStream
}

/// Fetches only player loudness metadata for a track, without resolving media.
public protocol AudioLoudnessResolving: Sendable {
  func loudness(for song: Song) async throws -> AudioLoudnessMetadata?
}

public protocol PlaybackPreparing: Sendable {
  func prepareHighPlayback() async
  func cancelPlaybackPreparation() async
}

extension PlaybackPreparing {
  public func cancelPlaybackPreparation() async {}
}

public actor InnerTubeMusicService:
  StreamRefreshingMusicService, QualityAudioStreamResolving, AudioLoudnessResolving,
  PlaybackPreparing
{
  // Internal for the catalog extension in this module. The client remains
  // private to Core's public API; catalog requests still go through the same
  // session-aware transport path as playback.
  let client: InnerTubeClient
  let primaryLyrics: any LyricsProviding
  let lyricsFallback: any LyricsProviding
  private let streamCipher: (any PlayerStreamCipher)?
  private let proofProvider: (any PlayerProofOfOriginProviding)?
  #if DEBUG
    private let highQualityLogger = Logger(
      subsystem: "com.hydraulophone", category: "high-quality-probe"
    )
  #endif
  private enum StreamCursor {
    case selected(String)
    case exhausted
  }
  private var streamCursors: [String: StreamCursor] = [:]

  public func prepareHighPlayback() async {
    do {
      guard let proofProvider else { return }
      try await client.preparePlaybackContext()
      guard await client.hasCompleteLogin(), await client.credentialTransportAllowed() else {
        return
      }
      let configuration = try await client.configurationSnapshot()
      guard let visitor = configuration.visitorData, Self.isValidProofVisitorData(visitor) else {
        return
      }
      let profile = InnerTubeClientProfile.webRemix(from: configuration)
      // Matches the reference's fixed public warmup identity. No media is
      // requested and this operation never enters the queue or listening history.
      async let proof = proofProvider.tokens(visitorData: visitor, videoID: "dQw4w9WgXcQ")
      let script = try await client.preparePlayerScript(videoID: "dQw4w9WgXcQ", profile: profile)
      try await (streamCipher as? any PlayerStreamCipherPreparing)?.prepare(
        playerScript: script.source)
      _ = try await proof
    } catch {
      // Speculation is best effort. Foreground resolution retains fresh fallback.
    }
  }

  public func cancelPlaybackPreparation() async {
    await client.cancelPlaybackPreparation()
    await proofProvider?.invalidate()
  }

  public init(
    client: InnerTubeClient = InnerTubeClient(),
    streamCipher: (any PlayerStreamCipher)? = nil,
    proofProvider: (any PlayerProofOfOriginProviding)? = nil,
    primaryLyrics: (any LyricsProviding)? = nil,
    lyricsFallback: (any LyricsProviding)? = nil
  ) {
    self.client = client
    self.primaryLyrics = primaryLyrics ?? BetterLyricsProvider()
    self.lyricsFallback = lyricsFallback ?? LRCLibLyricsProvider()
    self.streamCipher = streamCipher
    self.proofProvider = proofProvider
  }

  public func setSession(_ session: UserSession?) async {
    let previousSession = await client.sessionSnapshot()
    await client.setSession(session)
    guard previousSession != session else {
      return
    }
    await proofProvider?.invalidate()
  }

  public func search(query: String) async throws -> [SearchResult] {
    try await searchPage(
      query: query, continuation: nil, policy: .reload
    ).items
  }

  public func playlists() async throws -> [Playlist] {
    try await playlistPage(continuation: nil, policy: .reload).items
  }

  public func tracks(in playlist: Playlist) async throws -> [Song] {
    try await trackPage(
      in: playlist, continuation: nil, policy: .reload
    ).items
  }

  public func stream(for song: Song) async throws -> URL {
    streamCursors.removeValue(forKey: song.id)
    return try await resolveAudioStream(for: song, refreshing: false).url
  }

  public func refreshStream(for song: Song) async throws -> URL {
    try await resolveAudioStream(for: song, refreshing: true).url
  }

  /// Reads metadata from one authenticated WEB_REMIX player response. It does
  /// not inspect media URLs, fetch media, decipher a stream, or request proof.
  public func loudness(for song: Song) async throws -> AudioLoudnessMetadata? {
    try Task.checkCancellation()
    let configuration = try await client.configurationSnapshot()
    let profile = InnerTubeClientProfile.webRemix(from: configuration)
    let request = try await makeBodyAndSession(
      ["videoId": song.id, "contentCheckOk": true, "racyCheckOk": true],
      profile: profile,
      authenticated: true
    )
    guard let session = request.session, session.isAuthenticated else {
      throw InnerTubeError.authenticationRequired
    }
    let data = try await client.post(
      endpoint: "player",
      body: request.body,
      authenticated: true,
      profile: profile,
      sessionOverride: session
    )
    try Task.checkCancellation()
    return ResponseParser.playbackLoudness(from: data)
  }

  public func resolveAudioStream(
    for song: Song,
    refreshing: Bool
  ) async throws -> ResolvedAudioStream {
    if !refreshing {
      streamCursors.removeValue(forKey: song.id)
    }
    let cursor = streamCursors[song.id]
    if case .exhausted = cursor {
      throw InnerTubeError.playbackUnavailable("no fresh audio candidate remains")
    }
    return try await resolveStream(
      for: song,
      after: cursor.flatMap { cursor in
        if case .selected(let profileKey) = cursor {
          return profileKey
        }
        return nil
      },
      refreshing: refreshing
    )
  }

  public func resolveAudioStream(
    for song: Song,
    refreshing: Bool,
    quality: AudioQualityPreference
  ) async throws -> ResolvedAudioStream {
    switch quality {
    case .standard:
      return try await resolveAudioStream(for: song, refreshing: refreshing)
    case .high:
      if refreshing {
        // A refreshed URL must not reuse a proof pair that may have been
        // rejected with the previous media URL. This is one bounded
        // invalidation; the fresh resolution below is never multiplied into a
        // retry loop.
        await proofProvider?.invalidate()
        await client.invalidatePlayerPreparation(includingHTTP: true)
      }
      return try await resolveHighQualityStream(for: song)
    }
  }

  private func resolveStream(
    for song: Song,
    after selectedProfileKey: String? = nil,
    refreshing: Bool
  ) async throws -> ResolvedAudioStream {
    try await client.preparePlaybackContext()
    let configuration = try await client.configurationSnapshot()
    let profiles = InnerTubePlaybackProfiles.resolutionOrder(
      webConfiguration: configuration,
      // Standard playback keeps the pinned profile order. Injecting a
      // decipherer is a high-quality capability and must not reorder the
      // normal HLS/native path.
      supportsStreamCipher: false
    )
    let startIndex: Int
    if let selectedProfileKey {
      guard
        let selectedIndex = profiles.firstIndex(where: {
          Self.profileKey($0) == selectedProfileKey
        })
      else {
        streamCursors[song.id] = .exhausted
        throw InnerTubeError.playbackUnavailable("no fresh audio candidate remains")
      }
      startIndex = selectedIndex + 1
    } else {
      startIndex = 0
    }
    guard startIndex < profiles.count else {
      streamCursors[song.id] = .exhausted
      throw InnerTubeError.playbackUnavailable("no fresh audio candidate remains")
    }

    var lastError: InnerTubeError?
    var lastRestriction: InnerTubeError?

    for profile in profiles.dropFirst(startIndex) {
      do {
        let request = try await makeBodyAndSession(
          [
            "videoId": song.id,
            "contentCheckOk": true,
            "racyCheckOk": true,
          ],
          profile: profile,
          authenticated: profile.loginSupported
        )
        let data = try await client.post(
          endpoint: "player",
          body: request.body,
          authenticated: request.session != nil,
          profile: profile,
          sessionOverride: request.session
        )
        await client.logPlayerDiagnostic(data: data, profile: profile)
        let stream = try await resolveAudioStream(
          from: data,
          song: song,
          profile: profile
        )
        streamCursors[song.id] = .selected(Self.profileKey(profile))
        await client.logStreamCandidate(profile: profile, probePassed: true, selected: true)
        return ResolvedAudioStream(
          url: stream.url,
          userAgent: profile.userAgent,
          mediaOrigin: profile.mediaOrigin,
          mediaReferer: profile.mediaReferer,
          authoritativeDuration: stream.authoritativeDuration,
          delivery: stream.delivery,
          bitrate: stream.bitrate,
          hlsFormatID: stream.hlsFormatID,
          loudness: stream.loudness
        )
      } catch let error as InnerTubeError {
        lastError = error
        if case .invalidConfiguration = error {
          throw error
        }
        if case .playbackRestricted(let status, _) = error {
          lastRestriction = error
          if Self.shouldStopPlaybackFallback(status: status, error: error) {
            if refreshing {
              streamCursors[song.id] = .exhausted
            }
            throw error
          }
        }
      } catch is CancellationError {
        throw CancellationError()
      } catch let error as URLError where error.code == .cancelled {
        throw CancellationError()
      } catch {
        // A candidate transport/probe failure is bounded to this profile.
        // Do not surface or log URLSession details, which may contain URL
        // query credentials.
        lastError = .playbackUnavailable("the stream candidate could not be checked")
      }
    }

    if refreshing {
      streamCursors[song.id] = .exhausted
    }
    if let lastRestriction {
      throw lastRestriction
    }
    throw lastError
      ?? InnerTubeError.playbackUnavailable("no supported audio stream was returned")
  }

  private func resolveAudioStream(
    from data: Data,
    song: Song,
    profile: InnerTubeClientProfile
  ) async throws -> ParsedAudioStream {
    if let manifestURL = HLSAudioSelection.manifestURL(from: data) {
      let master = try await client.fetchMediaPlaylist(at: manifestURL, profile: profile)
      let selection = try HLSAudioSelection.parse(master.text, relativeTo: master.url)
      await client.logHLSSelection(
        audioCount: selection.audio.count, variantCount: selection.variantCount,
        audioOnlyVariantCount: selection.audioOnlyVariantCount,
        audioGroupCount: selection.audioGroupCount,
        bitrate: selection.audio.map(\.bitrate).max() ?? 0
      )
      guard let chosen = selection.audio.max(by: { $0.bitrate < $1.bitrate }) else {
        throw InnerTubeError.playbackUnavailable("the manifest had no audio-only rendition")
      }
      for rendition in selection.audio {
        await client.logHLSRendition(
          formatID: rendition.formatID, bitrate: rendition.bitrate,
          selected: rendition.url == chosen.url
        )
      }
      let playlist = try await client.fetchMediaPlaylist(at: chosen.url, profile: profile)
      let playlistDuration = try HLSAudioSelection.validateVOD(
        playlist.text, relativeTo: playlist.url
      )
      let playlistShape = HLSAudioSelection.playlistShape(
        playlist.text, relativeTo: playlist.url)
      await client.logHLSPlaylistShape(
        segmentCount: playlistShape.segmentCount,
        transportStreamSegments: playlistShape.transportStreamSegments,
        fragmentedMP4Segments: playlistShape.fragmentedMP4Segments,
        otherSegments: playlistShape.otherSegments,
        aes128KeyCount: playlistShape.aes128KeyCount,
        sampleEncryptionKeyCount: playlistShape.sampleEncryptionKeyCount,
        mapCount: playlistShape.mapCount, byteRangeCount: playlistShape.byteRangeCount)
      let metadataCandidate = try ResponseParser.audioCandidates(from: data)
        .max(by: { $0.bitrate < $1.bitrate })
      return ParsedAudioStream(
        url: playlist.url,
        authoritativeDuration: metadataCandidate?.authoritativeDuration ?? playlistDuration,
        delivery: .hls, bitrate: chosen.bitrate,
        hlsFormatID: chosen.formatID,
        loudness: metadataCandidate?.loudness ?? ResponseParser.responseLoudness(from: data)
      )
    }
    let candidates = try ResponseParser.audioCandidates(from: data)
      .sorted { $0.bitrate > $1.bitrate }
    var playerScript: String?
    var lastCandidateError = InnerTubeError.playbackUnavailable(
      "the resolved stream URL was not usable"
    )

    for candidate in candidates {
      try Task.checkCancellation()
      let url: URL
      let requiresCipher =
        candidate.cipher != nil
        || (candidate.directURL != nil && candidate.n != nil && streamCipher != nil)
      if !requiresCipher, let directURL = candidate.directURL {
        // Keep direct URLs usable when no decipherer is installed. Some
        // clients return an `n` parameter on an otherwise playable URL, and
        // older callers rely on passing that URL through unchanged.
        url = directURL
      } else if requiresCipher, let streamCipher {
        var stage = PlayerStreamCipherStage.script
        do {
          if playerScript == nil {
            playerScript = try await client.fetchPlayerJavaScript(
              from: data,
              videoID: song.id,
              profile: profile
            )
            await client.logStreamCipher(profile: profile, stage: .script, succeeded: true)
          }

          stage = .decipher
          guard let requestURL = candidate.cipher?.url ?? candidate.directURL else {
            continue
          }
          let request = PlayerStreamCipherRequest(
            url: requestURL,
            signature: candidate.cipher?.signature,
            signatureParameter: candidate.cipher?.signatureParameter ?? "sig",
            n: candidate.cipher?.n ?? candidate.n,
            playerScript: playerScript ?? ""
          )
          let decipheredURL = try await streamCipher.decipher(request)
          guard InnerTubeMediaURLPolicy.isAllowedMediaURL(decipheredURL) else {
            await client.logStreamCipher(
              profile: profile, stage: .decipher, succeeded: false, error: .invalidResult
            )
            continue
          }
          await client.logStreamCipher(profile: profile, stage: .decipher, succeeded: true)
          url = decipheredURL
        } catch is CancellationError {
          throw CancellationError()
        } catch let error as URLError where error.code == .cancelled {
          throw CancellationError()
        } catch {
          // Deciphering and script discovery are optional per profile. A
          // failure remains bounded and lets the profile resolver continue.
          await client.logStreamCipher(
            profile: profile, stage: stage, succeeded: false,
            error: error as? PlayerStreamCipherError
          )
          lastCandidateError = .playbackUnavailable(
            "the ciphered stream candidate could not be resolved"
          )
          continue
        }
      } else {
        continue
      }

      do {
        let probePassed = try await client.probeStreamURL(url, profile: profile)
        await client.logStreamCandidate(profile: profile, probePassed: probePassed)
        guard probePassed else {
          lastCandidateError = .playbackUnavailable("the resolved stream URL was not usable")
          continue
        }
        return ParsedAudioStream(
          url: url,
          authoritativeDuration: candidate.authoritativeDuration,
          loudness: candidate.loudness
        )
      } catch is CancellationError {
        throw CancellationError()
      } catch let error as URLError where error.code == .cancelled {
        throw CancellationError()
      } catch {
        lastCandidateError = .playbackUnavailable("the resolved stream URL was not usable")
      }
    }
    throw lastCandidateError
  }

  private func resolveHighQualityStream(for song: Song) async throws -> ResolvedAudioStream {
    do {
      return try await resolveHighQualityStreamOnce(for: song)
    } catch is HighQualityMediaProbeError {
      // Refresh the proof and aligned player response once after a rejected
      // media range, then stop; never retry the rejected URL.
      await proofProvider?.invalidate()
      await client.invalidatePlayerPreparation(includingHTTP: true)
      do {
        return try await resolveHighQualityStreamOnce(for: song)
      } catch is HighQualityMediaProbeError {
        throw InnerTubeError.playbackUnavailable(
          "the high-quality Opus stream was rejected after refreshing proof"
        )
      }
    }
  }

  private func resolveHighQualityStreamOnce(for song: Song) async throws -> ResolvedAudioStream {
    #if DEBUG
      var timing = PlaybackStartupTiming()
    #endif
    try Task.checkCancellation()
    guard let proofProvider else {
      throw InnerTubeError.playbackUnavailable(
        "high-quality playback requires proof-of-origin configuration"
      )
    }
    try await client.preparePlaybackContext()
    try Task.checkCancellation()

    guard await client.hasCompleteLogin() else {
      throw InnerTubeError.authenticationRequired
    }
    guard await client.credentialTransportAllowed() else {
      throw InnerTubeError.invalidConfiguration(
        "high-quality playback requires the music.youtube.com origin"
      )
    }

    let configuration = try await client.configurationSnapshot()
    guard
      let visitorData = configuration.visitorData,
      Self.isValidProofVisitorData(visitorData)
    else {
      throw InnerTubeError.invalidConfiguration(
        "high-quality playback requires existing visitor data"
      )
    }

    let profile = InnerTubeClientProfile.webRemix(from: configuration)
    let session = await client.sessionSnapshot()
    guard UserSessionCredentials.hasCompleteLogin(in: session?.cookieHeader ?? "") else {
      throw InnerTubeError.authenticationRequired
    }

    let proofTokens: PlayerProofTokens?
    #if DEBUG
      timing.mark(.context)
    #endif
    if profile.useWebPoTokens {
      let suppliedTokens = try await proofProvider.tokens(
        visitorData: visitorData,
        videoID: song.id
      )
      proofTokens = PlayerProofTokens(
        player: try Self.validatedProofToken(suppliedTokens.player),
        streaming: try Self.validatedProofToken(suppliedTokens.streaming)
      )
    } else {
      proofTokens = nil
    }
    try Task.checkCancellation()

    #if DEBUG
      timing.mark(.proof)
    #endif

    let preparedScript: InnerTubeClient.PreparedPlayerScript
    if let cached = await client.cachedPlayerScript(profile: profile) {
      preparedScript = cached
    } else {
      // Preserve proven fresh discovery when no valid prepared version exists.
      let initialPlayerData = try await highQualityPlayerResponse(
        for: song, profile: profile, configuration: configuration,
        session: session, proofTokens: proofTokens)
      #if DEBUG
        timing.mark(.initialPlayer)
      #endif
      preparedScript = try await client.preparePlayerScript(
        from: initialPlayerData, videoID: song.id, profile: profile)
    }
    let playerScript = preparedScript.source
    let signatureTimestamp = preparedScript.timestamp
    try Task.checkCancellation()
    guard await client.sessionSnapshot() == session else { throw CancellationError() }
    #if DEBUG
      timing.mark(.playerScript)
    #endif
    let playerData = try await highQualityPlayerResponse(
      for: song,
      profile: profile,
      configuration: configuration,
      session: session,
      proofTokens: proofTokens,
      signatureTimestamp: signatureTimestamp
    )
    #if DEBUG
      timing.mark(.alignedPlayer)
      highQualityLogger.notice("high_quality timestamp_alignment=true")
    #endif

    guard let candidate = try Self.highestOpusCandidate(from: playerData) else {
      throw InnerTubeError.playbackUnavailable(
        "no high-quality Opus stream was returned"
      )
    }

    #if DEBUG
      highQualityLogger.notice(
        "high_quality candidate direct=\(candidate.directURL != nil) ciphered=\(candidate.cipher != nil) has_n=\(candidate.n != nil) has_player_proof=\(proofTokens?.player != nil) has_stream_proof=\(proofTokens?.streaming != nil)"
      )
    #endif

    let resolvedURL: URL
    do {
      resolvedURL = try await resolveHighQualityCandidate(candidate, playerScript: playerScript)
    } catch is CancellationError {
      throw CancellationError()
    } catch {
      throw HighQualityMediaProbeError.stalePlayer
    }
    let streamURL: URL
    if let streamingToken = proofTokens?.streaming {
      guard
        let urlWithProof = Self.mediaURLByAppendingStreamingProofToken(
          to: resolvedURL,
          token: streamingToken
        )
      else {
        throw InnerTubeError.playbackUnavailable(
          "the high-quality stream URL was not allowed"
        )
      }
      streamURL = urlWithProof
    } else {
      streamURL = resolvedURL
    }

    try Task.checkCancellation()
    #if DEBUG
      timing.mark(.decipher)
    #endif
    let probeStatus = try await client.probeStreamURLStatus(streamURL, profile: profile)
    #if DEBUG
      timing.mark(.mediaProbe)
      highQualityLogger.notice(
        "high_quality media_probe_status=\(probeStatus.map(String.init) ?? "none", privacy: .public)"
      )
    #endif
    if probeStatus == 403 {
      throw HighQualityMediaProbeError.forbidden
    }
    guard let probeStatus, (200..<300).contains(probeStatus) else {
      throw InnerTubeError.playbackUnavailable(
        "the high-quality Opus stream was rejected"
      )
    }
    guard await client.sessionSnapshot() == session else { throw CancellationError() }
    return ResolvedAudioStream(
      url: streamURL,
      userAgent: profile.userAgent,
      mediaOrigin: profile.mediaOrigin,
      mediaReferer: profile.mediaReferer,
      authoritativeDuration: candidate.authoritativeDuration,
      delivery: .progressive,
      codec: .opus,
      bitrate: candidate.bitrate,
      cacheIdentity: TrackAssetIdentity(
        trackID: song.id, formatID: candidate.formatID, version: candidate.version,
        contentLength: candidate.contentLength),
      loudness: candidate.loudness
    )
  }

  private func highQualityPlayerResponse(
    for song: Song,
    profile: InnerTubeClientProfile,
    configuration: MusicWebConfiguration,
    session: UserSession?,
    proofTokens: PlayerProofTokens?,
    signatureTimestamp: Int? = nil
  ) async throws -> Data {
    let values = Self.highQualityPlayerValues(
      videoID: song.id,
      playerToken: proofTokens?.player,
      signatureTimestamp: signatureTimestamp
    )
    let body = try InnerTubeRequestBodyBuilder(configuration: configuration).makeBody(
      values: values,
      profile: profile,
      session: session,
      authenticated: true
    )
    guard UserSessionCredentials.hasCompleteLogin(in: session?.cookieHeader ?? "") else {
      throw InnerTubeError.authenticationRequired
    }
    return try await client.post(
      endpoint: "player",
      body: body,
      authenticated: true,
      profile: profile,
      sessionOverride: session
    )
  }

  static func highQualityPlayerValues(
    videoID: String,
    playerToken: String?,
    signatureTimestamp: Int? = nil
  ) -> [String: Any] {
    var values: [String: Any] = [
      "videoId": videoID,
      "contentCheckOk": true,
      "racyCheckOk": true,
    ]
    if let playerToken {
      values["serviceIntegrityDimensions"] = ["poToken": playerToken]
    }
    if let signatureTimestamp {
      values["playbackContext"] = [
        "contentPlaybackContext": ["signatureTimestamp": signatureTimestamp]
      ]
    }
    return values
  }

  private static func highestOpusCandidate(from data: Data) throws -> ParsedAudioCandidate? {
    try ResponseParser.audioCandidates(from: data, probeOpus: true)
      .filter { $0.bitrate > 0 }
      .max(by: { $0.bitrate < $1.bitrate })
  }

  private func resolveHighQualityCandidate(
    _ candidate: ParsedAudioCandidate,
    playerScript: String?
  ) async throws -> URL {
    if let directURL = candidate.directURL {
      // Direct-format URLs are intentionally preserved byte-for-byte until
      // the optional streaming proof is appended below.
      return directURL
    }
    guard
      let cipher = candidate.cipher,
      let streamCipher,
      let playerScript
    else {
      throw InnerTubeError.playbackUnavailable(
        "the high-quality Opus format could not be deciphered"
      )
    }
    try Task.checkCancellation()
    do {
      let url = try await streamCipher.decipher(
        PlayerStreamCipherRequest(
          url: cipher.url,
          signature: cipher.signature,
          signatureParameter: cipher.signatureParameter,
          n: cipher.n,
          playerScript: playerScript
        )
      )
      guard InnerTubeMediaURLPolicy.isAllowedMediaURL(url) else {
        throw InnerTubeError.playbackUnavailable(
          "the high-quality stream URL was not allowed"
        )
      }
      return url
    } catch is CancellationError {
      throw CancellationError()
    } catch let error as URLError where error.code == .cancelled {
      throw CancellationError()
    } catch let error as InnerTubeError {
      throw error
    } catch {
      throw InnerTubeError.playbackUnavailable(
        "the high-quality Opus format could not be deciphered"
      )
    }
  }

  #if DEBUG
    /// Bounded simulator experiment: one Opus candidate per profile, at most
    /// three tiny media reads each. No format is handed to AVPlayer.
    public func probeOpusAccess(
      for song: Song,
      onReadable: (@Sendable (ResolvedAudioStream, Int) async -> Void)? = nil
    ) async throws -> Bool {
      try await client.preparePlaybackContext()
      let configuration = try await client.configurationSnapshot()
      let profiles = InnerTubePlaybackProfiles.resolutionOrder(webConfiguration: configuration)
      var anyReadable = false
      var reportedReadable = false
      for profile in profiles {
        try Task.checkCancellation()
        do {
          let request = try await makeBodyAndSession(
            ["videoId": song.id, "contentCheckOk": true, "racyCheckOk": true],
            profile: profile, authenticated: profile.loginSupported
          )
          let data = try await client.post(
            endpoint: "player", body: request.body, authenticated: request.session != nil,
            profile: profile, sessionOverride: request.session
          )
          await client.logPlayerDiagnostic(data: data, profile: profile)
          await client.logAlternativePlayerShape(data: data, profile: profile)
          let candidates = try ResponseParser.audioCandidates(from: data, probeOpus: true)
            .sorted { $0.bitrate > $1.bitrate }
          await client.logOpusCandidates(profile: profile, count: candidates.count)
          guard let candidate = candidates.first,
            var url = candidate.directURL ?? candidate.cipher?.url
          else { continue }
          await client.logOpusCandidate(
            profile: profile,
            bitrate: candidate.bitrate,
            direct: candidate.directURL != nil,
            ciphered: candidate.cipher != nil
          )
          // Match Aura's audio path: direct URLs are used unchanged.
          if candidate.cipher != nil {
            guard let streamCipher else { continue }
            let script = try await client.fetchPlayerJavaScript(
              from: data, videoID: song.id, profile: profile
            )
            url = try await streamCipher.decipher(
              PlayerStreamCipherRequest(
                url: url, signature: candidate.cipher?.signature,
                signatureParameter: candidate.cipher?.signatureParameter ?? "sig",
                n: candidate.n, playerScript: script
              )
            )
          }
          let first = try await client.probeAlternativeRange(
            url: url, profile: profile, offset: 0, percent: 0
          )
          guard first.valid, let length = first.length, length > 10 else { continue }
          var allValid = true
          for percent: Int64 in [65, 90] {
            let offset = (length / 100) * percent
            let probe = try await client.probeAlternativeRange(
              url: url, profile: profile, offset: offset, percent: Int(percent)
            )
            allValid = allValid && probe.valid && probe.length == length
          }
          anyReadable = anyReadable || allValid
          if allValid, !reportedReadable, let onReadable {
            reportedReadable = true
            await onReadable(
              ResolvedAudioStream(
                url: url,
                userAgent: profile.userAgent,
                mediaOrigin: profile.mediaOrigin,
                mediaReferer: profile.mediaReferer,
                authoritativeDuration: candidate.authoritativeDuration,
                delivery: .progressive,
                codec: .opus,
                bitrate: candidate.bitrate,
                loudness: candidate.loudness
              ),
              candidate.bitrate
            )
          }
        } catch is CancellationError {
          throw CancellationError()
        } catch let error as URLError where error.code == .cancelled {
          throw CancellationError()
        } catch {
          await client.logOpusCandidates(profile: profile, count: -1)
        }
      }
      return anyReadable
    }

    /// Checks whether the authenticated WEB_REMIX player response exposes a
    /// AAC or Opus candidate whose expiring URL accepts the three
    /// bounded ranged reads used by the simulator experiment. This is
    /// viability evidence only; it does not claim that AVPlayer can decode or
    /// play the candidate.
    public func probeHighQualityAccess(
      for song: Song, alignSignatureTimestamp: Bool = false,
      onReadable: (@Sendable (ResolvedAudioStream, String, Int) async -> Void)? = nil
    ) async throws -> Bool {
      try await client.preparePlaybackContext()
      try Task.checkCancellation()

      // Keep this experiment on the same credential boundary as the normal
      // authenticated WEB_REMIX path. In particular, do not silently turn a
      // missing login into an anonymous player request.
      guard await client.hasCompleteLogin() else {
        throw InnerTubeError.authenticationRequired
      }

      let configuration = try await client.configurationSnapshot()
      let profile = InnerTubeClientProfile.webRemix(from: configuration)
      let proofTokens: PlayerProofTokens?
      if let proofProvider, profile.useWebPoTokens {
        guard let visitorData = configuration.visitorData,
          Self.isValidProofVisitorData(visitorData)
        else {
          throw InnerTubeError.invalidConfiguration(
            "high-quality proof tokens require existing visitor data"
          )
        }
        let suppliedTokens = try await proofProvider.tokens(
          visitorData: visitorData,
          videoID: song.id
        )
        proofTokens = PlayerProofTokens(
          player: try Self.validatedProofToken(suppliedTokens.player),
          streaming: try Self.validatedProofToken(suppliedTokens.streaming)
        )
      } else {
        proofTokens = nil
      }
      try Task.checkCancellation()

      var playerValues: [String: Any] = [
        "videoId": song.id,
        "contentCheckOk": true,
        "racyCheckOk": true,
      ]
      if let playerToken = proofTokens?.player {
        playerValues["serviceIntegrityDimensions"] = ["poToken": playerToken]
      }
      let request = try await makeBodyAndSession(
        playerValues,
        profile: profile,
        authenticated: true
      )
      guard let session = request.session else {
        throw InnerTubeError.authenticationRequired
      }
      var data = try await client.post(
        endpoint: "player",
        body: request.body,
        authenticated: true,
        profile: profile,
        sessionOverride: session
      )
      await client.logPlayerDiagnostic(data: data, profile: profile)

      var playerScript: String?
      var attemptedPlayerScriptFetch = false
      if alignSignatureTimestamp {
        attemptedPlayerScriptFetch = true
        let script = try await client.fetchPlayerJavaScript(
          from: data, videoID: song.id, profile: profile
        )
        playerScript = script
        guard let timestamp = ResponseParser.playerSignatureTimestamp(from: script) else {
          highQualityLogger.notice("high_quality timestamp_alignment=false")
          return false
        }
        var alignedValues: [String: Any] = [
          "videoId": song.id,
          "contentCheckOk": true,
          "racyCheckOk": true,
          "playbackContext": [
            "contentPlaybackContext": ["signatureTimestamp": timestamp]
          ],
        ]
        if let playerToken = proofTokens?.player {
          alignedValues["serviceIntegrityDimensions"] = ["poToken": playerToken]
        }
        let aligned = try await makeBodyAndSession(
          alignedValues,
          profile: profile, authenticated: true
        )
        data = try await client.post(
          endpoint: "player", body: aligned.body, authenticated: true,
          profile: profile, sessionOverride: aligned.session
        )
        highQualityLogger.notice("high_quality timestamp_alignment=true")
        await client.logPlayerDiagnostic(data: data, profile: profile)
      }

      let playerStatus = ResponseParser.playerDiagnostic(from: data).status
      let aac = try ResponseParser.audioCandidates(from: data)
        .max(by: { $0.bitrate < $1.bitrate })
      let opus = try ResponseParser.audioCandidates(from: data, probeOpus: true)
        .max(by: { $0.bitrate < $1.bitrate })
      let candidates: [(codec: String, candidate: ParsedAudioCandidate)] =
        [
          ("Opus", opus),
          ("AAC", aac),
        ].compactMap { codec, candidate in
          guard let candidate, candidate.bitrate > 0 else {
            return nil
          }
          return (codec: codec, candidate: candidate)
        }

      guard !candidates.isEmpty else {
        highQualityLogger.notice(
          "high_quality player_status=\(playerStatus, privacy: .public) candidates=false"
        )
        return false
      }

      // There are at most two candidates and each successful resolution gets
      // exactly three reads below, so this loop is capped at six media reads.
      for item in candidates {
        try Task.checkCancellation()
        let candidate = item.candidate
        let resolvedURL: URL

        do {
          if let directURL = candidate.directURL {
            // Aura's direct-format path deliberately preserves this URL,
            // including any existing query parameters.
            resolvedURL = directURL
          } else if let cipher = candidate.cipher, let streamCipher {
            if !attemptedPlayerScriptFetch {
              attemptedPlayerScriptFetch = true
              playerScript = try await client.fetchPlayerJavaScript(
                from: data, videoID: song.id, profile: profile
              )
            }
            guard let playerScript else {
              logHighQualityCandidate(
                codec: item.codec,
                bitrate: candidate.bitrate,
                playerStatus: playerStatus,
                resolved: false,
                rangeReadable: false,
                ciphered: true
              )
              continue
            }
            resolvedURL = try await streamCipher.decipher(
              PlayerStreamCipherRequest(
                url: cipher.url,
                signature: cipher.signature,
                signatureParameter: cipher.signatureParameter,
                n: cipher.n,
                playerScript: playerScript
              )
            )
            guard InnerTubeMediaURLPolicy.isAllowedMediaURL(resolvedURL) else {
              logHighQualityCandidate(
                codec: item.codec,
                bitrate: candidate.bitrate,
                playerStatus: playerStatus,
                resolved: false,
                rangeReadable: false,
                ciphered: true
              )
              continue
            }
          } else {
            logHighQualityCandidate(
              codec: item.codec,
              bitrate: candidate.bitrate,
              playerStatus: playerStatus,
              resolved: false,
              rangeReadable: false,
              ciphered: candidate.isCiphered
            )
            continue
          }
        } catch is CancellationError {
          throw CancellationError()
        } catch let error as URLError where error.code == .cancelled {
          throw CancellationError()
        } catch {
          logHighQualityCandidate(
            codec: item.codec,
            bitrate: candidate.bitrate,
            playerStatus: playerStatus,
            resolved: false,
            rangeReadable: false,
            ciphered: candidate.isCiphered
          )
          continue
        }

        let probeURL: URL
        if let streamingToken = proofTokens?.streaming {
          guard
            let urlWithProof = Self.mediaURLByAppendingStreamingProofToken(
              to: resolvedURL, token: streamingToken
            )
          else {
            logHighQualityCandidate(
              codec: item.codec,
              bitrate: candidate.bitrate,
              playerStatus: playerStatus,
              resolved: false,
              rangeReadable: false,
              ciphered: candidate.isCiphered
            )
            continue
          }
          probeURL = urlWithProof
        } else {
          probeURL = resolvedURL
        }

        do {
          let first = try await client.probeAlternativeRange(
            url: probeURL, profile: profile, offset: 0, percent: 0
          )
          guard first.valid, let length = first.length, length > 10 else {
            logHighQualityCandidate(
              codec: item.codec,
              bitrate: candidate.bitrate,
              playerStatus: playerStatus,
              resolved: true,
              rangeReadable: false,
              ciphered: candidate.isCiphered
            )
            continue
          }

          var rangeReadable = true
          for percent: Int64 in [65, 90] {
            let offset = (length / 100) * percent
            let probe = try await client.probeAlternativeRange(
              url: probeURL,
              profile: profile,
              offset: offset,
              percent: Int(percent)
            )
            rangeReadable = rangeReadable && probe.valid && probe.length == length
          }
          logHighQualityCandidate(
            codec: item.codec,
            bitrate: candidate.bitrate,
            playerStatus: playerStatus,
            resolved: true,
            rangeReadable: rangeReadable,
            ciphered: candidate.isCiphered
          )
          if rangeReadable {
            if let onReadable {
              await onReadable(
                ResolvedAudioStream(
                  url: probeURL, userAgent: profile.userAgent,
                  mediaOrigin: profile.mediaOrigin, mediaReferer: profile.mediaReferer,
                  authoritativeDuration: candidate.authoritativeDuration,
                  loudness: candidate.loudness
                ),
                item.codec, candidate.bitrate
              )
            }
            return true
          }
        } catch is CancellationError {
          throw CancellationError()
        } catch let error as URLError where error.code == .cancelled {
          throw CancellationError()
        } catch {
          logHighQualityCandidate(
            codec: item.codec,
            bitrate: candidate.bitrate,
            playerStatus: playerStatus,
            resolved: true,
            rangeReadable: false,
            ciphered: candidate.isCiphered
          )
        }
      }
      return false
    }

    private func logHighQualityCandidate(
      codec: String,
      bitrate: Int,
      playerStatus: String,
      resolved: Bool,
      rangeReadable: Bool,
      ciphered: Bool
    ) {
      highQualityLogger.notice(
        "high_quality codec=\(codec, privacy: .public) bitrate=\(bitrate, privacy: .public) player_status=\(playerStatus, privacy: .public) resolved=\(resolved, privacy: .public) range_readable=\(rangeReadable, privacy: .public) ciphered=\(ciphered, privacy: .public)"
      )
    }
  #endif

  private static func validatedProofToken(_ token: String) throws -> String {
    guard !token.isEmpty else {
      throw PlayerProofTokenError.empty
    }
    guard token.utf8.count <= 16 * 1024 else {
      throw PlayerProofTokenError.tooLarge
    }
    guard
      token.unicodeScalars.allSatisfy({ scalar in
        scalar.value >= 0x21 && scalar.value <= 0x7E
      })
    else {
      throw PlayerProofTokenError.malformed
    }
    return token
  }

  private static func isValidProofVisitorData(_ visitorData: String?) -> Bool {
    guard let visitorData,
      !visitorData.isEmpty,
      visitorData.caseInsensitiveCompare("null") != .orderedSame,
      visitorData.utf8.count <= 4096
    else {
      return false
    }
    return !visitorData.unicodeScalars.contains { scalar in
      scalar.value == 0x0A || scalar.value == 0x0D
    }
  }

  /// Adds the streaming proof only when the media URL does not already carry
  /// a `pot` query item. Existing query items are retained by URLComponents,
  /// and the final URL is checked again before it reaches playback.
  private static func mediaURLByAppendingStreamingProofToken(
    to url: URL, token: String
  ) -> URL? {
    guard InnerTubeMediaURLPolicy.isAllowedMediaURL(url),
      var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
    else {
      return nil
    }
    let existingQuery = components.percentEncodedQuery
    let hasExistingProof =
      existingQuery?.split(
        separator: "&", omittingEmptySubsequences: false
      ).contains { item in
        let encodedName =
          item.split(
            separator: "=", maxSplits: 1, omittingEmptySubsequences: false
          ).first ?? ""
        return String(encodedName).removingPercentEncoding == "pot"
      } ?? false
    if hasExistingProof {
      return url
    }
    var tokenComponents = URLComponents()
    tokenComponents.queryItems = [URLQueryItem(name: "pot", value: token)]
    guard let encodedTokenQuery = tokenComponents.percentEncodedQuery else {
      return nil
    }
    components.percentEncodedQuery = [existingQuery, encodedTokenQuery]
      .compactMap { value in
        guard let value, !value.isEmpty else {
          return nil
        }
        return value
      }
      .joined(separator: "&")
    guard let result = components.url,
      InnerTubeMediaURLPolicy.isAllowedMediaURL(result)
    else {
      return nil
    }
    return result
  }

  private static func profileKey(_ profile: InnerTubeClientProfile) -> String {
    "\(profile.clientName):\(profile.clientVersion):\(profile.clientID)"
  }

  private static func shouldStopPlaybackFallback(
    status: String,
    error: InnerTubeError
  ) -> Bool {
    guard status != "LOGIN_REQUIRED" else {
      // An authenticated WEB_REMIX candidate may still resolve a login-required
      // response returned by an anonymous profile.
      return false
    }
    if status == "CONTENT_CHECK_REQUIRED" || status == "AGE_CHECK_REQUIRED" {
      return true
    }
    guard case .playbackRestricted(_, let reason) = error,
      let reason
    else {
      return false
    }
    let normalizedReason = reason.lowercased()
    let terminalMarkers = [
      "private",
      "paid",
      "purchase",
      "members-only",
      "restricted mode",
      "country",
      "disabled by the video owner",
      "content check",
    ]
    return terminalMarkers.contains(where: normalizedReason.contains)
  }

  private func makeBody(
    _ values: [String: Any],
    profile: InnerTubeClientProfile? = nil,
    authenticated: Bool = false
  ) async throws -> Data {
    try await makeBodyAndSession(
      values,
      profile: profile,
      authenticated: authenticated
    ).body
  }

  func makeBodyAndSession(
    _ values: [String: Any],
    profile: InnerTubeClientProfile? = nil,
    authenticated: Bool = false
  ) async throws -> (body: Data, session: UserSession?) {
    let configuration = try await client.configurationSnapshot()
    let resolvedProfile = profile ?? .webRemix(from: configuration)
    let hasCompleteLogin = await client.hasCompleteLogin()
    let credentialOriginAllowed = await client.credentialTransportAllowed()
    let useLogin =
      authenticated
      && resolvedProfile.loginSupported
      && credentialOriginAllowed
      && hasCompleteLogin
    let currentSession = useLogin ? await client.sessionSnapshot() : nil
    let body = try InnerTubeRequestBodyBuilder(configuration: configuration).makeBody(
      values: values,
      profile: resolvedProfile,
      session: currentSession,
      authenticated: useLogin
    )
    return (body: body, session: currentSession)
  }
}

private enum HighQualityMediaProbeError: Error {
  case forbidden
  case stalePlayer
}