-
-
Notifications
You must be signed in to change notification settings - Fork 728
Expand file tree
/
Copy pathNowPlayingController.swift
More file actions
431 lines (362 loc) · 15.3 KB
/
NowPlayingController.swift
File metadata and controls
431 lines (362 loc) · 15.3 KB
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//
// NowPlayingController.swift
// boringNotch
//
// Created by Alexander on 2025-03-29.
//
import AppKit
import Combine
import Foundation
final class NowPlayingController: ObservableObject, MediaControllerProtocol {
func updatePlaybackInfo() async {
await fetchFavoriteStateIfSupported()
}
// MARK: - Properties
@Published private(set) var playbackState: PlaybackState = .init(
bundleIdentifier: "com.apple.Music"
)
var playbackStatePublisher: AnyPublisher<PlaybackState, Never> {
$playbackState.eraseToAnyPublisher()
}
var supportsVolumeControl: Bool {
let bundleID = playbackState.bundleIdentifier
return bundleID == "com.apple.Music" || bundleID == "com.spotify.client"
}
var supportsFavorite: Bool {
let bundleID = playbackState.bundleIdentifier
return bundleID == "com.apple.Music"
}
func setFavorite(_ favorite: Bool) async {
let bundleID = playbackState.bundleIdentifier
if bundleID == "com.apple.Music" {
let runningApps = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.Music")
if !runningApps.isEmpty {
let script = """
tell application "Music"
try
set favorited of current track to \(favorite ? "true" : "false")
end try
end tell
"""
try? await AppleScriptHelper.executeVoid(script)
}
}
// Update the favorite state locally and fetch updated info
try? await Task.sleep(for: .milliseconds(150))
await updatePlaybackInfo()
}
private var lastMusicItem:
(title: String, artist: String, album: String, duration: TimeInterval, artworkData: Data?)?
// MARK: - Media Remote Functions
private let mediaRemoteBundle: CFBundle
private let MRMediaRemoteSendCommandFunction: @convention(c) (Int, AnyObject?) -> Void
private let MRMediaRemoteSetElapsedTimeFunction: @convention(c) (Double) -> Void
private let MRMediaRemoteSetShuffleModeFunction: @convention(c) (Int) -> Void
private let MRMediaRemoteSetRepeatModeFunction: @convention(c) (Int) -> Void
private var process: Process?
private var pipeHandler: JSONLinesPipeHandler?
private var streamTask: Task<Void, Never>?
// MARK: - Initialization
init?() {
guard
let bundle = CFBundleCreate(
kCFAllocatorDefault,
NSURL(fileURLWithPath: "/System/Library/PrivateFrameworks/MediaRemote.framework")),
let MRMediaRemoteSendCommandPointer = CFBundleGetFunctionPointerForName(
bundle, "MRMediaRemoteSendCommand" as CFString),
let MRMediaRemoteSetElapsedTimePointer = CFBundleGetFunctionPointerForName(
bundle, "MRMediaRemoteSetElapsedTime" as CFString),
let MRMediaRemoteSetShuffleModePointer = CFBundleGetFunctionPointerForName(
bundle, "MRMediaRemoteSetShuffleMode" as CFString),
let MRMediaRemoteSetRepeatModePointer = CFBundleGetFunctionPointerForName(
bundle, "MRMediaRemoteSetRepeatMode" as CFString)
else { return nil }
mediaRemoteBundle = bundle
MRMediaRemoteSendCommandFunction = unsafeBitCast(
MRMediaRemoteSendCommandPointer, to: (@convention(c) (Int, AnyObject?) -> Void).self)
MRMediaRemoteSetElapsedTimeFunction = unsafeBitCast(
MRMediaRemoteSetElapsedTimePointer, to: (@convention(c) (Double) -> Void).self)
MRMediaRemoteSetShuffleModeFunction = unsafeBitCast(
MRMediaRemoteSetShuffleModePointer, to: (@convention(c) (Int) -> Void).self)
MRMediaRemoteSetRepeatModeFunction = unsafeBitCast(
MRMediaRemoteSetRepeatModePointer, to: (@convention(c) (Int) -> Void).self)
Task { await setupNowPlayingObserver() }
}
deinit {
streamTask?.cancel()
if let pipeHandler = self.pipeHandler {
Task { await pipeHandler.close()
}
}
if let process = self.process {
if process.isRunning {
process.terminate()
process.waitUntilExit()
}
}
self.process = nil
self.pipeHandler = nil
}
// MARK: - Protocol Implementation
func play() async {
MRMediaRemoteSendCommandFunction(0, nil)
}
func pause() async {
MRMediaRemoteSendCommandFunction(1, nil)
}
func togglePlay() async {
MRMediaRemoteSendCommandFunction(2, nil)
}
func nextTrack() async {
MRMediaRemoteSendCommandFunction(4, nil)
}
func previousTrack() async {
MRMediaRemoteSendCommandFunction(5, nil)
}
func seek(to time: Double) async {
MRMediaRemoteSetElapsedTimeFunction(time)
}
func isActive() -> Bool {
// Check if the currently tracked app (from playback state) is running
let bundleID = playbackState.bundleIdentifier
if bundleID.isEmpty {
return false
}
return NSWorkspace.shared.runningApplications.contains { $0.bundleIdentifier == bundleID }
}
func toggleShuffle() async {
// MRMediaRemoteSendCommandFunction(6, nil)
MRMediaRemoteSetShuffleModeFunction(playbackState.isShuffled ? 1 : 3)
playbackState.isShuffled.toggle()
}
func toggleRepeat() async {
// MRMediaRemoteSendCommandFunction(7, nil)
let newRepeatMode = (playbackState.repeatMode == .off) ? 3 : (playbackState.repeatMode.rawValue - 1)
playbackState.repeatMode = RepeatMode(rawValue: newRepeatMode) ?? .off
MRMediaRemoteSetRepeatModeFunction(newRepeatMode)
}
func setVolume(_ level: Double) async {
// MediaRemote framework doesn't provide direct volume control for the active audio session
// As a workaround, try to control the currently active music app directly
let clampedLevel = max(0.0, min(1.0, level))
let volumePercentage = Int(clampedLevel * 100)
let bundleID = playbackState.bundleIdentifier
if !bundleID.isEmpty {
if bundleID == "com.apple.Music" {
let runningApps = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.Music")
if !runningApps.isEmpty {
let script = "tell application \"Music\" to set sound volume to \(volumePercentage)"
try? await AppleScriptHelper.executeVoid(script)
}
} else if bundleID == "com.spotify.client" {
let runningApps = NSRunningApplication.runningApplications(withBundleIdentifier: "com.spotify.client")
if !runningApps.isEmpty {
let script = "tell application \"Spotify\" to set sound volume to \(volumePercentage)"
try? await AppleScriptHelper.executeVoid(script)
}
}
}
playbackState.volume = clampedLevel
}
// MARK: - Setup Methods
private func setupNowPlayingObserver() async {
let process = Process()
guard
let scriptURL = Bundle.main.url(forResource: "mediaremote-adapter", withExtension: "pl"),
let frameworkPath = Bundle.main.privateFrameworksPath?.appending("/MediaRemoteAdapter.framework")
else {
assertionFailure("Could not find mediaremote-adapter.pl script or framework path")
return
}
process.executableURL = URL(fileURLWithPath: "/usr/bin/perl")
process.arguments = [scriptURL.path, frameworkPath, "stream"]
let pipeHandler = JSONLinesPipeHandler()
process.standardOutput = await pipeHandler.getPipe()
self.process = process
self.pipeHandler = pipeHandler
do {
try process.run()
streamTask = Task { [weak self] in
await self?.processJSONStream()
}
} catch {
assertionFailure("Failed to launch mediaremote-adapter.pl: \(error)")
}
}
// MARK: - Async Stream Processing
private func processJSONStream() async {
guard let pipeHandler = self.pipeHandler else { return }
await pipeHandler.readJSONLines(as: NowPlayingUpdate.self) { [weak self] update in
await self?.handleAdapterUpdate(update)
}
}
// MARK: - Update Methods
private func handleAdapterUpdate(_ update: NowPlayingUpdate) async {
let payload = update.payload
let diff = update.diff ?? false
var newPlaybackState = PlaybackState(bundleIdentifier: playbackState.bundleIdentifier)
newPlaybackState.title = payload.title ?? (diff ? self.playbackState.title : "")
newPlaybackState.artist = payload.artist ?? (diff ? self.playbackState.artist : "")
newPlaybackState.album = payload.album ?? (diff ? self.playbackState.album : "")
newPlaybackState.duration = payload.duration ?? (diff ? self.playbackState.duration : 0)
if let elapsedTime = payload.elapsedTime {
newPlaybackState.currentTime = elapsedTime
} else if diff {
if payload.playing == false {
let timeSinceLastUpdate = Date().timeIntervalSince(self.playbackState.lastUpdated)
newPlaybackState.currentTime = self.playbackState.currentTime + (self.playbackState.playbackRate * timeSinceLastUpdate)
} else {
newPlaybackState.currentTime = self.playbackState.currentTime
}
} else {
newPlaybackState.currentTime = 0
}
if let shuffleMode = payload.shuffleMode {
newPlaybackState.isShuffled = shuffleMode != 1
} else if !diff {
newPlaybackState.isShuffled = false
} else {
newPlaybackState.isShuffled = self.playbackState.isShuffled
}
if let repeatModeValue = payload.repeatMode {
newPlaybackState.repeatMode = RepeatMode(rawValue: repeatModeValue) ?? .off
} else if !diff {
newPlaybackState.repeatMode = .off
} else {
newPlaybackState.repeatMode = self.playbackState.repeatMode
}
if let artworkDataString = payload.artworkData {
newPlaybackState.artwork = Data(
base64Encoded: artworkDataString.trimmingCharacters(in: .whitespacesAndNewlines)
)
} else if !diff {
newPlaybackState.artwork = nil
}
if let dateString = payload.timestamp,
let date = ISO8601DateFormatter().date(from: dateString) {
newPlaybackState.lastUpdated = date
} else if !diff {
newPlaybackState.lastUpdated = Date()
} else {
newPlaybackState.lastUpdated = self.playbackState.lastUpdated
}
newPlaybackState.playbackRate = payload.playbackRate ?? (diff ? self.playbackState.playbackRate : 1.0)
newPlaybackState.isPlaying = payload.playing ?? (diff ? self.playbackState.isPlaying : false)
newPlaybackState.bundleIdentifier = (
payload.parentApplicationBundleIdentifier ??
payload.bundleIdentifier ??
(diff ? self.playbackState.bundleIdentifier : "")
)
newPlaybackState.volume = payload.volume ?? (diff ? self.playbackState.volume : 0.5)
self.playbackState = newPlaybackState
// Fetch favorite state for supported apps asynchronously
// await fetchFavoriteStateIfSupported()
}
private func fetchFavoriteStateIfSupported() async {
let bundleID = playbackState.bundleIdentifier
if bundleID == "com.apple.Music" {
let runningApps = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.Music")
guard !runningApps.isEmpty else { return }
let script = """
tell application "Music"
try
return favorited of current track
on error
return false
end try
end tell
"""
if let result = try? await AppleScriptHelper.execute(script) {
var updated = self.playbackState
updated.isFavorite = result.booleanValue
self.playbackState = updated
}
}
}
}
struct NowPlayingUpdate: Codable {
let payload: NowPlayingPayload
let diff: Bool?
}
struct NowPlayingPayload: Codable {
let title: String?
let artist: String?
let album: String?
let duration: Double?
let elapsedTime: Double?
let shuffleMode: Int?
let repeatMode: Int?
let artworkData: String?
let timestamp: String?
let playbackRate: Double?
let playing: Bool?
let parentApplicationBundleIdentifier: String?
let bundleIdentifier: String?
let volume: Double?
}
actor JSONLinesPipeHandler {
private let pipe: Pipe
private let fileHandle: FileHandle
private var buffer = ""
init() {
self.pipe = Pipe()
self.fileHandle = pipe.fileHandleForReading
}
func getPipe() -> Pipe {
return pipe
}
func readJSONLines<T: Decodable>(as type: T.Type, onLine: @escaping (T) async -> Void) async {
do {
try await self.processLines(as: type) { decodedObject in
await onLine(decodedObject)
}
} catch {
print("Error processing JSON stream: \(error)")
}
}
private func processLines<T: Decodable>(as type: T.Type, onLine: @escaping (T) async -> Void) async throws {
while true {
let data = try await readData()
guard !data.isEmpty else { break }
if let chunk = String(data: data, encoding: .utf8) {
buffer.append(chunk)
while let range = buffer.range(of: "\n") {
let line = String(buffer[..<range.lowerBound])
buffer = String(buffer[range.upperBound...])
if !line.isEmpty {
await processJSONLine(line, as: type, onLine: onLine)
}
}
}
}
}
private func processJSONLine<T: Decodable>(_ line: String, as type: T.Type, onLine: @escaping (T) async -> Void) async {
guard let data = line.data(using: .utf8) else {
return
}
do {
let decodedObject = try JSONDecoder().decode(T.self, from: data)
await onLine(decodedObject)
} catch {
// Ignore lines that can't be decoded
}
}
private func readData() async throws -> Data {
return try await withCheckedThrowingContinuation { continuation in
fileHandle.readabilityHandler = { handle in
let data = handle.availableData
handle.readabilityHandler = nil
continuation.resume(returning: data)
}
}
}
func close() async {
do {
fileHandle.readabilityHandler = nil
try fileHandle.close()
try pipe.fileHandleForWriting.close()
} catch {
print("Error closing pipe handler: \(error)")
}
}
}