import Foundation import HydraulophoneCore import OSLog import UIKit import WebKit struct WebMAudioSnapshot: Equatable, Sendable { let position: TimeInterval let duration: TimeInterval let isPlaying: Bool let isSeeking: Bool let hasEnded: Bool let bufferedRanges: [ClosedRange] } struct WebMAudioSeekEvidence: Sendable { let target: TimeInterval let wasBufferedAtAssignment: Bool } enum WebMAudioError: Error, Equatable, Sendable { case unsupported case load case playback case timedOut case cancelled } @MainActor final class WebMAudioEngine: NSObject, WKNavigationDelegate, WKUIDelegate { var onRemoteAction: (@MainActor (String, Double?) -> Void)? var onSnapshot: (@MainActor (WebMAudioSnapshot) -> Void)? var onFailure: (@MainActor (WebMAudioError) -> Void)? private(set) var snapshot: WebMAudioSnapshot private static let emptySnapshot = WebMAudioSnapshot( position: 0, duration: 0, isPlaying: false, isSeeking: false, hasEnded: false, bufferedRanges: [] ) private var webView: WKWebView? private var documentBaseURL: URL? private var generation: UInt64 = 0 private var seekGeneration: UInt64 = 0 private var readinessGate: CompletionGate? private var pendingJavaScriptCalls: [UUID: CompletionGate] = [:] private var activeSeekCallID: UUID? private var monitorTask: Task? private var mediaSessionUpdateGeneration: UInt64 = 0 private let mediaSessionLogger = Logger(subsystem: "com.hydraulophone", category: "media-session") private var lastMediaSessionDiagnostic: String? override init() { snapshot = Self.emptySnapshot super.init() } func updateMediaSession( song: Song, isPlaying: Bool, position: Double, duration: Double, canSkipNext: Bool, canSkipPrevious: Bool ) { guard let webView else { logMediaSessionDiagnostic("webview-unavailable") return } let metadata: [String: Any] = [ "title": song.title, "artist": song.artist, "album": song.album ?? "", "artwork": song.thumbnailURL.map { [["src": $0.absoluteString]] } ?? [], ] mediaSessionUpdateGeneration &+= 1 let updateGeneration = mediaSessionUpdateGeneration webView.callAsyncJavaScript( "return updateMediaSession(metadata, playing, position, duration, next, previous)", arguments: [ "metadata": metadata, "playing": isPlaying, "position": position, "duration": duration, "next": canSkipNext, "previous": canSkipPrevious, ], in: nil, in: .page, completionHandler: { [weak self] result in guard let self, self.mediaSessionUpdateGeneration == updateGeneration else { return } switch result { case .success(let value): guard let capabilities = value as? [String: Any] else { self.logMediaSessionDiagnostic("result-unreadable") return } let hasMediaSession = capabilities["mediaSession"] as? Bool ?? false let hasMediaMetadata = capabilities["mediaMetadata"] as? Bool ?? false let metadataOwner = capabilities["metadataOwner"] as? String ?? "unknown" let webMetadataWrite = capabilities["webMetadataWrite"] as? String ?? "unknown" let metadataAssigned = capabilities["metadataAssigned"] as? Bool ?? false let metadataError = capabilities["metadataError"] as? String ?? "none" let actionHandlers = capabilities["actionHandlers"] as? [String: Bool] ?? [:] let supportedActions = actionHandlers .filter { $0.value } .map(\.key) .sorted() .joined(separator: ",") let diagnostic = "success mediaSession=\(hasMediaSession) mediaMetadata=\(hasMediaMetadata) " + "metadataOwner=\(metadataOwner) webMetadataWrite=\(webMetadataWrite) " + "metadataAssigned=\(metadataAssigned) metadataError=\(metadataError) " + "actions=\(supportedActions)" self.logMediaSessionDiagnostic(diagnostic) case .failure(let error): let nsError = error as NSError self.logMediaSessionDiagnostic( "failure domain=\(nsError.domain) code=\(nsError.code)" ) } } ) } private func logMediaSessionDiagnostic(_ diagnostic: String) { guard lastMediaSessionDiagnostic != diagnostic else { return } lastMediaSessionDiagnostic = diagnostic mediaSessionLogger.info("Web Media Session \(diagnostic, privacy: .public)") #if DEBUG let line = "Hydraulophone Web Media Session \(diagnostic)\n" FileHandle.standardOutput.write(Data(line.utf8)) #endif } func prepare(stream: PlaybackResolvedStream) async throws { try await perform(fallback: .load) { try await self.prepareImplementation(stream: stream) } } func play() async throws { try await perform(fallback: .playback) { try await self.playImplementation() } } func pause() async throws { try await perform(fallback: .playback) { try await self.pauseImplementation() } } func seek(to seconds: TimeInterval) async throws -> WebMAudioSeekEvidence { try await perform(fallback: .playback) { try await self.seekImplementation(to: seconds) } } private func perform( fallback: WebMAudioError, operation: () async throws -> Value ) async throws -> Value { do { return try await operation() } catch { if error is CancellationError || (error as? WebMAudioError) == .cancelled { throw CancellationError() } let mapped = Self.map(error, fallback: fallback) report(mapped) throw mapped } } func stop() { tearDown() } private func prepareImplementation(stream: PlaybackResolvedStream) async throws { tearDown() try Task.checkCancellation() guard stream.delivery == .progressive, Self.isApprovedMediaURL(stream.url) else { throw WebMAudioError.unsupported } let activeGeneration = generation var completed = false defer { if !completed, generation == activeGeneration { tearDown() } } let baseURL = Self.baseURL(for: stream.mediaHeaders) guard let window = foregroundWindow() else { throw WebMAudioError.load } let view = makeWebView() view.customUserAgent = stream.userAgent webView = view documentBaseURL = baseURL window.addSubview(view) try await waitForDocument(view: view, baseURL: baseURL, generation: activeGeneration) try Task.checkCancellation() guard generation == activeGeneration, webView === view else { throw WebMAudioError.cancelled } let canPlayValue = try await callJavaScript( "return canPlayOpus();", arguments: [:], generation: activeGeneration, timeout: 2, failure: .load ) try Task.checkCancellation() guard let canPlay = canPlayValue as? String, canPlay == "probably" || canPlay == "maybe" else { throw WebMAudioError.unsupported } _ = try await callJavaScript( "return await loadMetadata(source);", arguments: ["source": stream.url.absoluteString], generation: activeGeneration, timeout: 15, failure: .load ) try Task.checkCancellation() let value = try await callJavaScript( "return readSnapshot();", arguments: [:], generation: activeGeneration, timeout: 2, failure: .load ) try Task.checkCancellation() let state = try decodeState(value, failure: .load) guard state.duration > 0 else { throw WebMAudioError.load } if let expected = stream.authoritativeDuration, abs(state.duration - expected) > 2 { throw WebMAudioError.load } publish( WebMAudioSnapshot( position: state.position, duration: state.duration, isPlaying: false, isSeeking: false, hasEnded: state.ended, bufferedRanges: state.bufferedRanges ) ) completed = true } private func playImplementation() async throws { guard webView != nil else { throw WebMAudioError.unsupported } let activeGeneration = generation let value = try await callJavaScript( "return await playAudio();", arguments: [:], generation: activeGeneration, timeout: 10, failure: .playback ) try Task.checkCancellation() guard generation == activeGeneration else { throw WebMAudioError.cancelled } guard (value as? Bool) != false else { throw WebMAudioError.playback } let stateValue = try await callJavaScript( "return readSnapshot();", arguments: [:], generation: activeGeneration, timeout: 2, failure: .playback ) try Task.checkCancellation() let state = try decodeState(stateValue, failure: .playback) publish(snapshot(from: state, isSeeking: false)) startMonitoring(generation: activeGeneration) } private func pauseImplementation() async throws { guard webView != nil else { throw WebMAudioError.unsupported } let activeGeneration = generation stopMonitoring() cancelActiveSeek() let value = try await callJavaScript( "return pauseAudio();", arguments: [:], generation: activeGeneration, timeout: 2, failure: .playback ) try Task.checkCancellation() guard generation == activeGeneration else { throw WebMAudioError.cancelled } let state = try decodeState(value, failure: .playback) publish(snapshot(from: state, isSeeking: false)) } private func seekImplementation(to seconds: TimeInterval) async throws -> WebMAudioSeekEvidence { guard webView != nil, snapshot.duration > 0 else { throw WebMAudioError.unsupported } guard seconds.isFinite else { throw WebMAudioError.playback } let activeGeneration = generation seekGeneration &+= 1 let activeSeekGeneration = seekGeneration let target = min(max(seconds, 0), snapshot.duration) stopMonitoring() publish( WebMAudioSnapshot( position: snapshot.position, duration: snapshot.duration, isPlaying: false, isSeeking: true, hasEnded: false, bufferedRanges: snapshot.bufferedRanges ) ) do { let value = try await callJavaScript( "return await seekAudio(target, token);", arguments: ["target": target, "token": activeSeekGeneration], generation: activeGeneration, timeout: 20, failure: .playback, replacesActiveSeek: true ) try Task.checkCancellation() guard generation == activeGeneration, seekGeneration == activeSeekGeneration else { throw WebMAudioError.cancelled } let state = try decodeState(value, failure: .playback) guard let object = value as? [String: Any], let seekTarget = Self.number(object["seekTarget"]), abs(seekTarget - target) <= 0.001, let wasBufferedAtAssignment = object["bufferedAtAssignment"] as? Bool else { throw WebMAudioError.playback } publish(snapshot(from: state, isSeeking: false)) if state.isPlaying { startMonitoring(generation: activeGeneration) } return WebMAudioSeekEvidence( target: seekTarget, wasBufferedAtAssignment: wasBufferedAtAssignment ) } catch { if generation == activeGeneration, seekGeneration == activeSeekGeneration { publish( WebMAudioSnapshot( position: snapshot.position, duration: snapshot.duration, isPlaying: false, isSeeking: false, hasEnded: snapshot.hasEnded, bufferedRanges: snapshot.bufferedRanges ) ) } throw error } } private func startMonitoring(generation activeGeneration: UInt64) { stopMonitoring() monitorTask = Task { @MainActor [weak self] in await self?.monitor(generation: activeGeneration) } } private func monitor(generation activeGeneration: UInt64) async { defer { if generation == activeGeneration { monitorTask = nil } } while !Task.isCancelled, generation == activeGeneration, webView != nil { do { try await Task.sleep(nanoseconds: 250_000_000) guard !Task.isCancelled, generation == activeGeneration else { return } let value = try await callJavaScript( "return readSnapshot();", arguments: [:], generation: activeGeneration, timeout: 2, failure: .playback ) guard generation == activeGeneration else { return } let state = try decodeState(value, failure: .playback) publish(snapshot(from: state)) if state.ended || state.paused { return } } catch is CancellationError { return } catch let error as WebMAudioError { guard error != .cancelled, generation == activeGeneration else { return } report(error) return } catch { guard generation == activeGeneration else { return } report(.playback) return } } } private func waitForDocument( view: WKWebView, baseURL: URL, generation activeGeneration: UInt64 ) async throws { let gate = CompletionGate() readinessGate = gate defer { if readinessGate === gate { readinessGate = nil } } _ = try await withTaskCancellationHandler( operation: { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in gate.install(continuation) guard !gate.isFinished, generation == activeGeneration, webView === view else { gate.finish(.failure(WebMAudioError.cancelled)) return } view.loadHTMLString(Self.page, baseURL: baseURL) gate.startTimeout(nanoseconds: 10_000_000_000, failure: .timedOut) } }, onCancel: { gate.finish(.failure(WebMAudioError.cancelled)) }) } private func callJavaScript( _ body: String, arguments: [String: Any], generation activeGeneration: UInt64, timeout: UInt64, failure: WebMAudioError, replacesActiveSeek: Bool = false ) async throws -> Any { guard generation == activeGeneration, let view = webView else { throw WebMAudioError.cancelled } if replacesActiveSeek, let previousID = activeSeekCallID { pendingJavaScriptCalls[previousID]?.finish(.failure(WebMAudioError.cancelled)) } let callID = UUID() let gate = CompletionGate() pendingJavaScriptCalls[callID] = gate if replacesActiveSeek { activeSeekCallID = callID } defer { pendingJavaScriptCalls.removeValue(forKey: callID) if activeSeekCallID == callID { activeSeekCallID = nil } } return try await withTaskCancellationHandler( operation: { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in gate.install(continuation) guard !gate.isFinished, generation == activeGeneration, webView === view else { gate.finish(.failure(WebMAudioError.cancelled)) return } view.callAsyncJavaScript( body, arguments: arguments, in: nil, in: .page, completionHandler: { [weak gate] result in guard let gate else { return } switch result { case .success(let value): gate.finish(.success(value)) case .failure: gate.finish(.failure(failure)) } } ) gate.startTimeout(nanoseconds: timeout * 1_000_000_000, failure: .timedOut) } }, onCancel: { gate.finish(.failure(WebMAudioError.cancelled)) }) } private func cancelActiveSeek() { seekGeneration &+= 1 if let callID = activeSeekCallID { pendingJavaScriptCalls[callID]?.finish(.failure(WebMAudioError.cancelled)) activeSeekCallID = nil } } private func stopMonitoring() { monitorTask?.cancel() monitorTask = nil } private func tearDown(failingWith failure: WebMAudioError? = nil) { generation &+= 1 seekGeneration &+= 1 stopMonitoring() let readiness = readinessGate readinessGate = nil if let failure { readiness?.finish(.failure(failure)) } else { readiness?.finish(.failure(WebMAudioError.cancelled)) } let calls = Array(pendingJavaScriptCalls.values) pendingJavaScriptCalls.removeAll() for call in calls { call.finish(.failure(failure ?? WebMAudioError.cancelled)) } activeSeekCallID = nil if let view = webView { view.callAsyncJavaScript( "clearAudio();", arguments: [:], in: nil, in: .page, completionHandler: { _ in } ) view.stopLoading() view.loadHTMLString("", baseURL: nil) view.navigationDelegate = nil view.uiDelegate = nil view.removeFromSuperview() } webView = nil documentBaseURL = nil if snapshot != Self.emptySnapshot { publish(Self.emptySnapshot) } } private func makeWebView() -> WKWebView { let configuration = WKWebViewConfiguration() configuration.websiteDataStore = .nonPersistent() configuration.userContentController.add( MediaActionHandler(engine: self), name: "mediaAction" ) configuration.allowsInlineMediaPlayback = true configuration.mediaTypesRequiringUserActionForPlayback = [] configuration.preferences.javaScriptCanOpenWindowsAutomatically = false let view = WKWebView( frame: CGRect(x: 0, y: 0, width: 1, height: 1), configuration: configuration ) view.navigationDelegate = self view.uiDelegate = self view.isUserInteractionEnabled = false view.isAccessibilityElement = false view.accessibilityElementsHidden = true view.alpha = 0.01 view.backgroundColor = .clear view.isOpaque = false return view } private func foregroundWindow() -> UIWindow? { let windows = UIApplication.shared.connectedScenes .compactMap { $0 as? UIWindowScene } .filter { $0.activationState == .foregroundActive } .flatMap(\.windows) return windows.first(where: \.isKeyWindow) ?? windows.first } private func publish(_ newSnapshot: WebMAudioSnapshot) { snapshot = newSnapshot onSnapshot?(newSnapshot) } private func snapshot(from state: AudioState, isSeeking: Bool? = nil) -> WebMAudioSnapshot { WebMAudioSnapshot( position: state.position, duration: state.duration, isPlaying: !state.paused && !state.seeking && state.readyState >= 3, isSeeking: isSeeking ?? state.seeking, hasEnded: state.ended, bufferedRanges: state.bufferedRanges ) } private func report(_ error: WebMAudioError) { guard error != .cancelled else { return } onFailure?(error) } private static func map(_ error: Error, fallback: WebMAudioError) -> WebMAudioError { if let error = error as? WebMAudioError { return error } if error is CancellationError { return .cancelled } return fallback } private static func isApprovedMediaURL(_ url: URL) -> Bool { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), components.scheme?.lowercased() == "https", components.user == nil, components.password == nil, components.port == nil || components.port == 443, let host = components.host?.lowercased() else { return false } return host == "googlevideo.com" || host.hasSuffix(".googlevideo.com") } private static func baseURL(for headers: [String: String]) -> URL { let origin = headers.first { key, _ in key.caseInsensitiveCompare("Origin") == .orderedSame }?.value if let origin, let url = URL(string: origin), let components = URLComponents(url: url, resolvingAgainstBaseURL: false), components.scheme?.lowercased() == "https", let host = components.host?.lowercased(), components.user == nil, components.password == nil, components.port == nil || components.port == 443, components.query == nil, components.fragment == nil, components.path.isEmpty || components.path == "/", host == "youtube.com" || host.hasSuffix(".youtube.com") { return URL(string: "https://\(host)") ?? Self.defaultBaseURL } return Self.defaultBaseURL } private static let defaultBaseURL = URL(string: "https://music.youtube.com")! private struct AudioState { let position: TimeInterval let duration: TimeInterval let paused: Bool let seeking: Bool let readyState: Int let ended: Bool let isPlaying: Bool let bufferedRanges: [ClosedRange] } private func decodeState(_ value: Any, failure: WebMAudioError) throws -> AudioState { guard let object = value as? [String: Any], let rawPosition = Self.number(object["position"]), let rawDuration = Self.number(object["duration"]), let paused = object["paused"] as? Bool, let seeking = object["seeking"] as? Bool, let readyState = Self.integer(object["readyState"]), let ended = object["ended"] as? Bool, rawPosition.isFinite, rawDuration.isFinite, rawDuration >= 0 else { throw failure } let duration = rawDuration let position = duration > 0 ? min(max(rawPosition, 0), duration) : max(rawPosition, 0) var ranges: [ClosedRange] = [] if let rawRanges = object["ranges"] as? [Any] { for rawRange in rawRanges { guard let range = rawRange as? [String: Any], let start = Self.number(range["start"]), let end = Self.number(range["end"]), start.isFinite, end.isFinite else { continue } let lower = max(0, start) let upper = min(duration, end) if lower <= upper { ranges.append(lower...upper) } } } return AudioState( position: position, duration: duration, paused: paused, seeking: seeking, readyState: readyState, ended: ended, isPlaying: !paused && !seeking && readyState >= 3, bufferedRanges: ranges ) } private static func number(_ value: Any?) -> Double? { if let value = value as? Double { return value } if let value = value as? NSNumber { return value.doubleValue } return nil } private static func integer(_ value: Any?) -> Int? { if let value = value as? Int { return value } if let value = value as? NSNumber { return value.intValue } return nil } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { guard webView === self.webView else { return } readinessGate?.finish(.success(NSNull())) } func webView( _ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error ) { guard webView === self.webView else { return } handleNavigationFailure() } func webView( _ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error ) { guard webView === self.webView else { return } handleNavigationFailure() } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { guard webView === self.webView else { return } let hasWaiter = readinessGate != nil || !pendingJavaScriptCalls.isEmpty tearDown(failingWith: readinessGate == nil ? .playback : .load) if !hasWaiter { report(.playback) } } func webView( _ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void ) { guard webView === self.webView else { decisionHandler(.cancel) return } if let url = navigationAction.request.url, !isAllowedDocumentURL(url) { decisionHandler(.cancel) handleNavigationFailure() return } decisionHandler(.allow) } func webView( _ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void ) { guard webView === self.webView else { decisionHandler(.cancel) return } if let url = navigationResponse.response.url, !isAllowedDocumentURL(url) { decisionHandler(.cancel) handleNavigationFailure() return } decisionHandler(.allow) } func webView( _ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures ) -> WKWebView? { nil } func webView( _ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin, initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType, decisionHandler: @escaping (WKPermissionDecision) -> Void ) { decisionHandler(.deny) } private func isAllowedDocumentURL(_ url: URL) -> Bool { if url.scheme?.lowercased() == "about", url.host == nil { return url.absoluteString == "about:blank" } guard let base = documentBaseURL, let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let baseHost = base.host?.lowercased(), let host = url.host?.lowercased(), url.scheme?.lowercased() == "https", components.query == nil, components.fragment == nil, components.path.isEmpty || components.path == "/" else { return false } return host == baseHost } private func handleNavigationFailure() { if readinessGate != nil { readinessGate?.finish(.failure(WebMAudioError.load)) } else { let hasWaiter = !pendingJavaScriptCalls.isEmpty tearDown(failingWith: .playback) if !hasWaiter { report(.playback) } } } private static let page = #""" """# } private final class CompletionGate: @unchecked Sendable { private let lock = NSLock() private var continuation: CheckedContinuation? private var finished = false private var terminalResult: Result? private var timeoutTask: Task? var isFinished: Bool { lock.lock() defer { lock.unlock() } return finished } func install(_ continuation: CheckedContinuation) { let resumeWith: Result? lock.lock() if finished { resumeWith = terminalResult ?? .failure(WebMAudioError.cancelled) } else { resumeWith = nil self.continuation = continuation } lock.unlock() if let resumeWith { continuation.resume(with: resumeWith) } } func finish(_ result: Result) { let continuation: CheckedContinuation? lock.lock() guard !finished else { lock.unlock() return } finished = true terminalResult = result continuation = self.continuation self.continuation = nil timeoutTask?.cancel() timeoutTask = nil lock.unlock() continuation?.resume(with: result) } func startTimeout(nanoseconds: UInt64, failure: WebMAudioError) { let task = Task { [weak self] in do { try await Task.sleep(nanoseconds: nanoseconds) guard !Task.isCancelled else { return } self?.finish(.failure(failure)) } catch { // Cancellation is the normal path after a callback wins the race. } } lock.lock() if finished { lock.unlock() task.cancel() } else { timeoutTask = task lock.unlock() } } } /// WKUserContentController retains handlers; keep the audio engine reference weak. @MainActor private final class MediaActionHandler: NSObject, WKScriptMessageHandler { weak var engine: WebMAudioEngine? init(engine: WebMAudioEngine) { self.engine = engine } func userContentController( _ userContentController: WKUserContentController, didReceive message: WKScriptMessage ) { guard message.frameInfo.isMainFrame, let body = message.body as? [String: Any], let action = body["action"] as? String else { return } engine?.onRemoteAction?(action, body["position"] as? Double) } }