Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/Integration/NowPlayingBridge.swift3// Description: Now Playing widget, media keys and remote commands through MediaPlayer.4import AppKit5import MediaPlayer6import SPMusicCore78/// macOS integration of the player: the Now Playing widget (Control Centre, lock screen), the media keys, AirPods9/// and other remote controls. Everything goes through MediaPlayer; nothing here knows about audio.10final class NowPlayingBridge {11 private weak var model: AppModel?12 private var lastTrackID: String?13 private var lastPlaying: Bool?14 private var lastPosition: Double = -1015 private var artwork: MPMediaItemArtwork?1617 func attach(_ model: AppModel) {18 self.model = model19 let c = MPRemoteCommandCenter.shared()20 // MediaPlayer may call these handlers from a queue of its own: they are not tied to the main actor and hop to it.21 func on(_ command: MPRemoteCommand, _ action: @escaping @MainActor @Sendable (AppModel, MPRemoteCommandEvent) -> Void) {22 command.addTarget { @Sendable [weak model] event in23 nonisolated(unsafe) let e = event24 Task { @MainActor in if let model { action(model, e) } }25 return .success26 }27 }28 on(c.playCommand) { m, _ in m.playback.resume() }29 on(c.pauseCommand) { m, _ in m.playback.pause() }30 on(c.togglePlayPauseCommand) { m, _ in m.playback.togglePlay() }31 on(c.nextTrackCommand) { m, _ in m.playback.next() }32 on(c.previousTrackCommand) { m, _ in m.playback.previous() }33 on(c.changePlaybackPositionCommand) { m, e in if let e = e as? MPChangePlaybackPositionCommandEvent { m.playback.seek(to: e.positionTime) } }34 c.skipForwardCommand.isEnabled = false; c.skipBackwardCommand.isEnabled = false35 }3637 /// The system asks for the image from a background queue: the handler must not be isolated to the main actor.38 nonisolated private static func makeArtwork(_ image: NSImage) -> MPMediaItemArtwork {39 nonisolated(unsafe) let img = image40 return MPMediaItemArtwork(boundsSize: image.size) { @Sendable _ in img }41 }4243 func update(_ model: AppModel, artworkChanged: Bool) {44 let p = model.playback45 let center = MPNowPlayingInfoCenter.default()46 guard let track = p.currentTrack else {47 if lastTrackID != nil { center.nowPlayingInfo = nil; center.playbackState = .stopped; lastTrackID = nil; lastPlaying = nil }48 return49 }50 let trackChanged = track.id != lastTrackID51 // The system extrapolates the clock from the rate: only tell it again when something actually changed.52 guard trackChanged || artworkChanged || lastPlaying != p.isPlaying || abs(p.position - lastPosition) > 1.5 || !p.isPlaying && abs(p.position - lastPosition) > 0.2 else { lastPosition += p.isPlaying ? 0.5 : 0; return }53 if trackChanged || artworkChanged {54 artwork = nil55 let image: NSImage? = model.externalArtwork[track.id] ?? track.artworkID.flatMap { id in model.session?.artwork.cached(id, size: 640) }.flatMap { NSImage(contentsOf: $0) }56 if let image { artwork = Self.makeArtwork(image) }57 }58 var info: [String: Any] = [59 MPMediaItemPropertyTitle: track.title, MPMediaItemPropertyArtist: track.artistName, MPMediaItemPropertyAlbumTitle: track.albumTitle,60 MPMediaItemPropertyPlaybackDuration: p.duration, MPNowPlayingInfoPropertyElapsedPlaybackTime: p.position,61 MPNowPlayingInfoPropertyPlaybackRate: p.isPlaying && !p.isBuffering ? 1.0 : 0.0, MPNowPlayingInfoPropertyMediaType: MPNowPlayingInfoMediaType.audio.rawValue,62 ]63 if let artwork { info[MPMediaItemPropertyArtwork] = artwork }64 center.nowPlayingInfo = info65 center.playbackState = p.isPlaying ? .playing : .paused66 lastTrackID = track.id; lastPlaying = p.isPlaying; lastPosition = p.position67 }68}69