-
Notifications
You must be signed in to change notification settings - Fork 1k
/
AerialView.swift
949 lines (785 loc) · 33.6 KB
/
AerialView.swift
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
//
// AerialView.swift
// Aerial
//
// Created by John Coates on 10/22/15.
// Copyright © 2015 John Coates. All rights reserved.
//
import Foundation
import ScreenSaver
import AVFoundation
import AVKit
@objc(AerialView)
// swiftlint:disable:next type_body_length
final class AerialView: ScreenSaverView, CAAnimationDelegate {
var layerManager: LayerManager
var playerLayer: AVPlayerLayer!
static var players: [AVPlayer] = [AVPlayer]()
static var previewPlayer: AVPlayer?
static var previewView: AerialView?
var player: AVPlayer?
var currentVideo: AerialVideo?
var preferencesController: PanelWindowController?
var observerWasSet = false
var hasStartedPlaying = false
var wasStopped = false
var isDisabled = false
var isQuickFading = false
var brightnessToRestore: Float?
var globalSpeed: Float = 1.0
var globalPause = false
// We use this for tentative Catalina bug workaround
var originalWidth, originalHeight: CGFloat
// We use this for tentative Sonoma bug workaround
var foundScreen: Screen?
var foundFrame: NSRect?
// Tentative improvement when only one video in playlist
var shouldLoop = false
static var shouldFade: Bool {
return (PrefsVideos.fadeMode != .disabled)
}
static var fadeDuration: Double {
switch PrefsVideos.fadeMode {
case .t0_5:
return 0.5
case .t1:
return 1
case .t2:
return 2
default:
return 0.10
}
}
static var textFadeDuration: Double {
switch PrefsInfo.fadeModeText {
case .t0_5:
return 0.5
case .t1:
return 1
case .t2:
return 2
default:
return 0.10
}
}
// Mirrored/cloned viewing mode and Spanned viewing mode share the same player for sync & ressource saving
static var sharingPlayers: Bool {
switch PrefsDisplays.viewingMode {
case .cloned, .mirrored, .spanned:
return true
default:
return false
}
}
static var sharedViews: [AerialView] = []
// Because of lifecycle in Preview, we may pile up old/no longer
// shared instanciated views that we need to track to not reuse
static var instanciatedViews: [AerialView] = []
// MARK: - Shared Player
static var singlePlayerAlreadySetup: Bool = false
static var sharedPlayerIndex: Int?
static var didSkipMain: Bool = false
class var sharedPlayer: AVPlayer {
struct Static {
static let instance: AVPlayer = AVPlayer()
// swiftlint:disable:next identifier_name
static var _player: AVPlayer?
static var player: AVPlayer {
if let activePlayer = _player {
return activePlayer
}
_player = AVPlayer()
return _player!
}
}
return Static.player
}
// MARK: - Init / Setup
// This is the one used by System Preferences/ScreenSaverEngine
override init?(frame: NSRect, isPreview: Bool) {
Aerial.helper.checkCompanion()
// Clear log if > 1MB on startup
rollLogIfNeeded()
// legacyScreenSaver always return true for isPreview on Catalina
// We need to detect and override ourselves
// This is finally fixed in Ventura
var preview = false
self.originalWidth = frame.width
self.originalHeight = frame.height
if frame.width < 400 && frame.height < 300 {
preview = true
}
// This is where we manage our location info layers, clock, etc
self.layerManager = LayerManager(isPreview: preview)
super.init(frame: frame, isPreview: preview)
debugLog("🖼️ AVinit (.saver) \(frame) p: \(isPreview) o: \(preview)")
self.animationTimeInterval = 1.0 / 30.0
if Aerial.helper.underCompanion && isPreview {
debugLog("Running under companion in preview mode, preventing setup")
} else {
// We need to delay things under Sonoma because legacyScreenSaver is awesome
if #available(macOS 14.0, *) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
debugLog("🖼️ AVinit delayed setup!")
self.setup()
}
} else {
setup()
}
}
}
// This is the one used by our App target used for debugging
required init?(coder: NSCoder) {
Aerial.helper.appMode = true
Aerial.helper.checkCompanion()
// Clear log if > 1MB on startup
rollLogIfNeeded()
self.layerManager = LayerManager(isPreview: false)
// ...
self.originalWidth = 0
self.originalHeight = 0
super.init(coder: coder)
self.originalWidth = frame.width
self.originalHeight = frame.height
debugLog("🖼️ AVinit .app")
// We need to delay things under Sonoma because legacyScreenSaver is awesome
if #available(macOS 14.0, *) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
debugLog("🖼️ AVinit delayed setup!")
self.setup()
}
} else {
setup()
}
}
deinit {
Aerial.helper.maybeUnmuteSound()
debugLog("🖼️ \(self.description) AVdeinit ")
NotificationCenter.default.removeObserver(self)
}
func ensureCorrectFormat() {
if #available(OSX 10.15, *) {
} else {
// No HDR allowed here
if PrefsVideos.videoFormat == .v4KHDR {
debugLog("🖼️⚠️ Fixing 4K HDR not allowed prior to Catalina")
PrefsVideos.videoFormat = .v4KHEVC
} else if PrefsVideos.videoFormat == .v1080pHDR {
debugLog("🖼️⚠️ Fixing 1080p HDR not allowed prior to Catalina")
PrefsVideos.videoFormat = .v1080pHEVC
}
}
}
// swiftlint:disable:next cyclomatic_complexity
func setup() {
// Disable HDR only on macOS Ventura
if !Aerial.helper.canHDR() {
if isPreview && (PrefsVideos.videoFormat == .v4KHDR || PrefsVideos.videoFormat == .v1080pHDR) {
// This will lead to crashing in up to Ventura beta5 so disable
let debugTextView = NSTextView(frame: bounds.insetBy(dx: 20, dy: 20))
debugTextView.font = .labelFont(ofSize: 10)
debugTextView.string += "HDR Previews hidden on Ventura"
isDisabled = true
self.addSubview(debugTextView)
return
}
}
// First we check the system appearance, as it relies on our view
Aerial.helper.computeDarkMode(view: self)
// Then check if we need to mute/unmute sound
Aerial.helper.maybeMuteSound()
// Kick up the timezone detection
_ = TimeManagement.sharedInstance
// This is to make sure we don't start in a format that's unsupported
ensureCorrectFormat()
if let version = Bundle(identifier: "com.JohnCoates.Aerial")?.infoDictionary?["CFBundleShortVersionString"] as? String {
debugLog("🖼️ \(self.description) AV setup init (V\(version)) preview: \(self.isPreview)")
debugLog("🖼️ Running \(ProcessInfo.processInfo.operatingSystemVersionString)")
}
// First thing, we may need to migrate the cache !
Cache.migrate()
// Now we need to check if we should remove lingering stuff from the cache !
if Cache.canNetwork() {
Cache.removeCruft()
}
// Check early if we need to enable power saver mode,
// black screen with minimal brightness
if !isPreview {
if (PrefsVideos.onBatteryMode == .alwaysDisabled && Battery.isUnplugged())
|| (PrefsVideos.onBatteryMode == .disableOnLow && Battery.isLow()) {
debugLog("🖼️ Engaging power saving mode")
isDisabled = true
Brightness.set(level: 0.0)
return
}
}
// We may need to set timers to progressively dim the screen
checkIfShouldSetBrightness()
// Shared views can get stuck, we may need to clean them up here
cleanupSharedViews()
// We look for the screen in our detected list.
// In case of preview or unknown screen result will be nil
let displayDetection = DisplayDetection.sharedInstance
let screenCount = displayDetection.getScreenCount()
debugLog("🖼️ Real screen count : \(screenCount)")
var thisScreen: Screen? = nil
if #available(macOS 14.0, *) {
//thisScreen = displayDetection.alternateFindScreenWith(frame: self.frame, backingScaleFactor: self.window?.backingScaleFactor ?? 1)
} else {
thisScreen = displayDetection.findScreenWith(frame: self.frame)
}
// We note the foundFrame as this is more accurate than the reported one! We need this for coordinates mapping
if let thisScreen = thisScreen {
foundFrame = thisScreen.bottomLeftFrame
foundScreen = thisScreen
debugLog("🖼️ Using : \(String(describing: thisScreen))")
}
for twindow in NSApplication.shared.windows {
debugLog("window : \(twindow.debugDescription)")
}
var localPlayer: AVPlayer?
// Is the current screen disabled by user ?
if !isPreview {
// If it's an unknown screen, we leave it enabled
if let screen = thisScreen {
if !displayDetection.isScreenActive(id: screen.id) {
// Then we disable and exit
debugLog("🖼️ This display is not active, disabling")
isDisabled = true
return
}
}
} else {
AerialView.previewView = self
}
// Track which views are sharing the sharedPlayer
if AerialView.sharingPlayers {
AerialView.sharedViews.append(self)
}
// We track all instanciated views here, independand of their shared status
AerialView.instanciatedViews.append(self)
// Setup the AVPlayer
if AerialView.sharingPlayers {
localPlayer = AerialView.sharedPlayer
} else {
localPlayer = AVPlayer()
}
guard let player = localPlayer else {
errorLog("\(self.description) Couldn't create AVPlayer!")
return
}
self.player = player
if isPreview {
AerialView.previewPlayer = player
} else if !AerialView.sharingPlayers {
// add to player list
AerialView.players.append(player)
}
setupPlayerLayer(withPlayer: player)
// In mirror mode we use the main instance player
if AerialView.sharingPlayers && AerialView.singlePlayerAlreadySetup {
if let index = AerialView.sharedPlayerIndex {
self.playerLayer.player = AerialView.instanciatedViews[index].player
self.playerLayer.opacity = 0
return
}
}
// We're never sharing the preview !
if !isPreview {
AerialView.singlePlayerAlreadySetup = true
AerialView.sharedPlayerIndex = AerialView.instanciatedViews.count-1
}
// So first we wait for our list to be ready
VideoList.instance.addCallback {
// Then we may need to delay things a bit if we haven't gathered the coordinates yet
if PrefsTime.timeMode == .locationService && Locations.sharedInstance.coordinates == nil {
debugLog("🖼️⚠️ No coordinates yet, delaying a bit...")
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {
self.playNextVideo()
}
} else {
self.playNextVideo()
}
}
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
debugLog("🖼️ \(self.description) viewDidMoveToWindow frame: \(self.frame) window: \(self.window)")
debugLog(self.window?.screen.debugDescription ?? "Unknown")
if let thisScreen = self.window?.screen {
let screenID = thisScreen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as! CGDirectDisplayID
debugLog(screenID.description)
foundScreen = DisplayDetection.sharedInstance.findScreenWith(id: screenID)
foundFrame = foundScreen?.bottomLeftFrame
debugLog("🖼️🌾 Using : \(String(describing: foundScreen))")
debugLog("🥬🌾 window.screen \(String(describing: self.window?.screen.debugDescription))")
}
}
// Handle window resize
override func viewDidEndLiveResize() {
layerManager.redrawAllCorners()
}
override func viewDidChangeBackingProperties() {
debugLog("🖼️ \(self.description) backing change \((self.window?.backingScaleFactor) ?? 1.0) isDisabled: \(isDisabled) frame: \(self.frame) preview: \(self.isPreview)")
// Tentative workaround for a Catalina+ bug
if self.frame.width < 300 && !isPreview {
debugLog("🖼️☢️ Frame size bug, trying to override to \(originalWidth)x\(originalHeight)!")
self.frame = CGRect(x: 0, y: 0, width: originalWidth, height: originalHeight)
}
if !isDisabled {
if let layer = layer {
layer.contentsScale = (self.window?.backingScaleFactor) ?? 1.0
self.playerLayer.contentsScale = (self.window?.backingScaleFactor) ?? 1.0
// And our additional layers
layerManager.setContentScale(scale: (self.window?.backingScaleFactor) ?? 1.0)
}
}
}
// On previews, it's possible that our shared player was stopped and is not reusable
func cleanupSharedViews() {
if AerialView.singlePlayerAlreadySetup {
if let index = AerialView.sharedPlayerIndex {
if AerialView.instanciatedViews[index].wasStopped {
AerialView.singlePlayerAlreadySetup = false
AerialView.sharedPlayerIndex = nil
AerialView.instanciatedViews = [AerialView]() // Clear the list of instanciated stuff
AerialView.sharedViews = [AerialView]() // And the list of sharedViews
}
}
}
}
// MARK: - Lifecycle stuff
override func startAnimation() {
super.startAnimation()
debugLog("🖼️ \(self.description) startAnimation frame \(self.frame) bounds \(self.bounds)")
if !isDisabled {
// Previews may be restarted, but our layer will get hidden (somehow) so show it back
if isPreview && player?.currentTime() != CMTime.zero {
debugLog("restarting playback")
playerLayer.opacity = 1
player?.play()
}
}
}
override func stopAnimation() {
Aerial.helper.maybeUnmuteSound()
wasStopped = true
debugLog("🖼️ \(self.description) stopAnimation")
if !isDisabled {
player?.pause()
player?.rate = 0
layerManager.removeAllLayers()
playerLayer.removeAllAnimations()
player?.replaceCurrentItem(with: nil)
isDisabled = true
}
if PrefsDisplays.dimBrightness {
if !isPreview, let brightnessToRestore = brightnessToRestore {
Brightness.set(level: brightnessToRestore)
self.brightnessToRestore = nil
}
}
teardown()
}
func teardown() {
debugLog("🖼️ \(self.description) teardown")
// Remove notifications observer
debugLog("🖼️ \(self.description) clear notif")
clearNotifications()
// Clear layer animations
debugLog("🖼️ \(self.description) clear anims")
clearAllLayerAnimations()
if let player = player {
// Remove from player index
let indexMaybe = AerialView.players.firstIndex(of: player)
guard let index = indexMaybe else {
return
}
AerialView.players.remove(at: index)
}
// Remove any download
VideoManager.sharedInstance.cancelAll()
debugLog("🖼️ end teardown, exiting")
}
// Wait for the player to be ready
// swiftlint:disable:next block_based_kvo
internal override func observeValue(forKeyPath keyPath: String?,
of object: Any?, change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?) {
debugLog("🖼️ \(description) observeValue \(String(describing: keyPath)) \(playerLayer.isReadyForDisplay)")
if let player = player, let currentVideo = currentVideo, playerLayer.isReadyForDisplay {
player.play()
hasStartedPlaying = true
if Aerial.helper.underCompanion {
player.rate = globalSpeed
} else {
player.rate = PlaybackSpeed.forVideo(currentVideo.id)
}
debugLog("🖼️ start playback: \(frame) \(bounds) rate: \(player.rate)")
debugLog("🥬🥬 window2 \(String(describing: window?.screen))")
// If we share a player, we need to add the fades and the text to all the
// instanciated views using it (eg: in mirrored mode)
if AerialView.sharingPlayers {
for view in AerialView.sharedViews {
self.addPlayerFades(view: view, player: player, video: currentVideo)
if (Aerial.helper.underCompanion && PrefsInfo.hideUnderCompanion) {
debugLog("🖼️ Disable overlays under Companion")
} else {
view.layerManager.setupLayersForVideo(video: currentVideo, player: player)
}
}
} else {
self.addPlayerFades(view: self, player: player, video: currentVideo)
if (Aerial.helper.underCompanion && PrefsInfo.hideUnderCompanion) {
debugLog("🖼️ Disable overlays under Companion")
} else {
self.layerManager.setupLayersForVideo(video: currentVideo, player: player)
}
}
}
}
// Remove all the layer animations on all shared views
func clearAllLayerAnimations() {
// Clear everything
if let player = player {
layerManager.clearLayerAnimations(player: player)
for view in AerialView.sharedViews {
view.layerManager.clearLayerAnimations(player: player)
}
}
}
func clearNotifications() {
NotificationCenter.default.removeObserver(self)
DistributedNotificationCenter.default.removeObserver(self)
}
func setNotifications(_ currentItem: AVPlayerItem) {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(AerialView.playerItemDidReachEnd(_:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: currentItem)
notificationCenter.addObserver(self,
selector: #selector(AerialView.playerItemNewErrorLogEntryNotification(_:)),
name: NSNotification.Name.AVPlayerItemNewErrorLogEntry,
object: currentItem)
notificationCenter.addObserver(self,
selector: #selector(AerialView.playerItemFailedtoPlayToEnd(_:)),
name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime,
object: currentItem)
notificationCenter.addObserver(self,
selector: #selector(AerialView.playerItemPlaybackStalledNotification(_:)),
name: NSNotification.Name.AVPlayerItemPlaybackStalled,
object: currentItem)
NSWorkspace.shared.notificationCenter.addObserver(
self, selector: #selector(onSleepNote(note:)),
name: NSWorkspace.willSleepNotification, object: nil)
DistributedNotificationCenter.default.addObserver(self,
selector: #selector(AerialView.willStart(_:)),
name: Notification.Name("com.apple.screensaver.willstart"), object: nil)
DistributedNotificationCenter.default.addObserver(self,
selector: #selector(AerialView.willStop(_:)),
name: Notification.Name("com.apple.screensaver.willstop"), object: nil)
/*DistributedNotificationCenter.default.addObserver(self,
selector: #selector(AerialView.screenIsUnlocked(_:)),
name: Notification.Name("com.apple.screenIsUnlocked"), object: nil)
*/
Music.instance.setup()
}
func sendNotification(video: AerialVideo) {
DistributedNotificationCenter.default.post(name: Notification.Name("com.glouel.aerial.nextvideo"), object: "aerialtest : " + video.name)
}
@objc func willStart(_ aNotification: Notification) {
if Aerial.helper.underCompanion {
debugLog("🖼️ 📢📢📢 willStart")
player?.pause()
}
}
@objc func screenIsUnlocked(_ aNotification: Notification) {
if #available(macOS 14.0, *) {
debugLog("🖼️ 📢📢📢 ☢️sonoma☢️ workaround screenIsUnlocked")
if !Aerial.helper.underCompanion {
if let player = player {
layerManager.removeAllLayers()
player.pause()
}
self.stopAnimation()
} else {
if !globalPause {
player?.play()
player?.rate = globalSpeed
}
}
}
}
@objc func onSleepNote(note: Notification) {
debugLog("🖼️ 📢📢📢 onSleepNote")
if !Aerial.helper.underCompanion {
if #available(macOS 14.0, *) {
exit(0)
}
}
}
@objc func willStop(_ aNotification: Notification) {
DisplayDetection.sharedInstance.resetUnusedScreens()
/* if #available(macOS 14.0, *) {
debugLog("🖼️ 📢📢📢 🖼️ 📢📢📢 ☢️sonoma☢️ workaround IGNORING willStop")
} else {*/
debugLog("🖼️ 📢📢📢 willStop")
if !Aerial.helper.underCompanion {
if let player = player {
player.pause()
}
if #available(macOS 14.0, *) {
exit(0)
}
self.stopAnimation()
} else {
if !globalPause {
player?.play()
player?.rate = globalSpeed
}
}
//}
}
// Tentative integration with companion of extra features
@objc func togglePause() {
debugLog("🖼️ Toggling pause")
if player?.rate == 0 {
player?.play()
player?.rate = globalSpeed
globalPause = false
} else {
player?.pause()
globalPause = true
}
removePlayerFades()
}
@objc func nextVideo() {
debugLog("🖼️ Next video")
fastFadeOut(andPlayNext: true)
}
@objc func skipAndHide() {
guard let currentVideo = currentVideo else {
errorLog("skipAndHide, no currentVideo")
return
}
debugLog("🖼️ Skip video and hide")
PrefsVideos.hidden.append(currentVideo.id)
fastFadeOut(andPlayNext: true)
}
@objc func getGlobalSpeed() -> Float {
guard let player = player else {
errorLog("getGlobalSpeed, no player")
return 0
}
debugLog("🖼️ Current global speed : " + String(globalSpeed))
return player.rate
}
@objc func setGlobalSpeed(_ speed : Float) {
debugLog("🖼️ Setting speed to : " + String(speed))
globalSpeed = speed
// Apply now if playing
if let player = player {
if (player.rate != 0) {
player.rate = globalSpeed
}
}
}
// MARK: - playNextVideo()
// swiftlint:disable:next cyclomatic_complexity
func playNextVideo() {
debugLog("🖼️ \(self) pnv")
clearAllLayerAnimations()
clearNotifications()
// play another video
let player = AVPlayer()
let oldPlayer = self.player
self.player = player
player.isMuted = PrefsAdvanced.muteSound
self.playerLayer.player = self.player
self.playerLayer.opacity = AerialView.shouldFade ? 0 : 1.0
if self.isPreview {
AerialView.previewPlayer = player
}
debugLog("🖼️ \(self.description) Setting player for all player layers in \(AerialView.sharedViews)")
for view in AerialView.sharedViews {
view.playerLayer.player = player
}
if oldPlayer == AerialView.previewPlayer {
AerialView.previewView?.playerLayer.player = self.player
}
playerLayer.drawsAsynchronously = true
// get a list of current videos that should be excluded from the candidate selection
// for the next video. This prevents the same video from being shown twice in a row
// as well as the same video being shown on two different monitors even when sharingPlayers
// is false
let currentVideos: [AerialVideo] = AerialView.players.compactMap { (player) -> AerialVideo? in
(player.currentItem as? AerialPlayerItem)?.video
}
let (randomVideo, pshouldLoop) = VideoList.instance.randomVideo(excluding: currentVideos, isVertical: isScreenVertical())
// If we only have one video in the playlist, we can rewind it for seamless transitions
self.shouldLoop = pshouldLoop
guard let video = randomVideo else {
errorLog("\(self.description) Error grabbing random video!")
return
}
self.currentVideo = video
// Workaround to avoid local playback making network calls
let item = AerialPlayerItem(video: video)
if !video.isAvailableOffline {
if let value = PrefsVideos.vibrance[video.id], !video.isHDR() {
item.setVibrance(value)
}
player.replaceCurrentItem(with: item)
debugLog("🖼️ \(self.description) streaming video (not fully available offline) : \(video.url)")
guard let currentItem = player.currentItem else {
errorLog("\(self.description) No current item!")
return
}
debugLog("🖼️ \(self.description) observing current item \(currentItem)")
// Descriptions and fades are set when we begin playback
if !self.observerWasSet {
observerWasSet = true
playerLayer.addObserver(self, forKeyPath: "readyForDisplay", options: .initial, context: nil)
}
sendNotification(video: video)
setNotifications(currentItem)
player.actionAtItemEnd = AVPlayer.ActionAtItemEnd.none
// Let's never download stuff in preview...
if !isPreview {
Cache.fillOrRollCache()
}
} else {
// The new localpath getter
let localPath = VideoList.instance.localPathFor(video: video)
// let localurl = URL(fileURLWithPath: VideoCache.cachePath(forVideo: video)!)
let localurl = URL(fileURLWithPath: localPath)
let localitem = AVPlayerItem(url: localurl)
if !video.isHDR() {
let value = PrefsVideos.vibrance[video.id] ?? 0
localitem.setVibrance(value)
}
DispatchQueue.global(qos: .default).async { [self] in
player.replaceCurrentItem(with: localitem)
debugLog("🖼️ \(self.description) playing video (OFFLINE MODE) : \(localurl)")
guard let currentItem = player.currentItem else {
errorLog("\(self.description) No current item!")
return
}
debugLog("🖼️ \(self.description) observing current item \(currentItem)")
// Descriptions and fades are set when we begin playback
if !self.observerWasSet {
observerWasSet = true
playerLayer.addObserver(self, forKeyPath: "readyForDisplay", options: .initial, context: nil)
}
sendNotification(video: video)
setNotifications(currentItem)
player.actionAtItemEnd = AVPlayer.ActionAtItemEnd.none
// Let's never download stuff in preview...
if !isPreview {
Cache.fillOrRollCache()
}
}
}
}
// Is the current screen vertical?
func isScreenVertical() -> Bool {
return self.frame.size.width < self.frame.size.height
}
override func keyDown(with event: NSEvent) {
debugLog("🖼️ keyDown")
if PrefsVideos.allowSkips {
if event.keyCode == 124 {
if !isQuickFading {
// If we share, just call this on our main view
if AerialView.sharingPlayers {
// The first view with the player gets the fade and the play next instruction,
// it controls the others
for view in AerialView.sharedViews where AerialView.sharedViews.first != view {
view.fastFadeOut(andPlayNext: false)
}
AerialView.sharedViews.first!.fastFadeOut(andPlayNext: true)
} else {
// If we do independant playback we have to skip all views
for view in AerialView.instanciatedViews {
view.fastFadeOut(andPlayNext: true)
}
}
} else {
debugLog("🖼️⚠️ Right arrow key currently locked")
}
} else if event.keyCode == 125 {
stopAnimation()
} else {
self.nextResponder!.keyDown(with: event)
// super.keyDown(with: event)
}
} else {
self.nextResponder?.keyDown(with: event)
// super.keyDown(with: event)
}
}
override var acceptsFirstResponder: Bool {
// swiftlint:disable:next implicit_getter
get {
return true
}
}
// MARK: - Extra Animations
private func fastFadeOut(andPlayNext: Bool) {
// We need to clear the current animations running on playerLayer
isQuickFading = true // Lock the use of keydown
playerLayer.removeAllAnimations()
let fadeOutAnimation = CAKeyframeAnimation(keyPath: "opacity")
fadeOutAnimation.values = [1, 0] as [Int]
fadeOutAnimation.keyTimes = [0, AerialView.fadeDuration] as [NSNumber]
if !Aerial.helper.underCompanion {
fadeOutAnimation.duration = AerialView.fadeDuration
} else {
fadeOutAnimation.values = [1, 1] as [Int]
fadeOutAnimation.duration = 0.1
}
fadeOutAnimation.delegate = self
fadeOutAnimation.isRemovedOnCompletion = false
fadeOutAnimation.calculationMode = CAAnimationCalculationMode.cubic
if andPlayNext {
playerLayer.add(fadeOutAnimation, forKey: "quickfadeandnext")
} else {
playerLayer.add(fadeOutAnimation, forKey: "quickfade")
}
}
// Stop callback for fastFadeOut
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
isQuickFading = false // Release our ugly lock
playerLayer.opacity = 0
if anim == playerLayer.animation(forKey: "quickfadeandnext") {
debugLog("🖼️ stop and next")
playerLayer.removeAllAnimations() // Make sure we get rid of our anim
playNextVideo()
} else {
debugLog("🖼️ stop")
playerLayer.removeAllAnimations() // Make sure we get rid of our anim
}
}
// Create a move animation
func createMoveAnimation(layer: CALayer, to: CGPoint, duration: Double) -> CABasicAnimation {
let moveAnimation = CABasicAnimation(keyPath: "position")
moveAnimation.fromValue = layer.position
moveAnimation.toValue = to
moveAnimation.duration = duration
layer.position = to
return moveAnimation
}
// MARK: - Preferences
override var hasConfigureSheet: Bool {
return true
}
override var configureSheet: NSWindow? {
if let controller = preferencesController {
return controller.window
}
let controller = PanelWindowController()
preferencesController = controller
return controller.window
}
}