AnimatedImageView.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. //
  2. // AnimatedImageView.swift
  3. // Kingfisher
  4. //
  5. // Created by bl4ckra1sond3tre on 4/22/16.
  6. //
  7. // The AnimatedImageView, 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: (any 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: any 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/swiftlang/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. // We have to assume this UIView deinit is called on main thread.
  224. MainActor.assumeIsolated { displayLink.invalidate() }
  225. }
  226. }
  227. #if os(macOS)
  228. public override init(frame frameRect: NSRect) {
  229. super.init(frame: frameRect)
  230. commonInit()
  231. }
  232. public required init?(coder: NSCoder) {
  233. super.init(coder: coder)
  234. commonInit()
  235. }
  236. private func commonInit() {
  237. super.animates = false
  238. wantsLayer = true
  239. }
  240. open override var animates: Bool {
  241. get {
  242. if isDisplayLinkInitialized {
  243. return !displayLink.isPaused
  244. } else {
  245. return super.animates
  246. }
  247. }
  248. set {
  249. if newValue {
  250. startAnimating()
  251. } else {
  252. stopAnimating()
  253. }
  254. }
  255. }
  256. open func startAnimating() {
  257. guard let animator = animator else { return }
  258. guard !animator.isReachMaxRepeatCount else { return }
  259. displayLink.isPaused = false
  260. }
  261. open func stopAnimating() {
  262. if isDisplayLinkInitialized {
  263. displayLink.isPaused = true
  264. }
  265. }
  266. open override var wantsUpdateLayer: Bool {
  267. return true
  268. }
  269. open override func updateLayer() {
  270. if let frame = animator?.currentFrameImage ?? currentFrame, let layer = layer {
  271. layer.contents = frame.kf.cgImage
  272. layer.contentsScale = frame.kf.scale
  273. layer.contentsGravity = determineContentsGravity(for: frame)
  274. currentFrame = frame
  275. }
  276. }
  277. private func determineContentsGravity(for image: NSImage) -> CALayerContentsGravity {
  278. switch imageScaling {
  279. case .scaleProportionallyDown:
  280. if image.size.width > bounds.width || image.size.height > bounds.height {
  281. return .resizeAspect
  282. } else {
  283. return .center
  284. }
  285. case .scaleProportionallyUpOrDown:
  286. return .resizeAspect
  287. case .scaleAxesIndependently:
  288. return .resize
  289. case .scaleNone:
  290. return .center
  291. default:
  292. return .resizeAspect
  293. }
  294. }
  295. open override func viewDidMoveToWindow() {
  296. super.viewDidMoveToWindow()
  297. didMove()
  298. }
  299. open override func viewDidMoveToSuperview() {
  300. super.viewDidMoveToSuperview()
  301. didMove()
  302. }
  303. #else
  304. override open var isAnimating: Bool {
  305. if isDisplayLinkInitialized {
  306. return !displayLink.isPaused
  307. } else {
  308. return super.isAnimating
  309. }
  310. }
  311. override open func startAnimating() {
  312. guard !isAnimating else { return }
  313. guard let animator = animator else { return }
  314. guard !animator.isReachMaxRepeatCount else { return }
  315. displayLink.isPaused = false
  316. }
  317. override open func stopAnimating() {
  318. super.stopAnimating()
  319. if isDisplayLinkInitialized {
  320. displayLink.isPaused = true
  321. }
  322. }
  323. override open func display(_ layer: CALayer) {
  324. layer.contents = animator?.currentFrameImage?.cgImage ?? image?.cgImage
  325. }
  326. override open func didMoveToWindow() {
  327. super.didMoveToWindow()
  328. didMove()
  329. }
  330. override open func didMoveToSuperview() {
  331. super.didMoveToSuperview()
  332. didMove()
  333. }
  334. #endif
  335. // This is for back compatibility that using regular `UIImageView` to show animated image.
  336. override func shouldPreloadAllAnimation() -> Bool {
  337. return false
  338. }
  339. // Reset the animator.
  340. private func reset() {
  341. animator = nil
  342. currentFrame = nil
  343. if let image = image, let frameSource = image.kf.frameSource {
  344. #if os(visionOS)
  345. let scale = UITraitCollection.current.displayScale
  346. #elseif os(macOS)
  347. let scale = image.recommendedLayerContentsScale(window?.backingScaleFactor ?? 0.0)
  348. let contentMode = imageScaling
  349. #else
  350. var scale: CGFloat = 0
  351. if #available(iOS 13.0, tvOS 13.0, *) {
  352. scale = UITraitCollection.current.displayScale
  353. } else {
  354. scale = UIScreen.main.scale
  355. }
  356. #endif
  357. currentFrame = image
  358. let targetSize = bounds.scaled(scale).size
  359. let animator = Animator(
  360. frameSource: frameSource,
  361. contentMode: contentMode,
  362. size: targetSize,
  363. imageSize: image.kf.size,
  364. imageScale: image.kf.scale,
  365. framePreloadCount: framePreloadCount,
  366. repeatCount: repeatCount,
  367. preloadQueue: preloadQueue)
  368. animator.delegate = self
  369. animator.needsPrescaling = needsPrescaling
  370. animator.prepareFramesAsynchronously()
  371. self.animator = animator
  372. }
  373. didMove()
  374. }
  375. private func didMove() {
  376. if autoPlayAnimatedImage && animator != nil {
  377. if let _ = superview, let _ = window {
  378. startAnimating()
  379. } else {
  380. stopAnimating()
  381. }
  382. }
  383. }
  384. /// If the Animator cannot prepare the next frame in time, `animator.currentFrameImage` will return nil.
  385. /// To prevent unexpected blinking in the ImageView, we maintain a cache of the currently displayed frame
  386. /// to use as a fallback in such scenarios.
  387. private var currentFrame: KFCrossPlatformImage?
  388. /// Update the current frame with the displayLink duration.
  389. @MainActor
  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. @MainActor
  422. protocol AnimatorDelegate: AnyObject {
  423. func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
  424. }
  425. extension AnimatedImageView: AnimatorDelegate {
  426. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  427. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  428. }
  429. }
  430. extension AnimatedImageView {
  431. // Represents a single frame in a GIF.
  432. struct AnimatedFrame {
  433. // The image to display for this frame. Its value is nil when the frame is removed from the buffer.
  434. let image: KFCrossPlatformImage?
  435. // The duration that this frame should remain active.
  436. let duration: TimeInterval
  437. // A placeholder frame with no image assigned.
  438. // Used to replace frames that are no longer needed in the animation.
  439. var placeholderFrame: AnimatedFrame {
  440. return AnimatedFrame(image: nil, duration: duration)
  441. }
  442. // Whether this frame instance contains an image or not.
  443. var isPlaceholder: Bool {
  444. return image == nil
  445. }
  446. // Returns a new instance from an optional image.
  447. //
  448. // - parameter image: An optional `UIImage` instance to be assigned to the new frame.
  449. // - returns: An `AnimatedFrame` instance.
  450. func makeAnimatedFrame(image: KFCrossPlatformImage?) -> AnimatedFrame {
  451. return AnimatedFrame(image: image, duration: duration)
  452. }
  453. }
  454. }
  455. extension AnimatedImageView {
  456. // MARK: - Animator
  457. // TODO: Check the thread-safety of `Animator` for Sendable again.
  458. /// An animator which is used to drive the data behind ``AnimatedImageView``.
  459. public class Animator: @unchecked Sendable {
  460. private let size: CGSize
  461. private let imageSize: CGSize
  462. private let imageScale: CGFloat
  463. /// The maximum count of image frames that need to be preloaded.
  464. public let maxFrameCount: Int
  465. private let frameSource: any ImageFrameSource
  466. private let maxRepeatCount: RepeatCount
  467. private let maxTimeStep: TimeInterval = 1.0
  468. private let animatedFrames = SafeArray<AnimatedFrame>()
  469. private var frameCount = 0
  470. private var timeSinceLastFrameChange: TimeInterval = 0.0
  471. private var currentRepeatCount: UInt = 0
  472. var isFinished: Bool = false
  473. var needsPrescaling = true
  474. weak var delegate: (any AnimatorDelegate)?
  475. // Total duration of one animation loop
  476. var loopDuration: TimeInterval = 0
  477. /// The image of the current frame.
  478. public var currentFrameImage: KFCrossPlatformImage? {
  479. return frame(at: currentFrameIndex)
  480. }
  481. /// The duration of the current active frame.
  482. public var currentFrameDuration: TimeInterval {
  483. return duration(at: currentFrameIndex)
  484. }
  485. /// The index of the current animation frame.
  486. public internal(set) var currentFrameIndex = 0 {
  487. didSet {
  488. previousFrameIndex = oldValue
  489. }
  490. }
  491. var previousFrameIndex = 0 {
  492. didSet {
  493. preloadQueue.async {
  494. self.updatePreloadedFrames()
  495. }
  496. }
  497. }
  498. var isReachMaxRepeatCount: Bool {
  499. switch maxRepeatCount {
  500. case .once:
  501. return currentRepeatCount >= 1
  502. case .finite(let maxCount):
  503. return currentRepeatCount >= maxCount
  504. case .infinite:
  505. return false
  506. }
  507. }
  508. /// Whether the current frame is the last frame or not in the animation sequence.
  509. public var isLastFrame: Bool {
  510. return currentFrameIndex == frameCount - 1
  511. }
  512. var preloadingIsNeeded: Bool {
  513. return maxFrameCount < frameCount - 1
  514. }
  515. #if os(macOS)
  516. var contentMode = NSImageScaling.scaleAxesIndependently
  517. #else
  518. var contentMode = UIView.ContentMode.scaleToFill
  519. #endif
  520. private lazy var preloadQueue: DispatchQueue = {
  521. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  522. }()
  523. /// Creates an animator with image source reference.
  524. ///
  525. /// - Parameters:
  526. /// - source: The reference of animated image.
  527. /// - mode: Content mode of the `AnimatedImageView`.
  528. /// - size: Size of the `AnimatedImageView`.
  529. /// - imageSize: Size of the `KingfisherWrapper`.
  530. /// - imageScale: Scale of the `KingfisherWrapper`.
  531. /// - count: Count of frames needed to be preloaded.
  532. /// - repeatCount: The repeat count should this animator uses.
  533. /// - preloadQueue: Dispatch queue used for preloading images.
  534. convenience init(imageSource source: CGImageSource,
  535. contentMode mode: KFCrossPlatformContentMode,
  536. size: CGSize,
  537. imageSize: CGSize,
  538. imageScale: CGFloat,
  539. framePreloadCount count: Int,
  540. repeatCount: RepeatCount,
  541. preloadQueue: DispatchQueue) {
  542. let frameSource = CGImageFrameSource(data: nil, imageSource: source, options: nil)
  543. self.init(frameSource: frameSource,
  544. contentMode: mode,
  545. size: size,
  546. imageSize: imageSize,
  547. imageScale: imageScale,
  548. framePreloadCount: count,
  549. repeatCount: repeatCount,
  550. preloadQueue: preloadQueue)
  551. }
  552. /// Creates an animator with a custom image frame source.
  553. ///
  554. /// - Parameters:
  555. /// - frameSource: The reference of animated image.
  556. /// - mode: Content mode of the `AnimatedImageView`.
  557. /// - size: Size of the `AnimatedImageView`.
  558. /// - imageSize: Size of the `KingfisherWrapper`.
  559. /// - imageScale: Scale of the `KingfisherWrapper`.
  560. /// - count: Count of frames needed to be preloaded.
  561. /// - repeatCount: The repeat count should this animator uses.
  562. /// - preloadQueue: Dispatch queue used for preloading images.
  563. init(frameSource source: any ImageFrameSource,
  564. contentMode mode: KFCrossPlatformContentMode,
  565. size: CGSize,
  566. imageSize: CGSize,
  567. imageScale: CGFloat,
  568. framePreloadCount count: Int,
  569. repeatCount: RepeatCount,
  570. preloadQueue: DispatchQueue) {
  571. self.frameSource = source
  572. self.contentMode = mode
  573. self.size = size
  574. self.imageSize = imageSize
  575. self.imageScale = imageScale
  576. self.maxFrameCount = count
  577. self.maxRepeatCount = repeatCount
  578. self.preloadQueue = preloadQueue
  579. }
  580. /// Gets the image frame of a given index.
  581. /// - Parameter index: The index of the desired image.
  582. /// - Returns: The decoded image at the frame. `nil` if the index is out of bounds or the image is not yet loaded.
  583. public func frame(at index: Int) -> KFCrossPlatformImage? {
  584. return animatedFrames[index]?.image
  585. }
  586. /// Gets the duration of an image for the given frame index.
  587. /// - Parameter index: The index of the desired image.
  588. /// - Returns: The duration of that frame.
  589. public func duration(at index: Int) -> TimeInterval {
  590. return animatedFrames[index]?.duration ?? .infinity
  591. }
  592. func prepareFramesAsynchronously() {
  593. frameCount = frameSource.frameCount
  594. animatedFrames.reserveCapacity(frameCount)
  595. preloadQueue.async { [weak self] in
  596. self?.setupAnimatedFrames()
  597. }
  598. }
  599. @MainActor
  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. @MainActor 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