AnimatedImageView.swift 30 KB

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