-
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
-
29
-
30
-
31
-
32
-
33
-
34
-
35
-
36
-
37
-
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
-
57
-
58
-
59
-
60
-
61
-
62
-
63
-
64
-
65
-
66
-
67
-
68
-
69
-
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
-
87
-
88
-
89
-
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
-
120
-
121
-
122
-
123
-
124
-
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
-
141
-
142
-
143
-
144
-
145
-
146
-
147
-
148
-
149
-
150
-
151
-
152
-
153
-
154
-
155
-
156
-
157
-
158
-
159
-
160
-
161
-
162
-
163
-
164
-
165
-
166
-
167
-
168
-
169
-
170
-
171
-
172
-
173
-
174
-
175
-
176
-
177
-
178
-
179
-
180
-
181
-
182
-
183
-
184
-
185
-
186
-
187
-
188
-
189
-
190
-
191
-
192
-
193
-
194
-
195
-
196
-
197
-
198
-
199
-
200
-
201
-
202
-
203
-
204
-
205
-
206
-
207
-
208
-
209
-
210
-
211
-
212
-
213
-
214
-
215
-
216
-
217
-
218
-
219
-
220
-
221
-
222
-
223
-
224
-
225
-
226
-
227
-
228
-
229
-
230
-
231
-
232
-
233
-
234
-
235
-
236
-
237
-
238
-
239
-
240
-
241
-
242
-
243
-
244
-
245
-
246
-
247
-
248
-
249
-
250
-
251
-
252
-
253
-
254
-
255
-
256
-
257
-
258
-
259
-
260
-
261
-
262
-
263
-
264
-
265
-
266
-
267
-
268
-
269
-
270
-
271
-
272
-
273
-
274
-
275
-
276
-
277
-
278
-
279
-
280
-
281
-
282
-
283
-
284
-
285
-
286
-
287
-
288
-
289
-
290
-
291
-
292
-
293
-
294
-
295
-
296
-
297
-
298
-
299
-
300
-
301
-
302
-
303
-
304
-
305
-
306
-
307
-
308
-
309
-
310
-
311
-
312
-
313
-
314
-
315
-
316
-
317
-
318
-
319
-
320
-
321
-
322
-
323
-
324
-
325
-
326
-
327
-
328
-
329
-
330
-
331
-
332
-
333
-
334
-
335
-
336
-
337
-
338
-
339
-
340
-
341
-
342
-
343
-
344
-
345
-
346
-
347
-
348
-
349
-
350
-
351
-
352
-
353
-
354
-
355
-
356
-
357
-
358
-
359
-
360
-
361
-
362
-
363
-
364
-
365
-
366
-
367
-
368
-
369
-
370
-
371
-
372
-
373
-
374
-
375
-
376
-
377
-
378
-
379
-
380
-
381
-
382
-
383
-
384
-
385
-
386
-
387
-
388
-
389
-
390
// Copyright 2025 Shota FUJI
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
import Foundation
import MediaPlayer
import OSLog
import RoonKit
import SwiftUI
@MainActor
@Observable
final class ZoneDataModel {
@ObservationIgnored
private let browsing: BrowsingDataModel?
@ObservationIgnored
private let imageURLBuilder: ImageURLBuilderDataModel?
// Now playing feature is not very suited for apps that work as a frontend for
// network audio. iOS/iPadOS aggressively suspends non foreground apps, that
// closes network connection, hence playback status no longer receives updates
// and playback controls would be ignored or errored out. As Roon client requires
// an alive connection whole time, "wake the app on incoming packet" technique
// won't work (OS will shutdown the connection, I guess.) Missing feature is better
// than fundamentally broken feature.
#if os(macOS)
@ObservationIgnored
private let commandCenter = MPRemoteCommandCenter.shared()
@ObservationIgnored private var playHandler: Any? = nil
@ObservationIgnored private var pauseHandler: Any? = nil
@ObservationIgnored private var prevHandler: Any? = nil
@ObservationIgnored private var nextHandler: Any? = nil
@ObservationIgnored private var seekHandler: Any? = nil
#endif
let conn: Communicatable
public var zone: TransportService.Zone? = nil {
didSet {
if !suppressSeekUpdates, let zone = zone {
seek = Float(seeks[zone.id].flatMap({ $0 }) ?? 0)
}
if let browsing = browsing {
browsing.zone = zone
}
updateNowPlaying()
}
}
private(set) var zones: [TransportService.Zone] = [] {
didSet {
if let zoneID = zone?.id {
for zone in zones {
if zone.id == zoneID {
self.zone = zone
return
}
}
}
for zone in zones {
self.zone = zone
return
}
zone = nil
}
}
/// Whenever this property is on, `ZoneDataModel` skips updating `seek` property.
/// Use this automatic changes to `seek` property is not desirable, e.g. user dragging a seekbar.
public var suppressSeekUpdates: Bool = false
private var seeks: [TransportService.Zone.ID: UInt64?] = [:] {
didSet {
guard let zone = zone else {
return
}
if !suppressSeekUpdates {
seek = Float(seeks[zone.id].flatMap({ $0 }) ?? 0)
}
}
}
public var seek: Float = 0.0
init(
conn: Communicatable,
browsing: BrowsingDataModel? = nil,
imageURLBuilder: ImageURLBuilderDataModel? = nil
) {
self.conn = conn
self.browsing = browsing
self.imageURLBuilder = imageURLBuilder
#if os(macOS)
// MPRemoteCommandCenter does not support async functions. As there seems no way
// to safely wait for async task, we simply returns success even if a request
// failed.
self.playHandler = commandCenter.playCommand.addTarget {
[unowned self] event in
guard let zone = self.zone else {
return .deviceNotFound
}
Task {
do {
let res = try await self.conn.request(
.init(control: .init(zoneID: zone.id, control: .play))
)
_ = try TransportService.ControlResponse.init(res)
} catch {
Logger().warning("Failed to send play request: \(error)")
}
}
return .success
}
self.pauseHandler = commandCenter.pauseCommand.addTarget {
[unowned self] event in
guard let zone = self.zone else {
return .deviceNotFound
}
Task {
do {
let res = try await self.conn.request(
.init(control: .init(zoneID: zone.id, control: .pause))
)
_ = try TransportService.ControlResponse.init(res)
} catch {
Logger().warning("Failed to send pause request: \(error)")
}
}
return .success
}
self.prevHandler = commandCenter.previousTrackCommand.addTarget {
[unowned self] event in
guard let zone = self.zone else {
return .deviceNotFound
}
Task {
do {
let res = try await self.conn.request(
.init(control: .init(zoneID: zone.id, control: .previous))
)
_ = try TransportService.ControlResponse.init(res)
} catch {
Logger().warning("Failed to send prev track request: \(error)")
}
}
return .success
}
self.nextHandler = commandCenter.nextTrackCommand.addTarget {
[unowned self] event in
guard let zone = self.zone else {
return .deviceNotFound
}
Task {
do {
let res = try await self.conn.request(
.init(control: .init(zoneID: zone.id, control: .next))
)
_ = try TransportService.ControlResponse.init(res)
} catch {
Logger().warning("Failed to send next track request: \(error)")
}
}
return .success
}
self.seekHandler = commandCenter.changePlaybackPositionCommand.addTarget {
[unowned self] event in
guard let zone = self.zone else {
return .deviceNotFound
}
guard let event = event as? MPChangePlaybackPositionCommandEvent else {
return .commandFailed
}
Task {
do {
let res = try await self.conn.request(
.init(
seek: .init(
zoneID: zone.id,
seconds: Int64(event.positionTime),
mode: .absolute
)
)
)
_ = try TransportService.SeekResponse.init(res)
} catch {
Logger().warning("Failed to send seek request: \(error)")
}
}
return .success
}
commandCenter.bookmarkCommand.isEnabled = false
commandCenter.changePlaybackRateCommand.isEnabled = false
commandCenter.changeRepeatModeCommand.isEnabled = false
commandCenter.changeShuffleModeCommand.isEnabled = false
commandCenter.disableLanguageOptionCommand.isEnabled = false
commandCenter.dislikeCommand.isEnabled = false
commandCenter.enableLanguageOptionCommand.isEnabled = false
commandCenter.likeCommand.isEnabled = false
commandCenter.ratingCommand.isEnabled = false
#endif
}
deinit {
#if os(macOS)
if let playHandler = playHandler {
commandCenter.playCommand.removeTarget(playHandler)
}
if let pauseHandler = pauseHandler {
commandCenter.pauseCommand.removeTarget(pauseHandler)
}
if let prevHandler = prevHandler {
commandCenter.previousTrackCommand.removeTarget(prevHandler)
}
if let nextHandler = nextHandler {
commandCenter.nextTrackCommand.removeTarget(nextHandler)
}
if let seekHandler = seekHandler {
commandCenter.changePlaybackPositionCommand.removeTarget(seekHandler)
}
#endif
}
func watchChanges() async throws {
let msg = try await conn.request(
Moo(subscribeZoneChange: .init(subscriptionID: UUID().uuidString))
)
let body = try TransportService.SubscribeZoneChangesResponse(msg)
zones = body.zones
for zone in zones {
seeks[zone.id] = zone.nowPlaying?.seekPosition
}
updateNowPlaying()
for try await message in await conn.messages.compactMap({
TransportService.ZoneChangeEvent($0)
}) {
for added in message.addedZones {
putZone(zone: added)
}
for changed in message.changedZones {
putZone(zone: changed)
}
for removedID in message.removedZoneIDs {
removeZone(zoneID: removedID)
}
for seekChange in message.seekChanges {
seeks[seekChange.zoneID] = seekChange.seekPosition
}
updateNowPlaying()
}
}
private func updateNowPlaying() {
#if os(macOS)
let center = MPNowPlayingInfoCenter.default()
var nowPlayingInfo = [String: Any]()
switch self.zone?.state {
case .playing:
center.playbackState = .playing
case .paused:
center.playbackState = .paused
default:
center.playbackState = .stopped
}
commandCenter.pauseCommand.isEnabled = zone?.isPauseAllowed ?? false
commandCenter.playCommand.isEnabled = zone?.isPauseAllowed ?? false
commandCenter.previousTrackCommand.isEnabled =
zone?.isPreviousAllowed ?? false
commandCenter.nextTrackCommand.isEnabled = zone?.isNextAllowed ?? false
commandCenter.changePlaybackPositionCommand.isEnabled =
zone?.isSeekAllowed ?? false
defer {
center.nowPlayingInfo = nowPlayingInfo
}
guard let zone = self.zone, let nowPlaying = zone.nowPlaying else {
return
}
if let secondLine = nowPlaying.doubleLine.line2 {
nowPlayingInfo[MPMediaItemPropertyArtist] = secondLine
}
if let artwork = nowPlaying.imageKey,
let imageURLBuilder = self.imageURLBuilder
{
let image = MPMediaItemArtwork(
boundsSize: .init(width: 256, height: 256),
requestHandler: { size in
let url = imageURLBuilder.build(
req: ImageService.GetRequest.init(
key: artwork,
format: .png,
scale: .fit,
width: UInt(size.width),
height: UInt(size.height)
)
)
guard let url = url, let data = try? Data(contentsOf: url),
let image = NSImage(data: data)
else {
return NSImage(size: size)
}
return image
}
)
nowPlayingInfo[MPMediaItemPropertyArtwork] = image
}
nowPlayingInfo[MPMediaItemPropertyMediaType] = MPMediaType.music.rawValue
if let duration = nowPlaying.length {
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = duration
}
nowPlayingInfo[MPMediaItemPropertyTitle] = nowPlaying.doubleLine.line1
if let seek = seeks[zone.id] ?? nowPlaying.seekPosition {
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = seek
}
#endif
}
private func putZone(zone: TransportService.Zone) {
if let index = zones.firstIndex(where: { z in z.id == zone.id }) {
zones[index] = zone
} else {
zones.append(zone)
}
seeks[zone.id] = zone.nowPlaying?.seekPosition
}
private func removeZone(zoneID: TransportService.Zone.ID) {
if let index = zones.firstIndex(where: { z in z.id == zoneID }) {
zones.remove(at: index)
}
seeks[zoneID] = nil
}
}