AnimatedImageView.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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. @MainActor @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. @MainActor
  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. self.displayLink.invalidate()
  224. }
  225. }
  226. #if os(macOS)
  227. public override init(frame frameRect: NSRect) {
  228. super.init(frame: frameRect)
  229. commonInit()
  230. }
  231. public required init?(coder: NSCoder) {
  232. super.init(coder: coder)
  233. commonInit()
  234. }
  235. private func commonInit() {
  236. super.animates = false
  237. wantsLayer = true
  238. }
  239. open override var animates: Bool {
  240. get {
  241. if isDisplayLinkInitialized {
  242. return !displayLink.isPaused
  243. } else {
  244. return super.animates
  245. }
  246. }
  247. set {
  248. if newValue {
  249. startAnimating()
  250. } else {
  251. stopAnimating()
  252. }
  253. }
  254. }
  255. open func startAnimating() {
  256. guard let animator = animator else { return }
  257. guard !animator.isReachMaxRepeatCount else { return }
  258. displayLink.isPaused = false
  259. }
  260. open func stopAnimating() {
  261. if isDisplayLinkInitialized {
  262. displayLink.isPaused = true
  263. }
  264. }
  265. open override var wantsUpdateLayer: Bool {
  266. return true
  267. }
  268. open override func updateLayer() {
  269. if let frame = animator?.currentFrameImage ?? currentFrame, let layer = layer {
  270. layer.contents = frame.kf.cgImage
  271. layer.contentsScale = frame.kf.scale
  272. layer.contentsGravity = determineContentsGravity(for: frame)
  273. currentFrame = frame
  274. }
  275. }
  276. private func determineContentsGravity(for image: NSImage) -> CALayerContentsGravity {
  277. switch imageScaling {
  278. case .scaleProportionallyDown:
  279. if image.size.width > bounds.width || image.size.height > bounds.height {
  280. return .resizeAspect
  281. } else {
  282. return .center
  283. }
  284. case .scaleProportionallyUpOrDown:
  285. return .resizeAspect
  286. case .scaleAxesIndependently:
  287. return .resize
  288. case .scaleNone:
  289. return .center
  290. default:
  291. return .resizeAspect
  292. }
  293. }
  294. open override func viewDidMoveToWindow() {
  295. super.viewDidMoveToWindow()
  296. didMove()
  297. }
  298. open override func viewDidMoveToSuperview() {
  299. super.viewDidMoveToSuperview()
  300. didMove()
  301. }
  302. #else
  303. override open var isAnimating: Bool {
  304. if isDisplayLinkInitialized {
  305. return !displayLink.isPaused
  306. } else {
  307. return super.isAnimating
  308. }
  309. }
  310. override open func startAnimating() {
  311. guard !isAnimating else { return }
  312. guard let animator = animator else { return }
  313. guard !animator.isReachMaxRepeatCount else { return }
  314. displayLink.isPaused = false
  315. }
  316. override open func stopAnimating() {
  317. super.stopAnimating()
  318. if isDisplayLinkInitialized {
  319. displayLink.isPaused = true
  320. }
  321. }
  322. override open func display(_ layer: CALayer) {
  323. layer.contents = animator?.currentFrameImage?.cgImage ?? image?.cgImage
  324. }
  325. override open func didMoveToWindow() {
  326. super.didMoveToWindow()
  327. didMove()
  328. }
  329. override open func didMoveToSuperview() {
  330. super.didMoveToSuperview()
  331. didMove()
  332. }
  333. #endif
  334. // This is for back compatibility that using regular `UIImageView` to show animated image.
  335. override func shouldPreloadAllAnimation() -> Bool {
  336. return false
  337. }
  338. // Reset the animator.
  339. private func reset() {
  340. animator = nil
  341. currentFrame = nil
  342. if let image = image, let frameSource = image.kf.frameSource {
  343. #if os(visionOS)
  344. let scale = UITraitCollection.current.displayScale
  345. #elseif os(macOS)
  346. let scale = image.recommendedLayerContentsScale(window?.backingScaleFactor ?? 0.0)
  347. let contentMode = imageScaling
  348. #else
  349. var scale: CGFloat = 0
  350. if #available(iOS 13.0, tvOS 13.0, *) {
  351. scale = UITraitCollection.current.displayScale
  352. } else {
  353. scale = UIScreen.main.scale
  354. }
  355. #endif
  356. currentFrame = image
  357. let targetSize = bounds.scaled(scale).size
  358. let animator = Animator(
  359. frameSource: frameSource,
  360. contentMode: contentMode,
  361. size: targetSize,
  362. imageSize: image.kf.size,
  363. imageScale: image.kf.scale,
  364. framePreloadCount: framePreloadCount,
  365. repeatCount: repeatCount,
  366. preloadQueue: preloadQueue)
  367. animator.delegate = self
  368. animator.needsPrescaling = needsPrescaling
  369. animator.prepareFramesAsynchronously()
  370. self.animator = animator
  371. }
  372. didMove()
  373. }
  374. private func didMove() {
  375. if autoPlayAnimatedImage && animator != nil {
  376. if let _ = superview, let _ = window {
  377. startAnimating()
  378. } else {
  379. stopAnimating()
  380. }
  381. }
  382. }
  383. /// If the Animator cannot prepare the next frame in time, `animator.currentFrameImage` will return nil.
  384. /// To prevent unexpected blinking in the ImageView, we maintain a cache of the currently displayed frame
  385. /// to use as a fallback in such scenarios.
  386. private var currentFrame: KFCrossPlatformImage?
  387. /// Update the current frame with the displayLink duration.
  388. private func updateFrameIfNeeded() {
  389. guard let animator = animator else {
  390. return
  391. }
  392. guard !animator.isFinished else {
  393. stopAnimating()
  394. delegate?.animatedImageViewDidFinishAnimating(self)
  395. return
  396. }
  397. let duration: CFTimeInterval
  398. // CA based display link is opt-out from ProMotion by default.
  399. // So the duration and its FPS might not match.
  400. // See [#718](https://github.com/onevcat/Kingfisher/issues/718)
  401. // By setting CADisableMinimumFrameDuration to YES in Info.plist may
  402. // cause the preferredFramesPerSecond being 0
  403. let preferredFramesPerSecond = displayLink.preferredFramesPerSecond
  404. if preferredFramesPerSecond == 0 {
  405. duration = displayLink.duration
  406. } else {
  407. // Some devices (like iPad Pro 10.5) will have a different FPS.
  408. duration = 1.0 / TimeInterval(preferredFramesPerSecond)
  409. }
  410. if animator.shouldChangeFrame(with: duration) {
  411. #if os(macOS)
  412. layer?.setNeedsDisplay()
  413. #else
  414. layer.setNeedsDisplay()
  415. #endif
  416. }
  417. }
  418. }
  419. @MainActor
  420. protocol AnimatorDelegate: AnyObject {
  421. func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
  422. }
  423. extension AnimatedImageView: AnimatorDelegate {
  424. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  425. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  426. }
  427. }
  428. extension AnimatedImageView {
  429. // Represents a single frame in a GIF.
  430. struct AnimatedFrame {
  431. // The image to display for this frame. Its value is nil when the frame is removed from the buffer.
  432. let image: KFCrossPlatformImage?
  433. // The duration that this frame should remain active.
  434. let duration: TimeInterval
  435. // A placeholder frame with no image assigned.
  436. // Used to replace frames that are no longer needed in the animation.
  437. var placeholderFrame: AnimatedFrame {
  438. return AnimatedFrame(image: nil, duration: duration)
  439. }
  440. // Whether this frame instance contains an image or not.
  441. var isPlaceholder: Bool {
  442. return image == nil
  443. }
  444. // Returns a new instance from an optional image.
  445. //
  446. // - parameter image: An optional `UIImage` instance to be assigned to the new frame.
  447. // - returns: An `AnimatedFrame` instance.
  448. func makeAnimatedFrame(image: KFCrossPlatformImage?) -> AnimatedFrame {
  449. return AnimatedFrame(image: image, duration: duration)
  450. }
  451. }
  452. }
  453. extension AnimatedImageView {
  454. // MARK: - Animator
  455. /// An animator which is used to drive the data behind ``AnimatedImageView``.
  456. @MainActor
  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. /// 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