AnimatedImageView.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. typealias KFCrossPlatformContentMode = UIView.ContentMode
  38. #elseif canImport(AppKit)
  39. import AppKit
  40. typealias KFCrossPlatformContentMode = NSImageScaling
  41. #endif
  42. /// Delegate of the ``AnimatedImageView``.
  43. ///
  44. /// It reports back some events of the animated image view.
  45. public protocol AnimatedImageViewDelegate: AnyObject {
  46. /// Called after the ``AnimatedImageView`` has finished each animation loop.
  47. ///
  48. /// - Parameters:
  49. /// - imageView: The ``AnimatedImageView`` that is being animated.
  50. /// - count: The loop count.
  51. func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt)
  52. /// Called after the ``AnimatedImageView`` has reached the maximum repeat count.
  53. ///
  54. /// - Parameter imageView: The ``AnimatedImageView`` that is being animated.
  55. func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView)
  56. }
  57. extension AnimatedImageViewDelegate {
  58. public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {}
  59. public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {}
  60. }
  61. let KFRunLoopModeCommon = RunLoop.Mode.common
  62. /// Represents a subclass of `UIImageView` for displaying animated images.
  63. ///
  64. /// Different from showing an animated image in a normal `UIImageView` (which loads all frames at one time),
  65. /// ``AnimatedImageView`` only tries to load several frames (defined by ``AnimatedImageView/framePreloadCount``) to
  66. /// reduce memory usage. It provides a tradeoff between memory usage and CPU time. If you have a memory issue when
  67. /// using a normal image view to load GIF data, you could give this class a try.
  68. ///
  69. /// Kingfisher supports setting GIF animated data to either `UIImageView` or ``AnimatedImageView`` out of the box. So
  70. /// it would be fairly easy to switch between them.
  71. @MainActor
  72. open class AnimatedImageView: KFCrossPlatformImageView {
  73. /// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`.
  74. class TargetProxy {
  75. private weak var target: AnimatedImageView?
  76. init(target: AnimatedImageView) {
  77. self.target = target
  78. }
  79. @MainActor @objc func onScreenUpdate() {
  80. target?.updateFrameIfNeeded()
  81. }
  82. }
  83. /// An enumeration that specifies the repeat count of a GIF.
  84. public enum RepeatCount: Equatable {
  85. /// The animated image should be only played once.
  86. case once
  87. /// The animated image should be played by a finite times defined in the associated value.
  88. case finite(count: UInt)
  89. /// The animated image should be played infinitely.
  90. case infinite
  91. public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool {
  92. switch (lhs, rhs) {
  93. case let (.finite(l), .finite(r)):
  94. return l == r
  95. case (.once, .once),
  96. (.infinite, .infinite):
  97. return true
  98. case (.once, .finite(let count)),
  99. (.finite(let count), .once):
  100. return count == 1
  101. case (.once, _),
  102. (.infinite, _),
  103. (.finite, _):
  104. return false
  105. }
  106. }
  107. }
  108. // MARK: - Public property
  109. /// Whether to automatically play the animation when the view becomes visible.
  110. ///
  111. /// The default is `true`.
  112. public var autoPlayAnimatedImage = true
  113. /// The count of frames that should be preloaded before being shown.
  114. public var framePreloadCount = 10
  115. /// Specifies whether the GIF frames should be pre-scaled to the image view's size or not.
  116. ///
  117. /// If the downloaded image is larger than the image view's size, it will help reduce some memory usage.
  118. ///
  119. /// The default is `true`.
  120. public var needsPrescaling = true
  121. /// Decode the GIF frames in background thread before using. It will decode frames data and do a off-screen
  122. /// rendering to extract pixel information in background. This can reduce the main thread CPU usage.
  123. ///
  124. @available(*, deprecated, message: """
  125. This property does not perform as declared and may lead to performance degradation.
  126. It is currently obsolete and scheduled for removal in a future version.
  127. """)
  128. public var backgroundDecode = true
  129. /// The animation timer's run loop mode. The default is `RunLoop.Mode.common`.
  130. ///
  131. /// Setting this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling.
  132. public var runLoopMode = KFRunLoopModeCommon {
  133. willSet {
  134. guard runLoopMode != newValue else { return }
  135. stopAnimating()
  136. displayLink.remove(from: .main, forMode: runLoopMode)
  137. displayLink.add(to: .main, forMode: newValue)
  138. startAnimating()
  139. }
  140. }
  141. /// The repeat count. The animated image will keep animating until the loop count reaches this value.
  142. ///
  143. /// Setting this value to another one will reset the current animation.
  144. ///
  145. /// The default is ``RepeatCount/infinite``, which means the animation will last forever.
  146. public var repeatCount = RepeatCount.infinite {
  147. didSet {
  148. if oldValue != repeatCount {
  149. reset()
  150. #if os(macOS)
  151. needsDisplay = true
  152. layer?.setNeedsDisplay()
  153. #else
  154. setNeedsDisplay()
  155. layer.setNeedsDisplay()
  156. #endif
  157. }
  158. }
  159. }
  160. /// The delegate of this `AnimatedImageView` object.
  161. ///
  162. /// See the ``AnimatedImageViewDelegate`` protocol for more information.
  163. public weak var delegate: AnimatedImageViewDelegate?
  164. /// The ``Animator`` instance that holds the frames of a specific image in memory.
  165. public private(set) var animator: Animator?
  166. // MARK: - Private property
  167. // Dispatch queue used for preloading images.
  168. private lazy var preloadQueue: DispatchQueue = {
  169. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  170. }()
  171. // A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy.
  172. private var isDisplayLinkInitialized: Bool = false
  173. // A display link that keeps calling the `updateFrame` method on every screen refresh.
  174. private lazy var displayLink: DisplayLinkCompatible = {
  175. isDisplayLinkInitialized = true
  176. let displayLink = self.compatibleDisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
  177. displayLink.add(to: .main, forMode: runLoopMode)
  178. displayLink.isPaused = true
  179. return displayLink
  180. }()
  181. // MARK: - Override
  182. override open var image: KFCrossPlatformImage? {
  183. didSet {
  184. if image != oldValue {
  185. reset()
  186. }
  187. #if os(macOS)
  188. needsDisplay = true
  189. layer?.setNeedsDisplay()
  190. #else
  191. setNeedsDisplay()
  192. layer.setNeedsDisplay()
  193. #endif
  194. }
  195. }
  196. open override var isHighlighted: Bool {
  197. get {
  198. super.isHighlighted
  199. }
  200. set {
  201. // Highlighted image is unsupported for animated images.
  202. // See https://github.com/onevcat/Kingfisher/issues/1679
  203. if displayLink.isPaused {
  204. super.isHighlighted = newValue
  205. }
  206. }
  207. }
  208. // Workaround for Apple xcframework creating issue on Apple TV in Swift 5.8.
  209. // https://github.com/apple/swift/issues/66015
  210. #if os(tvOS)
  211. public override init(image: UIImage?, highlightedImage: UIImage?) {
  212. super.init(image: image, highlightedImage: highlightedImage)
  213. }
  214. required public init?(coder: NSCoder) {
  215. super.init(coder: coder)
  216. }
  217. init() {
  218. super.init(frame: .zero)
  219. }
  220. #endif
  221. deinit {
  222. if isDisplayLinkInitialized {
  223. Task { @MainActor in
  224. self.displayLink.invalidate()
  225. }
  226. }
  227. }
  228. #if os(macOS)
  229. public override init(frame frameRect: NSRect) {
  230. super.init(frame: frameRect)
  231. commonInit()
  232. }
  233. public required init?(coder: NSCoder) {
  234. super.init(coder: coder)
  235. commonInit()
  236. }
  237. private func commonInit() {
  238. super.animates = false
  239. wantsLayer = true
  240. }
  241. open override var animates: Bool {
  242. get {
  243. if isDisplayLinkInitialized {
  244. return !displayLink.isPaused
  245. } else {
  246. return super.animates
  247. }
  248. }
  249. set {
  250. if newValue {
  251. startAnimating()
  252. } else {
  253. stopAnimating()
  254. }
  255. }
  256. }
  257. open func startAnimating() {
  258. guard let animator = animator else { return }
  259. guard !animator.isReachMaxRepeatCount else { return }
  260. displayLink.isPaused = false
  261. }
  262. open func stopAnimating() {
  263. if isDisplayLinkInitialized {
  264. displayLink.isPaused = true
  265. }
  266. }
  267. open override var wantsUpdateLayer: Bool {
  268. return true
  269. }
  270. open override func updateLayer() {
  271. if let frame = animator?.currentFrameImage ?? currentFrame, let layer = layer {
  272. layer.contents = frame.kf.cgImage
  273. layer.contentsScale = frame.kf.scale
  274. layer.contentsGravity = determineContentsGravity(for: frame)
  275. currentFrame = frame
  276. }
  277. }
  278. private func determineContentsGravity(for image: NSImage) -> CALayerContentsGravity {
  279. switch imageScaling {
  280. case .scaleProportionallyDown:
  281. if image.size.width > bounds.width || image.size.height > bounds.height {
  282. return .resizeAspect
  283. } else {
  284. return .center
  285. }
  286. case .scaleProportionallyUpOrDown:
  287. return .resizeAspect
  288. case .scaleAxesIndependently:
  289. return .resize
  290. case .scaleNone:
  291. return .center
  292. default:
  293. return .resizeAspect
  294. }
  295. }
  296. open override func viewDidMoveToWindow() {
  297. super.viewDidMoveToWindow()
  298. didMove()
  299. }
  300. open override func viewDidMoveToSuperview() {
  301. super.viewDidMoveToSuperview()
  302. didMove()
  303. }
  304. #else
  305. override open var isAnimating: Bool {
  306. if isDisplayLinkInitialized {
  307. return !displayLink.isPaused
  308. } else {
  309. return super.isAnimating
  310. }
  311. }
  312. override open func startAnimating() {
  313. guard !isAnimating else { return }
  314. guard let animator = animator else { return }
  315. guard !animator.isReachMaxRepeatCount else { return }
  316. displayLink.isPaused = false
  317. }
  318. override open func stopAnimating() {
  319. super.stopAnimating()
  320. if isDisplayLinkInitialized {
  321. displayLink.isPaused = true
  322. }
  323. }
  324. override open func display(_ layer: CALayer) {
  325. layer.contents = animator?.currentFrameImage?.cgImage ?? image?.cgImage
  326. }
  327. override open func didMoveToWindow() {
  328. super.didMoveToWindow()
  329. didMove()
  330. }
  331. override open func didMoveToSuperview() {
  332. super.didMoveToSuperview()
  333. didMove()
  334. }
  335. #endif
  336. // This is for back compatibility that using regular `UIImageView` to show animated image.
  337. override func shouldPreloadAllAnimation() -> Bool {
  338. return false
  339. }
  340. // Reset the animator.
  341. private func reset() {
  342. animator = nil
  343. currentFrame = nil
  344. if let image = image, let frameSource = image.kf.frameSource {
  345. #if os(visionOS)
  346. let scale = UITraitCollection.current.displayScale
  347. #elseif os(macOS)
  348. let scale = image.recommendedLayerContentsScale(window?.backingScaleFactor ?? 0.0)
  349. let contentMode = imageScaling
  350. #else
  351. var scale: CGFloat = 0
  352. if #available(iOS 13.0, tvOS 13.0, *) {
  353. scale = UITraitCollection.current.displayScale
  354. } else {
  355. scale = UIScreen.main.scale
  356. }
  357. #endif
  358. currentFrame = image
  359. let targetSize = bounds.scaled(scale).size
  360. let animator = Animator(
  361. frameSource: frameSource,
  362. contentMode: contentMode,
  363. size: targetSize,
  364. imageSize: image.kf.size,
  365. imageScale: image.kf.scale,
  366. framePreloadCount: framePreloadCount,
  367. repeatCount: repeatCount,
  368. preloadQueue: preloadQueue)
  369. animator.delegate = self
  370. animator.needsPrescaling = needsPrescaling
  371. animator.prepareFramesAsynchronously()
  372. self.animator = animator
  373. }
  374. didMove()
  375. }
  376. private func didMove() {
  377. if autoPlayAnimatedImage && animator != nil {
  378. if let _ = superview, let _ = window {
  379. startAnimating()
  380. } else {
  381. stopAnimating()
  382. }
  383. }
  384. }
  385. /// If the Animator cannot prepare the next frame in time, `animator.currentFrameImage` will return nil.
  386. /// To prevent unexpected blinking in the ImageView, we maintain a cache of the currently displayed frame
  387. /// to use as a fallback in such scenarios.
  388. private var currentFrame: KFCrossPlatformImage?
  389. /// Update the current frame with the displayLink duration.
  390. private func updateFrameIfNeeded() {
  391. guard let animator = animator else {
  392. return
  393. }
  394. guard !animator.isFinished else {
  395. stopAnimating()
  396. delegate?.animatedImageViewDidFinishAnimating(self)
  397. return
  398. }
  399. let duration: CFTimeInterval
  400. // CA based display link is opt-out from ProMotion by default.
  401. // So the duration and its FPS might not match.
  402. // See [#718](https://github.com/onevcat/Kingfisher/issues/718)
  403. // By setting CADisableMinimumFrameDuration to YES in Info.plist may
  404. // cause the preferredFramesPerSecond being 0
  405. let preferredFramesPerSecond = displayLink.preferredFramesPerSecond
  406. if preferredFramesPerSecond == 0 {
  407. duration = displayLink.duration
  408. } else {
  409. // Some devices (like iPad Pro 10.5) will have a different FPS.
  410. duration = 1.0 / TimeInterval(preferredFramesPerSecond)
  411. }
  412. if animator.shouldChangeFrame(with: duration) {
  413. #if os(macOS)
  414. layer?.setNeedsDisplay()
  415. #else
  416. layer.setNeedsDisplay()
  417. #endif
  418. }
  419. }
  420. }
  421. protocol AnimatorDelegate: AnyObject {
  422. func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
  423. }
  424. extension AnimatedImageView: AnimatorDelegate {
  425. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  426. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  427. }
  428. }
  429. extension AnimatedImageView {
  430. // Represents a single frame in a GIF.
  431. struct AnimatedFrame {
  432. // The image to display for this frame. Its value is nil when the frame is removed from the buffer.
  433. let image: KFCrossPlatformImage?
  434. // The duration that this frame should remain active.
  435. let duration: TimeInterval
  436. // A placeholder frame with no image assigned.
  437. // Used to replace frames that are no longer needed in the animation.
  438. var placeholderFrame: AnimatedFrame {
  439. return AnimatedFrame(image: nil, duration: duration)
  440. }
  441. // Whether this frame instance contains an image or not.
  442. var isPlaceholder: Bool {
  443. return image == nil
  444. }
  445. // Returns a new instance from an optional image.
  446. //
  447. // - parameter image: An optional `UIImage` instance to be assigned to the new frame.
  448. // - returns: An `AnimatedFrame` instance.
  449. func makeAnimatedFrame(image: KFCrossPlatformImage?) -> AnimatedFrame {
  450. return AnimatedFrame(image: image, duration: duration)
  451. }
  452. }
  453. }
  454. extension AnimatedImageView {
  455. // MARK: - Animator
  456. /// An animator which is used to drive the data behind ``AnimatedImageView``.
  457. public class Animator {
  458. private let size: CGSize
  459. private let imageSize: CGSize
  460. private let imageScale: CGFloat
  461. /// The maximum count of image frames that need to be preloaded.
  462. public let maxFrameCount: Int
  463. private let frameSource: ImageFrameSource
  464. private let maxRepeatCount: RepeatCount
  465. private let maxTimeStep: TimeInterval = 1.0
  466. private let animatedFrames = SafeArray<AnimatedFrame>()
  467. private var frameCount = 0
  468. private var timeSinceLastFrameChange: TimeInterval = 0.0
  469. private var currentRepeatCount: UInt = 0
  470. var isFinished: Bool = false
  471. var needsPrescaling = true
  472. weak var delegate: AnimatorDelegate?
  473. // Total duration of one animation loop
  474. var loopDuration: TimeInterval = 0
  475. /// The image of the current frame.
  476. public var currentFrameImage: KFCrossPlatformImage? {
  477. return frame(at: currentFrameIndex)
  478. }
  479. /// The duration of the current active frame.
  480. public var currentFrameDuration: TimeInterval {
  481. return duration(at: currentFrameIndex)
  482. }
  483. /// The index of the current animation frame.
  484. public internal(set) var currentFrameIndex = 0 {
  485. didSet {
  486. previousFrameIndex = oldValue
  487. }
  488. }
  489. var previousFrameIndex = 0 {
  490. didSet {
  491. preloadQueue.async {
  492. self.updatePreloadedFrames()
  493. }
  494. }
  495. }
  496. var isReachMaxRepeatCount: Bool {
  497. switch maxRepeatCount {
  498. case .once:
  499. return currentRepeatCount >= 1
  500. case .finite(let maxCount):
  501. return currentRepeatCount >= maxCount
  502. case .infinite:
  503. return false
  504. }
  505. }
  506. /// Whether the current frame is the last frame or not in the animation sequence.
  507. public var isLastFrame: Bool {
  508. return currentFrameIndex == frameCount - 1
  509. }
  510. var preloadingIsNeeded: Bool {
  511. return maxFrameCount < frameCount - 1
  512. }
  513. #if os(macOS)
  514. var contentMode = NSImageScaling.scaleAxesIndependently
  515. #else
  516. var contentMode = UIView.ContentMode.scaleToFill
  517. #endif
  518. private lazy var preloadQueue: DispatchQueue = {
  519. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  520. }()
  521. /// Creates an animator with image source reference.
  522. ///
  523. /// - Parameters:
  524. /// - source: The reference of animated image.
  525. /// - mode: Content mode of the `AnimatedImageView`.
  526. /// - size: Size of the `AnimatedImageView`.
  527. /// - imageSize: Size of the `KingfisherWrapper`.
  528. /// - imageScale: Scale of the `KingfisherWrapper`.
  529. /// - count: Count of frames needed to be preloaded.
  530. /// - repeatCount: The repeat count should this animator uses.
  531. /// - preloadQueue: Dispatch queue used for preloading images.
  532. convenience init(imageSource source: CGImageSource,
  533. contentMode mode: KFCrossPlatformContentMode,
  534. size: CGSize,
  535. imageSize: CGSize,
  536. imageScale: CGFloat,
  537. framePreloadCount count: Int,
  538. repeatCount: RepeatCount,
  539. preloadQueue: DispatchQueue) {
  540. let frameSource = CGImageFrameSource(data: nil, imageSource: source, options: nil)
  541. self.init(frameSource: frameSource,
  542. contentMode: mode,
  543. size: size,
  544. imageSize: imageSize,
  545. imageScale: imageScale,
  546. framePreloadCount: count,
  547. repeatCount: repeatCount,
  548. preloadQueue: preloadQueue)
  549. }
  550. /// Creates an animator with a custom image frame source.
  551. ///
  552. /// - Parameters:
  553. /// - frameSource: The reference of animated image.
  554. /// - mode: Content mode of the `AnimatedImageView`.
  555. /// - size: Size of the `AnimatedImageView`.
  556. /// - imageSize: Size of the `KingfisherWrapper`.
  557. /// - imageScale: Scale of the `KingfisherWrapper`.
  558. /// - count: Count of frames needed to be preloaded.
  559. /// - repeatCount: The repeat count should this animator uses.
  560. /// - preloadQueue: Dispatch queue used for preloading images.
  561. init(frameSource source: ImageFrameSource,
  562. contentMode mode: KFCrossPlatformContentMode,
  563. size: CGSize,
  564. imageSize: CGSize,
  565. imageScale: CGFloat,
  566. framePreloadCount count: Int,
  567. repeatCount: RepeatCount,
  568. preloadQueue: DispatchQueue) {
  569. self.frameSource = source
  570. self.contentMode = mode
  571. self.size = size
  572. self.imageSize = imageSize
  573. self.imageScale = imageScale
  574. self.maxFrameCount = count
  575. self.maxRepeatCount = repeatCount
  576. self.preloadQueue = preloadQueue
  577. }
  578. deinit {
  579. resetAnimatedFrames()
  580. }
  581. /// Gets the image frame of a given index.
  582. /// - Parameter index: The index of the desired image.
  583. /// - Returns: The decoded image at the frame. `nil` if the index is out of bounds or the image is not yet loaded.
  584. public func frame(at index: Int) -> KFCrossPlatformImage? {
  585. return animatedFrames[index]?.image
  586. }
  587. /// Gets the duration of an image for the given frame index.
  588. /// - Parameter index: The index of the desired image.
  589. /// - Returns: The duration of that frame.
  590. public func duration(at index: Int) -> TimeInterval {
  591. return animatedFrames[index]?.duration ?? .infinity
  592. }
  593. func prepareFramesAsynchronously() {
  594. frameCount = frameSource.frameCount
  595. animatedFrames.reserveCapacity(frameCount)
  596. preloadQueue.async { [weak self] in
  597. self?.setupAnimatedFrames()
  598. }
  599. }
  600. func shouldChangeFrame(with duration: CFTimeInterval) -> Bool {
  601. incrementTimeSinceLastFrameChange(with: duration)
  602. if currentFrameDuration > timeSinceLastFrameChange {
  603. return false
  604. } else {
  605. resetTimeSinceLastFrameChange()
  606. incrementCurrentFrameIndex()
  607. return true
  608. }
  609. }
  610. private func setupAnimatedFrames() {
  611. resetAnimatedFrames()
  612. var duration: TimeInterval = 0
  613. (0..<frameCount).forEach { index in
  614. let frameDuration = frameSource.duration(at: index)
  615. duration += min(frameDuration, maxTimeStep)
  616. animatedFrames.append(AnimatedFrame(image: nil, duration: frameDuration))
  617. if index > maxFrameCount { return }
  618. animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index))
  619. }
  620. self.loopDuration = duration
  621. }
  622. private func resetAnimatedFrames() {
  623. animatedFrames.removeAll()
  624. }
  625. private func loadFrame(at index: Int) -> KFCrossPlatformImage? {
  626. let resize = needsPrescaling && size != .zero
  627. let maxSize = resize ? size : nil
  628. guard let cgImage = frameSource.frame(at: index, maxSize: maxSize) else {
  629. return nil
  630. }
  631. #if os(macOS)
  632. return KFCrossPlatformImage(cgImage: cgImage, size: .zero)
  633. #else
  634. if #available(iOS 15, tvOS 15, *) {
  635. // From iOS 15, a plain image loading causes iOS calling `-[_UIImageCGImageContent initWithCGImage:scale:]`
  636. // in ImageIO, which holds the image ref on the creating thread.
  637. // To get a workaround, create another image ref and use that to create the final image. This leads to
  638. // some performance loss, but there is little we can do.
  639. // https://github.com/onevcat/Kingfisher/issues/1844
  640. // https://github.com/onevcat/Kingfisher/pulls/2194
  641. guard let unretainedImage = CGImage.create(ref: cgImage) else {
  642. return KFCrossPlatformImage(cgImage: cgImage)
  643. }
  644. return KFCrossPlatformImage(cgImage: unretainedImage)
  645. } else {
  646. return KFCrossPlatformImage(cgImage: cgImage)
  647. }
  648. #endif
  649. }
  650. private func updatePreloadedFrames() {
  651. guard preloadingIsNeeded else {
  652. return
  653. }
  654. let previousFrame = animatedFrames[previousFrameIndex]
  655. animatedFrames[previousFrameIndex] = previousFrame?.placeholderFrame
  656. // ensure the image dealloc in main thread
  657. defer {
  658. if let image = previousFrame?.image {
  659. DispatchQueue.main.async {
  660. _ = image
  661. }
  662. }
  663. }
  664. preloadIndexes(start: currentFrameIndex).forEach { index in
  665. guard let currentAnimatedFrame = animatedFrames[index] else { return }
  666. if !currentAnimatedFrame.isPlaceholder { return }
  667. animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
  668. }
  669. }
  670. private func incrementCurrentFrameIndex() {
  671. let wasLastFrame = isLastFrame
  672. currentFrameIndex = increment(frameIndex: currentFrameIndex)
  673. if isLastFrame {
  674. currentRepeatCount += 1
  675. if isReachMaxRepeatCount {
  676. isFinished = true
  677. // Notify the delegate here because the animation is stopping.
  678. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  679. }
  680. } else if wasLastFrame {
  681. // Notify the delegate that the loop completed
  682. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  683. }
  684. }
  685. private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
  686. timeSinceLastFrameChange += min(maxTimeStep, duration)
  687. }
  688. private func resetTimeSinceLastFrameChange() {
  689. timeSinceLastFrameChange -= currentFrameDuration
  690. }
  691. private func increment(frameIndex: Int, by value: Int = 1) -> Int {
  692. return (frameIndex + value) % frameCount
  693. }
  694. private func preloadIndexes(start index: Int) -> [Int] {
  695. let nextIndex = increment(frameIndex: index)
  696. let lastIndex = increment(frameIndex: index, by: maxFrameCount)
  697. if lastIndex >= nextIndex {
  698. return [Int](nextIndex...lastIndex)
  699. } else {
  700. return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
  701. }
  702. }
  703. }
  704. }
  705. class SafeArray<Element> {
  706. private var array: Array<Element> = []
  707. private let lock = NSLock()
  708. subscript(index: Int) -> Element? {
  709. get {
  710. lock.lock()
  711. defer { lock.unlock() }
  712. return array.indices ~= index ? array[index] : nil
  713. }
  714. set {
  715. lock.lock()
  716. defer { lock.unlock() }
  717. if let newValue = newValue, array.indices ~= index {
  718. array[index] = newValue
  719. }
  720. }
  721. }
  722. var count : Int {
  723. lock.lock()
  724. defer { lock.unlock() }
  725. return array.count
  726. }
  727. func reserveCapacity(_ count: Int) {
  728. lock.lock()
  729. defer { lock.unlock() }
  730. array.reserveCapacity(count)
  731. }
  732. func append(_ element: Element) {
  733. lock.lock()
  734. defer { lock.unlock() }
  735. array += [element]
  736. }
  737. func removeAll() {
  738. lock.lock()
  739. defer { lock.unlock() }
  740. array = []
  741. }
  742. }
  743. #endif