DisplayLink.swift 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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, Sendable {
  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, @unchecked Sendable {}
  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, @unchecked Sendable {
  66. var preferredFramesPerSecond: NSInteger { return 0 }
  67. }
  68. #endif
  69. final class DisplayLink: DisplayLinkCompatible, @unchecked Sendable {
  70. private var link: CVDisplayLink?
  71. private var target: Any?
  72. private var selector: Selector?
  73. private var schedulers: [RunLoop: [RunLoop.Mode]] = [:]
  74. var preferredFramesPerSecond: NSInteger = 0
  75. var timestamp: CFTimeInterval = 0
  76. var duration: CFTimeInterval = 0
  77. init(target: Any, selector: Selector) {
  78. self.target = target
  79. self.selector = selector
  80. CVDisplayLinkCreateWithActiveCGDisplays(&link)
  81. if let link = link {
  82. CVDisplayLinkSetOutputHandler(link) { displayLink, inNow, inOutputTime, flagsIn, flagsOut in
  83. self.displayLinkCallback(
  84. displayLink, inNow: inNow, inOutputTime: inOutputTime, flagsIn: flagsIn, flagsOut: flagsOut
  85. )
  86. }
  87. }
  88. }
  89. deinit {
  90. self.invalidate()
  91. }
  92. private func displayLinkCallback(_ link: CVDisplayLink,
  93. inNow: UnsafePointer<CVTimeStamp>,
  94. inOutputTime: UnsafePointer<CVTimeStamp>,
  95. flagsIn: CVOptionFlags,
  96. flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn
  97. {
  98. let outputTime = inOutputTime.pointee
  99. DispatchQueue.main.async {
  100. guard let selector = self.selector, let target = self.target else { return }
  101. if outputTime.videoTimeScale != 0 {
  102. self.duration = CFTimeInterval(Double(outputTime.videoRefreshPeriod) / Double(outputTime.videoTimeScale))
  103. }
  104. if self.timestamp != 0 {
  105. for scheduler in self.schedulers {
  106. scheduler.key.perform(selector, target: target, argument: nil, order: 0, modes: scheduler.value)
  107. }
  108. }
  109. self.timestamp = CFTimeInterval(Double(outputTime.hostTime) / 1_000_000_000)
  110. }
  111. return kCVReturnSuccess
  112. }
  113. var isPaused: Bool = true {
  114. didSet {
  115. guard let link = link else { return }
  116. if isPaused {
  117. if CVDisplayLinkIsRunning(link) {
  118. CVDisplayLinkStop(link)
  119. }
  120. } else {
  121. if !CVDisplayLinkIsRunning(link) {
  122. CVDisplayLinkStart(link)
  123. }
  124. }
  125. }
  126. }
  127. func add(to runLoop: RunLoop, forMode mode: RunLoop.Mode) {
  128. assert(runLoop == .main)
  129. schedulers[runLoop, default: []].append(mode)
  130. }
  131. func remove(from runLoop: RunLoop, forMode mode: RunLoop.Mode) {
  132. schedulers[runLoop]?.removeAll { $0 == mode }
  133. if let modes = schedulers[runLoop], modes.isEmpty {
  134. schedulers.removeValue(forKey: runLoop)
  135. }
  136. }
  137. func invalidate() {
  138. schedulers = [:]
  139. isPaused = true
  140. target = nil
  141. selector = nil
  142. if let link = link {
  143. CVDisplayLinkSetOutputHandler(link) { _, _, _, _, _ in kCVReturnSuccess }
  144. }
  145. }
  146. }
  147. #endif
  148. #endif