AnimatedImageView.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. //
  2. // AnimatableImageView.swift
  3. // Kingfisher
  4. //
  5. // Created by bl4ckra1sond3tre on 4/22/16.
  6. //
  7. // The AnimatableImageView, AnimatedFrame and Animator is a modified version of
  8. // some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu)
  9. //
  10. // The MIT License (MIT)
  11. //
  12. // Copyright (c) 2019 Reda Lemeden.
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining a copy of
  15. // this software and associated documentation files (the "Software"), to deal in
  16. // the Software without restriction, including without limitation the rights to
  17. // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  18. // the Software, and to permit persons to whom the Software is furnished to do so,
  19. // subject to the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be included in all
  22. // copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  25. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  26. // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  27. // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  28. // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  29. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. // The name and characters used in the demo of this software are property of their
  32. // respective owners.
  33. #if !os(watchOS)
  34. #if canImport(UIKit)
  35. import UIKit
  36. import ImageIO
  37. public typealias KFCrossPlatformContentMode = UIView.ContentMode
  38. #elseif canImport(AppKit)
  39. import AppKit
  40. import CoreVideo
  41. public typealias KFCrossPlatformContentMode = NSImageScaling
  42. #endif
  43. /// Protocol of `AnimatedImageView`.
  44. public protocol AnimatedImageViewDelegate: AnyObject {
  45. /// Called after the animatedImageView has finished each animation loop.
  46. ///
  47. /// - Parameters:
  48. /// - imageView: The `AnimatedImageView` that is being animated.
  49. /// - count: The looped count.
  50. func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt)
  51. /// Called after the `AnimatedImageView` has reached the max repeat count.
  52. ///
  53. /// - Parameter imageView: The `AnimatedImageView` that is being animated.
  54. func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView)
  55. }
  56. extension AnimatedImageViewDelegate {
  57. public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {}
  58. public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {}
  59. }
  60. let KFRunLoopModeCommon = RunLoop.Mode.common
  61. /// Represents a subclass of `UIImageView` for displaying animated image.
  62. /// Different from showing animated image in a normal `UIImageView` (which load all frames at one time),
  63. /// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage.
  64. /// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image
  65. /// view to load GIF data, you could give this class a try.
  66. ///
  67. /// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So
  68. /// it would be fairly easy to switch between them.
  69. open class AnimatedImageView: KFCrossPlatformImageView {
  70. /// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`.
  71. class TargetProxy {
  72. private weak var target: AnimatedImageView?
  73. init(target: AnimatedImageView) {
  74. self.target = target
  75. }
  76. @objc func onScreenUpdate() {
  77. target?.updateFrameIfNeeded()
  78. }
  79. }
  80. /// Enumeration that specifies repeat count of GIF
  81. public enum RepeatCount: Equatable {
  82. case once
  83. case finite(count: UInt)
  84. case infinite
  85. public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool {
  86. switch (lhs, rhs) {
  87. case let (.finite(l), .finite(r)):
  88. return l == r
  89. case (.once, .once),
  90. (.infinite, .infinite):
  91. return true
  92. case (.once, .finite(let count)),
  93. (.finite(let count), .once):
  94. return count == 1
  95. case (.once, _),
  96. (.infinite, _),
  97. (.finite, _):
  98. return false
  99. }
  100. }
  101. }
  102. // MARK: - Public property
  103. /// Whether automatically play the animation when the view become visible. Default is `true`.
  104. public var autoPlayAnimatedImage = true
  105. /// The count of the frames should be preloaded before shown.
  106. public var framePreloadCount = 10
  107. /// Specifies whether the GIF frames should be pre-scaled to the image view's size or not.
  108. /// If the downloaded image is larger than the image view's size, it will help to reduce some memory use.
  109. /// Default is `true`.
  110. public var needsPrescaling = true
  111. /// Decode the GIF frames in background thread before using. It will decode frames data and do a off-screen
  112. /// rendering to extract pixel information in background. This can reduce the main thread CPU usage.
  113. public var backgroundDecode = true
  114. /// The animation timer's run loop mode. Default is `RunLoop.Mode.common`.
  115. /// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling.
  116. public var runLoopMode = KFRunLoopModeCommon {
  117. willSet {
  118. guard runLoopMode != newValue else { return }
  119. stopAnimating()
  120. displayLink.remove(from: .main, forMode: runLoopMode)
  121. displayLink.add(to: .main, forMode: newValue)
  122. startAnimating()
  123. }
  124. }
  125. /// The repeat count. The animated image will keep animate until it the loop count reaches this value.
  126. /// Setting this value to another one will reset current animation.
  127. ///
  128. /// Default is `.infinite`, which means the animation will last forever.
  129. public var repeatCount = RepeatCount.infinite {
  130. didSet {
  131. if oldValue != repeatCount {
  132. reset()
  133. #if os(macOS)
  134. needsDisplay = true
  135. layer?.setNeedsDisplay()
  136. #else
  137. setNeedsDisplay()
  138. layer.setNeedsDisplay()
  139. #endif
  140. }
  141. }
  142. }
  143. /// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more.
  144. public weak var delegate: AnimatedImageViewDelegate?
  145. /// The `Animator` instance that holds the frames of a specific image in memory.
  146. public private(set) var animator: Animator?
  147. // MARK: - Private property
  148. // Dispatch queue used for preloading images.
  149. private lazy var preloadQueue: DispatchQueue = {
  150. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  151. }()
  152. // A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy.
  153. private var isDisplayLinkInitialized: Bool = false
  154. #if os(macOS)
  155. class DisplayLink {
  156. private let link: UnsafeMutablePointer<CVDisplayLink?>
  157. private var target: Any?
  158. private var selector: Selector?
  159. private var schedulers: [RunLoop: [RunLoop.Mode]] = [:]
  160. init(target: Any, selector: Selector) {
  161. link = UnsafeMutablePointer<CVDisplayLink?>.allocate(capacity: 1)
  162. self.target = target
  163. self.selector = selector
  164. CVDisplayLinkCreateWithActiveCGDisplays(link)
  165. if let link = link.pointee {
  166. CVDisplayLinkSetOutputHandler(link, displayLinkCallback(_:inNow:inOutputTime:flagsIn:flagsOut:))
  167. }
  168. }
  169. deinit {
  170. self.invalidate()
  171. link.deallocate()
  172. }
  173. private func displayLinkCallback(_ link: CVDisplayLink,
  174. inNow: UnsafePointer<CVTimeStamp>,
  175. inOutputTime: UnsafePointer<CVTimeStamp>,
  176. flagsIn: CVOptionFlags,
  177. flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn
  178. {
  179. let outputTime = inOutputTime.pointee
  180. DispatchQueue.main.async {
  181. guard let selector = self.selector, let target = self.target else { return }
  182. if outputTime.videoTimeScale != 0 {
  183. self.duration = CFTimeInterval(Double(outputTime.videoRefreshPeriod) / Double(outputTime.videoTimeScale))
  184. }
  185. if self.timestamp != 0 {
  186. for scheduler in self.schedulers {
  187. scheduler.key.perform(selector, target: target, argument: nil, order: 0, modes: scheduler.value)
  188. }
  189. }
  190. self.timestamp = CFTimeInterval(Double(outputTime.hostTime) / 1_000_000_000)
  191. }
  192. return kCVReturnSuccess
  193. }
  194. var isPaused: Bool = true {
  195. didSet {
  196. guard let link = link.pointee else { return }
  197. if isPaused {
  198. if CVDisplayLinkIsRunning(link) {
  199. CVDisplayLinkStop(link)
  200. }
  201. } else {
  202. if !CVDisplayLinkIsRunning(link) {
  203. CVDisplayLinkStart(link)
  204. }
  205. }
  206. }
  207. }
  208. var preferredFramesPerSecond: NSInteger = 0
  209. var timestamp: CFTimeInterval = 0
  210. var duration: CFTimeInterval = 0
  211. func add(to runLoop: RunLoop, forMode mode: RunLoop.Mode) {
  212. assert(runLoop == .main)
  213. schedulers[runLoop, default: []].append(mode)
  214. }
  215. func remove(from runLoop: RunLoop, forMode mode: RunLoop.Mode) {
  216. schedulers[runLoop]?.removeAll { $0 == mode }
  217. if let modes = schedulers[runLoop], modes.isEmpty {
  218. schedulers.removeValue(forKey: runLoop)
  219. }
  220. }
  221. func invalidate() {
  222. schedulers = [:]
  223. isPaused = true
  224. target = nil
  225. selector = nil
  226. if let link = link.pointee {
  227. CVDisplayLinkSetOutputHandler(link) { _, _, _, _, _ in kCVReturnSuccess }
  228. }
  229. }
  230. }
  231. // A display link that keeps calling the `updateFrame` method on every screen refresh.
  232. private lazy var displayLink: DisplayLink = {
  233. isDisplayLinkInitialized = true
  234. let displayLink = DisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
  235. displayLink.add(to: .main, forMode: runLoopMode)
  236. displayLink.isPaused = true
  237. return displayLink
  238. }()
  239. #else
  240. // A display link that keeps calling the `updateFrame` method on every screen refresh.
  241. private lazy var displayLink: CADisplayLink = {
  242. isDisplayLinkInitialized = true
  243. let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
  244. displayLink.add(to: .main, forMode: runLoopMode)
  245. displayLink.isPaused = true
  246. return displayLink
  247. }()
  248. #endif
  249. // MARK: - Override
  250. override open var image: KFCrossPlatformImage? {
  251. didSet {
  252. if image != oldValue {
  253. reset()
  254. }
  255. #if os(macOS)
  256. needsDisplay = true
  257. layer?.setNeedsDisplay()
  258. #else
  259. setNeedsDisplay()
  260. layer.setNeedsDisplay()
  261. #endif
  262. }
  263. }
  264. open override var isHighlighted: Bool {
  265. get {
  266. super.isHighlighted
  267. }
  268. set {
  269. // Highlighted image is unsupported for animated images.
  270. // See https://github.com/onevcat/Kingfisher/issues/1679
  271. if displayLink.isPaused {
  272. super.isHighlighted = newValue
  273. }
  274. }
  275. }
  276. // Workaround for Apple xcframework creating issue on Apple TV in Swift 5.8.
  277. // https://github.com/apple/swift/issues/66015
  278. #if os(tvOS)
  279. public override init(image: UIImage?, highlightedImage: UIImage?) {
  280. super.init(image: image, highlightedImage: highlightedImage)
  281. }
  282. required public init?(coder: NSCoder) {
  283. super.init(coder: coder)
  284. }
  285. init() {
  286. super.init(frame: .zero)
  287. }
  288. #endif
  289. deinit {
  290. if isDisplayLinkInitialized {
  291. displayLink.invalidate()
  292. }
  293. }
  294. #if os(macOS)
  295. public override init(frame frameRect: NSRect) {
  296. super.init(frame: frameRect)
  297. commonInit()
  298. }
  299. public required init?(coder: NSCoder) {
  300. super.init(coder: coder)
  301. commonInit()
  302. }
  303. private func commonInit() {
  304. super.animates = false
  305. }
  306. open override var animates: Bool {
  307. get {
  308. if isDisplayLinkInitialized {
  309. return !displayLink.isPaused
  310. } else {
  311. return super.animates
  312. }
  313. }
  314. set {
  315. if newValue {
  316. startAnimating()
  317. } else {
  318. stopAnimating()
  319. }
  320. }
  321. }
  322. open func startAnimating() {
  323. guard let animator = animator else { return }
  324. guard !animator.isReachMaxRepeatCount else { return }
  325. displayLink.isPaused = false
  326. }
  327. open func stopAnimating() {
  328. if isDisplayLinkInitialized {
  329. displayLink.isPaused = true
  330. }
  331. }
  332. open override var wantsUpdateLayer: Bool {
  333. return true
  334. }
  335. open override func updateLayer() {
  336. if let frame = animator?.currentFrameImage ?? currentFrame {
  337. layer?.contents = frame.kf.cgImage
  338. currentFrame = frame
  339. }
  340. }
  341. open override func viewDidMoveToWindow() {
  342. super.viewDidMoveToWindow()
  343. didMove()
  344. }
  345. open override func viewDidMoveToSuperview() {
  346. super.viewDidMoveToSuperview()
  347. didMove()
  348. }
  349. #else
  350. override open var isAnimating: Bool {
  351. if isDisplayLinkInitialized {
  352. return !displayLink.isPaused
  353. } else {
  354. return super.isAnimating
  355. }
  356. }
  357. /// Starts the animation.
  358. override open func startAnimating() {
  359. guard !isAnimating else { return }
  360. guard let animator = animator else { return }
  361. guard !animator.isReachMaxRepeatCount else { return }
  362. displayLink.isPaused = false
  363. }
  364. /// Stops the animation.
  365. override open func stopAnimating() {
  366. super.stopAnimating()
  367. if isDisplayLinkInitialized {
  368. displayLink.isPaused = true
  369. }
  370. }
  371. override open func display(_ layer: CALayer) {
  372. layer.contents = animator?.currentFrameImage?.cgImage ?? image?.cgImage
  373. }
  374. override open func didMoveToWindow() {
  375. super.didMoveToWindow()
  376. didMove()
  377. }
  378. override open func didMoveToSuperview() {
  379. super.didMoveToSuperview()
  380. didMove()
  381. }
  382. #endif
  383. // This is for back compatibility that using regular `UIImageView` to show animated image.
  384. override func shouldPreloadAllAnimation() -> Bool {
  385. return false
  386. }
  387. // Reset the animator.
  388. private func reset() {
  389. animator = nil
  390. currentFrame = nil
  391. if let image = image, let frameSource = image.kf.frameSource {
  392. #if os(visionOS)
  393. let scale = UITraitCollection.current.displayScale
  394. #elseif os(macOS)
  395. let scale = image.recommendedLayerContentsScale(window?.backingScaleFactor ?? 0.0)
  396. let contentMode = imageScaling
  397. #else
  398. var scale: CGFloat = 0
  399. if #available(iOS 13.0, tvOS 13.0, *) {
  400. scale = UITraitCollection.current.displayScale
  401. } else {
  402. scale = UIScreen.main.scale
  403. }
  404. #endif
  405. currentFrame = image
  406. let targetSize = bounds.scaled(scale).size
  407. let animator = Animator(
  408. frameSource: frameSource,
  409. contentMode: contentMode,
  410. size: targetSize,
  411. imageSize: image.kf.size,
  412. imageScale: image.kf.scale,
  413. framePreloadCount: framePreloadCount,
  414. repeatCount: repeatCount,
  415. preloadQueue: preloadQueue)
  416. animator.delegate = self
  417. animator.needsPrescaling = needsPrescaling
  418. animator.backgroundDecode = backgroundDecode
  419. animator.prepareFramesAsynchronously()
  420. self.animator = animator
  421. }
  422. didMove()
  423. }
  424. private func didMove() {
  425. if autoPlayAnimatedImage && animator != nil {
  426. if let _ = superview, let _ = window {
  427. startAnimating()
  428. } else {
  429. stopAnimating()
  430. }
  431. }
  432. }
  433. /// If the Animator cannot prepare the next frame in time, `animator.currentFrameImage` will return nil.
  434. /// To prevent unexpected blinking in the ImageView, we maintain a cache of the currently displayed frame
  435. /// to use as a fallback in such scenarios.
  436. private var currentFrame: KFCrossPlatformImage?
  437. /// Update the current frame with the displayLink duration.
  438. private func updateFrameIfNeeded() {
  439. guard let animator = animator else {
  440. return
  441. }
  442. guard !animator.isFinished else {
  443. stopAnimating()
  444. delegate?.animatedImageViewDidFinishAnimating(self)
  445. return
  446. }
  447. let duration: CFTimeInterval
  448. // CA based display link is opt-out from ProMotion by default.
  449. // So the duration and its FPS might not match.
  450. // See [#718](https://github.com/onevcat/Kingfisher/issues/718)
  451. // By setting CADisableMinimumFrameDuration to YES in Info.plist may
  452. // cause the preferredFramesPerSecond being 0
  453. let preferredFramesPerSecond = displayLink.preferredFramesPerSecond
  454. if preferredFramesPerSecond == 0 {
  455. duration = displayLink.duration
  456. } else {
  457. // Some devices (like iPad Pro 10.5) will have a different FPS.
  458. duration = 1.0 / TimeInterval(preferredFramesPerSecond)
  459. }
  460. animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in
  461. if hasNewFrame {
  462. #if os(macOS)
  463. self?.layer?.setNeedsDisplay()
  464. #else
  465. self?.layer.setNeedsDisplay()
  466. #endif
  467. }
  468. }
  469. }
  470. }
  471. protocol AnimatorDelegate: AnyObject {
  472. func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
  473. }
  474. extension AnimatedImageView: AnimatorDelegate {
  475. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  476. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  477. }
  478. }
  479. extension AnimatedImageView {
  480. // Represents a single frame in a GIF.
  481. struct AnimatedFrame {
  482. // The image to display for this frame. Its value is nil when the frame is removed from the buffer.
  483. let image: KFCrossPlatformImage?
  484. // The duration that this frame should remain active.
  485. let duration: TimeInterval
  486. // A placeholder frame with no image assigned.
  487. // Used to replace frames that are no longer needed in the animation.
  488. var placeholderFrame: AnimatedFrame {
  489. return AnimatedFrame(image: nil, duration: duration)
  490. }
  491. // Whether this frame instance contains an image or not.
  492. var isPlaceholder: Bool {
  493. return image == nil
  494. }
  495. // Returns a new instance from an optional image.
  496. //
  497. // - parameter image: An optional `UIImage` instance to be assigned to the new frame.
  498. // - returns: An `AnimatedFrame` instance.
  499. func makeAnimatedFrame(image: KFCrossPlatformImage?) -> AnimatedFrame {
  500. return AnimatedFrame(image: image, duration: duration)
  501. }
  502. }
  503. }
  504. extension AnimatedImageView {
  505. // MARK: - Animator
  506. /// An animator which used to drive the data behind `AnimatedImageView`.
  507. public class Animator {
  508. private let size: CGSize
  509. private let imageSize: CGSize
  510. private let imageScale: CGFloat
  511. /// The maximum count of image frames that needs preload.
  512. public let maxFrameCount: Int
  513. private let frameSource: ImageFrameSource
  514. private let maxRepeatCount: RepeatCount
  515. private let maxTimeStep: TimeInterval = 1.0
  516. private let animatedFrames = SafeArray<AnimatedFrame>()
  517. private var frameCount = 0
  518. private var timeSinceLastFrameChange: TimeInterval = 0.0
  519. private var currentRepeatCount: UInt = 0
  520. var isFinished: Bool = false
  521. var needsPrescaling = true
  522. var backgroundDecode = true
  523. weak var delegate: AnimatorDelegate?
  524. // Total duration of one animation loop
  525. var loopDuration: TimeInterval = 0
  526. /// The image of the current frame.
  527. public var currentFrameImage: KFCrossPlatformImage? {
  528. return frame(at: currentFrameIndex)
  529. }
  530. /// The duration of the current active frame duration.
  531. public var currentFrameDuration: TimeInterval {
  532. return duration(at: currentFrameIndex)
  533. }
  534. /// The index of the current animation frame.
  535. public internal(set) var currentFrameIndex = 0 {
  536. didSet {
  537. previousFrameIndex = oldValue
  538. }
  539. }
  540. var previousFrameIndex = 0 {
  541. didSet {
  542. preloadQueue.async {
  543. self.updatePreloadedFrames()
  544. }
  545. }
  546. }
  547. var isReachMaxRepeatCount: Bool {
  548. switch maxRepeatCount {
  549. case .once:
  550. return currentRepeatCount >= 1
  551. case .finite(let maxCount):
  552. return currentRepeatCount >= maxCount
  553. case .infinite:
  554. return false
  555. }
  556. }
  557. /// Whether the current frame is the last frame or not in the animation sequence.
  558. public var isLastFrame: Bool {
  559. return currentFrameIndex == frameCount - 1
  560. }
  561. var preloadingIsNeeded: Bool {
  562. return maxFrameCount < frameCount - 1
  563. }
  564. #if os(macOS)
  565. var contentMode = NSImageScaling.scaleAxesIndependently
  566. #else
  567. var contentMode = UIView.ContentMode.scaleToFill
  568. #endif
  569. private lazy var preloadQueue: DispatchQueue = {
  570. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  571. }()
  572. /// Creates an animator with image source reference.
  573. ///
  574. /// - Parameters:
  575. /// - source: The reference of animated image.
  576. /// - mode: Content mode of the `AnimatedImageView`.
  577. /// - size: Size of the `AnimatedImageView`.
  578. /// - imageSize: Size of the `KingfisherWrapper`.
  579. /// - imageScale: Scale of the `KingfisherWrapper`.
  580. /// - count: Count of frames needed to be preloaded.
  581. /// - repeatCount: The repeat count should this animator uses.
  582. /// - preloadQueue: Dispatch queue used for preloading images.
  583. convenience init(imageSource source: CGImageSource,
  584. contentMode mode: KFCrossPlatformContentMode,
  585. size: CGSize,
  586. imageSize: CGSize,
  587. imageScale: CGFloat,
  588. framePreloadCount count: Int,
  589. repeatCount: RepeatCount,
  590. preloadQueue: DispatchQueue) {
  591. let frameSource = CGImageFrameSource(data: nil, imageSource: source, options: nil)
  592. self.init(frameSource: frameSource,
  593. contentMode: mode,
  594. size: size,
  595. imageSize: imageSize,
  596. imageScale: imageScale,
  597. framePreloadCount: count,
  598. repeatCount: repeatCount,
  599. preloadQueue: preloadQueue)
  600. }
  601. /// Creates an animator with a custom image frame source.
  602. ///
  603. /// - Parameters:
  604. /// - frameSource: The reference of animated image.
  605. /// - mode: Content mode of the `AnimatedImageView`.
  606. /// - size: Size of the `AnimatedImageView`.
  607. /// - imageSize: Size of the `KingfisherWrapper`.
  608. /// - imageScale: Scale of the `KingfisherWrapper`.
  609. /// - count: Count of frames needed to be preloaded.
  610. /// - repeatCount: The repeat count should this animator uses.
  611. /// - preloadQueue: Dispatch queue used for preloading images.
  612. init(frameSource source: ImageFrameSource,
  613. contentMode mode: KFCrossPlatformContentMode,
  614. size: CGSize,
  615. imageSize: CGSize,
  616. imageScale: CGFloat,
  617. framePreloadCount count: Int,
  618. repeatCount: RepeatCount,
  619. preloadQueue: DispatchQueue) {
  620. self.frameSource = source
  621. self.contentMode = mode
  622. self.size = size
  623. self.imageSize = imageSize
  624. self.imageScale = imageScale
  625. self.maxFrameCount = count
  626. self.maxRepeatCount = repeatCount
  627. self.preloadQueue = preloadQueue
  628. GraphicsContext.begin(size: imageSize, scale: imageScale)
  629. }
  630. deinit {
  631. resetAnimatedFrames()
  632. // Sometimes the Animator instance may deallocate on a non-main thread.
  633. // Dispatch it to main thread if needed to avoid potential crashes.
  634. CallbackQueue.mainCurrentOrAsync.execute {
  635. GraphicsContext.end()
  636. }
  637. }
  638. /// Gets the image frame of a given index.
  639. /// - Parameter index: The index of desired image.
  640. /// - Returns: The decoded image at the frame. `nil` if the index is out of bound or the image is not yet loaded.
  641. public func frame(at index: Int) -> KFCrossPlatformImage? {
  642. return animatedFrames[index]?.image
  643. }
  644. public func duration(at index: Int) -> TimeInterval {
  645. return animatedFrames[index]?.duration ?? .infinity
  646. }
  647. func prepareFramesAsynchronously() {
  648. frameCount = frameSource.frameCount
  649. animatedFrames.reserveCapacity(frameCount)
  650. preloadQueue.async { [weak self] in
  651. self?.setupAnimatedFrames()
  652. }
  653. }
  654. func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
  655. incrementTimeSinceLastFrameChange(with: duration)
  656. if currentFrameDuration > timeSinceLastFrameChange {
  657. handler(false)
  658. } else {
  659. resetTimeSinceLastFrameChange()
  660. incrementCurrentFrameIndex()
  661. handler(true)
  662. }
  663. }
  664. private func setupAnimatedFrames() {
  665. resetAnimatedFrames()
  666. var duration: TimeInterval = 0
  667. (0..<frameCount).forEach { index in
  668. let frameDuration = frameSource.duration(at: index)
  669. duration += min(frameDuration, maxTimeStep)
  670. animatedFrames.append(AnimatedFrame(image: nil, duration: frameDuration))
  671. if index > maxFrameCount { return }
  672. animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index))
  673. }
  674. self.loopDuration = duration
  675. }
  676. private func resetAnimatedFrames() {
  677. animatedFrames.removeAll()
  678. }
  679. private func loadFrame(at index: Int) -> KFCrossPlatformImage? {
  680. let resize = needsPrescaling && size != .zero
  681. let maxSize = resize ? size : nil
  682. guard let cgImage = frameSource.frame(at: index, maxSize: maxSize) else {
  683. return nil
  684. }
  685. #if os(macOS)
  686. return KFCrossPlatformImage(cgImage: cgImage, size: .zero)
  687. #else
  688. if #available(iOS 15, tvOS 15, *) {
  689. // From iOS 15, a plain image loading causes iOS calling `-[_UIImageCGImageContent initWithCGImage:scale:]`
  690. // in ImageIO, which holds the image ref on the creating thread.
  691. // To get a workaround, create another image ref and use that to create the final image. This leads to
  692. // some performance loss, but there is little we can do.
  693. // https://github.com/onevcat/Kingfisher/issues/1844
  694. guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage),
  695. let decodedImageRef = cgImage.decoded(on: context, scale: imageScale)
  696. else {
  697. return KFCrossPlatformImage(cgImage: cgImage)
  698. }
  699. return KFCrossPlatformImage(cgImage: decodedImageRef)
  700. } else {
  701. let image = KFCrossPlatformImage(cgImage: cgImage)
  702. if backgroundDecode {
  703. guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage) else {
  704. return image
  705. }
  706. return image.kf.decoded(on: context)
  707. } else {
  708. return image
  709. }
  710. }
  711. #endif
  712. }
  713. private func updatePreloadedFrames() {
  714. guard preloadingIsNeeded else {
  715. return
  716. }
  717. let previousFrame = animatedFrames[previousFrameIndex]
  718. animatedFrames[previousFrameIndex] = previousFrame?.placeholderFrame
  719. // ensure the image dealloc in main thread
  720. defer {
  721. if let image = previousFrame?.image {
  722. DispatchQueue.main.async {
  723. _ = image
  724. }
  725. }
  726. }
  727. preloadIndexes(start: currentFrameIndex).forEach { index in
  728. guard let currentAnimatedFrame = animatedFrames[index] else { return }
  729. if !currentAnimatedFrame.isPlaceholder { return }
  730. animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
  731. }
  732. }
  733. private func incrementCurrentFrameIndex() {
  734. let wasLastFrame = isLastFrame
  735. currentFrameIndex = increment(frameIndex: currentFrameIndex)
  736. if isLastFrame {
  737. currentRepeatCount += 1
  738. if isReachMaxRepeatCount {
  739. isFinished = true
  740. // Notify the delegate here because the animation is stopping.
  741. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  742. }
  743. } else if wasLastFrame {
  744. // Notify the delegate that the loop completed
  745. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  746. }
  747. }
  748. private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
  749. timeSinceLastFrameChange += min(maxTimeStep, duration)
  750. }
  751. private func resetTimeSinceLastFrameChange() {
  752. timeSinceLastFrameChange -= currentFrameDuration
  753. }
  754. private func increment(frameIndex: Int, by value: Int = 1) -> Int {
  755. return (frameIndex + value) % frameCount
  756. }
  757. private func preloadIndexes(start index: Int) -> [Int] {
  758. let nextIndex = increment(frameIndex: index)
  759. let lastIndex = increment(frameIndex: index, by: maxFrameCount)
  760. if lastIndex >= nextIndex {
  761. return [Int](nextIndex...lastIndex)
  762. } else {
  763. return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
  764. }
  765. }
  766. }
  767. }
  768. class SafeArray<Element> {
  769. private var array: Array<Element> = []
  770. private let lock = NSLock()
  771. subscript(index: Int) -> Element? {
  772. get {
  773. lock.lock()
  774. defer { lock.unlock() }
  775. return array.indices ~= index ? array[index] : nil
  776. }
  777. set {
  778. lock.lock()
  779. defer { lock.unlock() }
  780. if let newValue = newValue, array.indices ~= index {
  781. array[index] = newValue
  782. }
  783. }
  784. }
  785. var count : Int {
  786. lock.lock()
  787. defer { lock.unlock() }
  788. return array.count
  789. }
  790. func reserveCapacity(_ count: Int) {
  791. lock.lock()
  792. defer { lock.unlock() }
  793. array.reserveCapacity(count)
  794. }
  795. func append(_ element: Element) {
  796. lock.lock()
  797. defer { lock.unlock() }
  798. array += [element]
  799. }
  800. func removeAll() {
  801. lock.lock()
  802. defer { lock.unlock() }
  803. array = []
  804. }
  805. }
  806. #endif