// The lock screen and Control Centre: what is playing (MPNowPlayingInfoCenter) // and the controls that reach the player from there and from headphones // (MPRemoteCommandCenter). The player says what it holds after every change; // the system's own controls call back into it. A seam, so the tests watch // what the player says without the system's centre. // // ONE PLAYER AT A TIME: each audio player (a podcast's episode, // `PodcastPlayback`; a song, `MusicPlayback`) holds a centre of its own, and the system's controls // reach only the one that showed something last (`NowPlayingClaim`); the one // that played before it is paused as the next one starts. import Foundation import MediaPlayer #if canImport(UIKit) import UIKit #endif /// What the lock screen shows of what is loaded. struct NowPlayingInfo: Equatable { var title: String? var subtitle: String? /// The album a song is from; a podcast's episode has none. var album: String? = nil var duration: TimeInterval var elapsed: TimeInterval var playing: Bool /// The speed it plays at while playing (a song's speed knob). var rate: Double = 1 var hasNext: Bool var hasPrevious: Bool /// Seconds the skip buttons jump, back and forward (a podcast's); nil /// shows next and previous instead. var skips: TimeInterval? = nil } /// The player's acts, as the system's controls reach them. struct NowPlayingCommands { var play: @MainActor () -> Void var pause: @MainActor () -> Void var toggle: @MainActor () -> Void var next: @MainActor () -> Void var previous: @MainActor () -> Void var seek: @MainActor (TimeInterval) -> Void /// A jump by seconds, back (negative) or forward: the skip buttons. var skip: (@MainActor (TimeInterval) -> Void)? = nil } /// Which centre the system's controls reach now, and how to pause the one /// that held them before. @MainActor enum NowPlayingClaim { static var holder: ObjectIdentifier? static var pauses: [ObjectIdentifier: @MainActor () -> Void] = [:] /// `centre` shows what plays now: the controls are its, and the player /// that held them before is paused. static func take(_ centre: ObjectIdentifier, playing: Bool) { let before = holder holder = centre if playing, let before, before != centre { pauses[before]?() } } } @MainActor protocol NowPlayingCentre: AnyObject { /// The controls call these; once, as the player is made. func connect(_ commands: NowPlayingCommands) /// What is loaded now; nil clears the lock screen. func show(_ info: NowPlayingInfo?) #if canImport(UIKit) /// The loaded item's art; nil while it has none here. func show(art: UIImage?) #endif } /// The system's centre. @MainActor final class SystemNowPlaying: NowPlayingCentre { #if canImport(UIKit) private var artwork: MPMediaItemArtwork? #endif private var shown: NowPlayingInfo? /// The player's acts, wired to the system's controls with the first /// thing shown: an app that never plays never claims them. private var commands: NowPlayingCommands? func connect(_ commands: NowPlayingCommands) { self.commands = commands NowPlayingClaim.pauses[ObjectIdentifier(self)] = commands.pause } private func wire() { guard let commands else { return } self.commands = nil let me = ObjectIdentifier(self) let centre = MPRemoteCommandCenter.shared() Self.on(centre.playCommand, me, commands.play) Self.on(centre.pauseCommand, me, commands.pause) Self.on(centre.togglePlayPauseCommand, me, commands.toggle) Self.on(centre.nextTrackCommand, me, commands.next) Self.on(centre.previousTrackCommand, me, commands.previous) Self.onSeek(centre.changePlaybackPositionCommand, me, commands.seek) if let skip = commands.skip { Self.onSkip(centre.skipForwardCommand, me, 1, skip) Self.onSkip(centre.skipBackwardCommand, me, -1, skip) } } // The system calls its handlers on the main thread, but a closure formed // in a main-actor body would be checked for it on whatever queue the // system uses: they are formed here, outside it. Each answers only while // its centre holds the controls. private nonisolated static func on(_ command: MPRemoteCommand, _ me: ObjectIdentifier, _ act: @escaping @MainActor () -> Void) { command.isEnabled = true command.addTarget { _ in MainActor.assumeIsolated { guard NowPlayingClaim.holder == me else { return .commandFailed } act() return .success } } } private nonisolated static func onSeek(_ command: MPChangePlaybackPositionCommand, _ me: ObjectIdentifier, _ seek: @escaping @MainActor (TimeInterval) -> Void) { command.isEnabled = true command.addTarget { event in guard let event = event as? MPChangePlaybackPositionCommandEvent else { return .commandFailed } let to = event.positionTime return MainActor.assumeIsolated { guard NowPlayingClaim.holder == me else { return .commandFailed } seek(to) return .success } } } private nonisolated static func onSkip(_ command: MPSkipIntervalCommand, _ me: ObjectIdentifier, _ way: Double, _ skip: @escaping @MainActor (TimeInterval) -> Void) { command.addTarget { event in guard let event = event as? MPSkipIntervalCommandEvent else { return .commandFailed } let by = event.interval * way return MainActor.assumeIsolated { guard NowPlayingClaim.holder == me else { return .commandFailed } skip(by) return .success } } } func show(_ info: NowPlayingInfo?) { shown = info let me = ObjectIdentifier(self) let centre = MPNowPlayingInfoCenter.default() guard let info else { // Cleared only while the controls are this centre's: another // player showing now keeps its lock screen. if NowPlayingClaim.holder == nil || NowPlayingClaim.holder == me { centre.nowPlayingInfo = nil NowPlayingClaim.holder = nil } return } // A player paused while another holds the controls stays quiet. if NowPlayingClaim.holder != me, !info.playing, NowPlayingClaim.holder != nil { return } wire() NowPlayingClaim.take(me, playing: info.playing) var said: [String: Any] = [ MPMediaItemPropertyPlaybackDuration: info.duration, MPNowPlayingInfoPropertyElapsedPlaybackTime: info.elapsed, MPNowPlayingInfoPropertyPlaybackRate: info.playing ? info.rate : 0.0, MPNowPlayingInfoPropertyDefaultPlaybackRate: info.rate, MPNowPlayingInfoPropertyMediaType: MPNowPlayingInfoMediaType.audio.rawValue, ] if let title = info.title { said[MPMediaItemPropertyTitle] = title } if let subtitle = info.subtitle { said[MPMediaItemPropertyArtist] = subtitle } if let album = info.album { said[MPMediaItemPropertyAlbumTitle] = album } #if canImport(UIKit) if let artwork { said[MPMediaItemPropertyArtwork] = artwork } #endif centre.nowPlayingInfo = said let commands = MPRemoteCommandCenter.shared() if let skips = info.skips { // A podcast: fifteen seconds back and forward where next and previous were. commands.skipForwardCommand.preferredIntervals = [NSNumber(value: skips)] commands.skipBackwardCommand.preferredIntervals = [NSNumber(value: skips)] commands.skipForwardCommand.isEnabled = true commands.skipBackwardCommand.isEnabled = true commands.nextTrackCommand.isEnabled = false commands.previousTrackCommand.isEnabled = false } else { commands.skipForwardCommand.isEnabled = false commands.skipBackwardCommand.isEnabled = false commands.nextTrackCommand.isEnabled = info.hasNext // Previous always does something: back to the start, or the track before. commands.previousTrackCommand.isEnabled = true } } #if canImport(UIKit) func show(art: UIImage?) { artwork = art.map(Self.artwork) show(shown) } /// The system asks the artwork for its picture on a queue of its own. private nonisolated static func artwork(_ image: UIImage) -> MPMediaItemArtwork { MPMediaItemArtwork(boundsSize: image.size) { _ in image } } #endif }