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

geesawra.industries/hydraulophone

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

0
0
main
150 lines · 6.1 KB Raw History
#if DEBUG
  import AVFoundation
  import Foundation
  import HydraulophoneCore
  import OSLog
  import UIKit
  import WebKit

  /// Explicit simulator-only decoding experiment. The page contains only our
  /// code and an audio element, with no login cookies or remote scripts.
  @MainActor
  final class WebMAudioProbe: NSObject, WKNavigationDelegate {
    private enum Failure: Error { case load, playback, duration }
    private let view: WKWebView
    private var ready = false
    private var failed = false
    private let logger = Logger(subsystem: "com.hydraulophone", category: "opus-playback")

    private override init() {
      let configuration = WKWebViewConfiguration()
      configuration.websiteDataStore = .nonPersistent()
      configuration.allowsInlineMediaPlayback = true
      configuration.mediaTypesRequiringUserActionForPlayback = []
      view = WKWebView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), configuration: configuration)
      super.init()
      view.navigationDelegate = self
      view.isUserInteractionEnabled = false
      view.alpha = 0.01
    }

    static func run(stream: ResolvedAudioStream, bitrate: Int) async {
      let probe = WebMAudioProbe()
      defer {
        probe.view.stopLoading()
        probe.view.loadHTMLString("", baseURL: nil)
        probe.view.removeFromSuperview()
        probe.view.navigationDelegate = nil
      }
      do {
        #if !targetEnvironment(macCatalyst)
          try AVAudioSession.sharedInstance().setActive(true)
        #endif
        probe.view.customUserAgent = stream.userAgent
        let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
          .first(where: { $0.activationState == .foregroundActive })
        scene?.windows.first(where: \.isKeyWindow)?.addSubview(probe.view)
        probe.view.loadHTMLString(Self.page, baseURL: URL(string: stream.mediaOrigin))
        let deadline = Date().addingTimeInterval(10)
        while !probe.ready, !probe.failed, Date() < deadline {
          try await Task.sleep(for: .milliseconds(100))
        }
        guard probe.ready, !probe.failed else { throw Failure.load }
        let start = Date()
        _ = try await probe.view.callAsyncJavaScript(
          """
          a.src = source;
          let timer;
          try {
            await Promise.race([a.play(), new Promise((_, reject) => {
              timer = setTimeout(() => reject("playback_timeout"), 10000);
            })]);
            return true;
          } finally { clearTimeout(timer); }
          """,
          arguments: ["source": stream.url.absoluteString], in: nil, contentWorld: .page
        )
        let first = try await probe.progress(near: nil)
        guard let duration = first["duration"] as? Double,
          let expected = stream.authoritativeDuration,
          abs(duration - expected) < 2
        else { throw Failure.duration }
        probe.logger.notice(
          "opus_playback bitrate=\(bitrate) duration=\(duration) verified_after_ms=\(Int(Date().timeIntervalSince(start) * 1000))"
        )
        for fraction in [0.65, 0.90] {
          let target = duration * fraction
          let buffered =
            try await probe.view.callAsyncJavaScript(
              """
              for (let i = 0; i < a.buffered.length; i++) {
                if (a.buffered.start(i) <= target && target < a.buffered.end(i)) return true;
              }
              return false;
              """,
              arguments: ["target": target], in: nil, contentWorld: .page
            ) as? Bool ?? false
          _ = try await probe.view.callAsyncJavaScript(
            "a.currentTime = target; return true;",
            arguments: ["target": target], in: nil, contentWorld: .page
          )
          _ = try await probe.progress(near: target)
          probe.logger.notice(
            "opus_playback seek_percent=\(Int(fraction * 100)) buffered_before=\(buffered) progress=true"
          )
        }
        try await Task.sleep(for: .seconds(5))
        _ = try await probe.view.evaluateJavaScript("a.pause()")
        probe.logger.notice("opus_playback outcome=success")
      } catch is CancellationError {
        probe.logger.notice("opus_playback outcome=cancelled")
      } catch {
        probe.logger.notice("opus_playback outcome=failure")
      }
    }

    private func progress(near target: Double?) async throws -> [String: Any] {
      let deadline = Date().addingTimeInterval(20)
      var first: Double?
      while Date() < deadline {
        try Task.checkCancellation()
        guard let sample = try await view.evaluateJavaScript("sample()") as? [String: Any],
          let time = sample["time"] as? Double, time.isFinite
        else { throw Failure.playback }
        if (sample["error"] as? Int ?? 0) != 0 { throw Failure.playback }
        if sample["playing"] as? Bool == true {
          if let first, time > first + 1 { return sample }
          if first == nil, target.map({ abs(time - $0) < 2 }) ?? true { first = time }
        }
        try await Task.sleep(for: .milliseconds(250))
      }
      throw Failure.playback
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
      ready = true
    }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
      failed = true
    }

    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
      failed = true
    }

    private static let page = #"""
      <!doctype html><html><head><title>Hydraulophone audio probe</title>
      <meta http-equiv="Content-Security-Policy"
        content="default-src 'none'; script-src 'unsafe-inline'; media-src https://*.googlevideo.com https://googlevideo.com">
      </head><body><audio id="audio" playsinline crossorigin="anonymous" preload="metadata"></audio>
      <script>
        const a = document.getElementById("audio");
        function sample() {
          return {time:a.currentTime, duration:Number.isFinite(a.duration)?a.duration:0,
            playing:!a.paused && !a.seeking && a.readyState >= 3, error:a.error?a.error.code:0};
        }
      </script></body></html>
      """#
  }
#endif