// 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.importFoundationimportMediaPlayer#if canImport(UIKit)import UIKit#endif/// What the lock screen shows of what is loaded.structNowPlayingInfo: Equatable {var title: String?var subtitle: String?/// The album a song is from; a podcast's episode has none.var album: String? = nilvar duration: TimeIntervalvar elapsed: TimeIntervalvar playing: Bool/// The speed it plays at while playing (a song's speed knob).var rate: Double = 1var hasNext: Boolvar 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.structNowPlayingCommands {var play: @MainActor () -> Voidvar pause: @MainActor () -> Voidvar toggle: @MainActor () -> Voidvar next: @MainActor () -> Voidvar previous: @MainActor () -> Voidvar 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.@MainActorenumNowPlayingClaim {staticvar holder: ObjectIdentifier?staticvar pauses: [ObjectIdentifier: @MainActor () -> Void] = [:]/// `centre` shows what plays now: the controls are its, and the player/// that held them before is paused.staticfunc take(_ centre: ObjectIdentifier, playing: Bool) {let before = holder holder = centreif playing, let before, before != centre { pauses[before]?() } }}@MainActorprotocolNowPlayingCentre: 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.@MainActorfinalclassSystemNowPlaying: NowPlayingCentre { #if canImport(UIKit)privatevar artwork: MPMediaItemArtwork? #endifprivatevar 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.privatevar commands: NowPlayingCommands?func connect(_ commands: NowPlayingCommands) {self.commands = commandsNowPlayingClaim.pauses[ObjectIdentifier(self)] = commands.pause }privatefunc wire() {guardlet commands else { return }self.commands = nillet 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)iflet 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 staticfunc on(_ command: MPRemoteCommand, _ me: ObjectIdentifier, _ act: @escaping @MainActor () -> Void) { command.isEnabled = true command.addTarget { _ inMainActor.assumeIsolated {guardNowPlayingClaim.holder == me else { return .commandFailed } act()return .success } } }private nonisolated staticfunc onSeek(_ command: MPChangePlaybackPositionCommand, _ me: ObjectIdentifier, _ seek: @escaping @MainActor (TimeInterval) -> Void) { command.isEnabled = true command.addTarget { event inguardlet event = event as? MPChangePlaybackPositionCommandEvent else { return .commandFailed }let to = event.positionTimereturnMainActor.assumeIsolated {guardNowPlayingClaim.holder == me else { return .commandFailed } seek(to)return .success } } }private nonisolated staticfunc onSkip(_ command: MPSkipIntervalCommand, _ me: ObjectIdentifier, _ way: Double, _ skip: @escaping @MainActor (TimeInterval) -> Void) { command.addTarget { event inguardlet event = event as? MPSkipIntervalCommandEvent else { return .commandFailed }let by = event.interval * wayreturnMainActor.assumeIsolated {guardNowPlayingClaim.holder == me else { return .commandFailed } skip(by)return .success } } }func show(_ info: NowPlayingInfo?) { shown = infolet me = ObjectIdentifier(self)let centre = MPNowPlayingInfoCenter.default()guardlet info else {// Cleared only while the controls are this centre's: another// player showing now keeps its lock screen.ifNowPlayingClaim.holder == nil || NowPlayingClaim.holder == me { centre.nowPlayingInfo = nilNowPlayingClaim.holder = nil }return }// A player paused while another holds the controls stays quiet.ifNowPlayingClaim.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, ]iflet title = info.title { said[MPMediaItemPropertyTitle] = title }iflet subtitle = info.subtitle { said[MPMediaItemPropertyArtist] = subtitle }iflet album = info.album { said[MPMediaItemPropertyAlbumTitle] = album } #if canImport(UIKit)iflet artwork { said[MPMediaItemPropertyArtwork] = artwork } #endif centre.nowPlayingInfo = saidlet commands = MPRemoteCommandCenter.shared()iflet 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 staticfunc artwork(_ image: UIImage) -> MPMediaItemArtwork { MPMediaItemArtwork(boundsSize: image.size) { _ in image } } #endif}