DisplayLink.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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(macOS)
  27. import UIKit
  28. #else
  29. import AppKit
  30. import CoreVideo
  31. #endif
  32. protocol DisplayLinkCompatible: AnyObject {
  33. var isPaused: Bool { get set }
  34. var preferredFramesPerSecond: NSInteger { get }
  35. var timestamp: CFTimeInterval { get }
  36. var duration: CFTimeInterval { get }
  37. func add(to runLoop: RunLoop, forMode mode: RunLoop.Mode)
  38. func remove(from runLoop: RunLoop, forMode mode: RunLoop.Mode)
  39. func invalidate()
  40. }
  41. #if !os(macOS)
  42. extension UIView {
  43. func compatibleDisplayLink(target: Any, selector: Selector) -> DisplayLinkCompatible {
  44. return CADisplayLink(target: target, selector: selector)
  45. }
  46. }
  47. extension CADisplayLink: DisplayLinkCompatible {}
  48. #else
  49. extension NSView {
  50. func compatibleDisplayLink(target: Any, selector: Selector) -> DisplayLinkCompatible {
  51. if #available(macOS 14.0, *) {
  52. return displayLink(target: target, selector: selector)
  53. } else {
  54. return DisplayLink(target: target, selector: selector)
  55. }
  56. }
  57. }
  58. @available(macOS 14.0, *)
  59. extension CADisplayLink: DisplayLinkCompatible {
  60. var preferredFramesPerSecond: NSInteger { return 0 }
  61. }
  62. class DisplayLink: DisplayLinkCompatible {
  63. private var link: CVDisplayLink?
  64. private var target: Any?
  65. private var selector: Selector?
  66. private var schedulers: [RunLoop: [RunLoop.Mode]] = [:]
  67. init(target: Any, selector: Selector) {
  68. self.target = target
  69. self.selector = selector
  70. CVDisplayLinkCreateWithActiveCGDisplays(&link)
  71. if let link = link {
  72. CVDisplayLinkSetOutputHandler(link, displayLinkCallback(_:inNow:inOutputTime:flagsIn:flagsOut:))
  73. }
  74. }
  75. deinit {
  76. self.invalidate()
  77. }
  78. private func displayLinkCallback(_ link: CVDisplayLink,
  79. inNow: UnsafePointer<CVTimeStamp>,
  80. inOutputTime: UnsafePointer<CVTimeStamp>,
  81. flagsIn: CVOptionFlags,
  82. flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn
  83. {
  84. let outputTime = inOutputTime.pointee
  85. DispatchQueue.main.async {
  86. guard let selector = self.selector, let target = self.target else { return }
  87. if outputTime.videoTimeScale != 0 {
  88. self.duration = CFTimeInterval(Double(outputTime.videoRefreshPeriod) / Double(outputTime.videoTimeScale))
  89. }
  90. if self.timestamp != 0 {
  91. for scheduler in self.schedulers {
  92. scheduler.key.perform(selector, target: target, argument: nil, order: 0, modes: scheduler.value)
  93. }
  94. }
  95. self.timestamp = CFTimeInterval(Double(outputTime.hostTime) / 1_000_000_000)
  96. }
  97. return kCVReturnSuccess
  98. }
  99. var isPaused: Bool = true {
  100. didSet {
  101. guard let link = link else { return }
  102. if isPaused {
  103. if CVDisplayLinkIsRunning(link) {
  104. CVDisplayLinkStop(link)
  105. }
  106. } else {
  107. if !CVDisplayLinkIsRunning(link) {
  108. CVDisplayLinkStart(link)
  109. }
  110. }
  111. }
  112. }
  113. var preferredFramesPerSecond: NSInteger = 0
  114. var timestamp: CFTimeInterval = 0
  115. var duration: CFTimeInterval = 0
  116. func add(to runLoop: RunLoop, forMode mode: RunLoop.Mode) {
  117. assert(runLoop == .main)
  118. schedulers[runLoop, default: []].append(mode)
  119. }
  120. func remove(from runLoop: RunLoop, forMode mode: RunLoop.Mode) {
  121. schedulers[runLoop]?.removeAll { $0 == mode }
  122. if let modes = schedulers[runLoop], modes.isEmpty {
  123. schedulers.removeValue(forKey: runLoop)
  124. }
  125. }
  126. func invalidate() {
  127. schedulers = [:]
  128. isPaused = true
  129. target = nil
  130. selector = nil
  131. if let link = link {
  132. CVDisplayLinkSetOutputHandler(link) { _, _, _, _, _ in kCVReturnSuccess }
  133. }
  134. }
  135. }
  136. #endif