DisplayLink.swift 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. //
  2. // DisplayLink.swift
  3. // Kingfisher
  4. //
  5. // Created by yeatse on 2024/1/9.
  6. //
  7. // Copyright (c) 2024 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if !os(watchOS)
  27. #if canImport(UIKit)
  28. import UIKit
  29. #else
  30. import AppKit
  31. import CoreVideo
  32. #endif
  33. protocol DisplayLinkCompatible: AnyObject {
  34. var isPaused: Bool { get set }
  35. var preferredFramesPerSecond: NSInteger { get }
  36. var timestamp: CFTimeInterval { get }
  37. var duration: CFTimeInterval { get }
  38. func add(to runLoop: RunLoop, forMode mode: RunLoop.Mode)
  39. func remove(from runLoop: RunLoop, forMode mode: RunLoop.Mode)
  40. func invalidate()
  41. }
  42. #if !os(macOS)
  43. extension UIView {
  44. func compatibleDisplayLink(target: Any, selector: Selector) -> DisplayLinkCompatible {
  45. return CADisplayLink(target: target, selector: selector)
  46. }
  47. }
  48. extension CADisplayLink: DisplayLinkCompatible {}
  49. #else
  50. extension NSView {
  51. func compatibleDisplayLink(target: Any, selector: Selector) -> DisplayLinkCompatible {
  52. #if swift(>=5.9) // macOS 14 SDK is included in Xcode 15, which comes with swift 5.9. Add this check to make old compilers happy.
  53. if #available(macOS 14.0, *) {
  54. return displayLink(target: target, selector: selector)
  55. } else {
  56. return DisplayLink(target: target, selector: selector)
  57. }
  58. #else
  59. return DisplayLink(target: target, selector: selector)
  60. #endif
  61. }
  62. }
  63. #if swift(>=5.9)
  64. @available(macOS 14.0, *)
  65. extension CADisplayLink: DisplayLinkCompatible {
  66. var preferredFramesPerSecond: NSInteger { return 0 }
  67. }
  68. #endif
  69. class DisplayLink: DisplayLinkCompatible {
  70. private var link: CVDisplayLink?
  71. private var target: Any?
  72. private var selector: Selector?
  73. private var schedulers: [RunLoop: [RunLoop.Mode]] = [:]
  74. init(target: Any, selector: Selector) {
  75. self.target = target
  76. self.selector = selector
  77. CVDisplayLinkCreateWithActiveCGDisplays(&link)
  78. if let link = link {
  79. CVDisplayLinkSetOutputHandler(link, displayLinkCallback(_:inNow:inOutputTime:flagsIn:flagsOut:))
  80. }
  81. }
  82. deinit {
  83. self.invalidate()
  84. }
  85. private func displayLinkCallback(_ link: CVDisplayLink,
  86. inNow: UnsafePointer<CVTimeStamp>,
  87. inOutputTime: UnsafePointer<CVTimeStamp>,
  88. flagsIn: CVOptionFlags,
  89. flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn
  90. {
  91. let outputTime = inOutputTime.pointee
  92. DispatchQueue.main.async {
  93. guard let selector = self.selector, let target = self.target else { return }
  94. if outputTime.videoTimeScale != 0 {
  95. self.duration = CFTimeInterval(Double(outputTime.videoRefreshPeriod) / Double(outputTime.videoTimeScale))
  96. }
  97. if self.timestamp != 0 {
  98. for scheduler in self.schedulers {
  99. scheduler.key.perform(selector, target: target, argument: nil, order: 0, modes: scheduler.value)
  100. }
  101. }
  102. self.timestamp = CFTimeInterval(Double(outputTime.hostTime) / 1_000_000_000)
  103. }
  104. return kCVReturnSuccess
  105. }
  106. var isPaused: Bool = true {
  107. didSet {
  108. guard let link = link else { return }
  109. if isPaused {
  110. if CVDisplayLinkIsRunning(link) {
  111. CVDisplayLinkStop(link)
  112. }
  113. } else {
  114. if !CVDisplayLinkIsRunning(link) {
  115. CVDisplayLinkStart(link)
  116. }
  117. }
  118. }
  119. }
  120. var preferredFramesPerSecond: NSInteger = 0
  121. var timestamp: CFTimeInterval = 0
  122. var duration: CFTimeInterval = 0
  123. func add(to runLoop: RunLoop, forMode mode: RunLoop.Mode) {
  124. assert(runLoop == .main)
  125. schedulers[runLoop, default: []].append(mode)
  126. }
  127. func remove(from runLoop: RunLoop, forMode mode: RunLoop.Mode) {
  128. schedulers[runLoop]?.removeAll { $0 == mode }
  129. if let modes = schedulers[runLoop], modes.isEmpty {
  130. schedulers.removeValue(forKey: runLoop)
  131. }
  132. }
  133. func invalidate() {
  134. schedulers = [:]
  135. isPaused = true
  136. target = nil
  137. selector = nil
  138. if let link = link {
  139. CVDisplayLinkSetOutputHandler(link) { _, _, _, _, _ in kCVReturnSuccess }
  140. }
  141. }
  142. }
  143. #endif
  144. #endif